@ensocode/server 0.3.4 → 0.3.5
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/out/phone/assets/{abnfDiagram-VCTEODGH-6JYofuK8.js → abnfDiagram-VCTEODGH-k76opPl1.js} +1 -1
- package/out/phone/assets/architecture-7GRP2DOG-DFA8x3QF.js +1 -0
- package/out/phone/assets/{architectureDiagram-5GKGNRK7-BeLeAQB1.js → architectureDiagram-5GKGNRK7-yxQH9IuZ.js} +1 -1
- package/out/phone/assets/{blockDiagram-I7D4REHJ-uXn3vhT2.js → blockDiagram-I7D4REHJ-DoHteZpO.js} +1 -1
- package/out/phone/assets/{c4Diagram-7LVT6UL2-CjzMFRll.js → c4Diagram-7LVT6UL2-DQVO6L4q.js} +1 -1
- package/out/phone/assets/channel-BBjWfdZr.js +1 -0
- package/out/phone/assets/{chunk-4HAMMTFA-BA8HaYy2.js → chunk-4HAMMTFA-N9Rw4SGW.js} +1 -1
- package/out/phone/assets/{chunk-75Z2AOVW-BhIfO9es.js → chunk-75Z2AOVW-DKJ8pOxp.js} +1 -1
- package/out/phone/assets/{chunk-DU6HZSFF-BTLBHwj-.js → chunk-DU6HZSFF-BqGW8Nbd.js} +1 -1
- package/out/phone/assets/{chunk-F27PBJKO-CUw8NZk8.js → chunk-F27PBJKO-PkFmkghF.js} +1 -1
- package/out/phone/assets/{chunk-GMAD6QVW-bZOKnRyM.js → chunk-GMAD6QVW-C9VeD3Jk.js} +1 -1
- package/out/phone/assets/{chunk-GVQU2GXP-B0WIm1dS.js → chunk-GVQU2GXP-COhntOeE.js} +1 -1
- package/out/phone/assets/{chunk-IMKFNOWR-DWND4rEr.js → chunk-IMKFNOWR-B87ghLVD.js} +1 -1
- package/out/phone/assets/{chunk-L3NEJ4N5-DgMknY3k.js → chunk-L3NEJ4N5-C3N2izjg.js} +1 -1
- package/out/phone/assets/{chunk-OSK3NFVY-C5aEouov.js → chunk-OSK3NFVY-DaAlvVhz.js} +1 -1
- package/out/phone/assets/{chunk-P2QGCYS3-D2ID3RxV.js → chunk-P2QGCYS3-BQpKr8IZ.js} +1 -1
- package/out/phone/assets/{chunk-POPQ4Y6H-C1lOuNpV.js → chunk-POPQ4Y6H-B2TZMY6U.js} +1 -1
- package/out/phone/assets/{chunk-PWAF6VOD-CfqWQZRE.js → chunk-PWAF6VOD-CgRhpUJy.js} +1 -1
- package/out/phone/assets/{chunk-SHT3W25Y-p37Dlvn4.js → chunk-SHT3W25Y-BySMFA99.js} +1 -1
- package/out/phone/assets/{chunk-SVP7TREG-CSSqW-zb.js → chunk-SVP7TREG-EDGanDUX.js} +1 -1
- package/out/phone/assets/{chunk-TICWLB2K-Bse5ne4b.js → chunk-TICWLB2K-BtCZ8R2k.js} +1 -1
- package/out/phone/assets/classDiagram-ZZMXUADV-CXXjdIIU.js +1 -0
- package/out/phone/assets/classDiagram-v2-VYDZK3BY-CXXjdIIU.js +1 -0
- package/out/phone/assets/{cynefin-OW5HDTMX-BGQqPhYk.js → cynefin-OW5HDTMX-CdZmp44V.js} +1 -1
- package/out/phone/assets/{cynefinDiagram-5FMLGOSQ-Cz3XWaxY.js → cynefinDiagram-5FMLGOSQ-BCz9KwUb.js} +1 -1
- package/out/phone/assets/{dagre-GXQ25YYZ-CjAF6lSz.js → dagre-GXQ25YYZ-CgFeNgh6.js} +1 -1
- package/out/phone/assets/desk-C_b7mE6l.js +2 -0
- package/out/phone/assets/{diagram-S7CK7UJ4-B135cp5a.js → diagram-S7CK7UJ4-CwvaZIBf.js} +1 -1
- package/out/phone/assets/{diagram-UQ7AKVKN-C4pCe0fQ.js → diagram-UQ7AKVKN-DqnD4XoZ.js} +1 -1
- package/out/phone/assets/{diagram-VSXAHHWV-CYkCrin2.js → diagram-VSXAHHWV-Kqc9GudQ.js} +1 -1
- package/out/phone/assets/{diagram-VX7I27RA-CT_vufh_.js → diagram-VX7I27RA-B_0DLDQ0.js} +1 -1
- package/out/phone/assets/{diagram-Z3DM3KII-XEkkXu3P.js → diagram-Z3DM3KII-CppKBEPW.js} +1 -1
- package/out/phone/assets/{ebnfDiagram-PWID7BFC-DfLyeXjw.js → ebnfDiagram-PWID7BFC-DeYPNCu9.js} +1 -1
- package/out/phone/assets/{erDiagram-RLTQ6QDP-pKNbKkAP.js → erDiagram-RLTQ6QDP-MsfxDUmk.js} +1 -1
- package/out/phone/assets/eventmodeling-NTZA5JFV-D4a6gbOs.js +1 -0
- package/out/phone/assets/flowDiagram-HODETNUW-BBTtB5oX.js +1 -0
- package/out/phone/assets/{ganttDiagram-EL5Y4UJY-Df4E50Mj.js → ganttDiagram-EL5Y4UJY-DaScS1os.js} +1 -1
- package/out/phone/assets/{gitGraph-4MIJSDKK-CkjzZeFD.js → gitGraph-4MIJSDKK-C-FzqpZm.js} +1 -1
- package/out/phone/assets/{gitGraphDiagram-WWUBYQGX-CBxfRAfy.js → gitGraphDiagram-WWUBYQGX-4Yv-hAwf.js} +1 -1
- package/out/phone/assets/{info-A6RAGUB7-CHFXa2pw.js → info-A6RAGUB7-CGLEP4t7.js} +1 -1
- package/out/phone/assets/{infoDiagram-27XIBGKW-K0DnZhi4.js → infoDiagram-27XIBGKW-DapEgYQa.js} +1 -1
- package/out/phone/assets/{ishikawaDiagram-5VMMS53U-DTQF2ZuR.js → ishikawaDiagram-5VMMS53U-D1B2lZSG.js} +1 -1
- package/out/phone/assets/{journeyDiagram-3NMN7TZE-wBltkU2i.js → journeyDiagram-3NMN7TZE-BSAtMVJw.js} +1 -1
- package/out/phone/assets/{kanban-definition-UXKFOSKX-BZpcOajP.js → kanban-definition-UXKFOSKX-CfZ4oI7A.js} +1 -1
- package/out/phone/assets/{line-BflnZFgp.js → line-DAXmUM4p.js} +1 -1
- package/out/phone/assets/{main-Crtf_g8h.js → main-B0yD1pMI.js} +97 -97
- package/out/phone/assets/main-DNRbLxEx.css +1 -0
- package/out/phone/assets/{mermaid-parser.core-BiCTmcqa.js → mermaid-parser.core-IObm7oM0.js} +3 -3
- package/out/phone/assets/{mermaid.core-D3TwYaLF.js → mermaid.core-C1wA-mhD.js} +4 -4
- package/out/phone/assets/{mindmap-definition-YA3MSWOX-Cz0aS_6Y.js → mindmap-definition-YA3MSWOX-3ph0EaB9.js} +1 -1
- package/out/phone/assets/{packet-AYTQ26CC-DW-djbhd.js → packet-AYTQ26CC-BbDAe9Au.js} +1 -1
- package/out/phone/assets/{pegDiagram-XKGWAZYB-CE0sZZAE.js → pegDiagram-XKGWAZYB-EsuDcX_3.js} +1 -1
- package/out/phone/assets/{pie-WAS4IAKB-CKGFlXok.js → pie-WAS4IAKB-BQfIj1fu.js} +1 -1
- package/out/phone/assets/{pieDiagram-E7YTZNPT-BrnQ32_6.js → pieDiagram-E7YTZNPT-Cw19z5Ip.js} +1 -1
- package/out/phone/assets/{quadrantDiagram-AXDQQJYC-BrxDAygB.js → quadrantDiagram-AXDQQJYC-Bqwz_sa8.js} +1 -1
- package/out/phone/assets/{radar-RG4KPBEZ-Bo2f5QyA.js → radar-RG4KPBEZ-Dmp-89iD.js} +1 -1
- package/out/phone/assets/{railroad-74A4TZTK-BZEmm0Ha.js → railroad-74A4TZTK-dq2H8w8Y.js} +1 -1
- package/out/phone/assets/railroad-abnf-HS5TGJTU-DddVaVQM.js +1 -0
- package/out/phone/assets/railroad-ebnf-LZEXJU2U-BjvyqMjh.js +1 -0
- package/out/phone/assets/railroad-peg-WCYAUIDC-lBl4CV1_.js +1 -0
- package/out/phone/assets/{railroadDiagram-O6MQD6OU-BvOyUNMC.js → railroadDiagram-O6MQD6OU-D2Sbc7Wn.js} +1 -1
- package/out/phone/assets/{requirementDiagram-BXWQKSXE-T42N3TW5.js → requirementDiagram-BXWQKSXE-CLNUqxbl.js} +1 -1
- package/out/phone/assets/{sankeyDiagram-P5KCCOFB-0us9ErVV.js → sankeyDiagram-P5KCCOFB-Dme5iwcw.js} +1 -1
- package/out/phone/assets/{sequenceDiagram-WJ2MYXX4-BMcYh2ll.js → sequenceDiagram-WJ2MYXX4-C5dYSwPE.js} +1 -1
- package/out/phone/assets/{stateDiagram-D77RDMKH-CgP9dUc3.js → stateDiagram-D77RDMKH-BuxkPvJ6.js} +1 -1
- package/out/phone/assets/stateDiagram-v2-MP3YSRHH-Exd8xDBD.js +1 -0
- package/out/phone/assets/storage-p-WxHA1h.js +1 -0
- package/out/phone/assets/{swimlanes-42K2YHIH-VnE4ceCW.js → swimlanes-42K2YHIH-DHyXnytv.js} +1 -1
- package/out/phone/assets/swimlanesDiagram-VR7AAH4N-B62_42fO.js +8 -0
- package/out/phone/assets/{timeline-definition-24CTP7MA-tH3izgae.js → timeline-definition-24CTP7MA-Bm8Z0u2Z.js} +1 -1
- package/out/phone/assets/{treeView-Q6P3EWNA-CVFDOC7i.js → treeView-Q6P3EWNA-DFUxvDDO.js} +1 -1
- package/out/phone/assets/{treemap-WGGIJYW6-vmikHzt3.js → treemap-WGGIJYW6-CMC-hwzt.js} +1 -1
- package/out/phone/assets/{vennDiagram-4TSXK5OY-b8ttDCR-.js → vennDiagram-4TSXK5OY-CNL4gZsd.js} +1 -1
- package/out/phone/assets/{wardley-WFR3VGLG-D32vKoC1.js → wardley-WFR3VGLG-CHQoq9KJ.js} +1 -1
- package/out/phone/assets/{wardleyDiagram-VM6X3IG4-CMkaIPVH.js → wardleyDiagram-VM6X3IG4-DAuBfK1O.js} +1 -1
- package/out/phone/assets/{xychartDiagram-S5SC5T6Z-pLYDcql3.js → xychartDiagram-S5SC5T6Z-B2T9ECKd.js} +1 -1
- package/out/phone/desk.html +2 -2
- package/out/phone/index.html +3 -3
- package/out/renderer/assets/{abnfDiagram-VCTEODGH-N6OiVFQx.js → abnfDiagram-VCTEODGH-gdhrQbX6.js} +1 -1
- package/out/renderer/assets/{arc-CXVc3U0J.js → arc-D6-Q4l2d.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-5GKGNRK7-BT5CXpcQ.js → architectureDiagram-5GKGNRK7-C4y0SbLT.js} +1 -1
- package/out/renderer/assets/{blockDiagram-I7D4REHJ-C32Vqzip.js → blockDiagram-I7D4REHJ-DrsoSFRK.js} +1 -1
- package/out/renderer/assets/{c4Diagram-7LVT6UL2-qjwL2BP8.js → c4Diagram-7LVT6UL2-1DD8BlM8.js} +1 -1
- package/out/renderer/assets/channel-Sck-tAAK.js +1 -0
- package/out/renderer/assets/{chunk-2Q5K7J3B-YC6CQiyD.js → chunk-2Q5K7J3B-DRyc0B7g.js} +1 -1
- package/out/renderer/assets/{chunk-5VM5RSS4-E-kluPz3.js → chunk-5VM5RSS4-BJe8SghE.js} +1 -1
- package/out/renderer/assets/{chunk-F27PBJKO-Bhx1_P75.js → chunk-F27PBJKO-BIipq4SK.js} +1 -1
- package/out/renderer/assets/{chunk-IMKFNOWR-Dgb_730B.js → chunk-IMKFNOWR-D5Ak3Xd9.js} +1 -1
- package/out/renderer/assets/{chunk-JWPE2WC7-COQNHw4u.js → chunk-JWPE2WC7-BcaWCpW-.js} +1 -1
- package/out/renderer/assets/{chunk-POPQ4Y6H-CQz4hRgP.js → chunk-POPQ4Y6H-C1TwLrrN.js} +1 -1
- package/out/renderer/assets/{chunk-SVP7TREG-DGp9XQFd.js → chunk-SVP7TREG-DDOXG_t3.js} +1 -1
- package/out/renderer/assets/{chunk-TICWLB2K-CovR1uHr.js → chunk-TICWLB2K-BqT15hZi.js} +1 -1
- package/out/renderer/assets/{chunk-XXDRQBXY-gVmqSU5b.js → chunk-XXDRQBXY-D01ts6SC.js} +1 -1
- package/out/renderer/assets/classDiagram-ZZMXUADV-DnB4QNNe.js +1 -0
- package/out/renderer/assets/classDiagram-v2-VYDZK3BY-DnB4QNNe.js +1 -0
- package/out/renderer/assets/{cose-bilkent-JH36ORCC-DD4PEqt_.js → cose-bilkent-JH36ORCC-C7NVrT2_.js} +1 -1
- package/out/renderer/assets/{cynefin-OW5HDTMX-DNsYCrBx.js → cynefin-OW5HDTMX-2LxdFmSk.js} +1 -1
- package/out/renderer/assets/{cynefinDiagram-5FMLGOSQ-CoSzqs25.js → cynefinDiagram-5FMLGOSQ-_AN_Mulc.js} +1 -1
- package/out/renderer/assets/{cytoscape-fcose-CV0MpCmk.js → cytoscape-fcose-COZkZZmX.js} +1 -1
- package/out/renderer/assets/{dagre-GXQ25YYZ-BxpTPeHN.js → dagre-GXQ25YYZ-BUTwlM6j.js} +1 -1
- package/out/renderer/assets/{diagram-S7CK7UJ4-Df_OM1vW.js → diagram-S7CK7UJ4-CseZZ-y2.js} +1 -1
- package/out/renderer/assets/{diagram-UQ7AKVKN-iovjmny_.js → diagram-UQ7AKVKN-Cb7llS-8.js} +1 -1
- package/out/renderer/assets/{diagram-VSXAHHWV-BMrwlcQx.js → diagram-VSXAHHWV-CtuGqQvp.js} +1 -1
- package/out/renderer/assets/{diagram-VX7I27RA-DqLh449X.js → diagram-VX7I27RA-BA8eov-1.js} +1 -1
- package/out/renderer/assets/{diagram-Z3DM3KII-CH_W77UO.js → diagram-Z3DM3KII-VZOjj6Hg.js} +1 -1
- package/out/renderer/assets/{ebnfDiagram-PWID7BFC-yjzodXoL.js → ebnfDiagram-PWID7BFC-YBIrle6d.js} +1 -1
- package/out/renderer/assets/{erDiagram-RLTQ6QDP-DXxhvHYS.js → erDiagram-RLTQ6QDP-BiKyPEqW.js} +1 -1
- package/out/renderer/assets/{flowDiagram-HODETNUW-b2AWCAaB.js → flowDiagram-HODETNUW-7wmZyLHw.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-EL5Y4UJY-COkyXL3K.js → ganttDiagram-EL5Y4UJY-D4j4GJaT.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-WWUBYQGX-BYPqy5fh.js → gitGraphDiagram-WWUBYQGX-BqveM1NI.js} +1 -1
- package/out/renderer/assets/globals-C9M_MZZV.js +2539 -0
- package/out/renderer/assets/globals-l3kDGoYH.css +1 -0
- package/out/renderer/assets/index-BzSTiwH2.js +117 -0
- package/out/renderer/assets/{infoDiagram-27XIBGKW-DNg-VxlH.js → infoDiagram-27XIBGKW-DLPLnIFP.js} +1 -1
- package/out/renderer/assets/{ishikawaDiagram-5VMMS53U-DProTI6a.js → ishikawaDiagram-5VMMS53U-48drIAMR.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-3NMN7TZE-BWhC4n3f.js → journeyDiagram-3NMN7TZE-vjigqUq_.js} +1 -1
- package/out/renderer/assets/{kanban-definition-UXKFOSKX-CHJRR0qi.js → kanban-definition-UXKFOSKX-CpsYVONZ.js} +1 -1
- package/out/renderer/assets/{layout-D8t6q8k0.js → layout-DqfoORoO.js} +1 -1
- package/out/renderer/assets/{linear-Cxb1p4iF.js → linear-CJzBBHcp.js} +1 -1
- package/out/renderer/assets/{mermaid.core-CFNOEUmc.js → mermaid.core-DdrGP-Hn.js} +5 -5
- package/out/renderer/assets/{mindmap-definition-YA3MSWOX-Ba78cyY4.js → mindmap-definition-YA3MSWOX-D68tLNxp.js} +1 -1
- package/out/renderer/assets/{pegDiagram-XKGWAZYB-C7zqoWMk.js → pegDiagram-XKGWAZYB-DkgLTcrv.js} +1 -1
- package/out/renderer/assets/{pieDiagram-E7YTZNPT-g304yFeX.js → pieDiagram-E7YTZNPT-bz5NuX1w.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-AXDQQJYC-Bwn3gGTO.js → quadrantDiagram-AXDQQJYC-o_VKLyJA.js} +1 -1
- package/out/renderer/assets/{railroadDiagram-O6MQD6OU-DRetS8pv.js → railroadDiagram-O6MQD6OU-Dkf03e07.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-BXWQKSXE-CHz0FVZ7.js → requirementDiagram-BXWQKSXE-CBUz_3YU.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-P5KCCOFB-BYGRDIG9.js → sankeyDiagram-P5KCCOFB-B0pjUr9g.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-WJ2MYXX4-B60RuFFk.js → sequenceDiagram-WJ2MYXX4-ClugIL0e.js} +1 -1
- package/out/renderer/assets/settings-DvhrDn2q.js +34 -0
- package/out/renderer/assets/{sizeCapture-INFHLROL-CB-i3Fmz.js → sizeCapture-INFHLROL-D6y0rctc.js} +1 -1
- package/out/renderer/assets/{stateDiagram-D77RDMKH-CJOcikAJ.js → stateDiagram-D77RDMKH-DiftQepS.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-DxB2-9tl.js +1 -0
- package/out/renderer/assets/{swimlanes-42K2YHIH-Buap2upT.js → swimlanes-42K2YHIH-DhuTjCNj.js} +1 -1
- package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-CYDUqExO.js +8 -0
- package/out/renderer/assets/{timeline-definition-24CTP7MA-BdQta3QT.js → timeline-definition-24CTP7MA-CrXqgptd.js} +1 -1
- package/out/renderer/assets/{vennDiagram-4TSXK5OY-BynM2l28.js → vennDiagram-4TSXK5OY-CDm8SO8U.js} +1 -1
- package/out/renderer/assets/{wardleyDiagram-VM6X3IG4-FZjDO9FY.js → wardleyDiagram-VM6X3IG4-CxyunHwQ.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-S5SC5T6Z-pJPSISxM.js → xychartDiagram-S5SC5T6Z-CvC5YMSy.js} +1 -1
- package/out/renderer/index.html +3 -3
- package/out/renderer/settings.html +4 -4
- package/out/renderer/web-preload.js +1 -1
- package/out/server/agent.js +562 -532
- package/out/server/chunks/{agent--Q7N17bY.js → agent-_G_O-Cpa.js} +155 -214
- package/out/server/chunks/{gpuBackendInstall-P7COXJlD.js → gpuBackendInstall-Cb6TFh_8.js} +9 -8
- package/out/server/chunks/{loadProvider-DvvFIF6F.js → loadProvider-Be9Lu1Oi.js} +7 -20
- package/out/server/chunks/{manifest-BvEa5QR3.js → manifest-CB63GQ-i.js} +6 -3
- package/out/server/chunks/{workflowPresets-CuLnfQqa.js → workflowPresets-Djlp5LPV.js} +786 -1832
- package/out/server/index.js +5743 -6563
- package/out/server/plugin-host.js +31 -25
- package/package.json +4 -4
- package/out/phone/assets/architecture-7GRP2DOG-D7mwyuxS.js +0 -1
- package/out/phone/assets/channel-BsGN1oT0.js +0 -1
- package/out/phone/assets/classDiagram-ZZMXUADV-a1PUvjC2.js +0 -1
- package/out/phone/assets/classDiagram-v2-VYDZK3BY-a1PUvjC2.js +0 -1
- package/out/phone/assets/desk-1McWacjU.js +0 -2
- package/out/phone/assets/eventmodeling-NTZA5JFV-DcUsfQiW.js +0 -1
- package/out/phone/assets/flowDiagram-HODETNUW-sUobw8zi.js +0 -1
- package/out/phone/assets/main-CnA1zWP8.css +0 -1
- package/out/phone/assets/railroad-abnf-HS5TGJTU-CGiIT1ZV.js +0 -1
- package/out/phone/assets/railroad-ebnf-LZEXJU2U-C85Q3c0J.js +0 -1
- package/out/phone/assets/railroad-peg-WCYAUIDC-8qPPCLgU.js +0 -1
- package/out/phone/assets/stateDiagram-v2-MP3YSRHH-WM4CNSf-.js +0 -1
- package/out/phone/assets/storage-CahQ0cyN.js +0 -1
- package/out/phone/assets/swimlanesDiagram-VR7AAH4N-65AiMWVp.js +0 -8
- package/out/renderer/assets/channel-B1Cv56hA.js +0 -1
- package/out/renderer/assets/classDiagram-ZZMXUADV-CDWgELaf.js +0 -1
- package/out/renderer/assets/classDiagram-v2-VYDZK3BY-CDWgELaf.js +0 -1
- package/out/renderer/assets/globals-DX-8GWfJ.css +0 -1
- package/out/renderer/assets/globals-y5_C1IiJ.js +0 -2539
- package/out/renderer/assets/index-CHJ6mVl2.js +0 -117
- package/out/renderer/assets/settings-Cd128yRb.js +0 -34
- package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-BosPi5SR.js +0 -1
- package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-B7TQEEbL.js +0 -8
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
import{r as m,eR as Ne,eS as Ks,j as i,c as ot,eT as qv,eU as Yv,eV as qP,eW as Pk,eX as YP,bi as Ak,q as Se,eY as xn,eZ as Vh,e_ as wf,e$ as XP,f0 as ZP,f1 as JP,p as J,di as Mk,au as od,X as ln,aQ as QP,cN as mi,e as W,d1 as Rk,ci as Fo,aB as sa,f2 as eA,f3 as tA,f4 as Lk,cl as Xv,bd as un,f5 as Ok,cm as ga,bQ as ia,du as Fi,cS as bg,f6 as nA,ax as wg,f7 as sA,f8 as iA,f9 as oA,fa as rA,fb as aA,fc as Dl,fd as xa,fe as uo,ff as lA,fg as dA,fh as cA,fi as xs,fj as _c,fk as uA,fl as hA,fm as Il,fn as El,fo as Pi,fp as Wh,fq as pA,fr as Nc,fs as Nr,ft as fA,fu as mA,fv as gA,fw as xA,fx as vA,fy as bA,fz as Uh,fA as Hr,fB as Zv,fC as zk,fD as Jv,fE as wA,fF as yA,fG as Yr,fH as SA,fI as ri,fJ as CA,fK as ar,fL as Gk,fM as Qv,fN as oa,fO as kA,fP as Pd,fQ as jA,fR as _A,fS as NA,fT as TA,fU as e0,fV as Fk,fW as yf,fX as DA,fY as IA,fZ as Hk,f_ as EA,f$ as t0,g0 as Bk,g1 as PA,g2 as AA,g3 as Sf,g4 as MA,g5 as $k,g6 as RA,g7 as LA,g8 as OA,g9 as zA,ga as GA,gb as n0,gc as FA,gd as HA,ge as BA,gf as s0,gg as Kh,gh as $A,gi as VA,gj as WA,gk as Vk,gl as Or,gm as Xa,gn as rr,go as Wk,gp as qh,gq as Cf,gr as UA,gs as Vu,gt as KA,gu as qA,gv as YA,gw as Ea,gx as XA,gy as ZA,gz as JA,gA as Uk,gB as QA,gC as eM,gD as tM,gE as nM,gF as sM,gG as Kk,gH as qk,gI as so,gJ as iM,gK as oM,gL as i0,gM as rM,cV as ra,cT as rd,cU as va,bu as aa,eB as Vs,$ as ad,gN as aM,gO as lM,gP as dM,gQ as cM,gR as uM,gS as hM,gT as pM,gU as fM,gV as mM,gW as gM,gX as xM,gY as vM,a5 as yg,ah as bM,gZ as wM,g_ as yM,g$ as SM,h0 as CM,h1 as kM,h2 as jM,h3 as _M,a6 as Yk,h4 as NM,h5 as TM,h6 as DM,h7 as IM,b as ld,h8 as EM,h9 as PM,ha as AM,hb as MM,hc as RM,hd as LM,d as OM,he as zM,hf as GM,hg as FM,hh as HM,dq as BM,cs as Xk,eC as Wu,hi as $M,cY as Zk,hj as Jn,cy as Kn,bN as Uu,dI as Hs,hk as _s,hl as Un,hm as VM,bb as Ku,ba as WM,dp as se,cn as Jk,bZ as $n,hn as Qk,ho,hp as po,hq as fo,hr as Yt,Z as kn,J as Fe,hs as UM,aC as gr,ht as KM,hu as qM,dh as qu,bk as Ho,hv as o0,ch as YM,hw as XM,at as Zt,hx as r0,hy as ej,hz as tj,hA as ZM,hB as JM,hC as nj,hD as QM,hE as eR,hF as tR,hG as nR,hH as sR,hI as iR,hJ as oR,hK as rR,hL as aR,hM as lR,hN as dR,hO as Ad,hP as gi,hQ as xi,hR as vi,aR as ms,hS as cR,hT as uR,hU as hR,hV as pR,hW as a0,bP as fR,hX as mR,hY as sj,hZ as gR,co as Sg,h_ as xR,h$ as ij,i0 as vR,cG as wo,s as vn,i1 as bR,v as bn,x as wn,y as yn,E as Mn,i2 as l0,i3 as wR,i4 as yR,eE as oj,i5 as SR,i6 as CR,i7 as kR,B as fe,i8 as Yu,ex as hi,b4 as kf,en as d0,bJ as Cg,bf as Pa,bj as ni,df as rj,i9 as jR,ia as aj,ib as _R,ic as NR,id as TR,ie as DR,ig as jf,ih as lj,ii as IR,ij as ER,bv as Bs,ik as PR,il as AR,im as MR,io as RR,ip as LR,iq as OR,ir as zR,is as dj,it as c0,iu as u0,iv as GR,iw as h0,ix as _f,iy as Nf,iz as Br,iA as FR,iB as HR,iC as BR,iD as p0,iE as $R,iF as VR,iG as WR,iH as f0,iI as UR,iJ as Yh,iK as Xh,iL as KR,de as dd,em as cj,bt as us,iM as cd,iN as ud,bM as $s,iO as qR,iP as YR,iQ as XR,iR as ZR,iS as JR,iT as QR,iU as e2,ck as mo,iV as t2,iW as uj,iX as ue,iY as n2,iZ as Xc,i_ as hj,i$ as Zc,ej as s2,j0 as i2,ez as pj,dd as pr,cP as Pl,j1 as o2,j2 as fj,j3 as m0,cI as Li,j4 as r2,j5 as a2,j6 as l2,j7 as mj,bI as sn,j8 as gj,j9 as d2,ja as c2,jb as go,jc as u2,jd as xj,je as vj,jf as bj,jg as Al,jh as h2,ji as p2,jj as f2,jk as Tf,jl as m2,jm as g2,jn as x2,jo as v2,jp as b2,jq as w2,jr as y2,js as S2,jt as C2,ju as k2,z as As,bh as j2,G as rs,jv as _2,bX as Xt,bg as kg,c2 as wj,aS as ci,I as Jt,jw as g0,jx as x0,jy as v0,F as hd,jz as Ml,cd as Zh,ec as Jh,c3 as ei,jA as N2,jB as yj,jC as T2,jD as Ss,jE as D2,el as jg,O as vs,P as bs,Q as ws,R as ys,T as os,bW as _g,jF as Df,jG as If,jH as Ef,bE as Xu,bF as Zu,bG as Is,bH as oo,c1 as Sj,jI as Cj,jJ as kj,jK as ol,jL as Jc,jM as jj,jN as I2,jO as E2,jP as P2,jQ as Ng,jR as A2,jS as M2,jT as _j,e0 as Hi,e1 as Bi,e3 as $i,e7 as fn,jU as Nj,jV as Tj,jW as Dj,e5 as ba,cq as Tg,jX as Ij,jY as Ju,jZ as Ns,b_ as Ej,bT as R2,bU as L2,c4 as O2,j_ as z2,c6 as G2,j$ as F2,k0 as Pj,k1 as H2,k2 as B2,k3 as $2,k4 as V2,k5 as Aj,k6 as W2,k7 as U2,k8 as K2,k9 as xr,ka as Dg,kb as Za,kc as Ig,kd as Eg,d6 as Qu,d8 as eh,cj as ti,d7 as th,ek as Mj,eq as wa,ke as q2,kf as Rj,kg as Lj,kh as Y2,ki as rl,av as nh,kj as Oj,kk as Pg,kl as zj,ct as ya,km as Gj,kn as X2,da as Z2,d9 as J2,ko as Q2,A as eL,kp as tL,kq as nL,n as sL,kr as iL,ks as oL,kt as rL,m as aL,ku as lL,kv as dL,C as cL,f as Fj,h as uL,i as hL,k as pL,S as fL,l as mL,o as gL,kw as xL,kx as vL,ky as bL,kz as wL,kA as yL,kB as SL,kC as Hj,cM as ai,kD as CL,cp as la,eG as Pf,kE as kL,kF as jL,kG as Ag,kH as Bj,kI as $j,kJ as Vj,kK as Mg,kL as _L,kM as NL,kN as TL,bD as Wj,bL as tr,bC as DL,kO as IL,kP as Uj,kQ as Tr,bK as b0,bS as EL,kR as PL,b$ as w0,et as sh,kS as y0,cz as is,kT as AL,eF as ML,kU as Kj,kV as RL,kW as LL,kX as OL,d_ as zL,kY as qj,kZ as Rg,dR as GL,k_ as FL,k$ as HL,l0 as Lg,l1 as BL,l2 as Yj,l3 as Xj,l4 as Og,ey as $L,l5 as VL,l6 as WL,l7 as UL,l8 as KL,l9 as Qh,la as S0,lb as qL,eu as Zj,lc as YL,ld as zg,eo as XL,cD as Os,cE as zs,le as Jj,lf as ZL,lg as JL,lh as QL,li as e5,lj as t5,eA as Qc,lk as n5,ll as s5,lm as i5,ln as o5,lo as Qj,lp as r5,lq as a5,cv as l5,lr as d5,dH as e_,ls as Gg,lt as c5,dk as t_,lu as u5,lv as C0,lw as h5,lx as p5,d4 as f5,d3 as m5,dg as g5,eD as x5,ly as n_,lz as Af,aD as s_,aE as i_,aF as o_,aG as r_,aH as a_,aI as l_,lA as Tc,lB as d_,es as v5,lC as Mf,lD as b5,aK as Fg,lE as eu,lF as Rl,lG as da,dF as Rf,lH as w5,lI as y5,dK as tu,lJ as S5,aN as ih,lK as Hg,ea as k0,e9 as C5,lL as hs,lM as In,lN as Eo,lO as c_,aO as k5,lP as nu,lQ as Ao,ce as j5,cC as _5,lR as N5,lS as u_,lT as al,lU as zr,lV as T5,lW as h_,lX as D5,lY as I5,lZ as E5,cx as j0,l_ as P5,l$ as p_,m0 as _0,cr as N0,e2 as Bg,m1 as A5,cF as M5,m2 as R5,m3 as L5,m4 as Lf,m5 as O5,b3 as z5,cB as G5,m6 as F5,ep as H5,dw as B5,m7 as $5,dT as V5,dU as W5,cH as U5,m8 as K5,er as q5,eb as Y5,m9 as X5,ma as Z5,mb as f_,mc as $g,md as m_,me as J5,mf as Q5,mg as eO,mh as tO,mi as nO,mj as sO,mk as iO,ml as T0,mm as g_,mn as Vg,dj as oO,mo as oh,mp as Md,mq as rO,mr as aO,ms as lO,mt as dO,mu as cO,mv as uO,mw as hO,mx as pO,my as fO,mz as mO,mA as D0,mB as gO,mC as xO,mD as vO,mE as bO,cW as wO,bc as yO,mF as ep,bO as I0,cX as SO,cZ as CO,mG as kO,mH as jO,mI as E0,mJ as _O,mK as NO,mL as TO,mM as Of,mN as x_,mO as DO,mP as IO,mQ as EO,mR as PO,mS as v_,mT as AO,mU as MO,mV as RO,mW as LO,mX as OO,mY as zO,mZ as ro,m_ as GO,m$ as FO,n0 as HO,n1 as BO,n2 as $O,n3 as VO,n4 as WO,n5 as P0,n6 as A0,n7 as UO,cR as KO,n8 as qO,n9 as YO,na as XO,nb as ZO,nc as JO,dx as QO,nd as ez,ne as M0,nf as tz,ng as nz,nh as b_,e8 as sz,ni as iz,nj as oz,nk as rz,eO as az,eP as lz,eK as dz,eQ as R0,eL as cz,aJ as uz,nl as hz,nm as pz,nn as fz,no as mz,np as gz,cO as xz,nq as vz,nr as bz,eH as wz,eI as yz,eJ as Sz}from"./globals-y5_C1IiJ.js";function Cz(){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 rh=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Sa(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Wg(e){return"nodeType"in e}function Ts(e){var t,n;return e?Sa(e)?e:Wg(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Ug(e){const{Document:t}=Ts(e);return e instanceof t}function pd(e){return Sa(e)?!1:e instanceof Ts(e).HTMLElement}function w_(e){return e instanceof Ts(e).SVGElement}function Ca(e){return e?Sa(e)?e.document:Wg(e)?Ug(e)?e:pd(e)||w_(e)?e.ownerDocument:document:document:document}const bi=rh?m.useLayoutEffect:m.useEffect;function ah(e){const t=m.useRef(e);return bi(()=>{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 kz(){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 Ll(e,t){t===void 0&&(t=[e]);const n=m.useRef(e);return bi(()=>{n.current!==e&&(n.current=e)},t),n}function fd(e,t){const n=m.useRef();return m.useMemo(()=>{const s=e(n.current);return n.current=s,s},[...t])}function su(e){const t=ah(e),n=m.useRef(null),s=m.useCallback(o=>{o!==n.current&&t?.(o,n.current),n.current=o},[]);return[n,s]}function iu(e){const t=m.useRef();return m.useEffect(()=>{t.current=e},[e]),t.current}let tp={};function md(e,t){return m.useMemo(()=>{if(t)return t;const n=tp[e]==null?0:tp[e]+1;return tp[e]=n,e+"-"+n},[e,t])}function y_(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 Xr=y_(1),ou=y_(-1);function jz(e){return"clientX"in e&&"clientY"in e}function lh(e){if(!e)return!1;const{KeyboardEvent:t}=Ts(e.target);return t&&e instanceof t}function _z(e){if(!e)return!1;const{TouchEvent:t}=Ts(e.target);return t&&e instanceof t}function ru(e){if(_z(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 jz(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}}}),L0="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Nz(e){return e.matches(L0)?e:e.querySelector(L0)}const Tz={display:"none"};function Dz(e){let{id:t,value:n}=e;return Ne.createElement("div",{id:t,style:Tz},n)}function Iz(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 Ez(){const[e,t]=m.useState("");return{announce:m.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const S_=m.createContext(null);function C_(e){const t=m.useContext(S_);m.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function Pz(){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 Az={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
|
-
`},Mz={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 Rz(e){let{announcements:t=Mz,container:n,hiddenTextDescribedById:s,screenReaderInstructions:o=Az}=e;const{announce:r,announcement:a}=Ez(),l=md("DndLiveRegion"),[d,c]=m.useState(!1);if(m.useEffect(()=>{c(!0)},[]),C_(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(Dz,{id:s,value:o.draggable}),Ne.createElement(Iz,{id:l,announcement:a}));return n?Ks.createPortal(u,n):u}var Qn;(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"})(Qn||(Qn={}));function au(){}function Lz(e,t){return m.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function Oz(){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 wi=Object.freeze({x:0,y:0});function zz(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function Gz(e,t){const n=ru(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 Fz(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return n-s}function Hz(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return s-n}function Bz(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 $z(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function Vz(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 k_=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=Vz(l,t);d>0&&o.push({id:a,data:{droppableContainer:r,value:d}})}}return o.sort(Hz)};function Wz(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 Uz=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&&Wz(s,l)){const c=Bz(l).reduce((h,p)=>h+zz(s,p),0),u=Number((c/4).toFixed(4));o.push({id:a,data:{droppableContainer:r,value:u}})}}return o.sort(Fz)};function Kz(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function j_(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:wi}function qz(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 Yz=qz(1);function __(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 Xz(e,t,n){const s=__(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 Zz={ignoreTransform:!1};function ka(e,t){t===void 0&&(t=Zz);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:u}=Ts(e).getComputedStyle(e);c&&(n=Xz(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 O0(e){return ka(e,{ignoreTransform:!0})}function Jz(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Qz(e,t){return t===void 0&&(t=Ts(e).getComputedStyle(e)),t.position==="fixed"}function e3(e,t){t===void 0&&(t=Ts(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 Kg(e,t){const n=[];function s(o){if(t!=null&&n.length>=t||!o)return n;if(Ug(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!pd(o)||w_(o)||n.includes(o))return n;const r=Ts(e).getComputedStyle(o);return o!==e&&e3(o,r)&&n.push(o),Qz(o,r)?n:s(o.parentNode)}return e?s(e):n}function N_(e){const[t]=Kg(e,1);return t??null}function np(e){return!rh||!e?null:Sa(e)?e:Wg(e)?Ug(e)||e===Ca(e).scrollingElement?window:pd(e)?e:null:null}function T_(e){return Sa(e)?e.scrollX:e.scrollLeft}function D_(e){return Sa(e)?e.scrollY:e.scrollTop}function zf(e){return{x:T_(e),y:D_(e)}}var ss;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ss||(ss={}));function I_(e){return!rh||!e?!1:e===document.scrollingElement}function E_(e){const t={x:0,y:0},n=I_(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 t3={x:.2,y:.2};function n3(e,t,n,s,o){let{top:r,left:a,right:l,bottom:d}=n;s===void 0&&(s=10),o===void 0&&(o=t3);const{isTop:c,isBottom:u,isLeft:h,isRight:p}=E_(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=ss.Backward,g.y=s*Math.abs((t.top+x.height-r)/x.height)):!u&&d>=t.bottom-x.height&&(f.y=ss.Forward,g.y=s*Math.abs((t.bottom-x.height-d)/x.height)),!p&&l>=t.right-x.width?(f.x=ss.Forward,g.x=s*Math.abs((t.right-x.width-l)/x.width)):!h&&a<=t.left+x.width&&(f.x=ss.Backward,g.x=s*Math.abs((t.left+x.width-a)/x.width)),{direction:f,speed:g}}function s3(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 P_(e){return e.reduce((t,n)=>Xr(t,zf(n)),wi)}function i3(e){return e.reduce((t,n)=>t+T_(n),0)}function o3(e){return e.reduce((t,n)=>t+D_(n),0)}function A_(e,t){if(t===void 0&&(t=ka),!e)return;const{top:n,left:s,bottom:o,right:r}=t(e);N_(e)&&(o<=0||r<=0||n>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const r3=[["x",["left","right"],i3],["y",["top","bottom"],o3]];class qg{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=Kg(n),o=P_(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[r,a,l]of r3)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 ll{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 a3(e){const{EventTarget:t}=Ts(e);return e instanceof t?e:Ca(e)}function sp(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 Us;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Us||(Us={}));function z0(e){e.preventDefault()}function l3(e){e.stopPropagation()}var pn;(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"})(pn||(pn={}));const M_={start:[pn.Space,pn.Enter],cancel:[pn.Esc],end:[pn.Space,pn.Enter,pn.Tab]},d3=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case pn.Right:return{...n,x:n.x+25};case pn.Left:return{...n,x:n.x-25};case pn.Down:return{...n,y:n.y+25};case pn.Up:return{...n,y:n.y-25}}};class R_{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 ll(Ca(n)),this.windowListeners=new ll(Ts(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Us.Resize,this.handleCancel),this.windowListeners.add(Us.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Us.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,s=t.node.current;s&&A_(s),n(wi)}handleKeyDown(t){if(lh(t)){const{active:n,context:s,options:o}=this.props,{keyboardCodes:r=M_,coordinateGetter:a=d3,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}:wi;this.referenceCoordinates||(this.referenceCoordinates=u);const h=a(t,{active:n,context:s.current,currentCoordinates:u});if(h){const p=ou(h,u),f={x:0,y:0},{scrollableAncestors:g}=s.current;for(const x of g){const v=t.code,{isTop:y,isRight:b,isLeft:w,isBottom:_,maxScroll:C,minScroll:N}=E_(x),S=s3(x),k={x:Math.min(v===pn.Right?S.right-S.width/2:S.right,Math.max(v===pn.Right?S.left:S.left+S.width/2,h.x)),y:Math.min(v===pn.Down?S.bottom-S.height/2:S.bottom,Math.max(v===pn.Down?S.top:S.top+S.height/2,h.y))},A=v===pn.Right&&!b||v===pn.Left&&!w,I=v===pn.Down&&!_||v===pn.Up&&!y;if(A&&k.x!==h.x){const E=x.scrollLeft+p.x,D=v===pn.Right&&E<=C.x||v===pn.Left&&E>=N.x;if(D&&!p.y){x.scrollTo({left:E,behavior:l});return}D?f.x=x.scrollLeft-E:f.x=v===pn.Right?x.scrollLeft-C.x:x.scrollLeft-N.x,f.x&&x.scrollBy({left:-f.x,behavior:l});break}else if(I&&k.y!==h.y){const E=x.scrollTop+p.y,D=v===pn.Down&&E<=C.y||v===pn.Up&&E>=N.y;if(D&&!p.x){x.scrollTo({top:E,behavior:l});return}D?f.y=x.scrollTop-E:f.y=v===pn.Down?x.scrollTop-C.y:x.scrollTop-N.y,f.y&&x.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(t,Xr(ou(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()}}R_.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:s=M_,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 G0(e){return!!(e&&"distance"in e)}function F0(e){return!!(e&&"delay"in e)}class Yg{constructor(t,n,s){var o;s===void 0&&(s=a3(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=Ca(a),this.documentListeners=new ll(this.document),this.listeners=new ll(s),this.windowListeners=new ll(Ts(a)),this.initialCoordinates=(o=ru(r))!=null?o:wi,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(Us.Resize,this.handleCancel),this.windowListeners.add(Us.DragStart,z0),this.windowListeners.add(Us.VisibilityChange,this.handleCancel),this.windowListeners.add(Us.ContextMenu,z0),this.documentListeners.add(Us.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(F0(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(G0(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(Us.Click,l3,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Us.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=ru(t))!=null?n:wi,c=ou(o,d);if(!s&&l){if(G0(l)){if(l.tolerance!=null&&sp(c,l.tolerance))return this.handleCancel();if(sp(c,l.distance))return this.handleStart()}if(F0(l)&&sp(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===pn.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const c3={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Xg extends Yg{constructor(t){const{event:n}=t,s=Ca(n.target);super(t,c3,s)}}Xg.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 u3={move:{name:"mousemove"},end:{name:"mouseup"}};var Gf;(function(e){e[e.RightClick=2]="RightClick"})(Gf||(Gf={}));class h3 extends Yg{constructor(t){super(t,u3,Ca(t.event.target))}}h3.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return n.button===Gf.RightClick?!1:(s?.({event:n}),!0)}}];const ip={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class p3 extends Yg{constructor(t){super(t,ip)}static setup(){return window.addEventListener(ip.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(ip.move.name,t)};function t(){}}}p3.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 dl;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(dl||(dl={}));var lu;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(lu||(lu={}));function f3(e){let{acceleration:t,activator:n=dl.Pointer,canScroll:s,draggingRect:o,enabled:r,interval:a=5,order:l=lu.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:u,delta:h,threshold:p}=e;const f=g3({delta:h,disabled:!r}),[g,x]=kz(),v=m.useRef({x:0,y:0}),y=m.useRef({x:0,y:0}),b=m.useMemo(()=>{switch(n){case dl.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case dl.DraggableRect:return o}},[n,o,d]),w=m.useRef(null),_=m.useCallback(()=>{const N=w.current;if(!N)return;const S=v.current.x*y.current.x,k=v.current.y*y.current.y;N.scrollBy(S,k)},[]),C=m.useMemo(()=>l===lu.TreeOrder?[...c].reverse():c,[l,c]);m.useEffect(()=>{if(!r||!c.length||!b){x();return}for(const N of C){if(s?.(N)===!1)continue;const S=c.indexOf(N),k=u[S];if(!k)continue;const{direction:A,speed:I}=n3(N,k,b,t,p);for(const E of["x","y"])f[E][A[E]]||(I[E]=0,A[E]=0);if(I.x>0||I.y>0){x(),w.current=N,g(_,a),v.current=I,y.current=A;return}}v.current={x:0,y:0},y.current={x:0,y:0},x()},[t,_,s,x,r,a,JSON.stringify(b),JSON.stringify(f),g,c,C,u,JSON.stringify(p)])}const m3={x:{[ss.Backward]:!1,[ss.Forward]:!1},y:{[ss.Backward]:!1,[ss.Forward]:!1}};function g3(e){let{delta:t,disabled:n}=e;const s=iu(t);return fd(o=>{if(n||!s||!o)return m3;const r={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[ss.Backward]:o.x[ss.Backward]||r.x===-1,[ss.Forward]:o.x[ss.Forward]||r.x===1},y:{[ss.Backward]:o.y[ss.Backward]||r.y===-1,[ss.Forward]:o.y[ss.Forward]||r.y===1}}},[n,t,s])}function x3(e,t){const n=t!=null?e.get(t):void 0,s=n?n.node.current:null;return fd(o=>{var r;return t==null?null:(r=s??o)!=null?r:null},[s,t])}function v3(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 Ol;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Ol||(Ol={}));var Ff;(function(e){e.Optimized="optimized"})(Ff||(Ff={}));const H0=new Map;function b3(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=Ll(h),f=m.useCallback(function(y){y===void 0&&(y=[]),!p.current&&a(b=>b===null?y:b.concat(y.filter(w=>!b.includes(w))))},[p]),g=m.useRef(null),x=fd(y=>{if(h&&!n)return H0;if(!y||y===H0||u.current!==e||r!=null){const b=new Map;for(let w of e){if(!w)continue;if(r&&r.length>0&&!r.includes(w.id)&&w.rect.current){b.set(w.id,w.rect.current);continue}const _=w.node.current,C=_?new qg(d(_),_):null;w.rect.current=C,C&&b.set(w.id,C)}return b}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 Ol.Always:return!1;case Ol.BeforeDragging:return n;default:return!n}}}function Zg(e,t){return fd(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function w3(e,t){return Zg(e,t)}function y3(e){let{callback:t,disabled:n}=e;const s=ah(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 dh(e){let{callback:t,disabled:n}=e;const s=ah(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 S3(e){return new qg(ka(e),e)}function B0(e,t,n){t===void 0&&(t=S3);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=y3({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=dh({callback:r});return bi(()=>{r(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),s}function C3(e){const t=Zg(e);return j_(e,t)}const $0=[];function k3(e){const t=m.useRef(e),n=fd(s=>e?s&&s!==$0&&e&&t.current&&e.parentNode===t.current.parentNode?s:Kg(e):$0,[e]);return m.useEffect(()=>{t.current=e},[e]),n}function j3(e){const[t,n]=m.useState(null),s=m.useRef(e),o=m.useCallback(r=>{const a=np(r.target);a&&n(l=>l?(l.set(a,zf(a)),new Map(l)):null)},[]);return m.useEffect(()=>{const r=s.current;if(e!==r){a(r);const l=e.map(d=>{const c=np(d);return c?(c.addEventListener("scroll",o,{passive:!0}),[c,zf(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=np(d);c?.removeEventListener("scroll",o)})}},[o,e]),m.useMemo(()=>e.length?t?Array.from(t.values()).reduce((r,a)=>Xr(r,a),wi):P_(e):wi,[e,t])}function V0(e,t){t===void 0&&(t=[]);const n=m.useRef(null);return m.useEffect(()=>{n.current=null},t),m.useEffect(()=>{const s=e!==wi;s&&!n.current&&(n.current=e),!s&&n.current&&(n.current=null)},[e]),n.current?ou(e,n.current):wi}function _3(e){m.useEffect(()=>{if(!rh)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 N3(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?Jz(e):null,[e])}const W0=[];function T3(e,t){t===void 0&&(t=ka);const[n]=e,s=L_(n?Ts(n):null),[o,r]=m.useState(W0);function a(){r(()=>e.length?e.map(d=>I_(d)?s:new qg(t(d),d)):W0)}const l=dh({callback:a});return bi(()=>{l?.disconnect(),a(),e.forEach(d=>l?.observe(d))},[e]),o}function O_(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return pd(t)?t:e}function D3(e){let{measure:t}=e;const[n,s]=m.useState(null),o=m.useCallback(c=>{for(const{target:u}of c)if(pd(u)){s(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),r=dh({callback:o}),a=m.useCallback(c=>{const u=O_(c);r?.disconnect(),u&&r?.observe(u),s(u?t(u):null)},[t,r]),[l,d]=su(a);return m.useMemo(()=>({nodeRef:l,rect:n,setRef:d}),[n,l,d])}const I3=[{sensor:Xg,options:{}},{sensor:R_,options:{}}],E3={current:{}},Dc={draggable:{measure:O0},droppable:{measure:O0,strategy:Ol.WhileDragging,frequency:Ff.Optimized},dragOverlay:{measure:ka}};class cl 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 P3={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new cl,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:au},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Dc,measureDroppableContainers:au,windowRect:null,measuringScheduled:!1},z_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:au,draggableNodes:new Map,over:null,measureDroppableContainers:au},gd=m.createContext(z_),G_=m.createContext(P3);function A3(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new cl}}}function M3(e,t){switch(t.type){case Qn.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Qn.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 Qn.DragEnd:case Qn.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Qn.RegisterDroppable:{const{element:n}=t,{id:s}=n,o=new cl(e.droppable.containers);return o.set(s,n),{...e,droppable:{...e.droppable,containers:o}}}case Qn.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 cl(e.droppable.containers);return a.set(n,{...r,disabled:o}),{...e,droppable:{...e.droppable,containers:a}}}case Qn.UnregisterDroppable:{const{id:n,key:s}=t,o=e.droppable.containers.get(n);if(!o||s!==o.key)return e;const r=new cl(e.droppable.containers);return r.delete(n),{...e,droppable:{...e.droppable,containers:r}}}default:return e}}function R3(e){let{disabled:t}=e;const{active:n,activatorEvent:s,draggableNodes:o}=m.useContext(gd),r=iu(s),a=iu(n?.id);return m.useEffect(()=>{if(!t&&!s&&r&&a!=null){if(!lh(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=Nz(u);if(h){h.focus();break}}})}},[s,t,o,a,r]),null}function F_(e,t){let{transform:n,...s}=t;return e!=null&&e.length?e.reduce((o,r)=>r({transform:o,...s}),n):n}function L3(e){return m.useMemo(()=>({draggable:{...Dc.draggable,...e?.draggable},droppable:{...Dc.droppable,...e?.droppable},dragOverlay:{...Dc.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function O3(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;bi(()=>{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=j_(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=N_(c);p&&p.scrollBy({top:h.y,left:h.x})}},[t,a,l,s,n])}const ch=m.createContext({...wi,scaleX:1,scaleY:1});var To;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(To||(To={}));const z3=m.memo(function(t){var n,s,o,r;let{id:a,accessibility:l,autoScroll:d=!0,children:c,sensors:u=I3,collisionDetection:h=k_,measuring:p,modifiers:f,...g}=t;const x=m.useReducer(M3,void 0,A3),[v,y]=x,[b,w]=Pz(),[_,C]=m.useState(To.Uninitialized),N=_===To.Initialized,{draggable:{active:S,nodes:k,translate:A},droppable:{containers:I}}=v,E=S!=null?k.get(S):null,D=m.useRef({initial:null,translated:null}),T=m.useMemo(()=>{var he;return S!=null?{id:S,data:(he=E?.data)!=null?he:E3,rect:D}:null},[S,E]),H=m.useRef(null),[F,O]=m.useState(null),[B,Y]=m.useState(null),U=Ll(g,Object.values(g)),ee=md("DndDescribedBy",a),L=m.useMemo(()=>I.getEnabled(),[I]),Q=L3(p),{droppableRects:V,measureDroppableContainers:ce,measuringScheduled:ve}=b3(L,{dragging:N,dependencies:[A.x,A.y],config:Q.droppable}),_e=x3(k,S),De=m.useMemo(()=>B?ru(B):null,[B]),me=K(),$=w3(_e,Q.draggable.measure);O3({activeNode:S!=null?k.get(S):null,config:me.layoutShiftCompensation,initialRect:$,measure:Q.draggable.measure});const z=B0(_e,Q.draggable.measure,$),de=B0(_e?_e.parentElement:null),X=m.useRef({activatorEvent:null,active:null,activeNode:_e,collisionRect:null,collisions:null,droppableRects:V,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:I,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),oe=I.getNodeFor((n=X.current.over)==null?void 0:n.id),Z=D3({measure:Q.dragOverlay.measure}),ae=(s=Z.nodeRef.current)!=null?s:_e,be=N?(o=Z.rect)!=null?o:z:null,ze=!!(Z.nodeRef.current&&Z.rect),Ye=C3(ze?null:z),Ve=L_(ae?Ts(ae):null),at=k3(N?oe??_e:null),Ze=T3(at),Et=F_(f,{transform:{x:A.x-Ye.x,y:A.y-Ye.y,scaleX:1,scaleY:1},activatorEvent:B,active:T,activeNodeRect:z,containerNodeRect:de,draggingNodeRect:be,over:X.current.over,overlayNodeRect:Z.rect,scrollableAncestors:at,scrollableAncestorRects:Ze,windowRect:Ve}),Gt=De?Xr(De,A):null,Pt=j3(at),ne=V0(Pt),ie=V0(Pt,[z]),He=Xr(Et,ne),St=be?Yz(be,Et):null,it=T&&St?h({active:T,collisionRect:St,droppableRects:V,droppableContainers:L,pointerCoordinates:Gt}):null,je=$z(it,"id"),[ht,$t]=m.useState(null),Oe=ze?Et:Xr(Et,ie),yt=Kz(Oe,(r=ht?.rect)!=null?r:null,z),Ht=m.useRef(null),re=m.useCallback((he,Ie)=>{let{sensor:Ee,options:Be}=Ie;if(H.current==null)return;const Je=k.get(H.current);if(!Je)return;const ge=he.nativeEvent,qe=new Ee({active:H.current,activeNode:Je,event:ge,options:Be,context:X,onAbort(Tt){if(!k.get(Tt))return;const{onDragAbort:cn}=U.current,P={id:Tt};cn?.(P),b({type:"onDragAbort",event:P})},onPending(Tt,zt,cn,P){if(!k.get(Tt))return;const{onDragPending:R}=U.current,j={id:Tt,constraint:zt,initialCoordinates:cn,offset:P};R?.(j),b({type:"onDragPending",event:j})},onStart(Tt){const zt=H.current;if(zt==null)return;const cn=k.get(zt);if(!cn)return;const{onDragStart:P}=U.current,M={activatorEvent:ge,active:{id:zt,data:cn.data,rect:D}};Ks.unstable_batchedUpdates(()=>{P?.(M),C(To.Initializing),y({type:Qn.DragStart,initialCoordinates:Tt,active:zt}),b({type:"onDragStart",event:M}),O(Ht.current),Y(ge)})},onMove(Tt){y({type:Qn.DragMove,coordinates:Tt})},onEnd:lt(Qn.DragEnd),onCancel:lt(Qn.DragCancel)});Ht.current=qe;function lt(Tt){return async function(){const{active:cn,collisions:P,over:M,scrollAdjustedTranslate:R}=X.current;let j=null;if(cn&&R){const{cancelDrop:G}=U.current;j={activatorEvent:ge,active:cn,collisions:P,delta:R,over:M},Tt===Qn.DragEnd&&typeof G=="function"&&await Promise.resolve(G(j))&&(Tt=Qn.DragCancel)}H.current=null,Ks.unstable_batchedUpdates(()=>{y({type:Tt}),C(To.Uninitialized),$t(null),O(null),Y(null),Ht.current=null;const G=Tt===Qn.DragEnd?"onDragEnd":"onDragCancel";if(j){const pe=U.current[G];pe?.(j),b({type:G,event:j})}})}}},[k]),$e=m.useCallback((he,Ie)=>(Ee,Be)=>{const Je=Ee.nativeEvent,ge=k.get(Be);if(H.current!==null||!ge||Je.dndKit||Je.defaultPrevented)return;const qe={active:ge};he(Ee,Ie.options,qe)===!0&&(Je.dndKit={capturedBy:Ie.sensor},H.current=Be,re(Ee,Ie))},[k,re]),st=v3(u,$e);_3(u),bi(()=>{z&&_===To.Initializing&&C(To.Initialized)},[z,_]),m.useEffect(()=>{const{onDragMove:he}=U.current,{active:Ie,activatorEvent:Ee,collisions:Be,over:Je}=X.current;if(!Ie||!Ee)return;const ge={active:Ie,activatorEvent:Ee,collisions:Be,delta:{x:He.x,y:He.y},over:Je};Ks.unstable_batchedUpdates(()=>{he?.(ge),b({type:"onDragMove",event:ge})})},[He.x,He.y]),m.useEffect(()=>{const{active:he,activatorEvent:Ie,collisions:Ee,droppableContainers:Be,scrollAdjustedTranslate:Je}=X.current;if(!he||H.current==null||!Ie||!Je)return;const{onDragOver:ge}=U.current,qe=Be.get(je),lt=qe&&qe.rect.current?{id:qe.id,rect:qe.rect.current,data:qe.data,disabled:qe.disabled}:null,Tt={active:he,activatorEvent:Ie,collisions:Ee,delta:{x:Je.x,y:Je.y},over:lt};Ks.unstable_batchedUpdates(()=>{$t(lt),ge?.(Tt),b({type:"onDragOver",event:Tt})})},[je]),bi(()=>{X.current={activatorEvent:B,active:T,activeNode:_e,collisionRect:St,collisions:it,droppableRects:V,draggableNodes:k,draggingNode:ae,draggingNodeRect:be,droppableContainers:I,over:ht,scrollableAncestors:at,scrollAdjustedTranslate:He},D.current={initial:be,translated:St}},[T,_e,it,St,k,ae,be,V,I,ht,at,He]),f3({...me,delta:A,draggingRect:St,pointerCoordinates:Gt,scrollableAncestors:at,scrollableAncestorRects:Ze});const Nt=m.useMemo(()=>({active:T,activeNode:_e,activeNodeRect:z,activatorEvent:B,collisions:it,containerNodeRect:de,dragOverlay:Z,draggableNodes:k,droppableContainers:I,droppableRects:V,over:ht,measureDroppableContainers:ce,scrollableAncestors:at,scrollableAncestorRects:Ze,measuringConfiguration:Q,measuringScheduled:ve,windowRect:Ve}),[T,_e,z,B,it,de,Z,k,I,V,ht,ce,at,Ze,Q,ve,Ve]),mt=m.useMemo(()=>({activatorEvent:B,activators:st,active:T,activeNodeRect:z,ariaDescribedById:{draggable:ee},dispatch:y,draggableNodes:k,over:ht,measureDroppableContainers:ce}),[B,st,T,z,y,ee,k,ht,ce]);return Ne.createElement(S_.Provider,{value:w},Ne.createElement(gd.Provider,{value:mt},Ne.createElement(G_.Provider,{value:Nt},Ne.createElement(ch.Provider,{value:yt},c)),Ne.createElement(R3,{disabled:l?.restoreFocus===!1})),Ne.createElement(Rz,{...l,hiddenTextDescribedById:ee}));function K(){const he=F?.autoScrollEnabled===!1,Ie=typeof d=="object"?d.enabled===!1:d===!1,Ee=N&&!he&&!Ie;return typeof d=="object"?{...d,enabled:Ee}:{enabled:Ee}}}),G3=m.createContext(null),U0="button",F3="Draggable";function Jg(e){let{id:t,data:n,disabled:s=!1,attributes:o}=e;const r=md(F3),{activators:a,activatorEvent:l,active:d,activeNodeRect:c,ariaDescribedById:u,draggableNodes:h,over:p}=m.useContext(gd),{role:f=U0,roleDescription:g="draggable",tabIndex:x=0}=o??{},v=d?.id===t,y=m.useContext(v?ch:G3),[b,w]=su(),[_,C]=su(),N=N3(a,t),S=Ll(n);bi(()=>(h.set(t,{id:t,key:r,node:b,activatorNode:_,data:S}),()=>{const A=h.get(t);A&&A.key===r&&h.delete(t)}),[h,t]);const k=m.useMemo(()=>({role:f,tabIndex:x,"aria-disabled":s,"aria-pressed":v&&f===U0?!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:k,isDragging:v,listeners:s?void 0:N,node:b,over:p,setNodeRef:w,setActivatorNodeRef:C,transform:y}}function xd(){return m.useContext(G_)}const H3="Droppable",B3={timeout:25};function vd(e){let{data:t,disabled:n=!1,id:s,resizeObserverConfig:o}=e;const r=md(H3),{active:a,dispatch:l,over:d,measureDroppableContainers:c}=m.useContext(gd),u=m.useRef({disabled:n}),h=m.useRef(!1),p=m.useRef(null),f=m.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:v}={...B3,...o},y=Ll(x??s),b=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]),w=dh({callback:b,disabled:g||!a}),_=m.useCallback((k,A)=>{w&&(A&&(w.unobserve(A),h.current=!1),k&&w.observe(k))},[w]),[C,N]=su(_),S=Ll(t);return m.useEffect(()=>{!w||!C.current||(w.disconnect(),h.current=!1,w.observe(C.current))},[C,w]),m.useEffect(()=>(l({type:Qn.RegisterDroppable,element:{id:s,key:r,disabled:n,node:C,rect:p,data:S}}),()=>l({type:Qn.UnregisterDroppable,key:r,id:s})),[s]),m.useEffect(()=>{n!==u.current.disabled&&(l({type:Qn.SetDroppableDisabled,id:s,key:r,disabled:n}),u.current.disabled=n)},[s,r,n,l]),{active:a,rect:p,isOver:d?.id===s,node:C,over:d,setNodeRef:N}}function $3(e){let{animation:t,children:n}=e;const[s,o]=m.useState(null),[r,a]=m.useState(null),l=iu(n);return!n&&!s&&l&&o(l),bi(()=>{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 V3={x:0,y:0,scaleX:1,scaleY:1};function W3(e){let{children:t}=e;return Ne.createElement(gd.Provider,{value:z_},Ne.createElement(ch.Provider,{value:V3},t))}const U3={position:"fixed",touchAction:"none"},K3=e=>lh(e)?"transform 250ms ease":void 0,q3=m.forwardRef((e,t)=>{let{as:n,activatorEvent:s,adjustScale:o,children:r,className:a,rect:l,style:d,transform:c,transition:u=K3}=e;if(!l)return null;const h=o?c:{...c,scaleX:1,scaleY:1},p={...U3,width:l.width,height:l.height,top:l.top,left:l.left,transform:zi.Transform.toString(h),transformOrigin:o&&s?Gz(s,l):void 0,transition:typeof u=="function"?u(s):u,...d};return Ne.createElement(n,{className:a,style:p,ref:t},r)}),Y3=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)}},X3=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:zi.Transform.toString(t)},{transform:zi.Transform.toString(n)}]},Z3={duration:250,easing:"ease",keyframes:X3,sideEffects:Y3({styles:{active:{opacity:"0"}}})};function J3(e){let{config:t,draggableNodes:n,droppableContainers:s,measuringConfiguration:o}=e;return ah((r,a)=>{if(t===null)return;const l=n.get(r);if(!l)return;const d=l.node.current;if(!d)return;const c=O_(a);if(!c)return;const{transform:u}=Ts(a).getComputedStyle(a),h=__(u);if(!h)return;const p=typeof t=="function"?t:Q3(t);return A_(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 Q3(e){const{duration:t,easing:n,sideEffects:s,keyframes:o}={...Z3,...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(b=>{y.onfinish=()=>{v?.(),b()}})}}let K0=0;function eG(e){return m.useMemo(()=>{if(e!=null)return K0++,K0},[e])}const tG=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:b,scrollableAncestors:w,scrollableAncestorRects:_,windowRect:C}=xd(),N=m.useContext(ch),S=eG(h?.id),k=F_(a,{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggingNodeRect:v.rect,over:y,overlayNodeRect:v.rect,scrollableAncestors:w,scrollableAncestorRects:_,transform:N,windowRect:C}),A=Zg(p),I=J3({config:s,draggableNodes:g,droppableContainers:x,measuringConfiguration:b}),E=A?v.setRef:void 0;return Ne.createElement(W3,null,Ne.createElement($3,{animation:I},h&&S?Ne.createElement(q3,{key:S,id:h.id,ref:E,as:l,activatorEvent:u,adjustScale:t,className:d,transition:r,rect:A,style:{zIndex:c,...o},transform:k},n):null))}),Qg=m.createContext({});function ex(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const nG=typeof window<"u",du=nG?m.useLayoutEffect:m.useEffect,uh=m.createContext(null);function tx(e,t){e.indexOf(t)===-1&&e.push(t)}function cu(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 hh=()=>{};const Mo={},H_=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),B_=e=>typeof e=="object"&&e!==null,$_=e=>/^0[^.\s]+$/u.test(e);function V_(e){let t;return()=>(t===void 0&&(t=e()),t)}const Js=e=>e,bd=(...e)=>e.reduce((t,n)=>s=>n(t(s))),zl=(e,t,n)=>{const s=t-e;return s?(n-e)/s:1};class nx{constructor(){this.subscriptions=[]}add(t){return tx(this.subscriptions,t),()=>cu(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 Gs=e=>e*1e3,qs=e=>e/1e3,W_=(e,t)=>t?e*(1e3/t):0,U_=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,sG=1e-7,iG=12;function oG(e,t,n,s,o){let r,a,l=0;do a=t+(n-t)/2,r=U_(a,s,o)-e,r>0?n=a:t=a;while(Math.abs(r)>sG&&++l<iG);return a}function wd(e,t,n,s){if(e===t&&n===s)return Js;const o=r=>oG(r,0,1,e,n);return r=>r===0||r===1?r:U_(o(r),t,s)}const K_=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,q_=e=>t=>1-e(1-t),Y_=wd(.33,1.53,.69,.99),sx=q_(Y_),X_=K_(sx),Z_=e=>e>=1?1:(e*=2)<1?.5*sx(e):.5*(2-Math.pow(2,-10*(e-1))),ix=e=>1-Math.sin(Math.acos(e)),J_=q_(ix),Q_=K_(ix),rG=wd(.42,0,1,1),aG=wd(0,0,.58,1),e1=wd(.42,0,.58,1),lG=e=>Array.isArray(e)&&typeof e[0]!="number",t1=e=>Array.isArray(e)&&typeof e[0]=="number",dG={linear:Js,easeIn:rG,easeInOut:e1,easeOut:aG,circIn:ix,circInOut:Q_,circOut:J_,backIn:sx,backInOut:X_,backOut:Y_,anticipate:Z_},cG=e=>typeof e=="string",q0=e=>{if(t1(e)){hh(e.length===4);const[t,n,s,o]=e;return wd(t,n,s,o)}else if(cG(e))return dG[e];return e},Rd=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function uG(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 hG=40;function n1(e,t){let n=!1,s=!0;const o={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,a=Rd.reduce((w,_)=>(w[_]=uG(r),w),{}),{setup:l,read:d,resolveKeyframes:c,preUpdate:u,update:h,preRender:p,render:f,postRender:g}=a,x=()=>{const w=Mo.useManualTiming,_=w?o.timestamp:performance.now();n=!1,w||(o.delta=s?1e3/60:Math.max(Math.min(_-o.timestamp,hG),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:Rd.reduce((w,_)=>{const C=a[_];return w[_]=(N,S=!1,k=!1)=>(n||v(),C.schedule(N,S,k)),w},{}),cancel:w=>{for(let _=0;_<Rd.length;_++)a[Rd[_]].cancel(w)},state:o,steps:a}}const{schedule:_n,cancel:Ro,state:ds,steps:op}=n1(typeof requestAnimationFrame<"u"?requestAnimationFrame:Js,!0);let Ic;function pG(){Ic=void 0}const Cs={now:()=>(Ic===void 0&&Cs.set(ds.isProcessing||Mo.useManualTiming?ds.timestamp:performance.now()),Ic),set:e=>{Ic=e,queueMicrotask(pG)}},s1=e=>t=>typeof t=="string"&&t.startsWith(e),i1=s1("--"),fG=s1("var(--"),ox=e=>fG(e)?mG.test(e.split("/*")[0].trim()):!1,mG=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Y0(e){return typeof e!="string"?!1:e.split("/*")[0].includes("var(--")}const ja={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Gl={...ja,transform:e=>Gi(0,1,e)},Ld={...ja,default:1},ul=e=>Math.round(e*1e5)/1e5,rx=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function gG(e){return e==null}const xG=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ax=(e,t)=>n=>!!(typeof n=="string"&&xG.test(n)&&n.startsWith(e)||t&&!gG(n)&&Object.prototype.hasOwnProperty.call(n,t)),o1=(e,t,n)=>s=>{if(typeof s!="string")return s;const[o,r,a,l]=s.match(rx);return{[e]:parseFloat(o),[t]:parseFloat(r),[n]:parseFloat(a),alpha:l!==void 0?parseFloat(l):1}},vG=e=>Gi(0,255,e),rp={...ja,transform:e=>Math.round(vG(e))},lr={test:ax("rgb","red"),parse:o1("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+rp.transform(e)+", "+rp.transform(t)+", "+rp.transform(n)+", "+ul(Gl.transform(s))+")"};function bG(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 Hf={test:ax("#"),parse:bG,transform:lr.transform},yd=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),eo=yd("deg"),Oi=yd("%"),vt=yd("px"),wG=yd("vh"),yG=yd("vw"),X0={...Oi,parse:e=>Oi.parse(e)/100,transform:e=>Oi.transform(e*100)},$r={test:ax("hsl","hue"),parse:o1("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Oi.transform(ul(t))+", "+Oi.transform(ul(n))+", "+ul(Gl.transform(s))+")"},Vn={test:e=>lr.test(e)||Hf.test(e)||$r.test(e),parse:e=>lr.test(e)?lr.parse(e):$r.test(e)?$r.parse(e):Hf.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?lr.transform(e):$r.transform(e),getAnimatableNone:e=>{const t=Vn.parse(e);return t.alpha=0,Vn.transform(t)}},SG=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function CG(e){return isNaN(e)&&typeof e=="string"&&(e.match(rx)?.length||0)+(e.match(SG)?.length||0)>0}const r1="number",a1="color",kG="var",jG="var(",Z0="${}",_G=/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 ca(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},o=[];let r=0;const l=t.replace(_G,d=>(Vn.test(d)?(s.color.push(r),o.push(a1),n.push(Vn.parse(d))):d.startsWith(jG)?(s.var.push(r),o.push(kG),n.push(d)):(s.number.push(r),o.push(r1),n.push(parseFloat(d))),++r,Z0)).split(Z0);return{values:n,split:l,indexes:s,types:o}}function NG(e){return ca(e).values}function l1({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===r1?o+=ul(s[r]):a===a1?o+=Vn.transform(s[r]):o+=s[r]}return o}}function TG(e){return l1(ca(e))}const DG=e=>typeof e=="number"?0:Vn.test(e)?Vn.getAnimatableNone(e):e,IG=(e,t)=>typeof e=="number"?t?.trim().endsWith("/")?e:0:DG(e);function EG(e){const t=ca(e);return l1(t)(t.values.map((s,o)=>IG(s,t.split[o])))}const pi={test:CG,parse:NG,createTransformer:TG,getAnimatableNone:EG};function ap(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 PG({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=ap(d,l,e+1/3),r=ap(d,l,e),a=ap(d,l,e-1/3)}return{red:Math.round(o*255),green:Math.round(r*255),blue:Math.round(a*255),alpha:s}}function uu(e,t){return n=>n>0?t:e}const jn=(e,t,n)=>e+(t-e)*n,lp=(e,t,n)=>{const s=e*e,o=n*(t*t-s)+s;return o<0?0:Math.sqrt(o)},AG=[Hf,lr,$r],MG=e=>AG.find(t=>t.test(e));function J0(e){const t=MG(e);if(!t)return!1;let n=t.parse(e);return t===$r&&(n=PG(n)),n}const Q0=(e,t)=>{const n=J0(e),s=J0(t);if(!n||!s)return uu(e,t);const o={...n};return r=>(o.red=lp(n.red,s.red,r),o.green=lp(n.green,s.green,r),o.blue=lp(n.blue,s.blue,r),o.alpha=jn(n.alpha,s.alpha,r),lr.transform(o))},Bf=new Set(["none","hidden"]);function RG(e,t){return Bf.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function LG(e,t){return n=>jn(e,t,n)}function lx(e){return typeof e=="number"?LG:typeof e=="string"?ox(e)?uu:Vn.test(e)?Q0:GG:Array.isArray(e)?d1:typeof e=="object"?Vn.test(e)?Q0:OG:uu}function d1(e,t){const n=[...e],s=n.length,o=e.map((r,a)=>lx(r)(r,t[a]));return r=>{for(let a=0;a<s;a++)n[a]=o[a](r);return n}}function OG(e,t){const n={...e,...t},s={};for(const o in n)e[o]!==void 0&&t[o]!==void 0&&(s[o]=lx(e[o])(e[o],t[o]));return o=>{for(const r in s)n[r]=s[r](o);return n}}function zG(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 GG=(e,t)=>{const n=pi.createTransformer(t),s=ca(e),o=ca(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?Bf.has(e)&&!o.values.length||Bf.has(t)&&!s.values.length?RG(e,t):bd(d1(zG(s,o),o.values),n):uu(e,t)};function c1(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?jn(e,t,n):lx(e)(e,t)}const FG=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>_n.update(t,n),stop:()=>Ro(t),now:()=>ds.isProcessing?ds.timestamp:Cs.now()}},u1=(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)})`},hu=2e4;function dx(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<hu;)t+=n,s=e.next(t);return t>=hu?1/0:t}function HG(e,t=100,n){const s=n({...e,keyframes:[0,t]}),o=Math.min(dx(s),hu);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 $f(e,t){return e*Math.sqrt(1-t*t)}const BG=12;function $G(e,t,n){let s=n;for(let o=1;o<BG;o++)s=s-e(s)/t(s);return s}const dp=.001;function VG({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=$f(c,a),g=Math.exp(-h);return dp-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=$f(Math.pow(c,2),a);return(-o(c)+dp>0?-1:1)*((p-f)*g)/x}):(o=c=>{const u=Math.exp(-c*e),h=(c-n)*e+1;return-dp+u*h},r=c=>{const u=Math.exp(-c*e),h=(n-c)*(e*e);return u*h});const l=5/e,d=$G(o,r,l);if(e=Gs(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 WG=["duration","bounce"],UG=["stiffness","damping","mass"];function eb(e,t){return t.some(n=>e[n]!==void 0)}function KG(e){let t={velocity:Gn.velocity,stiffness:Gn.stiffness,damping:Gn.damping,mass:Gn.mass,isResolvedFromDuration:!1,...e};if(!eb(e,UG)&&eb(e,WG))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=VG({...e,velocity:0});t={...t,...n,mass:Gn.mass},t.isResolvedFromDuration=!0}return t}function pu(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}=KG({...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)),b=Math.abs(v)<5;s||(s=b?Gn.restSpeed.granular:Gn.restSpeed.default),o||(o=b?Gn.restDelta.granular:Gn.restDelta.default);let w,_,C,N,S,k;if(x<1)C=$f(y,x),N=(g+x*y*v)/C,w=I=>{const E=Math.exp(-x*y*I);return a-E*(N*Math.sin(C*I)+v*Math.cos(C*I))},S=x*y*N+v*C,k=x*y*v-N*C,_=I=>Math.exp(-x*y*I)*(S*Math.sin(C*I)+k*Math.cos(C*I));else if(x===1){w=E=>a-Math.exp(-y*E)*(v+(g+y*v)*E);const I=g+y*v;_=E=>Math.exp(-y*E)*(y*I*E-g)}else{const I=y*Math.sqrt(x*x-1);w=H=>{const F=Math.exp(-x*y*H),O=Math.min(I*H,300);return a-F*((g+x*y*v)*Math.sinh(O)+I*v*Math.cosh(O))/I};const E=(g+x*y*v)/I,D=x*y*E-v*I,T=x*y*v-E*I;_=H=>{const F=Math.exp(-x*y*H),O=Math.min(I*H,300);return F*(D*Math.sinh(O)+T*Math.cosh(O))}}const A={calculatedDuration:f&&h||null,velocity:I=>Gs(_(I)),next:I=>{if(!f&&x<1){const D=Math.exp(-x*y*I),T=Math.sin(C*I),H=Math.cos(C*I),F=a-D*(N*T+v*H),O=Gs(D*(S*T+k*H));return l.done=Math.abs(O)<=s&&Math.abs(a-F)<=o,l.value=l.done?a:F,l}const E=w(I);if(f)l.done=I>=h;else{const D=Gs(_(I));l.done=Math.abs(D)<=s&&Math.abs(a-E)<=o}return l.value=l.done?a:E,l},toString:()=>{const I=Math.min(dx(A),hu),E=u1(D=>A.next(I*D).value,I,30);return I+"ms "+E},toTransition:()=>{}};return A}pu.applyToOptions=e=>{const t=HG(e,100,pu);return e.ease=t.ease,e.duration=Gs(t.duration),e.type="keyframes",e};const qG=5;function h1(e,t,n){const s=Math.max(t-qG,0);return W_(n-e(s),t-s)}function Vf({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=k=>l!==void 0&&k<l||d!==void 0&&k>d,g=k=>l===void 0?d:d===void 0||Math.abs(l-k)<Math.abs(d-k)?l:d;let x=n*t;const v=h+x,y=a===void 0?v:a(v);y!==v&&(x=y-h);const b=k=>-x*Math.exp(-k/s),w=k=>y+b(k),_=k=>{const A=b(k),I=w(k);p.done=Math.abs(A)<=c,p.value=p.done?y:I};let C,N;const S=k=>{f(p.value)&&(C=k,N=pu({keyframes:[p.value,g(p.value)],velocity:h1(w,k,p.value),damping:o,stiffness:r,restDelta:c,restSpeed:u}))};return S(0),{calculatedDuration:null,next:k=>{let A=!1;return!N&&C===void 0&&(A=!0,_(k),S(k)),C!==void 0&&k>=C?N.next(k-C):(!A&&_(k),p)}}}function YG(e,t,n){const s=[],o=n||Mo.mix||c1,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=bd(d,l)}s.push(l)}return s}function XG(e,t,{clamp:n=!0,ease:s,mixer:o}={}){const r=e.length;if(hh(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=YG(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=zl(e[h],e[h+1],u);return l[h](p)};return n?u=>c(Gi(e[0],e[r-1],u)):c}function ZG(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const o=zl(0,t,s);e.push(jn(n,1,o))}}function JG(e){const t=[0];return ZG(t,e.length-1),t}function QG(e,t){return e.map(n=>n*t)}function eF(e,t){return e.map(()=>t||e1).splice(0,e.length-1)}function hl({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const o=lG(s)?s.map(q0):q0(s),r={done:!1,value:t[0]},a=QG(n&&n.length===t.length?n:JG(t),e),l=XG(a,t,{ease:Array.isArray(o)?o:eF(t,o)});return{calculatedDuration:e,next:d=>(r.value=l(d),r.done=d>=e,r)}}const tF=e=>e!==null;function ph(e,{repeat:t,repeatType:n="loop"},s,o=1){const r=e.filter(tF),l=o<0||t&&n!=="loop"&&t%2===1?0:r.length-1;return!l||s===void 0?r[l]:s}const nF={decay:Vf,inertia:Vf,tween:hl,keyframes:hl,spring:pu};function p1(e){typeof e.type=="string"&&(e.type=nF[e.type])}class cx{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 sF=e=>e/100;class fu extends cx{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!==Cs.now()&&this.tick(Cs.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;p1(t);const{type:n=hl,repeat:s=0,repeatDelay:o=0,repeatType:r,velocity:a=0}=t;let{keyframes:l}=t;const d=n||hl;d!==hl&&typeof l[0]!="number"&&(this.mixKeyframes=bd(sF,c1(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=dx(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),b=this.playbackSpeed>=0?y<0:y>o;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=o);let w=this.currentTime,_=s;if(h){const k=Math.min(this.currentTime,o)/l;let A=Math.floor(k),I=k%1;!I&&k>=1&&(I=1),I===1&&A--,A=Math.min(A,h+1),A%2&&(p==="reverse"?(I=1-I,f&&(I-=f/l)):p==="mirror"&&(_=a)),w=Gi(0,1,I)*l}let C;b?(this.delayState.value=u[0],C=this.delayState):C=_.next(w),r&&!b&&(C.value=r(C.value));let{done:N}=C;!b&&d!==null&&(N=this.playbackSpeed>=0?this.currentTime>=o:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return S&&g!==Vf&&(C.value=ph(u,this.options,v,this.speed)),x&&x(C.value),S&&this.finish(),C}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=Gs(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 h1(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(Cs.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=qs(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=FG,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(Cs.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 iF(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const dr=e=>e*180/Math.PI,Wf=e=>{const t=dr(Math.atan2(e[1],e[0]));return Uf(t)},oF={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Wf,rotateZ:Wf,skewX:e=>dr(Math.atan(e[1])),skewY:e=>dr(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Uf=e=>(e=e%360,e<0&&(e+=360),e),tb=Wf,nb=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),sb=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),rF={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:nb,scaleY:sb,scale:e=>(nb(e)+sb(e))/2,rotateX:e=>Uf(dr(Math.atan2(e[6],e[5]))),rotateY:e=>Uf(dr(Math.atan2(-e[2],e[0]))),rotateZ:tb,rotate:tb,skewX:e=>dr(Math.atan(e[4])),skewY:e=>dr(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Kf(e){return e.includes("scale")?1:0}function qf(e,t){if(!e||e==="none")return Kf(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,o;if(n)s=rF,o=n;else{const l=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=oF,o=l}if(!o)return Kf(t);const r=s[t],a=o[1].split(",").map(lF);return typeof r=="function"?r(a):a[r]}const aF=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return qf(n,t)};function lF(e){return parseFloat(e.trim())}const _a=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Na=new Set([..._a,"pathRotation"]),ib=e=>e===ja||e===vt,dF=new Set(["x","y","z"]),cF=_a.filter(e=>!dF.has(e));function uF(e){const t=[];return cF.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Po={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})=>qf(t,"x"),y:(e,{transform:t})=>qf(t,"y")};Po.translateX=Po.x;Po.translateY=Po.y;const fr=new Set;let Yf=!1,Xf=!1,Zf=!1;function f1(){if(Xf){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=uF(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)})}Xf=!1,Yf=!1,fr.forEach(e=>e.complete(Zf)),fr.clear()}function m1(){fr.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Xf=!0)})}function hF(){Zf=!0,m1(),f1(),Zf=!1}class ux{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),Yf||(Yf=!0,_n.read(m1),_n.resolveKeyframes(f1))):(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])}iF(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 pF=e=>e.startsWith("--");function g1(e,t,n){pF(t)?e.style.setProperty(t,n):e.style[t]=n}const fF={};function x1(e,t){const n=V_(e);return()=>fF[t]??n()}const mF=x1(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),v1=x1(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Ja=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,ob={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ja([0,.65,.55,1]),circOut:Ja([.55,0,1,.45]),backIn:Ja([.31,.01,.66,-.59]),backOut:Ja([.33,1.53,.69,.99])};function b1(e,t){if(e)return typeof e=="function"?v1()?u1(e,t):"ease-out":t1(e)?Ja(e):Array.isArray(e)?e.map(n=>b1(n,t)||ob.easeOut):ob[e]}function gF(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=b1(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 w1(e){return typeof e=="function"&&"applyToOptions"in e}function xF({type:e,...t}){return w1(e)&&v1()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class y1 extends cx{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,hh(typeof t.type!="string");const c=xF(t);this.animation=gF(n,s,o,c,r),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=ph(o,this.options,l,this.speed);this.updateMotionValue&&this.updateMotionValue(u),g1(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=Gs(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&&mF()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),s&&(this.animation.rangeEnd=s),Js):o(this)}}const S1={anticipate:Z_,backInOut:X_,circInOut:Q_};function vF(e){return e in S1}function bF(e){typeof e.ease=="string"&&vF(e.ease)&&(e.ease=S1[e.ease])}const cp=10;class wF extends y1{constructor(t){bF(t),p1(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 fu({...a,autoplay:!1}),d=Math.max(cp,Cs.now()-this.startTime),c=Gi(0,cp,d-cp),u=l.sample(d).value,{name:h}=this.options;r&&h&&g1(r,h,u),n.setWithVelocity(l.sample(Math.max(0,d-c)).value,u,c),l.stop()}}const rb=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(pi.test(e)||e==="0")&&!e.startsWith("url("));function yF(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 SF(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=rb(o,t),l=rb(r,t);return!a||!l?!1:yF(e)||(n==="spring"||w1(n))&&s}function Jf(e){e.duration=0,e.type="keyframes"}const C1=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),CF=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function kF(e){for(let t=0;t<e.length;t++)if(typeof e[t]=="string"&&CF.test(e[t]))return!0;return!1}const jF=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),_F=V_(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function NF(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 _F()&&n&&(C1.has(n)||jF.has(n)&&kF(l))&&(n!=="transform"||!u)&&!c&&!s&&o!=="mirror"&&r!==0&&a!=="inertia"}const TF=40;class DF extends cx{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=Cs.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||ux;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=Cs.now();let h=!0;SF(t,r,a,l)||(h=!1,(Mo.instantAnimations||!d)&&u?.(ph(t,s,n)),t[0]=t[t.length-1],Jf(s),s.repeat=0);const f={startTime:o?this.resolvedAt?this.resolvedAt-this.createdAt>TF?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=h&&!c&&NF(f),x=f.motionValue?.owner?.current;let v;if(g)try{v=new wF({...f,element:x})}catch{v=new fu(f)}else v=new fu(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(),hF()),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 k1(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 ab=30,IF=e=>!isNaN(parseFloat(e));class EF{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const o=Cs.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=Cs.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=IF(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 nx);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=Cs.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>ab)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,ab);return W_(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 ua(e,t){return new EF(e,t)}function j1(e,t){if(e?.inherit&&t){const{inherit:n,...s}=e;return{...t,...s}}return e}function hx(e,t){const n=e?.[t]??e?.default??e;return n!==e?j1(n,e):n}const PF={type:"spring",stiffness:500,damping:25,restSpeed:10},AF=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),MF={type:"keyframes",duration:.8},RF={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},LF=(e,{keyframes:t})=>t.length>2?MF:Na.has(e)?e.startsWith("scale")?AF(t[1]):PF:RF,OF=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function zF(e){for(const t in e)if(!OF.has(t))return!0;return!1}const px=(e,t,n,s={},o,r)=>a=>{const l=hx(s,e)||{},d=l.delay||s.delay||0;let{elapsed:c=0}=s;c=c-Gs(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};zF(l)||Object.assign(u,LF(e,u)),u.duration&&(u.duration=Gs(u.duration)),u.repeatDelay&&(u.repeatDelay=Gs(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Jf(u),u.delay===0&&(h=!0)),(Mo.instantAnimations||Mo.skipAnimations||o?.shouldSkipAnimations||l.skipAnimations)&&(h=!0,Jf(u),u.delay=0),u.allowFlatten=!l.type&&!l.ease,h&&!r&&t.get()!==void 0){const p=ph(u.keyframes,l);if(p!==void 0){_n.update(()=>{u.onUpdate(p),u.onComplete()});return}}return l.isSync?new fu(u):new DF(u)},GF=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function FF(e){const t=GF.exec(e);if(!t)return[,];const[,n,s,o]=t;return[`--${n??s}`,o]}function _1(e,t,n=1){const[s,o]=FF(e);if(!s)return;const r=window.getComputedStyle(t).getPropertyValue(s);if(r){const a=r.trim();return H_(a)?parseFloat(a):a}return ox(o)?_1(o,t,n+1):o}function lb(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function fx(e,t,n,s){if(typeof t=="function"){const[o,r]=lb(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]=lb(s);t=t(n!==void 0?n:e.custom,o,r)}return t}function mr(e,t,n){const s=e.getProps();return fx(s,t,n!==void 0?n:s.custom,e)}const N1=new Set(["width","height","top","left","right","bottom",..._a]),Qf=e=>Array.isArray(e);function HF(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,ua(n))}function BF(e){return Qf(e)?e[e.length-1]||0:e}function $F(e,t){const n=mr(e,t);let{transitionEnd:s={},transition:o={},...r}=n||{};r={...r,...s};for(const a in r){const l=BF(r[a]);HF(e,a,l)}}const cs=e=>!!(e&&e.getVelocity);function VF(e){return!!(cs(e)&&e.add)}function em(e,t){const n=e.getValue("willChange");if(VF(n))return n.add(t);if(!n&&Mo.WillChange){const s=new Mo.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function mx(e){return e.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const WF="framerAppearId",T1="data-"+mx(WF);function D1(e){return e.props[T1]}const UF=typeof window<"u";function KF({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function I1(e,t,{delay:n=0,transitionOverride:s,type:o}={}){let{transition:r,transitionEnd:a,...l}=t;const d=e.getDefaultTransition();r=r?j1(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&&KF(p,g))continue;const y={delay:n,...hx(r||{},g)};u&&(y.skipAnimations=!0);const b=x.get();if(b!==void 0&&!x.isAnimating()&&!Array.isArray(v)&&v===b&&!y.velocity){_n.update(()=>x.set(v));continue}let w=!1;if(UF&&window.MotionHandoffAnimation){const N=D1(e);if(N){const S=window.MotionHandoffAnimation(N,g,_n);S!==null&&(y.startTime=S,w=!0)}}em(e,g);const _=c??e.shouldReduceMotion;x.start(px(g,x,v,_&&N1.has(g)?{type:!1}:y,e,w));const C=x.animation;C&&h.push(C)}if(a){const g=()=>_n.update(()=>{a&&$F(e,a)});h.length?Promise.all(h).then(g):g()}return h}function tm(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(I1(e,s,n)):()=>Promise.resolve(),a=e.variantChildren&&e.variantChildren.size?(d=0)=>{const{delayChildren:c=0,staggerChildren:u,staggerDirection:h}=o;return qF(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 qF(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(tm(d,t,{...a,delay:n+(typeof s=="function"?0:s)+k1(e.variantChildren,d,s,o,r)}).then(()=>d.notify("AnimationComplete",t)));return Promise.all(l)}function YF(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const o=t.map(r=>tm(e,r,n));s=Promise.all(o)}else if(typeof t=="string")s=tm(e,t,n);else{const o=typeof t=="function"?mr(e,t,n.custom):t;s=Promise.all(I1(e,o,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}const XF={test:e=>e==="auto",parse:e=>e},E1=e=>t=>t.test(e),P1=[ja,vt,Oi,eo,yG,wG,XF],db=e=>P1.find(E1(e));function ZF(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||$_(e):!0}const JF=new Set(["brightness","contrast","saturate","opacity"]);function QF(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(rx)||[];if(!s)return e;const o=n.replace(s,"");let r=JF.has(t)?1:0;return s!==n&&(r*=100),t+"("+r+o+")"}const eH=/\b([a-z-]*)\(.*?\)/gu,nm={...pi,getAnimatableNone:e=>{const t=e.match(eH);return t?t.map(QF).join(" "):e}},sm={...pi,getAnimatableNone:e=>{const t=pi.parse(e);return pi.createTransformer(e)(t.map(s=>typeof s=="number"?0:typeof s=="object"?{...s,alpha:1}:s))}},cb={...ja,transform:Math.round},tH={rotate:eo,pathRotation:eo,rotateX:eo,rotateY:eo,rotateZ:eo,scale:Ld,scaleX:Ld,scaleY:Ld,scaleZ:Ld,skew:eo,skewX:eo,skewY:eo,distance:vt,translateX:vt,translateY:vt,translateZ:vt,x:vt,y:vt,z:vt,perspective:vt,transformPerspective:vt,opacity:Gl,originX:X0,originY:X0,originZ:vt},mu={borderWidth:vt,borderTopWidth:vt,borderRightWidth:vt,borderBottomWidth:vt,borderLeftWidth:vt,borderRadius:vt,borderTopLeftRadius:vt,borderTopRightRadius:vt,borderBottomRightRadius:vt,borderBottomLeftRadius:vt,width:vt,maxWidth:vt,height:vt,maxHeight:vt,top:vt,right:vt,bottom:vt,left:vt,inset:vt,insetBlock:vt,insetBlockStart:vt,insetBlockEnd:vt,insetInline:vt,insetInlineStart:vt,insetInlineEnd:vt,padding:vt,paddingTop:vt,paddingRight:vt,paddingBottom:vt,paddingLeft:vt,paddingBlock:vt,paddingBlockStart:vt,paddingBlockEnd:vt,paddingInline:vt,paddingInlineStart:vt,paddingInlineEnd:vt,margin:vt,marginTop:vt,marginRight:vt,marginBottom:vt,marginLeft:vt,marginBlock:vt,marginBlockStart:vt,marginBlockEnd:vt,marginInline:vt,marginInlineStart:vt,marginInlineEnd:vt,fontSize:vt,backgroundPositionX:vt,backgroundPositionY:vt,...tH,zIndex:cb,fillOpacity:Gl,strokeOpacity:Gl,numOctaves:cb},nH={...mu,color:Vn,backgroundColor:Vn,outlineColor:Vn,fill:Vn,stroke:Vn,borderColor:Vn,borderTopColor:Vn,borderRightColor:Vn,borderBottomColor:Vn,borderLeftColor:Vn,filter:nm,WebkitFilter:nm,mask:sm,WebkitMask:sm},A1=e=>nH[e],sH=new Set([nm,sm]);function M1(e,t){let n=A1(e);return sH.has(n)||(n=pi),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const iH=new Set(["auto","none","0"]);function oH(e,t,n){let s=0,o;for(;s<e.length&&!o;){const r=e[s];typeof r=="string"&&!iH.has(r)&&ca(r).values.length&&(o=e[s]),s++}if(o&&n)for(const r of t)e[r]=M1(n,o)}class rH extends ux{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(),ox(h))){const p=_1(h,n.current);p!==void 0&&(t[u]=p),u===t.length-1&&(this.finalKeyframe=h)}}if(this.resolveNoneKeyframes(),!N1.has(s)||t.length!==2)return;const[o,r]=t,a=db(o),l=db(r),d=Y0(o),c=Y0(r);if(d!==c&&Po[s]){this.needsMeasurement=!0;return}if(a!==l)if(ib(a)&&ib(l))for(let u=0;u<t.length;u++){const h=t[u];typeof h=="string"&&(t[u]=parseFloat(h))}else Po[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let o=0;o<t.length;o++)(t[o]===null||ZF(t[o]))&&s.push(o);s.length&&oH(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=Po[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]=Po[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 gx=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function R1(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 im=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function Ec(e){return B_(e)&&"offsetHeight"in e&&!("ownerSVGElement"in e)}const{schedule:xx}=n1(queueMicrotask,!1),oi={x:!1,y:!1};function L1(){return oi.x||oi.y}function aH(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 O1(e,t){const n=R1(e),s=new AbortController,o={passive:!0,...t,signal:s.signal};return[n,o,()=>s.abort()]}function lH(e){return!(e.pointerType==="touch"||L1())}function dH(e,t,n={}){const[s,o,r]=O1(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(!lH(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 z1=(e,t)=>t?e===t?!0:z1(e,t.parentElement):!1,vx=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,cH=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function uH(e){return cH.has(e.tagName)||e.isContentEditable===!0}const hH=new Set(["INPUT","SELECT","TEXTAREA"]);function pH(e){return hH.has(e.tagName)||e.isContentEditable===!0}const Pc=new WeakSet;function ub(e){return t=>{t.key==="Enter"&&e(t)}}function up(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const fH=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=ub(()=>{if(Pc.has(n))return;up(n,"down");const o=ub(()=>{up(n,"up")}),r=()=>up(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 hb(e){return vx(e)&&!L1()}const pb=new WeakSet;function mH(e,t,n={}){const[s,o,r]=O1(e,n),a=l=>{const d=l.currentTarget;if(!hb(l)||pb.has(l))return;Pc.add(d),n.stopPropagation&&pb.add(l);const c=t(d,l),u={...o,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",p,u),window.removeEventListener("pointercancel",f,u),Pc.has(d)&&Pc.delete(d),hb(g)&&typeof c=="function"&&c(g,{success:x})},p=g=>{h(g,d===window||d===document||n.useGlobalTarget||z1(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),Ec(l)&&(l.addEventListener("focus",c=>fH(c,o)),!uH(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),r}function bx(e){return B_(e)&&"ownerSVGElement"in e}const Ac=new WeakMap;let Mc;const G1=(e,t,n)=>(s,o)=>o&&o[0]?o[0][e+"Size"]:bx(s)&&"getBBox"in s?s.getBBox()[t]:s[n],gH=G1("inline","width","offsetWidth"),xH=G1("block","height","offsetHeight");function vH({target:e,borderBoxSize:t}){Ac.get(e)?.forEach(n=>{n(e,{get width(){return gH(e,t)},get height(){return xH(e,t)}})})}function bH(e){e.forEach(vH)}function wH(){typeof ResizeObserver>"u"||(Mc=new ResizeObserver(bH))}function yH(e,t){Mc||wH();const n=R1(e);return n.forEach(s=>{let o=Ac.get(s);o||(o=new Set,Ac.set(s,o)),o.add(t),Mc?.observe(s)}),()=>{n.forEach(s=>{const o=Ac.get(s);o?.delete(t),o?.size||Mc?.unobserve(s)})}}const Rc=new Set;let Vr;function SH(){Vr=()=>{const e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Rc.forEach(t=>t(e))},window.addEventListener("resize",Vr)}function CH(e){return Rc.add(e),Vr||SH(),()=>{Rc.delete(e),!Rc.size&&typeof Vr=="function"&&(window.removeEventListener("resize",Vr),Vr=void 0)}}function fb(e,t){return typeof e=="function"?CH(e):yH(e,t)}function kH(e){return bx(e)&&e.tagName==="svg"}const jH=[...P1,Vn,pi],_H=e=>jH.find(E1(e)),mb=()=>({translate:0,scale:1,origin:0,originPoint:0}),Wr=()=>({x:mb(),y:mb()}),gb=()=>({min:0,max:0}),Yn=()=>({x:gb(),y:gb()}),NH=new WeakMap;function fh(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Fl(e){return typeof e=="string"||Array.isArray(e)}const wx=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],yx=["initial",...wx];function mh(e){return fh(e.animate)||yx.some(t=>Fl(e[t]))}function F1(e){return!!(mh(e)||e.variants)}function TH(e,t,n){for(const s in t){const o=t[s],r=n[s];if(cs(o))e.addValue(s,o);else if(cs(r))e.addValue(s,ua(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,ua(a!==void 0?a:o,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const gu={current:null},Sx={current:!1},DH=typeof window<"u";function H1(){if(Sx.current=!0,!!DH)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>gu.current=e.matches;e.addEventListener("change",t),t()}else gu.current=!1}const xb=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let xu={};function B1(e){xu=e}function IH(){return xu}class EH{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=ux,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=Cs.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=mh(n),this.isVariantNode=F1(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&&cs(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,NH.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:(Sx.current||H1(),this.shouldReduceMotion=gu.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(),Ro(this.notifyUpdate),Ro(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&&C1.has(t)&&this.current instanceof HTMLElement){const{factory:a,keyframes:l,times:d,ease:c,duration:u}=n.accelerate,h=new y1({element:this.current,name:t,keyframes:l,times:d,ease:c,duration:Gs(u)}),p=a(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const s=Na.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 xu){const n=xu[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):Yn()}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<xb.length;s++){const o=xb[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=TH(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=ua(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"&&(H_(s)||$_(s))?s=parseFloat(s):!_H(s)&&pi.test(n)&&(s=M1(t,n)),this.setBaseTarget(t,cs(s)?s.get():s)),cs(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=fx(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&&!cs(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 nx),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){xx.render(this.render)}}class $1 extends EH{constructor(){super(...arguments),this.KeyframeResolver=rH}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;cs(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Bo{constructor(t){this.isMounted=!1,this.node=t}update(){}}function V1({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function PH({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function AH(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 hp(e){return e===void 0||e===1}function om({scale:e,scaleX:t,scaleY:n}){return!hp(e)||!hp(t)||!hp(n)}function nr(e){return om(e)||W1(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function W1(e){return vb(e.x)||vb(e.y)}function vb(e){return e&&e!=="0%"}function vu(e,t,n){const s=e-n,o=t*s;return n+o}function bb(e,t,n,s,o){return o!==void 0&&(e=vu(e,o,s)),vu(e,n,s)+t}function rm(e,t=0,n=1,s,o){e.min=bb(e.min,t,n,s,o),e.max=bb(e.max,t,n,s,o)}function U1(e,{x:t,y:n}){rm(e.x,t.translate,t.scale,t.originPoint),rm(e.y,n.translate,n.scale,n.originPoint)}const wb=.999999999999,yb=1.0000000000001;function MH(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&&(Di(e.x,-r.scroll.offset.x),Di(e.y,-r.scroll.offset.y)),a&&(t.x*=a.x.scale,t.y*=a.y.scale,U1(e,a)),s&&nr(r.latestValues)&&Lc(e,r.latestValues,r.layout?.layoutBox))}t.x<yb&&t.x>wb&&(t.x=1),t.y<yb&&t.y>wb&&(t.y=1)}function Di(e,t){e.min+=t,e.max+=t}function Sb(e,t,n,s,o=.5){const r=jn(e.min,e.max,o);rm(e,t,n,r,s)}function Cb(e,t){return typeof e=="string"?parseFloat(e)/100*(t.max-t.min):e}function Lc(e,t,n){const s=n??e;Sb(e.x,Cb(t.x,s.x),t.scaleX,t.scale,t.originX),Sb(e.y,Cb(t.y,s.y),t.scaleY,t.scale,t.originY)}function K1(e,t){return V1(AH(e.getBoundingClientRect(),t))}function RH(e,t,n){const s=K1(e,n),{scroll:o}=t;return o&&(Di(s.x,o.offset.x),Di(s.y,o.offset.y)),s}const LH={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},OH=_a.length;function zH(e,t,n){let s="",o=!0;for(let a=0;a<OH;a++){const l=_a[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=im(d,mu[l]);if(!c){o=!1;const h=LH[l]||l;s+=`${h}(${u}) `}n&&(t[l]=u)}}const r=e.pathRotation;return r&&(o=!1,s+=`rotate(${im(r,mu.pathRotation)}) `),s=s.trim(),n?s=n(t,o?"":s):o&&(s="none"),s}function Cx(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(Na.has(d)){a=!0;continue}else if(i1(d)){o[d]=c;continue}else{const u=im(c,mu[d]);d.startsWith("origin")?(l=!0,r[d]=u):s[d]=u}}if(t.transform||(a||n?s.transform=zH(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 q1(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 kb(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Aa={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(vt.test(e))e=parseFloat(e);else return e;const n=kb(e,t.target.x),s=kb(e,t.target.y);return`${n}% ${s}%`}},GH={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,o=pi.parse(e);if(o.length>5)return s;const r=pi.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)}},am={borderRadius:{...Aa,applyTo:[...gx]},borderTopLeftRadius:Aa,borderTopRightRadius:Aa,borderBottomLeftRadius:Aa,borderBottomRightRadius:Aa,boxShadow:GH};function Y1(e,{layout:t,layoutId:n}){return Na.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!am[e]||e==="opacity")}function kx(e,t,n){const s=e.style,o=t?.style,r={};if(!s)return r;for(const a in s)(cs(s[a])||o&&cs(o[a])||Y1(a,e)||n?.getValue(a)?.liveStyle!==void 0)&&(r[a]=s[a]);return r}function FH(e){return window.getComputedStyle(e)}class HH extends $1{constructor(){super(...arguments),this.type="html",this.renderInstance=q1}mount(t){hh(!!t.style),super.mount(t)}readValueFromInstance(t,n){if(Na.has(n))return this.projection?.isProjecting?Kf(n):aF(t,n);{const s=FH(t),o=(i1(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return K1(t,n)}build(t,n,s){Cx(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return kx(t,n,s)}}const BH={offset:"stroke-dashoffset",array:"stroke-dasharray"},$H={offset:"strokeDashoffset",array:"strokeDasharray"};function VH(e,t,n=1,s=0,o=!0){e.pathLength=1;const r=o?BH:$H;e[r.offset]=`${-s}`,e[r.array]=`${t} ${n}`}const X1=["transform","opacity","offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Z1(e,{attrX:t,attrY:n,attrScale:s,pathLength:o,pathSpacing:r=1,pathOffset:a=0,...l},d,c,u){if(Cx(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 X1)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&&VH(h,o,r,a,!1)}const J1=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"]),Q1=e=>typeof e=="string"&&e.toLowerCase()==="svg";function WH(e,t,n,s){q1(e,t,void 0,s);for(const o in t.attrs)e.setAttribute(J1.has(o)?o:mx(o),t.attrs[o])}function eN(e,t,n){const s=kx(e,t,n);for(const o in e)if(cs(e[o])||cs(t[o])){const r=_a.indexOf(o)!==-1?"attr"+o.charAt(0).toUpperCase()+o.substring(1):o;s[r]=e[o]}return s}class UH extends $1{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Yn}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Na.has(n)){const s=A1(n);return s&&s.default||0}if(X1.includes(n)){const o=getComputedStyle(t)[n];if(typeof o=="string"&&o)return o.trim()}return n=J1.has(n)?n:mx(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return eN(t,n,s)}build(t,n,s){Z1(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,o){WH(t,n,s,o)}mount(t){this.isSVGTag=Q1(t.tagName),super.mount(t)}}const KH=yx.length;function tN(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?tN(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<KH;n++){const s=yx[n],o=e.props[s];(Fl(o)||o===!1)&&(t[s]=o)}return t}function nN(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 qH=[...wx].reverse(),YH=wx.length;function XH(e){return t=>Promise.all(t.map(({animation:n,options:s})=>YF(e,n,s)))}function ZH(e){let t=XH(e),n=jb(),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=tN(e.parent)||{},p=[],f=new Set;let g={},x=1/0;for(let y=0;y<YH;y++){const b=qH[y],w=n[b],_=u[b]!==void 0?u[b]:h[b],C=Fl(_),N=b===c?w.isActive:null;N===!1&&(x=y);let S=_===h[b]&&_!==u[b]&&C;if(S&&(s||o)&&e.manuallyAnimateOnMount&&(S=!1),w.protectedKeys={...g},!w.isActive&&N===null||!_&&!w.prevProp||fh(_)||typeof _=="boolean")continue;if(b==="exit"&&w.isActive&&N!==!0){w.prevResolvedValues&&(g={...g,...w.prevResolvedValues});continue}const k=JH(w.prevProp,_);let A=k||b===c&&w.isActive&&!S&&C||y>x&&C,I=!1;const E=Array.isArray(_)?_:[_];let D=E.reduce(r(b),{});N===!1&&(D={});const{prevResolvedValues:T={}}=w,H={...T,...D},F=Y=>{A=!0,f.has(Y)&&(I=!0,f.delete(Y)),w.needsAnimating[Y]=!0;const U=e.getValue(Y);U&&(U.liveStyle=!1)};for(const Y in H){const U=D[Y],ee=T[Y];if(g.hasOwnProperty(Y))continue;let L=!1;Qf(U)&&Qf(ee)?L=!nN(U,ee)||k:L=U!==ee,L?U!=null?F(Y):f.add(Y):U!==void 0&&f.has(Y)?F(Y):w.protectedKeys[Y]=!0}w.prevProp=_,w.prevResolvedValues=D,w.isActive&&(g={...g,...D}),(s||o)&&e.blockInitialAnimation&&(A=!1);const O=S&&k;A&&(!O||I)&&p.push(...E.map(Y=>{const U={type:b};if(typeof Y=="string"&&(s||o)&&!O&&e.manuallyAnimateOnMount&&e.parent){const{parent:ee}=e,L=mr(ee,Y);if(ee.enteringChildren&&L){const{delayChildren:Q}=L.transition||{};U.delay=k1(ee.enteringChildren,e,Q)}}return{animation:Y,options:U}}))}if(f.size){const y={};if(typeof u.initial!="boolean"){const b=mr(e,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(y.transition=b.transition)}f.forEach(b=>{const w=e.getBaseTarget(b),_=e.getValue(b);_&&(_.liveStyle=!0),y[b]=w??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=jb(),o=!0}}}function JH(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!nN(t,e):!1}function Xo(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function jb(){return{animate:Xo(!0),whileInView:Xo(),whileHover:Xo(),whileTap:Xo(),whileDrag:Xo(),whileFocus:Xo(),exit:Xo()}}function lm(e,t){e.min=t.min,e.max=t.max}function si(e,t){lm(e.x,t.x),lm(e.y,t.y)}function _b(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}const sN=1e-4,QH=1-sN,eB=1+sN,iN=.01,tB=0-iN,nB=0+iN;function ks(e){return e.max-e.min}function sB(e,t,n){return Math.abs(e-t)<=n}function Nb(e,t,n,s=.5){e.origin=s,e.originPoint=jn(t.min,t.max,e.origin),e.scale=ks(n)/ks(t),e.translate=jn(n.min,n.max,e.origin)-e.originPoint,(e.scale>=QH&&e.scale<=eB||isNaN(e.scale))&&(e.scale=1),(e.translate>=tB&&e.translate<=nB||isNaN(e.translate))&&(e.translate=0)}function pl(e,t,n,s){Nb(e.x,t.x,n.x,s?s.originX:void 0),Nb(e.y,t.y,n.y,s?s.originY:void 0)}function Tb(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+ks(t)}function iB(e,t,n,s){Tb(e.x,t.x,n.x,s?.x),Tb(e.y,t.y,n.y,s?.y)}function Db(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+ks(t)}function bu(e,t,n,s){Db(e.x,t.x,n.x,s?.x),Db(e.y,t.y,n.y,s?.y)}function Ib(e,t,n,s,o){return e-=t,e=vu(e,1/n,s),o!==void 0&&(e=vu(e,1/o,s)),e}function oB(e,t=0,n=1,s=.5,o,r=e,a=e){if(Oi.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=Ib(e.min,t,n,l,o),e.max=Ib(e.max,t,n,l,o)}function Eb(e,t,[n,s,o],r,a){oB(e,t[n],t[s],t[o],t.scale,r,a)}const rB=["x","scaleX","originX"],aB=["y","scaleY","originY"];function Pb(e,t,n,s){Eb(e.x,t,rB,n?n.x:void 0,s?s.x:void 0),Eb(e.y,t,aB,n?n.y:void 0,s?s.y:void 0)}function Ab(e){return e.translate===0&&e.scale===1}function oN(e){return Ab(e.x)&&Ab(e.y)}function Mb(e,t){return e.min===t.min&&e.max===t.max}function lB(e,t){return Mb(e.x,t.x)&&Mb(e.y,t.y)}function Rb(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function rN(e,t){return Rb(e.x,t.x)&&Rb(e.y,t.y)}function Lb(e){return ks(e.x)/ks(e.y)}function Ob(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function Ti(e){return[e("x"),e("y")]}function dB(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 cB=gx.length,zb=e=>typeof e=="string"?parseFloat(e):e,Gb=e=>typeof e=="number"||vt.test(e);function uB(e,t,n,s,o,r){o?(e.opacity=jn(0,n.opacity??1,hB(s)),e.opacityExit=jn(t.opacity??1,0,pB(s))):r&&(e.opacity=jn(t.opacity??1,n.opacity??1,s));for(let a=0;a<cB;a++){const l=gx[a];let d=Fb(t,l),c=Fb(n,l);if(d===void 0&&c===void 0)continue;d||(d=0),c||(c=0),d===0||c===0||Gb(d)===Gb(c)?(e[l]=Math.max(jn(zb(d),zb(c),s),0),(Oi.test(c)||Oi.test(d))&&(e[l]+="%")):e[l]=c}(t.rotate||n.rotate)&&(e.rotate=jn(t.rotate||0,n.rotate||0,s))}function Fb(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const hB=aN(0,.5,J_),pB=aN(.5,.95,Js);function aN(e,t,n){return s=>s<e?0:s>t?1:n(zl(e,t,s))}function fB(e,t,n){const s=cs(e)?e:ua(e);return s.start(px("",s,t,n)),s.animation}function Hl(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}const mB=(e,t)=>e.depth-t.depth;class gB{constructor(){this.children=[],this.isDirty=!1}add(t){tx(this.children,t),this.isDirty=!0}remove(t){cu(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(mB),this.isDirty=!1,this.children.forEach(t)}}function xB(e,t){const n=Cs.now(),s=({timestamp:o})=>{const r=o-n;r>=t&&(Ro(s),e(r-t))};return _n.setup(s,!0),()=>Ro(s)}function Oc(e){return cs(e)?e.get():e}class vB{constructor(){this.members=[]}add(t){tx(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&&(cu(this.members,s),s.unmount())}t.scheduleRender()}remove(t){if(cu(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 zc={hasAnimatedSinceResize:!0,hasEverUpdated:!1},pp=["","X","Y","Z"],bB=1e3;let wB=0;function fp(e,t,n,s){const{latestValues:o}=t;o[e]&&(n[e]=o[e],t.setStaticValue(e,0),s&&(s[e]=0))}function lN(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=D1(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&&lN(s)}function dN({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:o}){return class{constructor(a={},l=t?.()){this.id=wB++,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(CB),this.nodes.forEach(DB),this.nodes.forEach(IB),this.nodes.forEach(kB)},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 gB)}addEventListener(a,l){return this.eventHandlers.has(a)||this.eventHandlers.set(a,new nx),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=bx(a)&&!kH(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=xB(p,250),zc.hasAnimatedSinceResize&&(zc.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()||RB,{onLayoutAnimationStart:x,onLayoutAnimationComplete:v}=c.getProps(),y=!this.targetLayout||!rN(this.targetLayout,f),b=!h&&p;if(this.options.layoutRoot||this.resumeFrom||b||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...hx(g,"layout"),onPlay:x,onComplete:v};(c.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,b,w.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(),Ro(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(EB),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&&lN(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(_B),this.nodes.forEach(Hb);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Bb);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(NB),this.nodes.forEach(TB),this.nodes.forEach(yB),this.nodes.forEach(SB)):this.nodes.forEach(Bb),this.clearAllSnapshots();const l=Cs.now();ds.delta=Gi(0,1e3/60,l-ds.timestamp),ds.timestamp=l,ds.isProcessing=!0,op.update.process(ds),op.preRender.process(ds),op.render.process(ds),ds.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,xx.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(jB),this.sharedNodes.forEach(PB)}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&&!ks(this.snapshot.measuredBox.x)&&!ks(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=Yn()),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&&!oN(this.projectionDelta),d=this.getTransformTemplate(),c=d?d(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;a&&this.instance&&(l||nr(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)),LB(d),{animationId:this.root.animationId,measuredBox:l,layoutBox:d,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:a}=this.options;if(!a)return Yn();const l=a.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(OB))){const{scroll:c}=this.root;c&&(Di(l.x,c.offset.x),Di(l.y,c.offset.y))}return l}removeElementScroll(a){const l=Yn();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),Di(l.x,u.offset.x),Di(l.y,u.offset.y))}return l}applyTransform(a,l=!1,d){const c=d||Yn();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&&(Di(c.x,-h.scroll.offset.x),Di(c.y,-h.scroll.offset.y)),nr(h.latestValues)&&Lc(c,h.latestValues,h.layout?.layoutBox)}return nr(this.latestValues)&&Lc(c,this.latestValues,this.layout?.layoutBox),c}removeTransform(a){const l=Yn();si(l,a);for(let d=0;d<this.path.length;d++){const c=this.path[d];if(!nr(c.latestValues))continue;let u;c.instance&&(om(c.latestValues)&&c.updateSnapshot(),u=Yn(),si(u,c.measurePageBox())),Pb(l,c.latestValues,c.snapshot?.layoutBox,u)}return nr(this.latestValues)&&Pb(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!==ds.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=ds.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=Yn(),this.targetWithTransforms=Yn()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),iB(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),U1(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||om(this.parent.latestValues)||W1(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=Yn(),this.relativeTargetOrigin=Yn(),bu(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===ds.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;MH(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=Yn());const{target:f}=a;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(_b(this.prevProjectionDelta.x,this.projectionDelta.x),_b(this.prevProjectionDelta.y,this.projectionDelta.y)),pl(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==p||!Ob(this.projectionDelta.x,this.prevProjectionDelta.x)||!Ob(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=Wr(),this.projectionDelta=Wr(),this.projectionDeltaWithTransform=Wr()}setAnimationOrigin(a,l=!1,d){const c=this.snapshot,u=c?c.latestValues:{},h={...this.latestValues},p=Wr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const f=Yn(),g=c?c.source:void 0,x=this.layout?this.layout.source:void 0,v=g!==x,y=this.getStack(),b=!y||y.members.length<=1,w=!!(v&&!b&&this.options.crossfade===!0&&!this.path.some(MB));this.animationProgress=0;let _;const C=d?.interpolateProjection(a);this.mixTargetDelta=N=>{const S=N/1e3,k=C?.(S);k?(p.x.translate=k.x,p.x.scale=jn(a.x.scale,1,S),p.x.origin=a.x.origin,p.x.originPoint=a.x.originPoint,p.y.translate=k.y,p.y.scale=jn(a.y.scale,1,S),p.y.origin=a.y.origin,p.y.originPoint=a.y.originPoint):(Vb(p.x,a.x,S),Vb(p.y,a.y,S)),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(bu(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),AB(this.relativeTarget,this.relativeTargetOrigin,f,S),_&&lB(this.relativeTarget,_)&&(this.isProjectionDirty=!1),_||(_=Yn()),si(_,this.relativeTarget)),v&&(this.animationValues=h,uB(h,u,this.latestValues,S,w,b)),k&&k.rotate!==void 0&&(this.animationValues||(this.animationValues=h),this.animationValues.pathRotation=k.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(a){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(Ro(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=_n.update(()=>{zc.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ua(0)),this.motionValue.jump(0,!1),this.currentAnimation=fB(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(bB),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&&cN(this.options.animationType,this.layout.layoutBox,c.layoutBox)){d=this.target||Yn();const h=ks(this.layout.layoutBox.x);d.x.min=a.target.x.min,d.x.max=d.x.min+h;const p=ks(this.layout.layoutBox.y);d.y.min=a.target.y.min,d.y.max=d.y.min+p}si(l,d),Lc(l,u),pl(this.projectionDeltaWithTransform,this.layoutCorrected,l,u)}}registerSharedNode(a,l){this.sharedNodes.has(a)||this.sharedNodes.set(a,new vB),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&&fp("z",a,c,this.animationValues);for(let u=0;u<pp.length;u++)fp(`rotate${pp[u]}`,a,c,this.animationValues),fp(`skew${pp[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=Oc(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=Oc(l?.pointerEvents)||""),this.hasProjected&&!nr(this.latestValues)&&(a.transform=d?d({},""):"none",this.hasProjected=!1);return}a.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let h=dB(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 am){if(u[g]===void 0)continue;const{correct:x,applyTo:v,isCSSVariable:y}=am[g],b=h==="none"?u[g]:x(u[g],c);if(v){const w=v.length;for(let _=0;_<w;_++)a[v[_]]=b}else y?this.options.visualElement.renderState.vars[g]=b:a[g]=b}this.options.layoutId&&(a.pointerEvents=c===this?Oc(l?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(a=>a.currentAnimation?.stop()),this.root.nodes.forEach(Hb),this.root.sharedNodes.clear()}}}function yB(e){e.updateLayout()}function SB(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")Ti(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=ks(h);h.min=n[u].min,h.max=h.min+p});else if(o==="x"||o==="y"){const u=o==="x"?"y":"x";lm(r?t.measuredBox[u]:t.layoutBox[u],n[u])}else cN(o,t.layoutBox,n)&&Ti(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=ks(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=Wr();pl(a,n,t.layoutBox);const l=Wr();r?pl(l,e.applyTransform(s,!0),t.measuredBox):pl(l,n,t.layoutBox);const d=!oN(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=Yn();bu(g,t.layoutBox,h.layoutBox,f);const x=Yn();bu(x,n,p.layoutBox,f),rN(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 CB(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 kB(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function jB(e){e.clearSnapshot()}function Hb(e){e.clearMeasurements()}function _B(e){e.isLayoutDirty=!0,e.updateLayout()}function Bb(e){e.isLayoutDirty=!1}function NB(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function TB(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 DB(e){e.resolveTargetDelta()}function IB(e){e.calcProjection()}function EB(e){e.resetSkewAndRotation()}function PB(e){e.removeLeadSnapshot()}function Vb(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 Wb(e,t,n,s){e.min=jn(t.min,n.min,s),e.max=jn(t.max,n.max,s)}function AB(e,t,n,s){Wb(e.x,t.x,n.x,s),Wb(e.y,t.y,n.y,s)}function MB(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const RB={duration:.45,ease:[.4,0,.1,1]},Ub=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Kb=Ub("applewebkit/")&&!Ub("chrome/")?Math.round:Js;function qb(e){e.min=Kb(e.min),e.max=Kb(e.max)}function LB(e){qb(e.x),qb(e.y)}function cN(e,t,n){return e==="position"||e==="preserve-aspect"&&!sB(Lb(t),Lb(n),.2)}function OB(e){return e!==e.root&&e.scroll?.wasRoot}const zB=dN({attachResizeListener:(e,t)=>Hl(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),mp={current:void 0},uN=dN({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!mp.current){const e=new zB({});e.mount(window),e.setOptions({layoutScroll:!0}),mp.current=e}return mp.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),jx=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Yb(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function GB(...e){return t=>{let n=!1;const s=e.map(o=>{const r=Yb(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():Yb(e[o],null)}}}}function FB(...e){return m.useCallback(GB(...e),e)}class HB extends m.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(Ec(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,o=Ec(s)&&s.offsetWidth||0,r=Ec(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 BB({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(jx),u=r!==!1?e.props?.ref??e?.ref:void 0,h=FB(l,u);return m.useInsertionEffect(()=>{const{width:p,height:f,top:g,left:x,right:v,bottom:y,direction:b}=d.current;if(t||r===!1||!l.current||!p||!f)return;const w=b==="rtl",_=n==="left"?w?`right: ${v}`:`left: ${x}`:w?`left: ${x}`:`right: ${v}`,C=s==="bottom"?`bottom: ${y}`:`top: ${g}`;l.current.dataset.motionPopId=a;const N=document.createElement("style");c&&(N.nonce=c);const S=o??document.head;return S.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
|
-
${C}px !important;
|
|
12
|
-
}
|
|
13
|
-
`),()=>{l.current?.removeAttribute("data-motion-pop-id"),S.contains(N)&&S.removeChild(N)}},[t]),i.jsx(HB,{isPresent:t,childRef:l,sizeRef:d,pop:r,children:r===!1?e:m.cloneElement(e,{ref:h})})}const $B=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:o,presenceAffectsLayout:r,mode:a,anchorX:l,anchorY:d,root:c})=>{const u=ex(VB),h=m.useId(),p=m.useRef(n),f=m.useRef(s);du(()=>{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(BB,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:d,root:c,children:e}),i.jsx(uh.Provider,{value:x,children:e})};function VB(){return new Map}function hN(e=!0){const t=m.useContext(uh);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 Od=e=>e.key||"";function Xb(e){const t=[];return m.Children.forEach(e,n=>{m.isValidElement(n)&&t.push(n)}),t}const fl=({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]=hN(a),p=m.useMemo(()=>Xb(e),[e]),f=a&&!u?[]:p.map(Od),g=m.useRef(!0),x=m.useRef(p),v=ex(()=>new Map),y=m.useRef(new Set),[b,w]=m.useState(p),[_,C]=m.useState(p);du(()=>{a&&!u&&!_.length&&h?.()},[u,a,_.length,h]),du(()=>{g.current=!1,x.current=p;for(let k=0;k<_.length;k++){const A=Od(_[k]);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!==b){let k=[...p],A=0;for(const I of _){const E=f.indexOf(Od(I));E===-1?(k.splice(A++,0,I),N.push(I)):A=E+N.length+1}return r==="wait"&&N.length&&(k=N),C(Xb(k)),w(p),null}const{forceRender:S}=m.useContext(Qg);return i.jsx(i.Fragment,{children:_.map(k=>{const A=Od(k),I=a&&!u?!1:p===_||f.includes(A),E=()=>{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&&(S?.(),C(x.current),a&&h?.(),s&&s())};return i.jsx($B,{isPresent:I,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:o,mode:r,root:c,onExitComplete:I?void 0:E,anchorX:l,anchorY:d,children:k},A)})})},pN=m.createContext({strict:!1}),Zb={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 Jb=!1;function WB(){if(Jb)return;const e={};for(const t in Zb)e[t]={isEnabled:n=>Zb[t].some(s=>!!n[s])};B1(e),Jb=!0}function fN(){return WB(),IH()}function UB(e){const t=fN();for(const n in e)t[n]={...t[n],...e[n]};B1(t)}const gh=m.createContext({});function KB(e,t){if(mh(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Fl(n)?n:void 0,animate:Fl(s)?s:void 0}}return e.inherit!==!1?t:{}}function qB(e){const{initial:t,animate:n}=KB(e,m.useContext(gh));return m.useMemo(()=>({initial:t,animate:n}),[Qb(t),Qb(n)])}function Qb(e){return Array.isArray(e)?e.join(" "):e}const _x=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function mN(e,t,n){for(const s in t)!cs(t[s])&&!Y1(s,n)&&(e[s]=t[s])}function YB({transformTemplate:e},t){return m.useMemo(()=>{const n=_x();return Cx(n,t,e),Object.assign({},n.vars,n.style)},[t])}function XB(e,t){const n=e.style||{},s={};return mN(s,n,e),Object.assign(s,YB(e,t)),s}function ZB(e,t){const n={},s=XB(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 gN=()=>({..._x(),attrs:{}});function JB(e,t,n,s){const o=m.useMemo(()=>{const r=gN();return Z1(r,t,Q1(s),e.transformTemplate,e.style),{...r.attrs,style:{...r.style}}},[t]);if(e.style){const r={};mN(r,e.style,e),o.style={...r,...o.style}}return o}const QB=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 wu(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||QB.has(e)}function e$(e,t){return e.startsWith("on")?!wu(e):t?.(e)??!wu(e)}function t$(e,t,n,s){const o={};for(const r in e)r==="values"&&typeof e.values=="object"||cs(e[r])||(e$(r,s)||n===!0&&wu(r)||!t&&!wu(r)||e.draggable&&r.startsWith("onDrag"))&&(o[r]=e[r]);return o}const n$=["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 Nx(e){return typeof e!="string"||e.includes("-")?!1:!!(n$.indexOf(e)>-1||/[A-Z]/u.test(e))}function s$(e,t,n,{latestValues:s},o,r=!1,a,l){const c=(a??Nx(e)?JB:ZB)(t,s,o,e),u=t$(t,typeof e=="string",r,l),h=e!==m.Fragment?{...u,...c,ref:n}:{},{children:p}=t,f=m.useMemo(()=>cs(p)?p.get():p,[p]);return m.createElement(e,{...h,children:f})}function i$({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,o){return{latestValues:o$(n,s,o,e),renderState:t()}}function o$(e,t,n,s){const o={},r=s(e,{});for(const p in r)o[p]=Oc(r[p]);let{initial:a,animate:l}=e;const d=mh(e),c=F1(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"&&!fh(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f<p.length;f++){const g=fx(e,p[f]);if(g){const{transitionEnd:x,transition:v,...y}=g;for(const b in y){let w=y[b];if(Array.isArray(w)){const _=u?w.length-1:0;w=w[_]}w!==null&&(o[b]=w)}for(const b in x)o[b]=x[b]}}}return o}const xN=e=>(t,n)=>{const s=m.useContext(gh),o=m.useContext(uh),r=()=>i$(e,t,s,o);return n?r():ex(r)},r$=xN({scrapeMotionValuesFromProps:kx,createRenderState:_x}),a$=xN({scrapeMotionValuesFromProps:eN,createRenderState:gN}),l$=Symbol.for("motionComponentSymbol");function d$(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 vN=m.createContext({});function Gr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function c$(e,t,n,s,o,r){const{visualElement:a}=m.useContext(gh),l=m.useContext(pN),d=m.useContext(uh),c=m.useContext(jx),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(vN);g&&!g.projection&&o&&(g.type==="html"||g.type==="svg")&&u$(p.current,n,o,x);const v=m.useRef(!1);m.useInsertionEffect(()=>{g&&v.current&&g.update(n,d)});const y=n[T1],b=m.useRef(!!y&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(y)&&window.MotionHasOptimisedAnimation?.(y));return du(()=>{f.current=!0,g&&(v.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),b.current&&g.animationState&&g.animationState.animateChanges())}),m.useEffect(()=>{g&&(!b.current&&g.animationState&&g.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(y)}),b.current=!1),g.enteringChildren=void 0)}),g}function u$(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:bN(e.parent)),e.projection.setOptions({layoutId:o,layout:r,alwaysMeasureLayout:!!a||l&&Gr(l),visualElement:e,animationType:typeof r=="string"?r:"both",initialPromotionConfig:s,crossfade:h,layoutScroll:d,layoutRoot:c,layoutAnchor:u})}function bN(e){if(e)return e.options.allowProjection!==!1?e.projection:bN(e.parent)}function gp(e,{forwardMotionProps:t=!1,type:n}={},s,o){s&&UB(s);const r=n?n==="svg":Nx(e),a=r?a$:r$;function l(c,u){let h;const p={...m.useContext(jx),...c,layoutId:h$(c)},{isStatic:f,isValidProp:g}=p,x=qB(c),v=a(c,f);if(!f&&typeof window<"u"){p$();const y=f$(p);h=y.MeasureLayout,x.visualElement=c$(e,v,p,o,y.ProjectionNode,r)}return i.jsxs(gh.Provider,{value:x,children:[h&&x.visualElement?i.jsx(h,{visualElement:x.visualElement,...p}):null,s$(e,c,d$(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[l$]=e,d}function h$({layoutId:e}){const t=m.useContext(Qg).id;return t&&e!==void 0?t+"-"+e:e}function p$(e,t){m.useContext(pN).strict}function f$(e){const t=fN(),{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 m$(e,t){if(typeof Proxy>"u")return gp;const n=new Map,s=(r,a)=>gp(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,gp(a,void 0,e,t)),n.get(a))})}const g$=(e,t)=>t.isSVG??Nx(e)?new UH(t):new HH(t,{allowProjection:e!==m.Fragment});class x$ extends Bo{constructor(t){super(t),t.animationState||(t.animationState=ZH(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();fh(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 v$=0;class b$ extends Bo{constructor(){super(...arguments),this.id=v$++,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 w$={animation:{Feature:x$},exit:{Feature:b$}};function Sd(e){return{point:{x:e.pageX,y:e.pageY}}}const y$=e=>t=>vx(t)&&e(t,Sd(t));function ml(e,t,n,s){return Hl(e,t,y$(n),s)}const wN=({current:e})=>e?e.ownerDocument.defaultView:null,ew=(e,t)=>Math.abs(e-t);function S$(e,t){const n=ew(e.x,t.x),s=ew(e.y,t.y);return Math.sqrt(n**2+s**2)}const tw=new Set(["auto","scroll"]);class yN{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=zd(this.lastRawMoveEventInfo,this.transformPagePoint));const g=xp(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,v=S$(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!v)return;const{point:y}=g,{timestamp:b}=ds;this.history.push({...y,timestamp:b});const{onStart:w,onMove:_}=this.handlers;x||(w&&w(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),_&&_(this.lastMoveEvent,g)},this.handlePointerMove=(g,x)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=zd(x,this.transformPagePoint),_n.update(this.updatePoint,!0)},this.handlePointerUp=(g,x)=>{this.end();const{onEnd:v,onSessionEnd:y,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=xp(g.type==="pointercancel"?this.lastMoveEventInfo:zd(x,this.transformPagePoint),this.history);this.startEvent&&v&&v(g,w),y&&y(g,w)},!vx(t))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=o||window;const d=Sd(t),c=zd(d,this.transformPagePoint),{point:u}=c,{timestamp:h}=ds;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,xp(c,this.history));const f={passive:!0,capture:!0};this.removeListeners=bd(ml(this.contextWindow,"pointermove",this.handlePointerMove,f),ml(this.contextWindow,"pointerup",this.handlePointerUp,f),ml(this.contextWindow,"pointercancel",this.handlePointerUp,f)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(tw.has(s.overflowX)||tw.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(),Ro(this.updatePoint)}}function zd(e,t){return t?{point:t(e.point)}:e}function nw(e,t){return{x:e.x-t.x,y:e.y-t.y}}function xp({point:e},t){return{point:e,delta:nw(e,SN(t)),offset:nw(e,C$(t)),velocity:k$(t,.1)}}function C$(e){return e[0]}function SN(e){return e[e.length-1]}function k$(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const o=SN(e);for(;n>=0&&(s=e[n],!(o.timestamp-s.timestamp>Gs(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&o.timestamp-s.timestamp>Gs(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 j$(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 sw(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 _$(e,{top:t,left:n,bottom:s,right:o}){return{x:sw(e.x,n,o),y:sw(e.y,t,s)}}function iw(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 N$(e,t){return{x:iw(e.x,t.x),y:iw(e.y,t.y)}}function T$(e,t){let n=.5;const s=ks(e),o=ks(t);return o>s?n=zl(t.min,t.max-s,e.min):s>o&&(n=zl(e.min,e.max-o,t.min)),Gi(0,1,n)}function D$(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 dm=.35;function I$(e=dm){return e===!1?e=0:e===!0&&(e=dm),{x:ow(e,"left","right"),y:ow(e,"top","bottom")}}function ow(e,t,n){return{min:rw(e,t),max:rw(e,n)}}function rw(e,t){return typeof e=="number"?e:e[t]||0}const E$=new WeakMap;class P${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=Yn(),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(Sd(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=aH(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),Ti(y=>{let b=this.getAxisMotionValue(y).get()||0;if(Oi.test(b)){const{projection:w}=this.visualElement;if(w&&w.layout){const _=w.layout.layoutBox[y];_&&(b=ks(_)*(parseFloat(b)/100))}}this.originPoint[y]=b}),x&&_n.update(()=>x(h,p),!1,!0),em(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=M$(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 yN(t,{onSessionStart:r,onStart:a,onMove:l,onSessionEnd:d,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:s,contextWindow:wN(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||!Gd(t,o,this.currentDirection))return;const r=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=j$(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&&Gr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=_$(s.layoutBox,t):this.constraints=!1,this.elastic=I$(n),o!==this.constraints&&!Gr(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&Ti(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=D$(s.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Gr(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=RH(s,o.root,this.visualElement.getTransformPagePoint());let a=N$(o.layout.layoutBox,r);if(n){const l=n(PH(a));this.hasMutatedConstraints=!!l,l&&(a=V1(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:o,dragTransition:r,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),d=this.constraints||{},c=Ti(u=>{if(!Gd(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 em(this.visualElement,t),s.start(px(t,s,0,n,this.visualElement,!1))}stopAnimation(){Ti(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){Ti(n=>{const{drag:s}=this.getProps();if(!Gd(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(!Gr(n)||!s||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Ti(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const d=l.get();o[a]=T$({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(),Ti(a=>{if(!Gd(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;E$.set(this.visualElement,this);const t=this.visualElement.current,n=ml(t,"pointerdown",c=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=c.target,f=p!==t&&pH(p);u&&h&&!f&&this.start(c)});let s;const o=()=>{const{dragConstraints:c}=this.getProps();Gr(c)&&c.current&&(this.constraints=this.resolveRefConstraints(),s||(s=A$(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=Hl(window,"resize",()=>this.scalePositionWithinConstraints()),d=r.addEventListener("didUpdate",(({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Ti(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=dm,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:o,dragConstraints:r,dragElastic:a,dragMomentum:l}}}function aw(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function A$(e,t,n){const s=fb(e,aw(n)),o=fb(t,aw(n));return()=>{s(),o()}}function Gd(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function M$(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class R$ extends Bo{constructor(t){super(t),this.removeGroupControls=Js,this.removeListeners=Js,this.controls=new P$(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 vp=e=>(t,n)=>{e&&_n.update(()=>e(t,n),!1,!0)};class L$ extends Bo{constructor(){super(...arguments),this.removePointerDownListener=Js}onPointerDown(t){this.session=new yN(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:wN(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:o}=this.node.getProps();return{onSessionStart:vp(t),onStart:vp(n),onMove:vp(s),onEnd:(r,a)=>{delete this.session,o&&_n.postRender(()=>o(r,a))}}}mount(){this.removePointerDownListener=ml(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 bp=!1;class O$ 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),bp&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),zc.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}),bp=!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(),xx.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:o}=t;bp=!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 CN(e){const[t,n]=hN(),s=m.useContext(Qg);return i.jsx(O$,{...e,layoutGroup:s,switchLayoutGroup:m.useContext(vN),isPresent:t,safeToRemove:n})}const z$={pan:{Feature:L$},drag:{Feature:R$,ProjectionNode:uN,MeasureLayout:CN}};function lw(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,Sd(t)))}class G$ extends Bo{mount(){const{current:t}=this.node;t&&(this.unmount=dH(t,(n,s)=>(lw(this.node,s,"Start"),o=>lw(this.node,o,"End"))))}unmount(){}}class F$ extends Bo{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=bd(Hl(this.node.current,"focus",()=>this.onFocus()),Hl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function dw(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,Sd(t)))}class H$ extends Bo{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=mH(t,(o,r)=>(dw(this.node,r,"Start"),(a,{success:l})=>dw(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const cm=new WeakMap,wp=new WeakMap,B$=e=>{const t=cm.get(e.target);t&&t(e)},$$=e=>{e.forEach(B$)};function V$({root:e,...t}){const n=e||document;wp.has(n)||wp.set(n,{});const s=wp.get(n),o=JSON.stringify(t);return s[o]||(s[o]=new IntersectionObserver($$,{root:e,...t})),s[o]}function W$(e,t,n){const s=V$(t);return cm.set(e,n),s.observe(e),()=>{cm.delete(e),s.unobserve(e)}}const U$={some:0,all:1};class K$ extends Bo{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:U$[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=W$(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(q$(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function q$({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Y$={inView:{Feature:K$},tap:{Feature:H$},focus:{Feature:F$},hover:{Feature:G$}},X$={layout:{ProjectionNode:uN,MeasureLayout:CN}},Z$={...w$,...Y$,...z$,...X$},Rs=m$(Z$,g$);function J$(){!Sx.current&&H1();const[e]=m.useState(gu.current);return e}const Q$=[["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"}]],eV=ot("alarm-clock",Q$);const tV=[["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"}]],Bl=ot("archive-restore",tV);const nV=[["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"}]],Ai=ot("archive",nV);const sV=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],iV=ot("arrow-down-to-line",sV);const oV=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],rV=ot("arrow-up-right",oV);const aV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]],lV=ot("ban",aV);const dV=[["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"}]],cw=ot("bell-off",dV);const cV=[["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"}]],uV=ot("bookmark-plus",cV);const hV=[["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"}]],kN=ot("bug",hV);const pV=[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]],fV=ot("chevrons-down-up",pV);const mV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],gV=ot("circle-dot",mV);const xV=[["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"}]],vV=ot("circle-play",xV);const bV=[["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"}]],wV=ot("circle-question-mark",bV);const yV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],SV=ot("circle-stop",yV);const CV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Tx=ot("circle",CV);const kV=[["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"}]],jN=ot("clipboard-check",kV);const jV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],_N=ot("clock",jV);const _V=[["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"}]],um=ot("code-xml",_V);const NV=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],TV=ot("code",NV);const DV=[["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"}]],IV=ot("coins",DV);const EV=[["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"}]],PV=ot("compass",EV);const AV=[["path",{d:"m15 10 5 5-5 5",key:"qqa56n"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]],MV=ot("corner-down-right",AV);const RV=[["path",{d:"M14 9 9 4 4 9",key:"1af5af"}],["path",{d:"M20 20h-7a4 4 0 0 1-4-4V4",key:"1blwi3"}]],LV=ot("corner-left-up",RV);const OV=[["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"}]],zV=ot("cpu",OV);const GV=[["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"}]],FV=ot("database",GV);const HV=[["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"}]],xh=ot("ellipsis",HV);const BV=[["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"}]],$V=ot("file-diff",BV);const VV=[["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"}]],WV=ot("file-pen",VV);const UV=[["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"}]],KV=ot("file-plus",UV);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:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],YV=ot("file",qV);const XV=[["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"}]],ZV=ot("fold-horizontal",XV);const JV=[["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"}]],QV=ot("folder-git-2",JV);const e6=[["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"}]],hm=ot("folder-plus",e6);const t6=[["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"}]],Cd=ot("folder",t6);const n6=[["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"}]],s6=ot("folders",n6);const i6=[["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"}]],o6=ot("git-branch-plus",i6);const r6=[["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"}]],Mi=ot("git-branch",r6);const a6=[["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"}]],l6=ot("git-commit-horizontal",a6);const d6=[["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"}]],Dx=ot("git-compare",d6);const c6=[["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"}]],uw=ot("hand",c6);const u6=[["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"}]],h6=ot("hourglass",u6);const p6=[["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"}]],hw=ot("house",p6);const f6=[["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"}]],NN=ot("image-off",f6);const m6=[["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"}]],vh=ot("image-plus",m6);const g6=[["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"}]],x6=ot("images",g6);const v6=[["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"}]],Ix=ot("inbox",v6);const b6=[["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"}]],w6=ot("list-tree",b6);const y6=[["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"}]],Ex=ot("list",y6);const S6=[["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"}]],C6=ot("mail",S6);const k6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],j6=ot("menu",k6);const _6=[["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=ot("message-circle",_6);const N6=[["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"}]],Lo=ot("message-square-plus",N6);const T6=[["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"}]],ha=ot("messages-square",T6);const D6=[["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"}]],I6=ot("package-minus",D6);const E6=[["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"}]],Px=ot("panel-left-close",E6);const P6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],TN=ot("panel-left",P6);const A6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],DN=ot("panel-right",A6);const M6=[["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"}]],R6=ot("pause",M6);const L6=[["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"}]],yu=ot("pin-off",L6);const O6=[["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=ot("pin",O6);const z6=[["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"}]],G6=ot("repeat",z6);const F6=[["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"}]],$o=ot("rotate-ccw-clock",F6);const H6=[["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"}]],Ax=ot("send",H6);const B6=[["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"}]],IN=ot("skip-forward",B6);const $6=[["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"}]],V6=ot("sliders-horizontal",$6);const W6=[["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"}]],U6=ot("square-dashed",W6);const K6=[["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"}]],EN=ot("square-pen",K6);const q6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]],PN=ot("square-slash",q6);const Y6=[["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"}]],X6=ot("square-x",Y6);const Z6=[["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"}]],J6=ot("tag",Z6);const Q6=[["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"}]],Ta=ot("target",Q6);const e4=[["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"}]],AN=ot("text-search",e4);const t4=[["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"}]],pa=ot("undo-2",t4);const n4=[["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"}]],s4=ot("unfold-horizontal",n4);const i4=[["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"}]],o4=ot("user-minus",i4);const r4=[["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"}]],$l=ot("user-plus",r4);const a4=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],l4=ot("user-round",a4);const d4=[["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"}]],c4=ot("wallet",d4),yp=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e;function u4(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:yp(s,16e3)};if(o!==void 0&&(d.rewrittenCommand=yp(o,16e3)),l!==void 0&&(d.reason=yp(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 h4=15e3;function p4(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 MN(e){if(e.length===0)return;const t="0 0, 100% 0, 100% 100%, 0 100%, 0 0",n=e.map(s=>`${f4(s).map(([o,r])=>`${fw(o)}px ${fw(r)}px`).join(", ")}, 0 0`);return`polygon(evenodd, ${[t,...n].join(", ")})`}const pw=6,fw=e=>Math.round(e*100)/100;function f4({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:pw+1},(f,g)=>{const x=(p+90*g/pw)*Math.PI/180;return[u+l*Math.cos(x),h+l*Math.sin(x)]}));return[...c,c[0]]}function mw(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 m4(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 g4(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 x4(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 v4=/^\[Referenced past chat "(.+)" — transcript file: (.+) \(pi session jsonl; read it if relevant\)\]$/,b4=/^@(\S.*)$/;function w4(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"?x4(t.label,t.sessionFile):YP(t)).join("")}function gw(e,t){qv.lastIndex=t,Yv.lastIndex=t;const n=qv.exec(e),s=Yv.exec(e),o=n?{index:n.index,length:n[0].length,segment:{type:"chat",label:n[1],sessionFile:n[2]}}:null,r=s?qP(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 y4(e){const t=[];let n=0,s=gw(e,0);for(;s;){const r=e.slice(n,s.index);for(const a of xw(r))a.type==="text"&&a.text===""||t.push(a);t.push(s.segment),n=s.index+s.length,s=gw(e,n)}const o=e.slice(n);if(o||t.length===0)for(const r of xw(o))r.type==="text"&&r.text===""&&t.length>0||t.push(r);return t}const S4=/^(?:[A-Za-z]:[\\/])?(?:[\p{L}\p{N}_./\\-]*\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\p{L}\p{N}_./\\-]+[\\/])$/u,C4=/^"([^"\n]*(?:\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\\/]))"/,k4=/#L\d+(?:-L\d+)?$/;function j4(e){return e.replace(k4,"")}function bh(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).at(-1)||e}function xw(e){return Pk(e).flatMap(t=>t.type==="file"?[t]:_4(t.text))}function _4(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
|
-
`?C4.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&&S4.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 N4(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=v4.exec(a);if(l){o.unshift({label:l[1],sessionFile:l[2]});continue}if(b4.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 vw(e){const t=w4(e.segments).trim(),n=e.segments.filter(o=>o.type!=="text").map(o=>o.type==="file"?{kind:"file",id:o.path,label:bh(o.path),relativePath:j4(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 T4={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 D4(){const e=Ak(),t=Se(x=>x.backgroundImageEnabled),n=Se(x=>x.backgroundSourceType),s=Se(x=>x.backgroundImagePath),o=Se(x=>x.backgroundFolderPath),r=Se(x=>x.backgroundUrlPath),a=Se(x=>x.backgroundRandomEnabled),l=Se(x=>x.backgroundRandomInterval),d=Se(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(I4,{children:[e?.source==="user"&&i.jsx(E4,{state:{sourceType:n,imagePath:s,folderPick:f,urlPath:r,tick:c},look:e}),e?.source==="theme"&&i.jsxs(ON,{look:e,children:[i.jsx(zN,{image:"var(--enso-asset-background)",look:e}),i.jsx(GN,{mask:e.mask})]})]})}function I4({children:e}){const t=xn(s=>s.browserHoles),n=MN(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 RN=({blur:e,brightness:t,saturation:n})=>`blur(${e}px) brightness(${t}) saturate(${n})`,LN=({blur:e})=>e>0?`-${e*2}px`:"0";function E4({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:wf(s),video:Vh(s)};if(n==="folder"&&o)return{src:wf(o),video:Vh(o)};if(n==="url"){const p=r.trim();if(/^https?:\/\//i.test(p))return{src:XP(p,a),video:Vh(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(ON,{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:RN(t),transition:"filter 0.3s ease"}},u):i.jsx(zN,{image:`url("${u}")`,look:t},u),i.jsx(GN,{mask:t.mask})]})}function ON({look:e,children:t}){return i.jsx("div",{"data-slot":"background-media",className:"absolute inset-0",style:{opacity:ZP(e.opacity).wallpaperOpacity},children:t})}function zN({image:e,look:t}){return i.jsx("div",{className:"absolute",style:{inset:LN(t),backgroundImage:e,...T4[t.size],filter:RN(t),transition:"filter 0.3s ease"}})}function GN({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 Su(e,t,n,s){return{left:e,top:t,right:n,bottom:s,x:e,y:t,width:n-e,height:s-t}}function P4(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function FN(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(P4(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:Su(s,o,r,a)}}function HN(e,t,n){return e.findIndex(s=>t>s.left-2&&t<s.right+2&&n>s.top-2&&n<s.bottom+2)}function bw(e){return Su(e.left,e.top,e.right,e.bottom)}function A4(e,t,n){const{lines:s}=FN(e.getClientRects());if(s.length<2)return;const o=HN(s,t,n);return{x:t,y:n,lineIndex:o===-1?void 0:o,element:e}}function M4(e,t,n){const{lines:s,fallback:o}=FN(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 bw(s[n.lineIndex]);if(r!=null&&a!=null){const g=HN(s,r,a);if(g!==-1)return bw(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 Su(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 Su(c,p.top,u,f.bottom)}function R4(e){return"contextElement"in e&&e.contextElement?e.contextElement:JP(e)?e:void 0}function L4(e,t){function n(o){BN(e,o.currentTarget,o.clientX,o.clientY)}function s(o){t||n(o)}return{onFocus(){e.current=void 0},onMouseEnter:s,onMouseMove:s}}function BN(e,t,n,s){const o=A4(t,n,s);return e.current=o,o}function O4(e){return{name:"inline",async fn(t){const n=t.elements.reference;if(typeof n?.getClientRects!="function")return{};const s=R4(n),o=e.current,r=o?.element===n||o?.element===s?o:void 0,a=M4(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 ww(){const{t:e}=J(),[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(Mk,{className:"h-3.5 w-3.5 shrink-0 text-blue-500"}):i.jsx(od,{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(ln,{className:"h-3.5 w-3.5"})})]}),i.jsx(QP,{open:l,onOpenChange:d,status:t})]})}const Sp="enso.zoomBanner.dismissedPercent";function z4(e,t){return e!==100&&e!==t}function G4(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function Cp(){return window.electronAPI.window.getZoomPercent()}function yw(){const{t:e}=J(),[t,n]=m.useState(Cp),[s,o]=m.useState(()=>G4(localStorage.getItem(Sp)));return m.useEffect(()=>{const r=()=>n(Cp());return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),z4(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:mi("mod+0")})}),i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.window.resetZoom(),localStorage.removeItem(Sp),o(null),n(Cp())},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(Sp,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(ln,{className:"h-3.5 w-3.5"})})]})}):null}function F4(e,t){return[t,...e.filter(n=>n.parentId===t.id).sort((n,s)=>n.createdAt-s.createdAt)]}function H4(e,t){return(t.activeThreadId?e.find(s=>s.id===t.activeThreadId&&s.parentId===t.id):void 0)??t}const B4=10,$N=e=>[...e].sort((t,n)=>n.activityAt-t.activityAt);function VN(e,t,n=B4){const s=$N(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 Sw(e,t,n){const s=t.trim().toLowerCase();return $N(e).filter(o=>(n==="all"||(n==="unread"?o.unread:o.running))&&(!s||`${o.title}
|
|
20
|
-
${o.preview??""}`.toLowerCase().includes(s)))}function Cu({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:W("relative z-20 shrink-0",s?"w-0":n?"w-[8px]":"w-px bg-border"),children:[i.jsx("div",{onMouseDown:l,className:W("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 $4={"external-send":"Protected: external send",delete:"Protected: delete",payment:"Protected: payment",deploy:"Protected: deploy / production",secret:"Protected: secrets",destructive:"Protected: destructive command"};function WN(e,t){return t($4[e])}const UN={exec:"Isolated sandbox",codemode:"Isolated sandbox",tool_search:"Tool search",apply_patch:"Apply patch",explore_mark:"Explore mark",explore_fold:"Explore fold",turn_discard:"Turn discard",turn_recall:"Turn recall",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",todo:"Todos"};function br(e,t){const n=UN[e];return n?t(n):e}const V4={report:"Read report",wait:"Wait",stop:"Stop",dismiss:"Dismiss agent",list:"List agents"};function Mx(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 Rx({remainingMs:e,expiredLabel:t}){const{t:n}=J();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 W4={command:Fo,"file-edit":WV,"file-write":KV,mcp:Rk};function U4({kind:e,summary:t}){const[n,s]=m.useState(null);m.useEffect(()=>{if(e!=="command")return;let r=!0;return tA(t,"shellscript").then(a=>{r&&s(a)}),()=>{r=!1}},[e,t]);const o=i.jsx(Lk,{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 K4={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 Vl({approvals:e,onRespond:t,allowSession:n=!0,handoff:s=!0,clockOffset:o}){const{t:r}=J(),[a,l]=m.useState(null),d=e[0],c=Mx(d?.phase==="reviewing"?void 0:d?.expiresAt,o);if(!d)return null;const u=W4[d.kind]??sa,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",{"data-enso":"approval",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(sa,{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&&eA(d.toolCallId)?`${r("Isolated sandbox")} › ${br(d.tool,r)}`:br(d.tool,r)})]}),d.protected&&i.jsx("span",{className:"shrink-0 rounded bg-destructive/15 px-1.5 text-[10px] text-destructive",children:WN(d.protected,r)}),i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[i.jsx(Rx,{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(K4[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(U4,{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 Cw(e){return e>=0&&e<9?String(e+1):null}function q4(e,t){const n=t===void 0?-1:e?.indexOf(t)??-1;return n>=0?n:0}function Y4(e,t,n){return n==="ArrowDown"?Math.min(e+1,t-1):n==="ArrowUp"?Math.max(e-1,0):null}function wh({asks:e,onAnswer:t,clockOffset:n,autoFocus:s=!0}){const{t:o}=J(),r=m.useRef(null),a=m.useRef([]),[l,d]=m.useState(""),[c,u]=m.useState(null),[h,p]=m.useState(()=>new Set),f=e[0],g=f?.requestId,x=Mx(f?.expiresAt,n),v=g!==void 0&&h.has(g),y=f?.options,b=f?.recommended,w=S=>{const k=a.current[S];y&&S<y.length&&k?k.focus():r.current?.focus()};if(m.useEffect(()=>{if(!s||!g||v)return;const S=q4(y,b),k=a.current[S];y&&S<y.length&&k?k.focus():r.current?.focus()},[s,g,v]),!f)return null;const _=c===f.requestId||x!==void 0&&x<=0,C=S=>{S.trim()&&(u(f.requestId),d(""),t(f.requestId,S.trim()))},N=()=>p(S=>S.has(f.requestId)?S:new Set(S).add(f.requestId));return v?i.jsxs("button",{type:"button","data-enso":"ask-later",onClick:()=>p(S=>{const k=new Set(S);return k.delete(f.requestId),k}),className:"mb-1 flex w-full items-center gap-2 rounded-lg border border-dashed border-border/60 px-2.5 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground",children:[i.jsx(Xv,{className:"h-3.5 w-3.5 shrink-0 text-blue-500"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:f.question}),e.length>1&&i.jsxs("span",{className:"shrink-0 text-[10px] tabular-nums",children:["1/",e.length]}),i.jsx(un,{className:"h-3 w-3 shrink-0"})]}):i.jsxs("div",{"data-enso":"ask",className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",onKeyDown:S=>{if(S.nativeEvent.isComposing||_)return;if(S.key==="Escape"){S.preventDefault(),N();return}const k=S.target,A=(y?.length??0)+1,I=k===r.current?A-1:a.current.indexOf(k),E=I>=0?Y4(I,A,S.key):null;if(E!==null){S.preventDefault(),w(E);return}if(k instanceof HTMLInputElement&&(k.value.length>0||S.key==="Enter"))return;const D=Number(S.key)-1,T=y?.[D];if(Cw(D)&&T){S.preventDefault(),C(T);return}k instanceof HTMLButtonElement&&I>=0&&(S.key==="Process"?r.current?.focus():S.key.length===1&&S.key!==" "&&!S.metaKey&&!S.ctrlKey&&!S.altKey&&(S.preventDefault(),d(H=>H+S.key),r.current?.focus()))},children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Xv,{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:f.question}),i.jsx("button",{type:"button",onClick:N,className:"shrink-0 rounded-md px-1.5 py-0.5 text-[10px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:o("Later")}),i.jsx(Rx,{remainingMs:x,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]})]}),y&&y.length>0&&i.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:y.map((S,k)=>{const A=Cw(k);return i.jsxs("button",{ref:I=>{a.current[k]=I},type:"button",disabled:_,onClick:()=>C(S),className:"flex items-center gap-2 rounded-md border border-border/60 px-2 py-1 text-left text-xs text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus:border-ring focus:bg-muted focus:text-foreground disabled:opacity-50",children:[A&&i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded bg-muted font-mono text-[10px] text-muted-foreground",children:A}),i.jsx("span",{className:"min-w-0 flex-1",children:S}),S===b&&i.jsx("span",{className:"shrink-0 rounded bg-success/15 px-1.5 text-[10px] text-success",children:o("Recommended")})]},S)})}),i.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[i.jsx("input",{ref:r,value:l,onChange:S=>d(S.target.value),onKeyDown:S=>{S.nativeEvent.isComposing||S.key==="Enter"&&C(l)},disabled:_,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:_||!l.trim(),onClick:()=>C(l),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(Ax,{className:"h-3.5 w-3.5"})})]})]})}const yh=0,Vo=1,Da=2,KN=4;function kw(e){return()=>e}function X4(e){e()}function qN(e,t){return n=>e(t(n))}function jw(e,t){return()=>e(t)}function Z4(e,t){return n=>e(t,n)}function Lx(e){return e!==void 0}function J4(...e){return()=>{e.map(X4)}}function Ia(){}function Sh(e,t){return t(e),e}function Q4(e,t){return t(e)}function Rn(...e){return e}function mn(e,t){return e(Vo,t)}function Ut(e,t){e(yh,t)}function Ox(e){e(Da)}function Ln(e){return e(KN)}function wt(e,t){return mn(e,Z4(t,yh))}function fi(e,t){const n=e(Vo,s=>{n(),t(s)});return n}function _w(e){let t,n;return s=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{s(t)},e)}}function YN(e,t){return e===t}function An(e=YN){let t;return n=>s=>{e(t,s)||(t=s,n(s))}}function Lt(e){return t=>n=>{e(n)&&t(n)}}function ft(e){return t=>qN(t,e)}function Ii(e){return t=>()=>{t(e)}}function Ue(e,...t){const n=eW(...t);return((s,o)=>{switch(s){case Da:Ox(e);return;case Vo:return mn(e,n(o))}})}function Ri(e,t){return n=>s=>{n(t=e(t,s))}}function wr(e){return t=>n=>{e>0?e--:t(n)}}function ao(e){let t=null,n;return s=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,s(t)},e))}}function Qt(...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;mn(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 eW(...e){return t=>e.reduceRight(Q4,t)}function tW(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=mn(e,r),t):(s(),Ia);case Da:s(),n=null;return}}}function Xe(e){let t=e;const n=rn();return((s,o)=>{switch(s){case yh:t=o;break;case Vo:{o(t);break}case KN:return t}return n(s,o)})}function fs(e,t){return Sh(Xe(t),n=>wt(e,n))}function rn(){const e=[];return((t,n)=>{switch(t){case yh:e.slice().forEach(s=>{s(n)});return;case Da:e.splice(0);return;case Vo:return e.push(n),()=>{const s=e.indexOf(n);s>-1&&e.splice(s,1)}}})}function Fs(e){return Sh(rn(),t=>wt(e,t))}const nW={singleton:!0};function hn(e,t=[],n=nW){const{singleton:s}=n;return{constructor:e,dependencies:t,id:sW(),singleton:s}}const sW=()=>Symbol("id");function iW(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=rn(),n=Array.from({length:e.length});let s=0;const o=2**e.length-1;return e.forEach((r,a)=>{const l=2**a;mn(r,d=>{n[a]=d,s|=l,s===o&&Ut(t,n)})}),function(r,a){switch(r){case Da:{Ox(t);return}case Vo:return s===o&&a(n),mn(t,a)}}}function Rt(e,t=YN){return Ue(e,An(t))}function pm(...e){return function(t,n){switch(t){case Da:return;case Vo:return J4(...e.map(s=>mn(s,n)))}}}const es={DEBUG:0,INFO:1,WARN:2,ERROR:3},oW={[es.DEBUG]:"debug",[es.ERROR]:"error",[es.INFO]:"log",[es.WARN]:"warn"},rW=()=>typeof globalThis>"u"?window:globalThis,Wo=hn(()=>{const e=Xe(es.ERROR);return{log:Xe((t,n,s=es.INFO)=>{const o=rW().VIRTUOSO_LOG_LEVEL??Ln(e);s>=o&&console[oW[s]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function aW(e){return"self"in e?e.document.documentElement:e}function XN(e){const t=aW(e);return t.ownerDocument.defaultView.getComputedStyle(t).direction==="rtl"}function cr(e,t){return XN(e)?-t:t}function Nw(e,t){return XN(e)?-t:t}function Cr(e,t,n){return zx(e,t,n).callbackRef}function zx(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 lW(e,t,n,s,o,r,a,l,d){const c=Ne.useCallback(u=>{const h=dW(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?cr(a,a.scrollLeft):a.scrollTop:f?l?cr(g,g.scrollX||g.document.documentElement.scrollLeft):g.scrollY||g.document.documentElement.scrollTop:l?cr(p,p.scrollLeft):p.scrollTop;s({scrollHeight:x,scrollTop:Math.max(y,0),viewportHeight:v}),r?.(l?Tw("column-gap",getComputedStyle(u).columnGap,o):Tw("row-gap",getComputedStyle(u).rowGap,o)),h!==null&&e(h)},[e,t,o,r,a,s,l]);return zx(c,n,d)}function dW(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},es.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 Tw(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,es.WARN),t==="normal"?0:parseInt(t??"0",10)}function ZN(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}=zx(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 Ds=hn(()=>{const e=rn(),t=rn(),n=Xe(0),s=rn(),o=Xe(0),r=rn(),a=rn(),l=Xe(0),d=Xe(0),c=Xe(0),u=Xe(0),h=rn(),p=rn(),f=Xe(!1),g=Xe(!1),x=Xe(!1);return wt(Ue(e,ft(({scrollTop:v})=>v)),t),wt(Ue(e,ft(({scrollHeight:v})=>v)),a),wt(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}),Wl={lvl:0};function JN(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 Cn(e){return e===Wl}function Ul(e,t){if(!Cn(e))return t===e.k?e.v:t<e.k?Ul(e.l,t):Ul(e.r,t)}function yi(e,t,n="k"){if(Cn(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const s=yi(e.r,t,n);return s[0]===-1/0?[e.k,e.v]:s}return yi(e.l,t,n)}function Ls(e,t,n){return Cn(e)?tT(t,n,1):t===e.k?Zn(e,{k:t,v:n}):t<e.k?Dw(Zn(e,{l:Ls(e.l,t,n)})):Dw(Zn(e,{r:Ls(e.r,t,n)}))}function Zr(){return Wl}function Jr(e,t,n){if(Cn(e))return[];const s=yi(e,t)[0];return cW(mm(e,s,n))}function fm(e,t){if(Cn(e))return Wl;const{k:n,l:s,r:o}=e;if(t===n){if(Cn(s))return o;if(Cn(o))return s;const[r,a]=eT(s);return Gc(Zn(e,{k:r,l:QN(s),v:a}))}return t<n?Gc(Zn(e,{l:fm(s,t)})):Gc(Zn(e,{r:fm(o,t)}))}function ur(e){return Cn(e)?[]:[...ur(e.l),{k:e.k,v:e.v},...ur(e.r)]}function mm(e,t,n){if(Cn(e))return[];const{k:s,l:o,r,v:a}=e;let l=[];return s>t&&(l=l.concat(mm(o,t,n))),s>=t&&s<=n&&l.push({k:s,v:a}),s<=n&&(l=l.concat(mm(r,t,n))),l}function Gc(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(kp(t))return nT(Zn(e,{lvl:n-1}));if(!Cn(t)&&!Cn(t.r))return Zn(t.r,{l:Zn(t,{r:t.r.l}),lvl:n,r:Zn(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}if(kp(e))return gm(Zn(e,{lvl:n-1}));if(!Cn(s)&&!Cn(s.l)){const o=s.l,r=kp(o)?s.lvl-1:s.lvl;return Zn(o,{l:Zn(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:gm(Zn(s,{l:o.r,lvl:r}))})}throw new Error("Unexpected empty nodes")}function Zn(e,t){return tT(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 QN(e){return Cn(e.r)?e.l:Gc(Zn(e,{r:QN(e.r)}))}function kp(e){return Cn(e)||e.lvl>e.r.lvl}function eT(e){return Cn(e.r)?[e.k,e.v]:eT(e.r)}function tT(e,t,n,s=Wl,o=Wl){return{k:e,l:s,lvl:n,r:o,v:t}}function Dw(e){return gm(nT(e))}function nT(e){const{l:t}=e;return!Cn(t)&&t.lvl===e.lvl?Zn(t,{r:Zn(e,{l:t.r})}):e}function gm(e){const{lvl:t,r:n}=e;return!Cn(n)&&!Cn(n.r)&&n.lvl===t&&n.r.lvl===t?Zn(n,{l:Zn(e,{r:n.l}),lvl:t+1}):e}function cW(e){return JN(e,({k:t,v:n})=>({index:t,value:n}))}function sT(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Kl(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const Gx=hn(()=>({recalcInProgress:Xe(!1)}),[],{singleton:!0});function iT(e,t,n){return e[ku(e,t,n)]}function ku(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 uW(e,t,n,s){const o=ku(e,t,s),r=ku(e,n,s,o);return e.slice(o,r+1)}function Oo(e,t){return Math.round(e.getBoundingClientRect()[t])}function Ch(e){return!Cn(e.groupOffsetTree)}function Fx({index:e},t){return t===e?0:t<e?-1:1}function hW(){return{groupIndices:[],groupOffsetTree:Zr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Zr()}}function pW(e,t){let n=Cn(e)?0:1/0;for(const s of t){const{endIndex:o,size:r,startIndex:a}=s;if(n=Math.min(n,a),Cn(e)){e=Ls(e,0,r);continue}const l=Jr(e,a-1,o+1);if(l.some(wW(s)))continue;let d=!1,c=!1;for(const{end:u,start:h,value:p}of l)d?(o>=h||r===p)&&(e=fm(e,h)):(c=p!==r,d=!0),u>o&&o>=h&&p!==r&&(e=Ls(e,o+1,p));c&&(e=Ls(e,a,r))}return[e,n]}function fW(e){return e.groupIndex!==void 0}function mW({offset:e},t){return t===e?0:t<e?-1:1}function ql(e,t,n){if(t.length===0)return 0;const{index:s,offset:o,size:r}=iT(t,e,Fx),a=e-s,l=r*a+(a-1)*n+o;return l>0?l+n:l}function oT(e,t){if(!Ch(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function rT(e,t,n){if(fW(e))return t.groupIndices[e.groupIndex]+1;const s=e.index==="LAST"?n:e.index;let o=oT(s,t);return o=Math.max(0,Math.min(n,o)),o}function gW(e,t,n,s=0){return s>0&&(t=Math.max(t,iT(e,s,Fx).offset)),JN(uW(e,t,n,mW),bW)}function xW(e,[t,n,s,o]){t.length>0&&s("received item sizes",t,es.DEBUG);const r=e.sizeTree;let a=r,l=0;if(n.length>0&&Cn(r)&&t.length===2){const p=t[0].size,f=t[1].size;a=n.reduce((g,x)=>Ls(Ls(g,x,p),x+1,f),a)}else[a,l]=pW(a,t);if(a===r)return e;const{lastIndex:d,lastOffset:c,lastSize:u,offsetTree:h}=xm(e.offsetTree,l,a,o);return{groupIndices:n,groupOffsetTree:n.reduce((p,f)=>Ls(p,f,ql(f,h,o)),Zr()),lastIndex:d,lastOffset:c,lastSize:u,offsetTree:h,sizeTree:a}}function vW(e){return ur(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 Iw(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 xm(e,t,n,s){let o=e,r=0,a=0,l=0,d=0;if(t===0)o=[];else{d=ku(o,t-1,Fx),l=o[d].offset;const c=yi(n,t-1);r=c[0],a=c[1],o.length&&o[d].size===yi(n,t)[1]&&(d-=1),o=o.slice(0,d+1)}for(const{start:c,value:u}of Jr(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 bW(e){return{index:e.index,value:e}}function wW(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 yW={offsetHeight:"height",offsetWidth:"width"},Vi=hn(([{log:e},{recalcInProgress:t}])=>{const n=rn(),s=rn(),o=fs(s,0),r=rn(),a=rn(),l=Xe(0),d=Xe([]),c=Xe(void 0),u=Xe(void 0),h=Xe(void 0),p=Xe(void 0),f=Xe((S,k)=>Oo(S,yW[k])),g=Xe(void 0),x=Xe(0),v=hW(),y=fs(Ue(n,Qt(d,e,x),Ri(xW,v),An()),v),b=fs(Ue(d,An(),Ri((S,k)=>({current:k,prev:S.current}),{current:[],prev:[]}),ft(({prev:S})=>S)),[]);wt(Ue(d,Lt(S=>S.length>0),Qt(y,x),ft(([S,k,A])=>{const I=S.reduce((E,D,T)=>Ls(E,D,ql(D,k.offsetTree,A)||T),Zr());return{...k,groupIndices:S,groupOffsetTree:I}})),y),wt(Ue(s,Qt(y),Lt(([S,{lastIndex:k}])=>S<k),ft(([S,{lastIndex:k,lastSize:A}])=>[{endIndex:k,size:A,startIndex:S}])),n),wt(c,u);const w=fs(Ue(c,ft(S=>S===void 0)),!0);wt(Ue(u,Lt(S=>S!==void 0&&Cn(Ln(y).sizeTree)),ft(S=>{const k=Ln(h),A=Ln(d).length>0;return k!==void 0&&k!==0?A?[{endIndex:0,size:k,startIndex:0},{endIndex:1,size:S,startIndex:1}]:[]:[{endIndex:0,size:S,startIndex:0}]})),n),wt(Ue(p,Lt(S=>S!==void 0&&S.length>0&&Cn(Ln(y).sizeTree)),ft(S=>{const k=[];let A=S[0],I=0;for(let E=1;E<S.length;E++){const D=S[E];D!==A&&(k.push({endIndex:E-1,size:A,startIndex:I}),A=D,I=E)}return k.push({endIndex:S.length-1,size:A,startIndex:I}),k})),n),wt(Ue(d,Qt(h,u),Lt(([,S,k])=>S!==void 0&&k!==void 0),ft(([S,k,A])=>{const I=[];for(let E=0;E<S.length;E++){const D=S[E],T=S[E+1];I.push({startIndex:D,endIndex:D,size:k}),T!==void 0&&I.push({startIndex:D+1,endIndex:T-1,size:A})}return I})),n);const _=Fs(Ue(n,Qt(y),Ri(({sizes:S},[k,A])=>({changed:A!==S,sizes:A}),{changed:!1,sizes:v}),ft(S=>S.changed)));mn(Ue(l,Ri((S,k)=>({diff:S.prev-k,prev:k}),{diff:0,prev:0}),ft(S=>S.diff)),S=>{const{groupIndices:k}=Ln(y);if(S>0)Ut(t,!0),Ut(r,S+Iw(S,k));else if(S<0){const A=Ln(b);A.length>0&&(S-=Iw(-S,A)),Ut(a,S)}}),mn(Ue(l,Qt(e)),([S,k])=>{S<0&&k("`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},es.ERROR)});const C=Fs(r);wt(Ue(r,Qt(y),ft(([S,k])=>{const A=k.groupIndices.length>0,I=[],E=k.lastSize;if(A){const D=Ul(k.sizeTree,0);let T=0,H=0;for(;T<S;){const O=k.groupIndices[H],B=k.groupIndices.length===H+1?1/0:k.groupIndices[H+1]-O-1;I.push({endIndex:O,size:D,startIndex:O}),I.push({endIndex:O+1+B-1,size:E,startIndex:O+1}),H++,T+=B+1}const F=ur(k.sizeTree);return T!==S&&F.shift(),F.reduce((O,{k:B,v:Y})=>{let U=O.ranges;return O.prevSize!==0&&(U=[...O.ranges,{endIndex:B+S-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:B+S,prevSize:Y,ranges:U}},{prevIndex:S,prevSize:0,ranges:I}).ranges}return ur(k.sizeTree).reduce((D,{k:T,v:H})=>({prevIndex:T+S,prevSize:H,ranges:[...D.ranges,{endIndex:T+S-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:E,ranges:[]}).ranges})),n);const N=Fs(Ue(a,Qt(y,x),ft(([S,{offsetTree:k},A])=>{const I=-S;return ql(I,k,A)})));return wt(Ue(a,Qt(y,x),ft(([S,k,A])=>{if(k.groupIndices.length>0){if(Cn(k.sizeTree))return k;let E=Zr();const D=Ln(b);let T=0,H=0,F=0;for(;T<-S;){F=D[H];const O=D[H+1]-F-1;H++,T+=O+1}if(E=ur(k.sizeTree).reduce((O,{k:B,v:Y})=>Ls(O,Math.max(0,B+S),Y),E),T!==-S){const O=Ul(k.sizeTree,F);E=Ls(E,0,O);const B=yi(k.sizeTree,-S+1)[1];E=Ls(E,1,B)}return{...k,sizeTree:E,...xm(k.offsetTree,0,E,A)}}const I=ur(k.sizeTree).reduce((E,{k:D,v:T})=>Ls(E,Math.max(0,D+S),T),Zr());return{...k,sizeTree:I,...xm(k.offsetTree,0,I,A)}})),y),{beforeUnshiftWith:C,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:w,unshiftWith:r}},Rn(Wo,Gx),{singleton:!0});function SW(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const aT=hn(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:s,scrollTop:o}])=>{const r=rn(),a=rn(),l=Fs(Ue(r,ft(SW)));return wt(Ue(l,ft(d=>d.totalCount)),n),wt(Ue(l,ft(d=>d.groupIndices)),e),wt(Ue(Bn(o,t,s),Lt(([d,c])=>Ch(c)),ft(([d,c,u])=>yi(c.groupOffsetTree,Math.max(d-u,0),"v")[0]),An(),ft(d=>[d])),a),{groupCounts:r,topItemsIndexes:a}},Rn(Vi,Ds)),Uo=hn(([{log:e}])=>{const t=Xe(!1),n=Fs(Ue(t,Lt(s=>s),An()));return mn(t,s=>{s&&Ln(e)("props updated",{},es.DEBUG)}),{didMount:n,propsReady:t}},Rn(Wo),{singleton:!0}),CW=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function lT(e){const t=typeof e=="number"?{index:e}:{...e};return t.align||(t.align="start"),(!t.behavior||!CW)&&(t.behavior="auto"),t.offset===void 0&&(t.offset=0),t}const kd=hn(([{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=rn(),g=rn(),x=Xe(0);let v=null,y=null,b=null;function w(){v!==null&&(v(),v=null),b!==null&&(b(),b=null),y&&(clearTimeout(y),y=null),Ut(d,!1)}return wt(Ue(f,Qt(n,h,s,x,l,a,p),Qt(e,r,o),ft(([[_,C,N,S,k,A,I,E],D,T,H])=>{const F=lT(_),{align:O,behavior:B,offset:Y}=F,U=S-1,ee=rT(F,C,U);let L=ql(ee,C.offsetTree,D)+A;O==="end"?(L+=T+yi(C.sizeTree,ee)[1]-N+H,ee===U&&(L+=I)):O==="center"?L+=(T+yi(C.sizeTree,ee)[1]-N+H)/2:L-=k,Y!==void 0&&Y!==0&&(L+=Y);const Q=V=>{w(),V?(E("retrying to scroll to",{location:_},es.DEBUG),Ut(f,_)):(Ut(g,!0),E("list did not change, scroll successful",{},es.DEBUG))};if(w(),B==="smooth"){let V=!1;b=mn(t,ce=>{V=V||ce}),v=fi(u,()=>{Q(V)})}else v=fi(Ue(t,kW(150)),Q);return y=setTimeout(()=>{w()},1200),Ut(d,!0),E("scrolling from index to",{behavior:B,index:ee,top:L},es.DEBUG),{behavior:B,top:L}})),c),{scrollTargetReached:g,scrollToIndex:f,topListHeight:x}},Rn(Vi,Ds,Wo),{singleton:!0});function kW(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return s=>{s&&(t(!0),clearTimeout(n))}}}function Hx(e,t){e===0?t():requestAnimationFrame(()=>{Hx(e-1,t)})}function Bx(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 vm(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 jd=hn(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:s},{scrollTargetReached:o,scrollToIndex:r},{didMount:a}])=>{const l=Xe(!0),d=Xe(0),c=Xe(!0);return wt(Ue(a,Qt(d),Lt(([u,h])=>!vm(h)),Ii(!1)),l),wt(Ue(a,Qt(d),Lt(([u,h])=>!vm(h)),Ii(!1)),c),mn(Ue(Bn(t,a),Qt(l,n,e,c),Lt(([[,u],h,{sizeTree:p},f,g])=>u&&(!Cn(p)||Lx(f))&&!h&&!g),Qt(d)),([,u])=>{if(u===void 0){Ut(l,!0),Ut(c,!0);return}fi(o,()=>{Ut(c,!0)}),Hx(4,()=>{fi(s,()=>{Ut(l,!0)}),Ut(r,u)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:d,scrolledToInitialItem:l}},Rn(Vi,Ds,kd,Uo),{singleton:!0});function dT(e,t){return Math.abs(e-t)<1.01}const Yl="up",gl="down",jW="none",_W={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},NW=0,_d=hn(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:s,scrollTop:o,viewportHeight:r}])=>{const a=Xe(!1),l=Xe(!0),d=rn(),c=rn(),u=Xe(4),h=Xe(NW),p=fs(Ue(pm(Ue(Rt(o),wr(1),Ii(!0)),Ue(Rt(o),wr(1),Ii(!1),_w(100))),An()),!1),f=fs(Ue(pm(Ue(n,Ii(!0)),Ue(n,Ii(!1),_w(200))),An()),!1);wt(Ue(Bn(Rt(o),Rt(h)),ft(([b,w])=>b<=w),An()),l),wt(Ue(l,ao(50)),c);const g=Fs(Ue(Bn(s,Rt(r),Rt(t),Rt(e),Rt(u)),Ri((b,[{scrollHeight:w,scrollTop:_},C,N,S,k])=>{const A=_+C-w>-k,I={scrollHeight:w,scrollTop:_,viewportHeight:C};if(A){let D,T;return _>b.state.scrollTop?(D="SCROLLED_DOWN",T=b.state.scrollTop-_):(D="SIZE_DECREASED",T=b.state.scrollTop-_||b.scrollTopDelta),{atBottom:!0,atBottomBecause:D,scrollTopDelta:T,state:I}}let E;return I.scrollHeight>b.state.scrollHeight?E="SIZE_INCREASED":C<b.state.viewportHeight?E="VIEWPORT_HEIGHT_DECREASING":_<b.state.scrollTop?E="SCROLLING_UPWARDS":E="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:E,state:I}},_W),An((b,w)=>b!==void 0&&b.atBottom===w.atBottom))),x=fs(Ue(s,Ri((b,{scrollHeight:w,scrollTop:_,viewportHeight:C})=>{if(!dT(b.scrollHeight,w)){const N=w-(_+C)<1;return b.scrollTop!==_&&N?{changed:!0,jump:b.scrollTop-_,scrollHeight:w,scrollTop:_}:{changed:!0,jump:0,scrollHeight:w,scrollTop:_}}return{changed:!1,jump:0,scrollHeight:w,scrollTop:_}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Lt(b=>b.changed),ft(b=>b.jump)),0);wt(Ue(g,ft(b=>b.atBottom)),a),wt(Ue(a,ao(50)),d);const v=Xe(gl);wt(Ue(s,ft(({scrollTop:b})=>b),An(),Ri((b,w)=>Ln(f)?{direction:b.direction,prevScrollTop:w}:{direction:w<b.prevScrollTop?Yl:gl,prevScrollTop:w},{direction:gl,prevScrollTop:0}),ft(b=>b.direction)),v),wt(Ue(s,ao(50),Ii(jW)),v);const y=Xe(0);return wt(Ue(p,Lt(b=>!b),Ii(0)),y),wt(Ue(o,ao(100),Qt(p),Lt(([b,w])=>w),Ri(([b,w],[_])=>[w,_],[0,0]),ft(([b,w])=>w-b)),y),{atBottomState:g,atBottomStateChange:d,atBottomThreshold:u,atTopStateChange:c,atTopThreshold:h,isAtBottom:a,isAtTop:l,isScrolling:p,lastJumpDueToItemResize:x,scrollDirection:v,scrollVelocity:y}},Rn(Ds)),Xl="top",Zl="bottom",Ew="none";function Pw(e,t,n){return typeof e=="number"?n===Yl&&t===Xl||n===gl&&t===Zl?e:0:n===Yl?t===Xl?e.main:e.reverse:t===Zl?e.main:e.reverse}function Aw(e,t){return typeof e=="number"?e:e[t]??0}const $x=hn(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:s,viewportHeight:o}])=>{const r=rn(),a=Xe(0),l=Xe(0),d=Xe(0),c=fs(Ue(Bn(Rt(s),Rt(o),Rt(n),Rt(r,Kl),Rt(d),Rt(a),Rt(t),Rt(e),Rt(l)),ft(([u,h,p,[f,g],x,v,y,b,w])=>{const _=u-b,C=v+y,N=Math.max(p-_,0);let S=Ew;const k=Aw(w,Xl),A=Aw(w,Zl);return f-=b,f+=p+y,g+=p+y,g-=b,f>u+C-k&&(S=Yl),g<u-N+h+A&&(S=gl),S!==Ew?[Math.max(_-p-Pw(x,Xl,S)-k,0),_-N-y+h+Pw(x,Zl,S)+A]:null}),Lt(u=>u!==null),An(Kl)),[0,0]);return{increaseViewportBy:l,listBoundary:r,overscan:d,topListHeight:a,visibleRange:c}},Rn(Ds),{singleton:!0});function TW(e,t,n){if(Ch(t)){const s=oT(e,t);return[{index:yi(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 jp={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Fc(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:Mw(e,o,r),offsetBottom:g,offsetTop:c,top:f,topItems:Mw(t,o,r),topListHeight:t.reduce((x,v)=>v.size+x,0),totalCount:n}}function cT(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=Bx(t,l),c=Array.from({length:l}).map((u,h)=>({data:r[h+d],index:h+d,offset:0,size:0}));return Fc(c,[],l,o,n,s)}function Mw(e,t,n){if(e.length===0)return[];if(!Ch(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=Jr(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 Rw(e,t){return e===void 0?0:typeof e=="number"?e:e[t]??0}const kr=hn(([{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=Xe([]),v=Xe(0),y=rn(),b=Xe(0);wt(r.topItemsIndexes,x);const w=fs(Ue(Bn(f,g,Rt(d,Kl),Rt(o),Rt(s),Rt(c),u,Rt(x),Rt(t),Rt(n),Rt(b),e),Lt(([S,k,,A,,,,,,,,I])=>{const E=I!==void 0&&I.length!==A;return S&&!k&&!E}),ft(([,,[S,k],A,I,E,D,T,H,F,O,B])=>{const Y=I,{offsetTree:U,sizeTree:ee}=Y,L=Ln(v);if(A===0)return{...jp,totalCount:A};if(S===0&&k===0)return L===0?{...jp,totalCount:A}:cT(L,E,I,H,F,B||[]);if(Cn(ee))return L>0?null:Fc(TW(Bx(E,A),Y,B),[],A,F,Y,H);const Q=[];if(T.length>0){const $=T[0],z=T[T.length-1];let de=0;for(const X of Jr(ee,$,z)){const oe=X.value,Z=Math.max(X.start,$),ae=Math.min(X.end,z);for(let be=Z;be<=ae;be++)Q.push({data:B?.[be],index:be,offset:de,size:oe}),de+=oe}}if(!D)return Fc([],Q,A,F,Y,H);const V=T.length>0?T[T.length-1]+1:0,ce=gW(U,S,k,V);if(ce.length===0)return null;const ve=A-1,_e=Sh([],$=>{for(const z of ce){const de=z.value;let X=de.offset,oe=z.start;const Z=de.size;if(de.offset<S){oe+=Math.floor((S-de.offset+F)/(Z+F));const be=oe-z.start;X+=be*Z+be*F}oe<V&&(X+=(V-oe)*Z,oe=V);const ae=Math.min(z.end,ve);for(let be=oe;be<=ae&&!(X>=k);be++)$.push({data:B?.[be],index:be,offset:X,size:Z}),X+=Z+F}}),De=Rw(O,Xl),me=Rw(O,Zl);if(_e.length>0&&(De>0||me>0)){const $=_e[0],z=_e[_e.length-1];if(De>0&&$.index>V){const de=Math.min(De,$.index-V),X=[];let oe=$.offset;for(let Z=$.index-1;Z>=$.index-de;Z--){const ae=Jr(ee,Z,Z)[0]?.value??$.size;oe-=ae+F,X.unshift({data:B?.[Z],index:Z,offset:oe,size:ae})}_e.unshift(...X)}if(me>0&&z.index<ve){const de=Math.min(me,ve-z.index);let X=z.offset+z.size+F;for(let oe=z.index+1;oe<=z.index+de;oe++){const Z=Jr(ee,oe,oe)[0]?.value??z.size;_e.push({data:B?.[oe],index:oe,offset:X,size:Z}),X+=Z+F}}}return Fc(_e,Q,A,F,Y,H)}),Lt(S=>S!==null),An()),jp);wt(Ue(e,Lt(Lx),ft(S=>S?.length)),o),wt(Ue(w,ft(S=>S.topListHeight)),h),wt(h,l),wt(Ue(w,ft(S=>[S.top,S.bottom])),a),wt(Ue(w,ft(S=>S.items)),y);const _=Fs(Ue(w,Lt(({items:S})=>S.length>0),Qt(o,e),Lt(([{items:S},k])=>S[S.length-1].originalIndex===k-1),ft(([,S,k])=>[S-1,k]),An(Kl),ft(([S])=>S))),C=Fs(Ue(w,ao(200),Lt(({items:S,topItems:k})=>S.length>0&&S[0].originalIndex===k.length),ft(({items:S})=>S[0].index),An())),N=Fs(Ue(w,Lt(({items:S})=>S.length>0),ft(({items:S})=>{let k=0,A=S.length-1;for(;S[k].type==="group"&&k<A;)k++;for(;S[A].type==="group"&&A>k;)A--;return{endIndex:S[A].index,startIndex:S[k].index}}),An(sT)));return{endReached:_,initialItemCount:v,itemsRendered:y,listState:w,minOverscanItemCount:b,rangeChanged:N,startReached:C,topItemsIndexes:x,...p}},Rn(Vi,aT,$x,jd,kd,_d,Uo,Gx),{singleton:!0}),uT=hn(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:s},{listState:o}])=>{const r=rn(),a=fs(Ue(Bn(n,e,s,t,o),ft(([l,d,c,u,h])=>l+d+c+u+h.offsetBottom+h.bottom)),0);return wt(Rt(a),r),{totalListHeight:a,totalListHeightChanged:r}},Rn(Ds,kr),{singleton:!0}),DW=hn(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Xe(!1),s=fs(Ue(Bn(n,e,t),Lt(([o])=>o),ft(([,o,r])=>Math.max(0,o-r)),ao(0),An()),0);return{alignToBottom:n,paddingTopAddition:s}},Rn(Ds,uT),{singleton:!0}),hT=hn(()=>({context:Xe(null)})),IW=({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,pT=hn(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:s,fixedHeaderHeight:o,headerHeight:r,scrollingInProgress:a,scrollTop:l,viewportHeight:d},{scrollToIndex:c}])=>{const u=rn();return wt(Ue(u,Qt(t,d,n,r,o,s,l),Qt(e),ft(([[h,p,f,g,x,v,y,b],w])=>{const{calculateViewLocation:_=IW,done:C,...N}=h,S=rT(h,p,g-1),k=ql(S,p.offsetTree,w)+x+v,A=k+yi(p.sizeTree,S)[1],I=b+v,E=b+f-y,D=_({itemBottom:A,itemTop:k,locationParams:N,viewportBottom:E,viewportTop:I});return D===null?C?.():C&&fi(Ue(a,Lt(T=>!T),wr(Ln(a)?1:2)),C),D}),Lt(h=>h!==null)),c),{scrollIntoView:u}},Rn(Vi,Ds,kd,kr,Wo),{singleton:!0});function Lw(e){return e===!1?!1:e==="smooth"?"smooth":"auto"}const EW=(e,t)=>typeof e=="function"?Lw(e(t)):t&&Lw(e),PW=hn(([{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=Xe(!1),x=rn();let v=null;function y(C){Ut(a,{align:"end",behavior:C,index:"LAST"})}mn(Ue(Bn(Ue(Rt(t),wr(1)),d),Qt(Rt(g),r,l,h),ft(([[C,N],S,k,A,I])=>{let E=N&&A,D="auto";return E&&(D=EW(S,k||I),E=E&&D!==!1),{followOutputBehavior:D,shouldFollow:E,totalCount:C}}),Lt(({shouldFollow:C})=>C)),({followOutputBehavior:C,totalCount:N})=>{v!==null&&(v(),v=null),Ln(n)===void 0?v=fi(e,()=>{Ln(u)("following output to ",{totalCount:N},es.DEBUG),y(C),v=null}):requestAnimationFrame(()=>{Ln(u)("following output to ",{totalCount:N},es.DEBUG),y(C)})});function b(C){const N=fi(o,S=>{C&&!S.atBottom&&S.notAtBottomBecause==="SIZE_INCREASED"&&v===null&&(Ln(u)("scrolling to bottom due to increased size",{},es.DEBUG),y("auto"))});setTimeout(N,100)}mn(Ue(Bn(Rt(g),t,c),Lt(([C,,N])=>C!==!1&&N),Ri(({value:C},[,N])=>({refreshed:C===N,value:N}),{refreshed:!1,value:0}),Lt(({refreshed:C})=>C),Qt(g,t)),([,C])=>{Ln(l)&&b(C!==!1)}),mn(x,()=>{b(Ln(g)!==!1)}),mn(Bn(Rt(g),o),([C,N])=>{C!==!1&&!N.atBottom&&N.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&y("auto")});const w=Xe(null),_=rn();return wt(pm(Ue(Rt(s),ft(C=>C?.length??0)),Ue(Rt(t))),_),mn(Ue(Bn(Ue(_,wr(1)),d),Qt(Rt(w),l,h,p),ft(([[C,N],S,k,A,I])=>N&&k&&S?.({context:I,totalCount:C,scrollingInProgress:A})),Lt(C=>!!C),ao(0)),C=>{v!==null&&(v(),v=null),Ln(n)===void 0?v=fi(e,()=>{Ln(u)("scrolling into view",{}),Ut(f,C),v=null}):requestAnimationFrame(()=>{Ln(u)("scrolling into view",{}),Ut(f,C)})}),{autoscrollToBottom:x,followOutput:g,scrollIntoViewOnChange:w}},Rn(Vi,_d,kd,jd,Uo,Wo,Ds,hT,pT)),AW=hn(([{data:e,firstItemIndex:t,gap:n,sizes:s},{initialTopMostItemIndex:o},{initialItemCount:r,listState:a},{didMount:l}])=>(wt(Ue(l,Qt(r),Lt(([,d])=>d!==0),Qt(o,s,t,n,e),ft(([[,d],c,u,h,p,f=[]])=>cT(d,c,u,h,p,f))),a),{}),Rn(Vi,jd,kr,Uo),{singleton:!0}),MW=hn(([{didMount:e},{scrollTo:t},{listState:n}])=>{const s=Xe(0);return mn(Ue(e,Qt(s),Lt(([,o])=>o!==0),ft(([,o])=>({top:o}))),o=>{fi(Ue(n,wr(1),Lt(r=>r.items.length>1)),()=>{requestAnimationFrame(()=>{Ut(t,o)})})}),{initialScrollTop:s}},Rn(Uo,Ds,kr),{singleton:!0}),fT=hn(([{scrollVelocity:e}])=>{const t=Xe(!1),n=rn(),s=Xe(!1);return wt(Ue(e,Qt(s,t,n),Lt(([o,r])=>r!==!1&&r!==void 0),ft(([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}),An()),t),mn(Ue(Bn(t,e,n),Qt(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}},Rn(_d),{singleton:!0}),Vx=hn(([{scrollContainerState:e,scrollTo:t}])=>{const n=rn(),s=rn(),o=rn(),r=Xe(!1),a=Xe(void 0);return wt(Ue(Bn(n,s),ft(([{scrollTop:l,viewportHeight:d},{offsetTop:c,listHeight:u}])=>({scrollHeight:u,scrollTop:Math.max(0,l-c),viewportHeight:d}))),e),wt(Ue(t,Qt(s),ft(([l,{offsetTop:d}])=>({...l,top:l.top+d}))),o),{customScrollParent:a,useWindowScroll:r,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:s}},Rn(Ds)),RW=hn(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:s},{initialTopMostItemIndex:o},{didMount:r},{useWindowScroll:a,windowScrollContainerState:l,windowViewportRect:d}])=>{const c=rn(),u=Xe(void 0),h=Xe(null),p=Xe(null);return wt(l,h),wt(d,p),mn(Ue(c,Qt(t,s,a,h,p,n)),([f,g,x,v,y,b,w])=>{const _=vW(g.sizeTree);v&&y!==null&&b!==null&&(x=y.scrollTop-b.offsetTop),x-=w,f({ranges:_,scrollTop:x})}),wt(Ue(u,Lt(Lx),ft(LW)),o),wt(Ue(r,Qt(u),Lt(([,f])=>f!==void 0),An(),ft(([,f])=>f.ranges)),e),{getState:c,restoreStateFrom:u}},Rn(Vi,Ds,jd,Uo,Vx));function LW(e){return{align:"start",index:0,offset:e.scrollTop}}const OW=hn(([{topItemsIndexes:e}])=>{const t=Xe(0);return wt(Ue(t,Lt(n=>n>=0),ft(n=>Array.from({length:n}).map((s,o)=>o))),e),{topItemCount:t}},Rn(kr));function mT(e){let t=!1,n;return(()=>(t||(t=!0,n=e()),n))}const zW=mT(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),GW=hn(([{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=Fs(Ue(d,Qt(a),Ri(([,y,b,w],[{bottom:_,items:C,offsetBottom:N,totalCount:S},k])=>{const A=_+N;let I=0;return b===S&&y.length>0&&C.length>0&&(C[0].originalIndex===0&&y[0].originalIndex===0||(I=A-w,I!==0&&(I+=k))),[I,C,S,A]},[0,[],0,0]),Lt(([y])=>y!==0),Qt(s,l,n,o,f,g),Lt(([,y,b,w,,,_])=>!_&&!w&&y!==0&&b===Yl),ft(([[y],,,,,b])=>(b("Upward scrolling compensation",{amount:y},es.DEBUG),y))));function v(y){y>0?(Ut(t,{behavior:"auto",top:-y}),Ut(e,0)):(Ut(e,0),Ut(t,{behavior:"auto",top:-y}))}return mn(Ue(x,Qt(e,r)),([y,b,w])=>{w&&zW()?Ut(e,b-y):v(-y)}),mn(Ue(Bn(fs(r,!1),e,g),Lt(([y,b,w])=>!y&&!w&&b!==0),ft(([y,b])=>b),ao(1)),v),wt(Ue(h,ft(y=>({top:-y}))),t),mn(Ue(c,Qt(p,u),ft(([y,{groupIndices:b,lastSize:w,sizeTree:_},C])=>{function N(E){return E*(w+C)}if(b.length===0)return N(y);let S=0;const k=Ul(_,0);let A=0,I=0;for(;A<y;){A++,S+=k;let E=b.length===I+1?1/0:b[I+1]-b[I]-1;A+E>y&&(S-=k,E=y-A+1),A+=E,S+=N(E),I++}return S})),y=>{Ut(e,y),requestAnimationFrame(()=>{Ut(t,{top:y}),requestAnimationFrame(()=>{Ut(e,0),Ut(g,!1)})})}),{deviation:e}},Rn(Ds,_d,kr,Vi,Wo,Gx)),FW=hn(([e,t,n,s,o,r,a,l,d,c,u])=>({...e,...t,...n,...s,...o,...r,...a,...l,...d,...c,...u}),Rn($x,AW,Uo,fT,uT,MW,DW,Vx,pT,Wo,hT)),gT=hn(([{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,b,w,_,{scrollToIndex:C},N,{topItemCount:S},{groupCounts:k},A])=>{const{listState:I,minOverscanItemCount:E,topItemsIndexes:D,rangeChanged:T,...H}=_;return wt(T,A.scrollSeekRangeChanged),wt(Ue(Bn(A.windowViewportRect,y.headerHeight,y.fixedHeaderHeight),ft(([F,O,B])=>Math.max(O+B+1,F.visibleHeight))),y.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:s,fixedGroupHeight:o,gap:r,groupCounts:k,heightEstimates:l,initialItemFinalLocationReached:g,initialTopMostItemIndex:x,scrolledToInitialItem:v,sizeRanges:c,topItemCount:S,topItemsIndexes:D,totalCount:p,...w,groupIndices:a,itemSize:d,listState:I,minOverscanItemCount:E,scrollToIndex:C,statefulTotalCount:h,trackItemSizes:f,rangeChanged:T,...H,...A,...y,sizes:u,...b}},Rn(Vi,jd,Ds,RW,PW,kr,kd,GW,OW,aT,FW));function HW(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 Fd=typeof document>"u"?Ne.useEffect:Ne.useLayoutEffect;function xT(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&&Ut(v.propsReady,!1);for(const b of s){const w=v[t.required[b]];Ut(w,y[b])}for(const b of o)if(b in y){const w=v[t.optional[b]];Ut(w,y[b])}v.propsReady!==void 0&&Ut(v.propsReady,!0)}function c(v){return r.reduce((y,b)=>(y[b]=w=>{const _=v[t.methods[b]];Ut(_,w)},y),{})}function u(v){return a.reduce((y,b)=>(y[b]=tW(v[t.events[b]]),y),{})}const h=Ne.forwardRef(function(v,y){const{children:b,...w}=v,[_]=Ne.useState(()=>Sh(iW(e),S=>{d(S,w)})),[C]=Ne.useState(jw(u,_));Fd(()=>{for(const S of a)S in w&&mn(C[S],w[S]);return()=>{Object.values(C).map(Ox)}},[w,C,_]),Fd(()=>{d(_,w)}),Ne.useImperativeHandle(y,kw(c(_)));const N=n;return i.jsx(l.Provider,{value:_,children:n===void 0?b:i.jsx(N,{...HW([...s,...o,...a],w),children:b})})}),p=v=>{const y=Ne.useContext(l);return Ne.useCallback(b=>{Ut(y[v],b)},[y,v])},f=v=>{const y=Ne.useContext(l)[v],b=Ne.useCallback(w=>mn(y,w),[y]);return Ne.useSyncExternalStore(b,()=>Ln(y),()=>Ln(y))},g=v=>{const y=Ne.useContext(l)[v],[b,w]=Ne.useState(jw(Ln,y));return Fd(()=>mn(y,_=>{_!==b&&w(kw(_))}),[y,b]),b},x=parseInt(Ne.version,10)>=18?f:g;return{Component:h,useEmitter:(v,y)=>{const b=Ne.useContext(l)[v];Fd(()=>mn(b,y),[y,b])},useEmitterValue:x,usePublisher:p}}const vT=Ne.createContext(void 0),bT=Ne.createContext(void 0),_p="-webkit-sticky",Ow="sticky",Wx=mT(()=>{if(typeof document>"u")return Ow;const e=document.createElement("div");return e.style.position=_p,e.style.position===_p?_p:Ow}),wT=typeof document>"u"?Ne.useEffect:Ne.useLayoutEffect;function Np(e){return"self"in e}function BW(e){return"body"in e}function yT(e,t,n,s=Ia,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(BW(v)||Np(v)){const b=Np(v)?v:v.defaultView;x=r===!0?cr(b,b.scrollX):b.scrollY,f=r===!0?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,g=r===!0?b.innerWidth:b.innerHeight}else x=r===!0?cr(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():Ok.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;Np(f)?(v=Math.max(Oo(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?cr(f,f.scrollX):f.scrollY):(v=f[r===!0?"scrollWidth":"scrollHeight"],x=Oo(f,r===!0?"width":"height"),y=r===!0?cr(f,f.scrollLeft):f.scrollTop);const b=v-x;if(p.top===void 0){f.scrollTo(p);return}const w=Math.ceil(Math.max(Math.min(b,p.top),0));if(p.top=w,dT(x,v)||w===y){e({scrollHeight:v,scrollTop:y,viewportHeight:x}),g&&t(!0);return}g?(l.current=w,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:Nw(f,w)}),f.scrollTo(p)}function h(p){r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},...p.top===void 0?{}:{left:Nw(a.current,p.top)}}),a.current.scrollBy(p)}return{scrollByCallback:h,scrollerRef:a,scrollToCallback:u}}function Ux(e){return e}const $W=hn(()=>{const e=Xe(l=>`Item ${l}`),t=Xe(l=>`Group ${l}`),n=Xe({}),s=Xe(Ux),o=Xe("div"),r=Xe(Ia),a=(l,d=null)=>fs(Ue(n,ft(c=>c[l]),An()),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")}}),VW=hn(([e,t])=>({...e,...t}),Rn(gT,$W)),WW=({height:e})=>i.jsx("div",{style:{height:e}}),UW={overflowAnchor:"none",position:Wx(),zIndex:1},ST={overflowAnchor:"none"},KW={...ST,display:"inline-block",height:"100%"},zw=Ne.memo(function({showTopList:e=!1}){const t=Ft("listState"),n=Ys("sizeRanges"),s=Ft("useWindowScroll"),o=Ft("customScrollParent"),r=Ys("windowScrollContainerState"),a=Ys("scrollContainerState"),l=o||s?r:a,d=Ft("itemContent"),c=Ft("context"),u=Ft("groupContent"),h=Ft("trackItemSizes"),p=Ft("itemSize"),f=Ft("log"),g=Ys("gap"),x=Ft("horizontalDirection"),{callbackRef:v}=lW(n,p,h,e?Ia:l,f,g,o,x,Ft("skipAnimationFrameInResizeObserver")),[y,b]=Ne.useState(0);qx("deviation",H=>{y!==H&&b(H)});const w=Ft("EmptyPlaceholder"),_=Ft("ScrollSeekPlaceholder")??WW,C=Ft("ListComponent"),N=Ft("ItemComponent"),S=Ft("GroupComponent"),k=Ft("computeItemKey"),A=Ft("isSeeking"),I=Ft("groupIndices").length>0,E=Ft("alignToBottom"),D=Ft("initialItemFinalLocationReached"),T=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginInlineStart:y===0?E?"auto":0:y,paddingInlineEnd:t.offsetBottom,paddingInlineStart:t.offsetTop,whiteSpace:"nowrap"}:{marginTop:y===0?E?"auto":0:y,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...D?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&w!==null&&w!==void 0?i.jsx(w,{...ps(w,c)}):i.jsx(C,{...ps(C,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:T,children:(e?t.topItems:t.items).map(H=>{const F=H.originalIndex,O=k(F+t.firstItemIndex,H.data,c);return A?m.createElement(_,{...ps(_,c),height:H.size,index:H.index,key:O,type:H.type||"item",...H.type==="group"?{}:{groupIndex:H.groupIndex}}):H.type==="group"?m.createElement(S,{...ps(S,c),"data-index":F,"data-item-index":H.index,"data-known-size":H.size,key:O,style:UW},u(H.index,c)):m.createElement(N,{...ps(N,c),...ZW(N,H.data),"data-index":F,"data-item-group-index":H.groupIndex,"data-item-index":H.index,"data-known-size":H.size,key:O,style:x?KW:ST},I?d(H.index,H.groupIndex,H.data,c):d(H.index,H.data,c))})})}),qW={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},YW={outline:"none",overflowX:"auto",position:"relative"},Kx=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:void 0}),CT=(e,t,n=0)=>({...Kx(e),position:t?"relative":"absolute",top:t?-n:0}),XW={position:Wx(),top:0,width:"100%",zIndex:1};function ps(e,t){if(typeof e!="string")return{context:t}}function ZW(e,t){return{item:typeof e=="string"?void 0:t}}const JW=Ne.memo(function(){const e=Ft("HeaderComponent"),t=Ys("headerHeight"),n=Ft("HeaderFooterTag"),s=Cr(Ne.useMemo(()=>r=>{t(Oo(r,"height"))},[t]),!0,Ft("skipAnimationFrameInResizeObserver")),o=Ft("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null}),QW=Ne.memo(function(){const e=Ft("FooterComponent"),t=Ys("footerHeight"),n=Ft("HeaderFooterTag"),s=Cr(Ne.useMemo(()=>r=>{t(Oo(r,"height"))},[t]),!0,Ft("skipAnimationFrameInResizeObserver")),o=Ft("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null});function kT({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}=yT(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?YW:qW,...o},tabIndex:0,...a,...ps(d,r),children:s})})}function jT({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}=yT(l,c,d,g,p);return wT(()=>(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,...ps(d,r),children:s})})}const e8=({children:e})=>{const t=Ne.useContext(vT),n=Ys("viewportHeight"),s=Ys("fixedItemHeight"),o=Ft("alignToBottom"),r=Ft("horizontalDirection"),a=Ne.useMemo(()=>qN(n,d=>Oo(d,r?"width":"height")),[n,r]),l=Cr(a,!0,Ft("skipAnimationFrameInResizeObserver"));return Ne.useEffect(()=>{t&&(n(t.viewportHeight),s(t.itemHeight))},[t,n,s]),i.jsx("div",{"data-viewport-type":"element",ref:l,style:Kx(o),children:e})},t8=({children:e})=>{const t=Ne.useContext(vT),n=Ys("windowViewportRect"),s=Ys("fixedItemHeight"),o=Ft("customScrollParent"),r=Ft("useWindowScroll"),a=Ft("topListHeight"),l=ZN(n,o,Ft("skipAnimationFrameInResizeObserver")),d=Ft("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:CT(d,r,a),children:e})},n8=({children:e})=>{const t=Ft("TopItemListComponent")??"div",n=Ft("headerHeight"),s={...XW,marginTop:`${n}px`},o=Ft("context");return i.jsx(t,{style:s,...ps(t,o),children:e})},s8=Ne.memo(function(e){const t=Ft("useWindowScroll"),n=Ft("topItemsIndexes").length>0,s=Ft("customScrollParent"),o=Ft("context");return i.jsxs(s||t?r8:o8,{...e,context:o,children:[n&&i.jsx(n8,{children:i.jsx(zw,{showTopList:!0})}),i.jsxs(s||t?t8:e8,{children:[i.jsx(JW,{}),i.jsx(zw,{}),i.jsx(QW,{})]})]})}),{Component:i8,useEmitter:qx,useEmitterValue:Ft,usePublisher:Ys}=xT(VW,{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"}},s8),o8=kT({useEmitter:qx,useEmitterValue:Ft,usePublisher:Ys}),r8=jT({useEmitter:qx,useEmitterValue:Ft,usePublisher:Ys}),a8=i8,l8=hn(()=>{const e=Xe(c=>i.jsxs("td",{children:["Item $",c]})),t=Xe(null),n=Xe(c=>i.jsxs("td",{colSpan:1e3,children:["Group ",c]})),s=Xe(null),o=Xe(null),r=Xe({}),a=Xe(Ux),l=Xe(Ia),d=(c,u=null)=>fs(Ue(r,ft(h=>h[c]),An()),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")}});Rn(gT,l8);Wx();const Gw={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},d8={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Fw,floor:ju,max:xl,min:Tp,round:Hw}=Math;function Bw(e,t,n){return Array.from({length:t-e+1}).map((s,o)=>({data:n===null?null:n[o+e],index:o+e}))}function c8(e){return{...d8,items:e}}function Hd(e,t){return e!==void 0&&e.width===t.width&&e.height===t.height}function u8(e,t){return e!==void 0&&e.column===t.column&&e.row===t.row}const h8=hn(([{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:b,windowScrollTo:w,windowViewportRect:_},C])=>{const N=Xe(0),S=Xe(0),k=Xe(Gw),A=Xe({height:0,width:0}),I=Xe({height:0,width:0}),E=rn(),D=rn(),T=Xe(0),H=Xe(null),F=Xe({column:0,row:0}),O=rn(),B=rn(),Y=Xe(!1),U=Xe(0),ee=Xe(!0),L=Xe(!1),Q=Xe(!1);mn(Ue(g,Qt(U),Lt(([me,$])=>!vm($))),()=>{Ut(ee,!1)}),mn(Ue(Bn(g,ee,I,A,U,L),Lt(([me,$,z,de,,X])=>me&&!$&&z.height!==0&&de.height!==0&&!X)),([,,,,me])=>{if(me===void 0){Ut(ee,!0);return}Ut(L,!0),Hx(1,()=>{Ut(E,me)}),fi(Ue(c),()=>{Ut(t,[0,0]),Ut(ee,!0)})}),wt(Ue(B,Lt(me=>me!=null&&me.scrollTop>0),Ii(0)),S),mn(Ue(g,Qt(B),Lt(([,me])=>me!=null)),([,me])=>{me&&(Ut(A,me.viewport),Ut(I,me.item),Ut(F,me.gap),me.scrollTop>0&&(Ut(Y,!0),fi(Ue(c,wr(1)),$=>{Ut(Y,!1)}),Ut(d,{top:me.scrollTop})))}),wt(Ue(A,ft(({height:me})=>me)),h),wt(Ue(Bn(Rt(A,Hd),Rt(I,Hd),Rt(F,(me,$)=>me!==void 0&&me.column===$.column&&me.row===$.row),Rt(c)),ft(([me,$,z,de])=>({gap:z,item:$,scrollTop:de,viewport:me}))),O),wt(Ue(Bn(Rt(N),s,Rt(F,u8),Rt(I,Hd),Rt(A,Hd),Rt(H),Rt(S),Rt(Y),Rt(ee),Rt(U)),Lt(([,,,,,,,me])=>!me),ft(([me,[$,z],de,X,oe,Z,ae,,be,ze])=>{const{column:Ye,row:Ve}=de,{height:at,width:Ze}=X,{width:Et}=oe;if(ae===0&&(me===0||Et===0))return Gw;if(Ze===0){const ht=Bx(ze,me),$t=ht+Math.max(ae-1,0);return c8(Bw(ht,$t,Z))}const Gt=_T(Et,Ze,Ye);let Pt,ne;be?$===0&&z===0&&ae>0?(Pt=0,ne=ae-1):(Pt=Gt*ju(($+Ve)/(at+Ve)),ne=Gt*Fw((z+Ve)/(at+Ve))-1,ne=Tp(me-1,xl(ne,Gt-1)),Pt=Tp(ne,xl(0,Pt))):(Pt=0,ne=-1);const ie=Bw(Pt,ne,Z),{bottom:He,top:St}=$w(oe,de,X,ie),it=Fw(me/Gt),je=it*at+(it-1)*Ve-He;return{bottom:He,itemHeight:at,items:ie,itemWidth:Ze,offsetBottom:je,offsetTop:St,top:St}})),k),wt(Ue(H,Lt(me=>me!==null),ft(me=>me.length)),N),wt(Ue(Bn(A,I,k,F),Lt(([me,$,{items:z}])=>z.length>0&&$.height!==0&&me.height!==0),ft(([me,$,{items:z},de])=>{const{bottom:X,top:oe}=$w(me,de,$,z);return[oe,X]}),An(Kl)),t);const V=Xe(!1);wt(Ue(c,Qt(V),ft(([me,$])=>$||me!==0)),V);const ce=Fs(Ue(Bn(k,N),Lt(([{items:me}])=>me.length>0),Qt(V),Lt(([[me,$],z])=>{const de=me.items[me.items.length-1].index===$-1;return(z||me.bottom>0&&me.itemHeight>0&&me.offsetBottom===0&&me.items.length===$)&&de}),ft(([[,me]])=>me-1),An())),ve=Fs(Ue(Rt(k),Lt(({items:me})=>me.length>0&&me[0].index===0),Ii(0),An())),_e=Fs(Ue(Rt(k),Qt(Y),Lt(([{items:me},$])=>me.length>0&&!$),ft(([{items:me}])=>({endIndex:me[me.length-1].index,startIndex:me[0].index})),An(sT),ao(0)));wt(_e,f.scrollSeekRangeChanged),wt(Ue(E,Qt(A,I,N,F),ft(([me,$,z,de,X])=>{const oe=lT(me),{align:Z,behavior:ae,offset:be}=oe;let ze=oe.index;ze==="LAST"&&(ze=de-1),ze=xl(0,ze,Tp(de-1,ze));let Ye=bm($,X,z,ze);return Z==="end"?Ye=Hw(Ye-$.height+z.height):Z==="center"&&(Ye=Hw(Ye-$.height/2+z.height/2)),be!==void 0&&be!==0&&(Ye+=be),{behavior:ae,top:Ye}})),d);const De=fs(Ue(k,ft(me=>me.offsetBottom+me.bottom)),0);return wt(Ue(_,ft(me=>({height:me.visibleHeight,width:me.visibleWidth}))),A),{customScrollParent:v,data:H,deviation:T,footerHeight:o,gap:F,headerHeight:r,increaseViewportBy:e,initialItemCount:S,itemDimensions:I,overscan:n,restoreStateFrom:B,scrollBy:a,scrollContainerState:l,scrollHeight:D,scrollTo:d,scrollToIndex:E,scrollTop:c,smoothScrollTargetReached:u,totalCount:N,useWindowScroll:y,viewportDimensions:A,windowScrollContainerState:b,windowScrollTo:w,windowViewportRect:_,...f,gridState:k,horizontalDirection:Q,initialTopMostItemIndex:U,totalListHeight:De,...p,endReached:ce,propsReady:x,rangeChanged:_e,startReached:ve,stateChanged:O,stateRestoreInProgress:Y,...C}},Rn($x,Ds,_d,fT,Uo,Vx,Wo));function _T(e,t,n){return xl(1,ju((e+n)/(ju(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=bm(e,t,n,s[0].index);return{bottom:bm(e,t,n,s[s.length-1].index)+o,top:r}}function bm(e,t,n,s){const o=_T(e.width,n.width,t.column),r=ju(s/o),a=r*n.height+xl(0,r-1)*t.row;return a>0?a+t.row:a}const p8=hn(()=>{const e=Xe(h=>`Item ${h}`),t=Xe({}),n=Xe(null),s=Xe("virtuoso-grid-item"),o=Xe("virtuoso-grid-list"),r=Xe(Ux),a=Xe("div"),l=Xe(Ia),d=(h,p=null)=>fs(Ue(t,ft(f=>f[h]),An()),p),c=Xe(!1),u=Xe(!1);return wt(Rt(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")}}),f8=hn(([e,t])=>({...e,...t}),Rn(h8,p8)),m8=Ne.memo(function(){const e=En("gridState"),t=En("listClassName"),n=En("itemClassName"),s=En("itemContent"),o=En("computeItemKey"),r=En("isSeeking"),a=Xs("scrollHeight"),l=En("ItemComponent"),d=En("ListComponent"),c=En("ScrollSeekPlaceholder"),u=En("context"),h=Xs("itemDimensions"),p=Xs("gap"),f=En("log"),g=En("stateRestoreInProgress"),x=Xs("reportReadyState"),v=Cr(Ne.useMemo(()=>y=>{const b=y.parentElement.parentElement.scrollHeight;a(b);const w=y.firstChild;if(w!==null){const{height:_,width:C}=w.getBoundingClientRect();h({height:_,width:C})}p({column:Vw("column-gap",getComputedStyle(y).columnGap,f),row:Vw("row-gap",getComputedStyle(y).rowGap,f)})},[a,h,p,f]),!0,!1);return wT(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),g?null:i.jsx(d,{className:t,ref:v,...ps(d,u),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(y=>{const b=o(y.index,y.data,u);return r?i.jsx(c,{...ps(c,u),height:e.itemHeight,index:y.index,width:e.itemWidth},b):m.createElement(l,{...ps(l,u),className:n,"data-index":y.index,key:b},s(y.index,y.data,u))})})}),g8=Ne.memo(function(){const e=En("HeaderComponent"),t=Xs("headerHeight"),n=En("headerFooterTag"),s=Cr(Ne.useMemo(()=>r=>{t(Oo(r,"height"))},[t]),!0,!1),o=En("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null}),x8=Ne.memo(function(){const e=En("FooterComponent"),t=Xs("footerHeight"),n=En("headerFooterTag"),s=Cr(Ne.useMemo(()=>r=>{t(Oo(r,"height"))},[t]),!0,!1),o=En("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null}),v8=({children:e})=>{const t=Ne.useContext(bT),n=Xs("itemDimensions"),s=Xs("viewportDimensions"),o=Cr(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:Kx(!1),children:e})},b8=({children:e})=>{const t=Ne.useContext(bT),n=Xs("windowViewportRect"),s=Xs("itemDimensions"),o=En("customScrollParent"),r=En("useWindowScroll"),a=ZN(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:CT(!1,r),children:e})},w8=Ne.memo(function({...e}){const t=En("useWindowScroll"),n=En("customScrollParent"),s=n||t?S8:y8,o=n||t?b8:v8,r=En("context");return i.jsx(s,{...e,...ps(s,r),children:i.jsxs(o,{children:[i.jsx(g8,{}),i.jsx(m8,{}),i.jsx(x8,{})]})})}),{useEmitter:NT,useEmitterValue:En,usePublisher:Xs}=xT(f8,{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"}},w8),y8=kT({useEmitter:NT,useEmitterValue:En,usePublisher:Xs}),S8=jT({useEmitter:NT,useEmitterValue:En,usePublisher:Xs});function Vw(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,es.WARN),t==="normal"?0:parseInt(t??"0",10)}function C8({className:e}){return i.jsx("svg",{viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",className:W("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 k8={rows:new Set,expanded:new Set};function j8(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 _8(e){return e==="right"||e==="off"?e:"left"}function N8(e,t,n){return e!=="off"&&!t&&n>=2}const Bd=40;function T8({items:e,activeKey:t,onJump:n}){const s=Se(g=>g.chatWide),o=_8(Se(g=>g.navRailSide)),[r,a]=m.useState(null);if(!N8(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(Bd/2)),Math.max(0,e.length-Bd)),u=e.slice(c,c+Bd),h=c>0,p=c+Bd<e.length,f=(g,x)=>{const v=x?24:12;if(r===null)return v;const y=Math.abs(g-r),b=Math.max(0,16-y*6);return v+b};return i.jsx("div",{className:W("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:W("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:W("flex h-[7px] w-10 items-center",l&&"justify-end"),children:i.jsx("span",{className:W("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:W("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 Hc="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 TT(e){return e.content.filter(t=>t.type==="text").map(t=>t.text??"").join("").trim()}function D8(e){const t=[];for(const n of e){if(n.role!=="user"&&n.role!=="assistant")continue;const s=TT(n);s&&t.push(`${n.role==="user"?"User":"Assistant"}: ${s}`)}return t.slice(-40).join(`
|
|
21
|
-
`)}function I8(e){for(const t of[...e].reverse()){if(t.role!=="assistant")continue;const n=TT(t);if(n)return n}return""}function Ww(e,t){if(e!=="contextual")return Hc;const n=t.trim();return n?`${Hc}
|
|
22
|
-
|
|
23
|
-
# Main conversation (background only)
|
|
24
|
-
${n}`:Hc}function E8(e){return e.startsWith(Hc)}function P8(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 A8({message:e}){const{t}=J(),n={queued:t("Queued"),running:t("In progress"),completed:t("Completed"),failed:t("Failed"),canceled:t("Canceled")},s=e.kind==="routine"?_N:e.kind==="group"?ha:e.kind==="delegation-task"?ga:e.kind==="delegation-retry"||e.kind==="delegation-check-failed"?ia:MV,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(ha,{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 DT=new Map;let Ur;function M8(e){if(Ur?.revision===e)return Ur.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:DT})),n={revision:e,request:t,data:void 0};return Ur=n,t.then(s=>{Ur===n&&(n.data=s)}),t}function R8(){const e=Fi(s=>s.snapshot.revision),[t,n]=m.useState(()=>Ur?.revision===e?Ur.data:void 0);return m.useEffect(()=>{let s=!1;return M8(e).then(o=>{s||n(o)}),()=>{s=!0}},[e]),t?.revision===e?t.emails:DT}function Uw(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 Yx(e,t,n){return`${e}:${Uw(t)}:${Uw(n,1)}`}const L8=/(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c|$)/g,O8=/(?:\x1b\[|\x9b)[0-?]*[ -/]*(?:[@-~]|$)/g;function Si(e){return e.replace(L8,"").replace(O8,"")}function z8(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 G8(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 F8(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=G8(x);y!==void 0&&(l+=y);const b=z8(x);b!==void 0&&(c+=b,u+=1);const w=x.usage?.output??0;y!==void 0&&y>0&&w>0&&(h+=y,p+=w),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 H8(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 Kw=bg(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}})})),B8={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 $8({value:e}){const t=nA(e),{t:n}=J();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(B8[t.reason])]})]})]})}function V8({ask:e,waiting:t}){const{t:n}=J(),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(qw,{selected:o===e.answer,text:o},o)),s!==null&&i.jsx(qw,{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 qw({selected:e,text:t,label:n}){const{t:s}=J(),o=e?wg:Tx;return i.jsxs("li",{"data-selected":e||void 0,className:W("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:W("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 W8=/^Subagent ".*" \(agentId [^,\s]+, runId [^)\s]+\) \S+ after .+\.$/gm,U8=/^The following is the subagent's report: .*$\n?/m,K8=/<usage>([\s\S]*?)<\/usage>/,Dp=(e,t)=>{const n=new RegExp(`^${t}: (\\d+)$`,"m").exec(e);return n?Number(n[1]):null};function q8(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=K8.exec(s);if(r){s=s.slice(0,r.index);const a=Dp(r[1],"subagent_tokens"),l=Dp(r[1],"tool_uses"),d=Dp(r[1],"duration_ms");a!==null&&l!==null&&d!==null&&(o={tokens:a,toolUses:l,durationMs:d})}return{header:n,report:s.replace(U8,"").trim(),usage:o}}function Y8(e){const t=e.trim(),n=[...t.matchAll(W8)].map(s=>s.index);return n[0]!==0?null:n.map((s,o)=>q8(t.slice(s,n[o+1]).replace(/\n+---\s*$/,"").trim()))}const kh=m.createContext(null);function Wi(){return m.useContext(kh)}const X8=["system","memory","tools","skills","files","results","chat"];function IT(e){const t=e.contextWindow&&e.contextWindow>0?e.contextWindow:e.used;if(!(t>0))return[];const n=new Map;if(e.parts&&e.parts.length>0)for(const s of e.parts)n.set(s.kind,s.tokens);else{const{buckets:s}=e;n.set("system",s.system),n.set("memory",s.instructions+s.reminders),n.set("tools",s.tools),n.set("skills",s.skills),n.set("chat",s.conversation+s.compaction)}return X8.flatMap(s=>{const o=n.get(s)??0;return o<=0?[]:[{kind:s,tokens:o,width:Math.round(o/t*1e3)/10}]})}const $d=8,Yw=(e,t)=>e.reduce((n,s)=>n+(s.tag===t?s.n??1:1),0),Xw=e=>e.reduce((t,n)=>t+n.tokens,0);function Zw(e,t){const n=e?.find(o=>o.kind===t)?.items??[];if(n.length<=$d)return n;if(t==="chat"){const o=n.filter(d=>d.tag==="compacted"),r=n.filter(d=>d.tag!=="compacted"),a=$d-o.length-1,l=r.slice(0,r.length-a);return[...o,{name:"earlier",tag:"turns",n:Yw(l,"turns"),tokens:Xw(l)},...r.slice(r.length-a)]}const s=n.slice($d-1);return[...n.slice(0,$d-1),{name:"other",tag:"more",n:Yw(s,"more"),tokens:Xw(s)}]}function Z8(e){switch(e.tag){case"more":return{key:"{{count}} more",vars:{count:e.n??0}};case"turns":return{key:"Earlier {{count}} turns",vars:{count:e.n??0}};case"turn":return{key:"Turn {{count}}",vars:{count:e.name}};case"compacted":return{key:"Compacted summary"};case"reminder":return{key:"System reminders"};default:return{raw:e.name}}}function J8(e,t){return!e||e<=0||t===void 0||t>=e?null:Math.round((1-t/e)*100)}const Ip=e=>({type:"settings",link:{category:e,rowId:`${e}.root`}});function Q8(e,t,n){const s=()=>{const o=sA(t.name,n);return o?{type:"file",rel:o}:null};switch(e){case"files":return t.tag==="read"||t.tag==="shell"?s():null;case"memory":return t.tag==="project"?s()??Ip("instructions"):null;case"tools":return t.tag==="more"?null:Ip(t.tag==="mcp"?"mcp":"tools");case"skills":return t.tag==="more"?null:Ip("skills");default:return null}}const eU=new TextEncoder,tU=new TextDecoder("utf-8",{ignoreBOM:!0}),nU=/[\uD800-\uDFFF]/,wm=1024;let Kr=new Uint8Array(wm);function sU(){Kr.length!==wm&&(Kr=new Uint8Array(wm))}function as(e){if(e.length===0)return e;if(nU.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;Kr.length<t&&(Kr=new Uint8Array(t));const{written:n}=eU.encodeInto(e,Kr);return tU.decode(Kr.subarray(0,n))}const iU=4096,oU=.5;function rU(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=lU(e,s);o!=null&&(t.hunkContent.splice(n,1,...o),n+=o.length-1)}aU(t,e)}}function aU(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 lU(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)>iU)return null;const d=[];for(let x=0;x<n;x++)d.push(Jw(e.deletionLines[o+x]??""));const c=[];for(let x=0;x<s;x++)c.push(Jw(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+=cU(d[y+(u?0:x)],c[y+(u?x:0)]);x===0?p=v+a*oU:v>p&&(p=v,h=x)}if(h===0)return null;const f=[],g=(x,v,y,b)=>{(x>0||v>0)&&f.push({type:"change",deletions:x,additions:v,deletionLineIndex:y,additionLineIndex:b})};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 dU=/\s+/g;function Jw(e){return e.replace(dU,"")}function cU(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 uU(e,t){try{return hU(e,t)}finally{sU()}}function hU(e,{cacheKey:t,isGitDiff:n=lA.test(e),oldFile:s,newFile:o,throwOnError:r=!1}={}){let a=0;const l=xU(e,"@@ ");let d;const c=s==null||o==null;let u=0,h=0;for(const p of l){const f=ET(p),g=f[0];if(g==null){if(r)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",p);continue}const x=mU(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?Qw(o.contents):[],deletionLines:!c&&s!=null&&o!=null?Qw(s.contents):[],cacheKey:ty(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 E=A.trim().match(iA),D=E?.[1]??E?.[2],T=E?.[3]??E?.[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=as(T.trim()),D!==T&&(d.prevName=as(D.trim()));continue}const I=A.startsWith("---")||A.startsWith("+++")?A.match(n?oA:rA):null;if(I!=null){const[,E,D]=I;if(E==="---"&&D!=="/dev/null"){const T=as(D.trim());d.prevName=T,d.name=T}else E==="+++"&&D!=="/dev/null"&&(d.name=as(D.trim()))}else if(n){if(A.startsWith("new mode ")&&(d.mode=as(A.slice(8).trim())),A.startsWith("old mode ")&&(d.prevMode=as(A.slice(8).trim())),A.startsWith("new file mode")&&(d.type="new",d.mode=as(A.slice(13).trim())),A.startsWith("deleted file mode")&&(d.type="deleted",d.mode=as(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[,E,D,T]=A.trim().match(aA)??[];E!=null&&(d.prevObjectId=as(E)),D!=null&&(d.newObjectId=as(D)),T!=null&&(d.mode=as(T))}A.startsWith("rename from ")&&(d.prevName=as(A.slice(12).trim())),A.startsWith("rename to ")&&(d.name=as(A.slice(10).trim()))}}continue}let b,w;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:C}=x;u=c?u:C-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:C,deletionLines:y,deletionLineIndex:u,additionLineIndex:h,hunkContent:[],hunkContext:ty(x.hunkContext),hunkSpecs:as(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let S=0,k=0;for(let A=1;A<f.length;A++){const I=f[A];if(S>=N.additionCount&&k>=N.deletionCount&&!I.startsWith("\\")){if(r&&pU(I)&&!fU(I))throw Error("parsePatchContent: hunk has more lines than expected");break}const E=I[0];if(E!=="+"&&E!=="-"&&E!==" "&&E!=="\\"){if(r)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${E}", full line: "${I}"`),console.error("processFile: invalid rawLine:",I);continue}const D=vU(E);if(D==="addition"){if(r&&S>=N.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const T=Ep(I);(b==null||b.type!=="change")&&(b=Pp("change",u,h),N.hunkContent.push(b)),h++,S++,c&&d.additionLines.push(T),b.additions++,v++,w="addition"}else if(D==="deletion"){if(r&&k>=N.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const T=Ep(I);(b==null||b.type!=="change")&&(b=Pp("change",u,h),N.hunkContent.push(b)),u++,k++,c&&d.deletionLines.push(T),b.deletions++,y++,w="deletion"}else if(D==="context"){if(r&&(k>=N.deletionCount||S>=N.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const T=Ep(I);(b==null||b.type!=="context")&&(b=Pp("context",u,h),N.hunkContent.push(b)),h++,u++,S++,k++,c&&(d.deletionLines.push(T),d.additionLines.push(T)),b.lines++,w="context"}else if(D==="metadata"&&b!=null){if(b.type==="context"?(N.noEOFCRAdditions=!0,N.noEOFCRDeletions=!0):w==="deletion"?N.noEOFCRDeletions=!0:w==="addition"&&(N.noEOFCRAdditions=!0),c&&(w==="addition"||w==="context")){const T=d.additionLines.length-1;T>=0&&(d.additionLines[T]=Dl(d.additionLines[T]))}if(c&&(w==="deletion"||w==="context")){const T=d.deletionLines.length-1;T>=0&&(d.deletionLines[T]=Dl(d.deletionLines[T]))}}}if(r&&(S!==N.additionCount||k!==N.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");N.additionLines=v,N.deletionLines=y,N.collapsedBefore=Math.max(xa(N.additionStart,N.additionCount)-a,0),d.hunks.push(N),a=uo(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=uo(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),rU(d),d}}function Qw(e){const t=ET(e);for(let n=0;n<t.length;n++)t[n]=as(t[n]);return t}function ET(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 pU(e){const t=e[0];return t==="+"||t==="-"||t===" "}function fU(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 mU(e){if(!e.startsWith("@@ -"))return;let t=4;const n=Vd(e,t);if(n==null)return;const s=n.value;t=n.endIndex;let o=1;if(e[t]===","){const u=Vd(e,t+1);if(u==null)return;o=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const r=Vd(e,t);if(r==null)return;const a=r.value;t=r.endIndex;let l=1;if(e[t]===","){const u=Vd(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=gU(e.slice(c+1))),{additionCount:l,additionStart:a,deletionCount:o,deletionStart:s,hunkContext:d}}function Vd(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 gU(e){return e.endsWith(`\r
|
|
32
|
-
`)?e.slice(0,-2):e.endsWith(`
|
|
33
|
-
`)?e.slice(0,-1):e}function xU(e,t){if(e.length===0)return[""];const n=`
|
|
34
|
-
${t}`,s=e.startsWith(t)?0:ey(e,n,0);if(s===-1)return[e];const o=[];s>0&&o.push(e.slice(0,s));let r=s;for(;;){const a=ey(e,n,r+1);if(a===-1)break;o.push(e.slice(r,a)),r=a}return o.push(e.slice(r)),o}function ey(e,t,n){const s=e.indexOf(t,n);return s===-1?-1:s+1}function ty(e){return e==null?e:as(e)}function vU(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Ep(e){const t=e.slice(1);return as(t===""?`
|
|
35
|
-
`:t)}function Pp(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 bU extends dA{constructor(){super(...arguments),this.tokenize=yU}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 wU=new bU;function ny(e,t,n){return wU.diff(e,t,n)}function yU(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 SU(e){for(let t=0;t<e.length;t++)if(e[t]<" "||e[t]>"~"||e[t]==='"'||e[t]==="\\")return!0;return!1}function ko(e){if(!SU(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 sy={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function iy(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;ny(n,s,Object.assign(Object.assign({},l),{callback:h=>{const p=c(h);u(p)}}))}else return c(ny(n,s,l));function c(u){if(!u)return;u.push({value:"",lines:[]});function h(b){return b.map(function(w){return" "+w})}const p=[];let f=0,g=0,x=[],v=1,y=1;for(let b=0;b<u.length;b++){const w=u[b],_=w.lines||kU(w.value);if(w.lines=_,w.added||w.removed){if(!f){const C=u[b-1];f=v,g=y,C&&(x=d>0?h(C.lines.slice(-d)):[],f-=x.length,g-=x.length)}for(const C of _)x.push((w.added?"+":"-")+C);w.added?y+=_.length:v+=_.length}else{if(f)if(_.length<=d*2&&b<u.length-2)for(const C of h(_))x.push(C);else{const C=Math.min(_.length,d);for(const S of h(_.slice(0,C)))x.push(S);const N={oldStart:f,oldLines:v-f+C,newStart:g,newLines:y-g+C,lines:x};p.push(N),f=0,g=0,x=[]}v+=_.length,y+=_.length}}for(const b of p)for(let w=0;w<b.lines.length;w++)b.lines[w].endsWith(`
|
|
41
|
-
`)?b.lines[w]=b.lines[w].slice(0,-1):(b.lines.splice(w+1,0,"\"),w++);return{oldFileName:e,newFileName:t,oldHeader:o,newHeader:r,hunks:p}}}function ym(e,t){var n,s,o,r,a,l;if(t||(t=sy),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=>ym(u,t)).join(`
|
|
42
|
-
`)}const d=[];if(e.isGit){if(t=sy,!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 "+ko(u)+" "+ko(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 "+ko(((o=e.oldFileName)!==null&&o!==void 0?o:"").replace(/^a\//,""))),d.push("rename to "+ko(((r=e.newFileName)!==null&&r!==void 0?r:"").replace(/^b\//,"")))),e.isCopy&&(d.push("copy from "+ko(((a=e.oldFileName)!==null&&a!==void 0?a:"").replace(/^a\//,""))),d.push("copy to "+ko(((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("--- "+ko(e.oldFileName)+(e.oldHeader?" "+e.oldHeader:"")),d.push("+++ "+ko(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 CU(e,t,n,s,o,r,a){if(typeof a=="function"&&(a={callback:a}),a?.callback){const{callback:l}=a;iy(e,t,n,s,o,r,Object.assign(Object.assign({},a),{callback:d=>{l(d?ym(d,a.headerOptions):void 0)}}))}else{const l=iy(e,t,n,s,o,r,a);return l?ym(l,a?.headerOptions):void 0}}function kU(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 jU="/dev/null";function xo(e,t,n,s=!1){if(e===null&&t===null)throw new Error("parseDiffFromFile: You must pass oldFile, newFile, or both");const o=e??oy(),r=t??oy(),a=uU(CU(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 oy(){return{name:jU,contents:""}}function _U(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function NU(e){return{...e,hunks:e.hunks.map(t=>({...t,hunkContent:t.hunkContent.map(n=>({...n}))})),deletionLines:[...e.deletionLines],additionLines:[...e.additionLines]}}function Sm(e){return e!==""?e.split(cA):[]}function Cm(e,t,n){const s=e==="clone"?NU(t):t;if(!s.isPartial)throw new Error("hydratePartialDiff: fileDiff must be partial");switch(s.type){case"change":case"rename-changed":return TU(s,IU(s,n),ry(s,n));case"rename-pure":{const o=ry(s,n);EU(s,n);const r=Sm(o.contents);return s.isPartial=!1,s.deletionLines=r,s.additionLines=r,PT(s,null,o),s}}throw new Error(`hydratePartialDiff: ${s.type} diffs cannot be hydrated from loaded files`)}function TU(e,t,n){const s=Sm(t.contents),o=Sm(n.contents),{hunks:r,splitLineCount:a,unifiedLineCount:l}=DU(e.hunks,o.length);return e.hunks=r,e.splitLineCount=a,e.unifiedLineCount=l,e.isPartial=!1,e.deletionLines=s,e.additionLines=o,PT(e,t,n),e}function DU(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(xa(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=uo(a.additionStart,a.additionCount)}if(r.length>0){const a=r[r.length-1],l=uo(a.additionStart,a.additionCount),d=Math.max(t-l,0);n+=d,s+=d}return{hunks:r,splitLineCount:n,unifiedLineCount:s}}function IU(e,t){if(t.oldFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile`);return t.oldFile}function ry(e,t){if(t.newFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires newFile`);return t.newFile}function EU(e,t){if(t.oldFile!==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile to be null`)}function PU(e,t,n){return e.cacheKey!=null?`${e.cacheKey}:hydrated`:AU(t,n)}function PT(e,t,n){const s=PU(e,t,n);if(s==null){delete e.cacheKey;return}e.cacheKey=s}function AU(e,t){return e!=null&&t!=null?e.cacheKey!=null&&t.cacheKey!=null?`${e.cacheKey}:${t.cacheKey}`:void 0:e?.cacheKey??t?.cacheKey}var MU=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 Wd(e){return xs({tagName:"div",properties:{"data-content-buffer":"","data-buffer-size":e,style:`grid-row: span ${e};min-height:calc(${e} * 1lh)`}})}function Ud(e){return xs({tagName:"div",children:[xs({tagName:"span",children:[_c("No newline at end of file")]})],properties:{"data-no-newline":"","data-line-type":e,"data-column-content":""}})}function Ap(e){return xs({tagName:"div",children:[uA({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 Dr({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(xs({tagName:"div",children:[_c(t)],properties:{"data-separator-wrapper":""}})),(e==="line-info"||e==="line-info-basic")&&t!=null){const c=[];n!=null&&(s?(r||(c.push(Ap("up")),l++),a||(c.push(Ap("down")),l++)):(c.push(Ap(!r&&!a?"both":r?"down":"up")),l++)),c.push(xs({tagName:"div",children:[xs({tagName:"span",children:[_c(t)],properties:{"data-unmodified-lines":""}})],properties:{"data-separator-content":""}})),s&&n!=null&&c.push(xs({tagName:"div",children:[_c("Expand all")],properties:{role:"button","data-expand-button":"","data-expand-all-button":""}})),d.push(xs({tagName:"div",children:c,properties:{"data-separator-wrapper":"","data-separator-multi-button":l>1?"":void 0}}))}return e==="custom"&&o!=null&&d.push(xs({tagName:"slot",properties:{name:o}})),xs({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 RU(e,t){return`hunk-separator-${e}-${t}`}function LU(e){const t=e.at(-1);return t==null?0:Math.max(uo(t.additionStart,t.additionCount),uo(t.deletionStart,t.deletionCount))}function km(e){return e.startingLine===0&&e.totalLines===1/0&&e.bufferBefore===0&&e.bufferAfter===0}function no(e,t){const n=xo({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 OU(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 zU(e){for(const t of e)if(t.trim().length>0)return!1;return!0}function jm(e,t){return t.length>0&&t.length<e.deletionLines.length&&zU(t)}function _u(e,t,n){const s=e.deletionLines.join(""),o=OU(t.length,s),r=xo({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 Bc(e,t){return _u(e,[""],t)}function AT(e,t){if(e.additionLines.length===0)return Bc(e,t);if(jm(e,e.additionLines))return _u(e,e.additionLines,t);const n=e.additionLines,s=no(e,t);return MT(s,n),s}function GU(e){return e.length>1&&e.at(-1)===""}function MT(e,t){if(!GU(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&&uo(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,Zx(e);return}}}function FU(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||Dl(a)===Dl(l))return qi(e,no(e,n))}const o=HU(e,s);if(o.size===0)return qi(e,no(e,n));for(const r of o)if(!$U(e,r,n))return qi(e,no(e,n));return Zx(e),hA(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 HU(e,t){const n=new Set;for(const s of t){const o=BU(e,s);if(o==null)return new Set;n.add(o)}return n}function BU(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 $U(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=xo({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:(VU(s,l),RT(e,t),!0)}function RT(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 VU(e,t){const n=e.additionLineIndex,s=e.deletionLineIndex;e.hunkContent=t.hunkContent.map(o=>LT(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,Xx(e)}function LT(e,t,n){return{...e,additionLineIndex:e.additionLineIndex+t,deletionLineIndex:e.deletionLineIndex+n}}function Xx(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 Zx(e){let t=0,n=0,s=0;for(const o of e.hunks)o.collapsedBefore=Math.max(xa(o.additionStart,o.additionCount)-s,0),o.splitLineStart=t+o.collapsedBefore,o.unifiedLineStart=n+o.collapsedBefore,Xx(o),t+=o.collapsedBefore+o.splitLineCount,n+=o.collapsedBefore+o.unifiedLineCount,s=uo(o.additionStart,o.additionCount);if(e.hunks.length>0){const o=e.hunks[e.hunks.length-1],r=Math.max(e.additionLines.length-uo(o.additionStart,o.additionCount),0);t+=r,n+=r}e.splitLineCount=t,e.unifiedLineCount=n}const ay=new WeakMap;function WU(e){return e.length>1&&e[e.length-1]===""?e.slice(0,-1):e}function UU(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 _m(e,t){const n=e.hunks,s=e.additionLines,o=WU(s),r=o===s?e:{...e,additionLines:o},a=t7(n,e7(r,t),e.deletionLines.length),l=i7(r,a);if(e.additionLines=o,e.hunks=l,e.editSessionDirty=!0,l7(e),MT(e,s),!!r7(n,e.hunks))return{regions:a.map(d=>d.previousSpan)}}function KU(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<Nu(h)+h.additionCount)break;l++}const c=r[l],u=c==null?void 0:Nu(c);if(u==null||d<u||a!=null&&a!==l)return _m(e,n);a=l}if(a!=null){if(qU(e,o,a,s,n)){e.editSessionDirty=!0;return}return _m(e,n)}}function qU(e,t,n,s,o){if(s==null||o?.ignoreWhitespace===!0||o?.stripTrailingCr===!0)return!1;const r=YU(e),a=e.hunks[n];if(a.hunkContent.some(XU))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 YU(e){const t=ay.get(e);if(t?.lines===e.deletionLines)return t.set;const n=new Set(e.deletionLines);return ay.set(e,{lines:e.deletionLines,set:n}),n}function XU(e){return e?.type==="change"&&(e.additions===0||e.deletions===0)}function ZU(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 JU(e,t,n){const s=[];if(e.isPartial)return s;for(const[r,a]of e.hunks.entries()){const l=Il({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:t,hunkIndex:r,collapsedContextThreshold:n});if(l.rangeSize<=n)continue;const d=yr(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=El({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=yr(r)+r.deletionCount;s.push([a,a+o.fromStart])}return s}function QU(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=yr(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,yr(o)+o.deletionCount,e.deletionLines.length),n}function Nm(e,t){return e.editSessionDirty!==!0?!1:(e.editSessionDirty=void 0,Object.assign(e,e.additionLines.length<=1&&e.additionLines.join("")===""?no(e,t):AT(e,t)),!0)}function e7(e,t){if(UU(e.deletionLines,e.additionLines)==null)return[];const n=xo({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=LT(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 t7(e,t,n){const s=e.map((a,l)=>{const d=yr(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&&n7(l,d,o[o.length-1])?o.pop():void 0;for(;r<s.length&&s[r].deletionStart<=d;)c=s7(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 n7(e,t,n){return e<=n.deletionEnd&&t>=n.deletionStart}function s7(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 i7(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");ly(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");ly(d,c,o,s),s+=c,o+=c,n.push(o7(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 o7(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:Kd(t.additionStart,s),additionCount:s,additionLines:r,additionLineIndex:cy(t.additionStart,s),deletionStart:Kd(t.deletionStart,o),deletionCount:o,deletionLines:a,deletionLineIndex:cy(t.deletionStart,o),hunkContent:n,hunkSpecs:`@@ -${Kd(t.deletionStart,o)},${o} +${Kd(t.additionStart,s)},${s} @@`,splitLineStart:0,splitLineCount:0,unifiedLineStart:0,unifiedLineCount:0,noEOFCRAdditions:!1,noEOFCRDeletions:!1};return Xx(l),l}function ly(e,t,n,s){t>0&&e.push({type:"context",lines:t,additionLineIndex:n,deletionLineIndex:s})}function r7(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(yr(s)!==yr(o)||s.deletionCount!==o.deletionCount||Nu(s)!==Nu(o)||s.additionCount!==o.additionCount||s.splitLineCount!==o.splitLineCount||!a7(s,o))return!0}return!1}function a7(e,t){const n=dy(e),s=dy(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*dy(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 Nu(e){return xa(e.additionStart,e.additionCount)}function yr(e){return xa(e.deletionStart,e.deletionCount)}function Kd(e,t){return t===0?e:e+1}function cy(e,t){return t===0?e-1:e}function l7(e){Zx(e);for(let t=0;t<e.hunks.length;t++)RT(e,t)}let d7=-1;var c7=class{options;onRenderUpdate;workerManager;__id=`diff-hunks-renderer:${++d7}`;highlighter;diff;expandedHunks=new Map;deletionAnnotations={};additionAnnotations={};computedLang="text";renderCache;editSessionActive=!1;constructor(e={theme:Pi},t,n){this.options=e,this.onRenderUpdate=t,this.workerManager=n,n?.isWorkingPool()!==!0&&(this.highlighter=Wh(e.theme??Pi)?pA():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,Bc(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||Nc(e.diff)||Xd(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);Nr(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)??fA}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=Dl(g);f&&(o.additionLines[c]=mA(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,b])=>v===0&&y===""?b===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:b}:{type:"element",tagName:"span",properties:{"data-char":v,style:`color:${y};`},children:[{type:"text",value:b}]})}}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,Bc(o,this.options.parseDiffOptions)),this.markEditSessionPass(o),d=!0;else if(jm(o,o.additionLines))Object.assign(o,_u(o,o.additionLines,this.options.parseDiffOptions)),this.markEditSessionPass(o),d=!0;else{const c=KU(o,a,this.options.parseDiffOptions,l);this.applyExpansionRemap(c),d=c!=null}}else Object.assign(o,FU(o,a,this.options.parseDiffOptions));return s.baseThemeType=t,this.renderCache.isDirty=!0,d}applyExpansionRemap(e){e!=null&&(this.expandedHunks=ZU(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=f7(e,s),n.code.additionLines=p7(s,t.additionLines,n.code.additionLines,e),t.additionLines.length<=1&&t.additionLines.join("")===""?(Object.assign(t,Bc(t,this.options.parseDiffOptions)),n.code.additionLines[0]=Tm(0,e.getLineText(0)),this.markEditSessionPass(t)):this.editSessionActive?this.applySessionDocumentChange(t):Object.assign(t,AT(t,this.options.parseDiffOptions)),this.renderCache.isDirty=!0}applySessionDocumentChange(e){const{parseDiffOptions:t}=this.options,n=e.additionLines;if(jm(e,n)){Object.assign(e,_u(e,n,t)),this.markEditSessionPass(e);return}this.applyExpansionRemap(_m(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=>gA(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=Pi,headerRenderMode:v="default",tokenizeMaxLineLength:y=1e3,tokenizeMaxLength:b=xA,useTokenTransformer:w=!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:b,useTokenTransformer:w,useCSSClasses:_}}async initializeHighlighter(){return this.highlighter=await vA(bA(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=Xd(e,this.getTokenizeMaxLength());let s=this.workerManager?.getDiffResultCache(e);s!=null&&!Nr(t,s.options)&&(s=void 0),this.renderCache??={diff:e,highlighted:!n&&!Nc(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??Uh(e.name),this.initializeHighlighter())}getLocalHighlightTheme(){return this.workerManager?.getDiffRenderOptions().theme??this.options.theme??Pi}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}:!Hr(e,n.diff)||!Nr(t,n.options)?{options:t,forceHighlight:!0}:{options:t,forceHighlight:!1}}renderDiff(e=this.renderCache?.diff,t=Zv){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||Nc(e)||Xd(e,this.getTokenizeMaxLength()),c=!Hr(e,this.renderCache.diff),u=!zk(this.renderCache.renderRange,t);if(!this.editSessionActive&&this.workerManager?.isWorkingPool()===!0){const h=this.renderCache.result==null&&this.renderCache.highlighted&&!d&&!c&&km(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,km(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??Uh(e.name);const h=this.highlighter!=null&&Wh(o.theme),p=this.highlighter!=null&&Jv(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=Zv){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 wA({type:"diff",diffIndicators:s,disableBackground:o,disableLineNumbers:r,overflow:a,split:e,totalLines:t,customProperties:n})}async asyncHighlight(e){const t=Xd(e,this.getTokenizeMaxLength());this.computedLang=t?"text":e.lang??Uh(e.name);const n=this.highlighter!=null&&Wh(this.getLocalHighlightTheme()),s=t||this.highlighter!=null&&Jv(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=yA(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(Yr({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]=Tm(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||!Nr(this.renderCache.options,n)||!Hr(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||!Nr(t,n.options)))return n}hasHighlightedRenderCache(e,t){const{renderCache:n}=this;return n?.result!=null&&n.highlighted&&Hr(e,n.diff)&&Nr(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=x7(e,this.options.loadDiffFiles!=null),g=!e.isPartial||f;let x=[],v=[],y=[];const b=[],{additionLines:w,deletionLines:_}=n,C={rowCount:0,hunkSeparators:u,additionsContentAST:x,deletionsContentAST:v,unifiedContentAST:y,unifiedGutterAST:Pd(),deletionsGutterAST:Pd(),additionsGutterAST:Pd(),expansionLineCount:d,hunkData:b,incrementRowCount(O=1){C.rowCount+=O},pushToGutter(O,B){switch(O){case"unified":C.unifiedGutterAST.children.push(B);break;case"deletions":C.deletionsGutterAST.children.push(B);break;case"additions":C.additionsGutterAST.children.push(B);break}}},N=SA({fileDiff:e,errorPrefix:"DiffHunksRenderer.processDiffResult"}),S={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"?(C.pushToGutter("additions",ri(void 0,"buffer",this.size)),x?.push(Wd(this.size))):(C.pushToGutter("deletions",ri(void 0,"buffer",this.size)),v?.push(Wd(this.size))),this.size=0,this.side=void 0}}},k=(O,B,Y,U,ee)=>{C.pushToGutter(O,jA(B,Y,U,ee))};function A(O){S.flush(),r==="unified"?Mp("unified",O,C):(Mp("deletions",O,C),Mp("additions",O,C))}this.pushFileLevelAnnotations(e,r,t,C),Yr({diff:e,diffStyle:r,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:l?!0:this.expandedHunks,collapsedContextThreshold:c,callback:({hunkIndex:O,hunk:B,collapsedBefore:Y,collapsedAfter:U,additionLine:ee,deletionLine:L,type:Q})=>{const V=L!=null?L.splitLineIndex:ee.splitLineIndex,ce=ee!=null?ee.unifiedLineIndex:L.unifiedLineIndex;r==="split"&&Q!=="change"&&S.flush(),Y>0&&A({hunkIndex:O,collapsedLines:Y,rangeSize:Math.max(B?.collapsedBefore??0,0),hunkSpecs:B?.hunkSpecs,isFirstHunk:O===0,isLastHunk:!1,isExpandable:g});const ve=r==="unified"?ce:V,_e={type:Q,hunkIndex:O,lineIndex:ve,unifiedLineIndex:ce,splitLineIndex:V,deletionLine:L,additionLine:ee};if(r==="unified"){const oe=this.getUnifiedInjectedRowsForLine?.(_e);oe?.before!=null&&hy(oe.before,C);let Z=L!=null?_[L.lineIndex]:void 0,ae=ee!=null?w[ee.lineIndex]:void 0;if(Z==null&&ae==null){const Ye="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(Ye,{file:e.name}),new Error(Ye)}const be=Q==="change"?ee!=null?"change-addition":"change-deletion":Q,ze=this.getUnifiedLineDecoration({type:Q,lineType:be,additionLineIndex:ee?.lineIndex,deletionLineIndex:L?.lineIndex});k("unified",ze.gutterLineType,ee!=null?ee.lineNumber:L.lineNumber,`${ce},${V}`,ze.gutterProperties),ae!=null?ae=Yd(ae,ze.contentProperties,h&&ee!=null?{"data-line":ee.lineNumber,"data-line-index":`${ce},${V}`}:void 0):Z!=null&&(Z=Yd(Z,ze.contentProperties,h&&L!=null?{"data-line":L.lineNumber,"data-line-index":`${ce},${V}`}:void 0)),qd({diffStyle:"unified",type:Q,deletionLine:Z,additionLine:ae,unifiedSpan:this.getAnnotations("unified",L?.lineNumber,ee?.lineNumber,O,ve),createAnnotationElement:Ye=>this.createAnnotationElement(Ye),context:C}),oe?.after!=null&&hy(oe.after,C)}else{const oe=this.getSplitInjectedRowsForLine?.(_e);oe?.before!=null&&py(oe.before,C,S);let Z=L!=null?_[L.lineIndex]:void 0,ae=ee!=null?w[ee.lineIndex]:void 0;const be=this.getSplitLineDecoration({side:"deletions",type:Q,lineIndex:L?.lineIndex}),ze=this.getSplitLineDecoration({side:"additions",type:Q,lineIndex:ee?.lineIndex});if(Z==null&&ae==null){const at="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(at,{file:e.name}),new Error(at)}const Ye=(()=>{if(Q==="change"){if(ae==null)return"additions";if(Z==null)return"deletions"}})();Ye!=null?(S.side!=null&&S.side!==Ye&&S.flush(),S.side=Ye,S.increment()):Q==="change"&&S.flush();const Ve=this.getAnnotations("split",L?.lineNumber,ee?.lineNumber,O,ve);if(Ve!=null&&S.size>0&&S.flush(),L!=null){const at=Yd(Z,be.contentProperties,h?{"data-line":L.lineNumber,"data-line-index":`${L.unifiedLineIndex},${V}`}:void 0);k("deletions",be.gutterLineType,L.lineNumber,`${L.unifiedLineIndex},${V}`,be.gutterProperties),at!=null&&(Z=at)}if(ee!=null){const at=Yd(ae,ze.contentProperties,h?{"data-line":ee.lineNumber,"data-line-index":`${ee.unifiedLineIndex},${V}`}:void 0);k("additions",ze.gutterLineType,ee.lineNumber,`${ee.unifiedLineIndex},${V}`,ze.gutterProperties),at!=null&&(ae=at)}qd({diffStyle:"split",type:Q,additionLine:ae,deletionLine:Z,...Ve,createAnnotationElement:at=>this.createAnnotationElement(at),context:C}),oe?.after!=null&&py(oe.after,C,S)}const De=r==="split"&&B!=null&&V===B.splitLineStart+B.splitLineCount-1,me=O===e.hunks.length-1&&B!=null&&(r==="split"?V===B.splitLineStart+B.splitLineCount-1:ce===B.unifiedLineStart+B.unifiedLineCount-1),$=De?B.noEOFCRDeletions:!1,z=De?B.noEOFCRAdditions:!1,de=(L?.noEOFCR??!1)||$,X=(ee?.noEOFCR??!1)||z;if(X||de){if(r==="split"&&S.flush(),de){const oe=Q==="context"||Q==="context-expanded"?Q:"change-deletion";r==="unified"?(C.unifiedContentAST.push(Ud(oe)),C.pushToGutter("unified",ri(oe,"metadata",1))):(C.deletionsContentAST.push(Ud(oe)),C.pushToGutter("deletions",ri(oe,"metadata",1)),X||(C.pushToGutter("additions",ri(void 0,"buffer",1)),C.additionsContentAST.push(Wd(1))))}if(X){const oe=Q==="context"||Q==="context-expanded"?Q:"change-addition";r==="unified"?(C.unifiedContentAST.push(Ud(oe)),C.pushToGutter("unified",ri(oe,"metadata",1))):(C.additionsContentAST.push(Ud(oe)),C.pushToGutter("additions",ri(oe,"metadata",1)),de||(C.pushToGutter("deletions",ri(void 0,"buffer",1)),C.deletionsContentAST.push(Wd(1))))}C.incrementRowCount(1)}u!=="simple"&&u!=="metadata"&&(U>0||me&&f)&&A({hunkIndex:Q==="context-expanded"?O:O+1,collapsedLines:me&&f?"unknown":U,rangeSize:N,hunkSpecs:void 0,isFirstHunk:!1,isLastHunk:!0,isExpandable:g}),C.incrementRowCount(1)}}),r==="split"&&S.flush();const I=Math.max(LU(e.hunks),e.additionLines.length??0,e.deletionLines.length??0),E=t.bufferBefore>0||t.bufferAfter>0,D=!p&&e.type!=="deleted",T=!p&&e.type!=="new",H=C.rowCount>0||E;x=D&&H?x:void 0,v=T&&H?v:void 0,y=p&&H?y:void 0;const F=this.createPreElement(v!=null&&x!=null,I);return{unifiedGutterAST:p&&H?C.unifiedGutterAST.children:void 0,unifiedContentAST:y,deletionsGutterAST:T&&H?C.deletionsGutterAST.children:void 0,deletionsContentAST:v,additionsGutterAST:D&&H?C.additionsGutterAST.children:void 0,additionsContentAST:x,hunkData:b,preNode:F,themeStyles:s,baseThemeType:o,headerElement:a?void 0:this.renderHeader(this.diff),totalLines:I,rowCount:C.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=Pd(n);return o.properties.style=`grid-row: span ${t.rowCount}`,[o,CA(s,t.rowCount)]}renderFullAST(e,t=[]){const n=this.getOptionsWithDefaults().hunkSeparators==="line-info",s=this.renderCodeAST("unified",e);if(s!=null)return t.push(xs({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(xs({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(xs({tagName:"code",children:r,properties:{"data-code":"","data-container-size":n?"":void 0,"data-additions":""}})),{...e.preNode,children:t}}renderFullHTML(e,t=[]){return ar(this.renderFullAST(e,t))}renderPartialHTML(e,t){return t==null?ar(e):ar(xs({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(!Gk(n))return;const o=e.type!=="new"?uy(Qv(this.deletionAnnotations)):[],r=e.type!=="deleted"?uy(Qv(this.additionAnnotations)):[];if(o.length===0&&r.length===0)return;const a=-1,l=-1,{createAnnotationElement:d}=this;if(t==="unified"){qd({diffStyle:t,type:"context",unifiedSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:o.concat(r)},createAnnotationElement:d,context:s});return}qd({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(oa(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(oa(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 kA({fileOrDiff:e,mode:t,stickyHeader:n})}};function uy(e){return e?.map(t=>oa(t))??[]}const u7=new Intl.PluralRules("en-US");function h7(e){return`${e} unmodified line${u7.select(e)==="one"?"":"s"}`}function hy(e,t){for(const n of e)t.unifiedContentAST.push(n.content),t.pushToGutter("unified",n.gutter),t.incrementRowCount(1)}function py(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 qd({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 Mp(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,Dr({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),c.push(Dr({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),e!=="additions"&&d.incrementRowCount(1));return}if(d.hunkSeparators==="simple"){t>0&&(d.pushToGutter(e,Dr({type:"simple",isFirstHunk:r,isLastHunk:!1})),c.push(Dr({type:"simple",isFirstHunk:r,isLastHunk:!1})),e!=="additions"&&d.incrementRowCount(1));return}const u=RU(e,t),h=s>d.expansionLineCount,p=l?t:void 0,f=typeof n=="number"?h7(n):"More unchanged context may be available";d.pushToGutter(e,Dr({type:d.hunkSeparators,content:f,expandIndex:p,chunked:h,slotName:u,isFirstHunk:r,isLastHunk:a})),c.push(Dr({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 Yd(e,t,n){return e==null||e.type!=="element"||t==null&&n==null?e:{...e,properties:{...e.properties,...t,...n}}}function fy(e){return e.length>0&&e[e.length-1]===""?e.length-1:e.length}function p7(e,t,n,s){const o=fy(e),r=fy(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]??=Tm(u,s.getLineText(u));return c}function Tm(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 f7(e,t){const n=[],s=g7(t);for(let o=0;o<e.lineCount;o++){const r=e.getLineText(o,!0);n.push(o<e.lineCount-1&&!m7(r)?r+s:r)}return n}function m7(e){return e.endsWith(`
|
|
52
|
-
`)||e.endsWith("\r")}function g7(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 Xd(e,t){return Math.max(e.additionLines.length,e.deletionLines.length)>t}function x7(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function v7(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side&&e.metadata===t.metadata}function b7(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 Dm(e,t=300){let n;try{await Promise.race([e(),new Promise(s=>{n=setTimeout(s,t)})])}finally{n!=null&&clearTimeout(n)}}function Im({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 w7(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:_A(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 y7(e){return e.isPartial&&(e.type==="change"||e.type==="rename-changed"||e.type==="rename-pure")}let S7=-1;var OT=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file-diff:${++S7}`;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:Pi},n,s=!1){this.options=t,this.workerManager=n,this.isContainerManaged=s,this.hunksRenderer=this.createHunksRenderer(t),this.resizeManager=new NA,this.scrollSyncManager=new MU,this.interactionManager=new TA("diff",e0(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 w7(t)}createHunksRenderer(t){return new c7(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=xa(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(e0(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&&!Fk(this.appliedThemeCSS.theme,this.options.theme??Pi)}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){yf(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=Im(a,"FileDiff.hydrate"),d=l?.oldFile,c=l?.newFile;this.hydrateElements(t,n),j7(this.pre,C7({fileDiff:r,oldFile:d,newFile:c}),this.options.collapsed)||_7(this.headerElement,k7({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),DA(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?xo(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||!y7(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||(Cm("merge",t,n),this.setHydratedState(n),await Dm(()=>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=Im(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(),b=u!=null,w=b&&(!my(h,this.deletionFile)||!my(p,this.additionFile));let _=t!=null&&t!==this.fileDiff;const C=r!=null&&(r.length>0||this.lineAnnotations.length>0)?r!==this.lineAnnotations:!1;if(!f&&zk(v,this.renderRange)&&!s&&!C&&!y&&(t!=null&&t===this.fileDiff||t==null&&!w))return this.applyCachedThemeState(g);let N;t==null&&b&&(w||this.fileDiff==null)&&(N=xo(u.oldFile,u.newFile,this.options.parseDiffOptions));const{renderRange:S}=this;if(this.renderRange=v,b?(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()&&(Nm(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:k=!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 I=this.hunksRenderer.renderDiff(this.fileDiff,IA);I!=null&&this.applyThemeState(a,I.themeStyles,g,I.baseThemeType),I?.headerElement!=null&&this.applyHeaderToDOM(I.headerElement,a),this.renderSeparators([]),this.injectUnsafeCSS()}catch(I){if(k)throw I;console.error(I),I instanceof Error&&this.applyErrorToDOM(I,a)}return o||this.emitPostRender(),!0}try{const I=this.getOrCreatePreNode(a);if(!(this.canPartiallyRender(s,C,w||_||y)&&this.applyPartialRender({previousRenderRange:S,renderRange:v}))){const E=this.hunksRenderer.renderDiff(this.fileDiff,v);if(E==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(a,E.themeStyles,g,E.baseThemeType),E.headerElement!=null&&this.applyHeaderToDOM(E.headerElement,a),E.additionsContentAST!=null||E.deletionsContentAST!=null||E.unifiedContentAST!=null?this.applyHunksToDOM(I,E):this.pre!=null&&(this.pre.remove(),this.pre=void 0),this.renderSeparators(E.hunkData)}this.applyBuffers(I,v),this.injectUnsafeCSS(),this.renderAnnotations(),this.renderGutterUtility(),this.managersDirty=!0,n||this.flushManagers(),this.editor!=null&&this.syncRenderViewToEditor()}catch(I){if(k)throw I;console.error(I),I instanceof Error&&this.applyErrorToDOM(I,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||km(t))return t;const{diffStyle:s="split",expandUnchanged:o=!1,collapsedContextThreshold:r=1}=this.options;let a,l;return Yr({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=JU(t,this.hunksRenderer.getExpandedHunksMap(),n);return Nm(t,this.options.parseDiffOptions),this.hunksRenderer.setExpandedHunksMap(QU(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 Hk({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 EA({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]=t0(h);if(t<p){const g=Il({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=El({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]=t0(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(){Bk(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||Nc(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||!b7(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}-${oa(o)}`;let a=this.annotationCache.get(r);if(a==null||!v7(o,a.annotation)){a?.element.remove();const l=n(o);if(l==null)continue;a={element:PA(oa(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=AA();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:Sf(s)&&s.hasAttribute("data-theme-css")?(this.themeCSSStyle??=s,this.hasAdoptedThemeCSS=!0):Sf(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=MA;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??ar(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,$k,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,RA,c),this.headerFilenameSuffix=this.upsertHeaderSlotElement(n,this.headerFilenameSuffix,LA,u),this.headerMetadata=this.upsertHeaderSlotElement(n,this.headerMetadata,OA,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??=zA(),this.unsafeCSSStyle.parentNode!==n&&n.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=GA(t),this.appliedUnsafeCSS=t)}}applyThemeState(t,n,s,o){const r=t.shadowRoot??t.attachShadow({mode:"open"}),a=o??s,l=this.options.theme??Pi,d=typeof l=="string"?l:{...l},c=n0(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=FA({shadowRoot:r,currentNode:this.themeCSSStyle,themeCSS:WA(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=HA(this.themeCSSStyle.textContent??"",n0(t)))}shouldGuardRebuildScroll(){return this.editor!=null&&BA()}applyHunksToDOM(t,n){this.shouldGuardRebuildScroll()?s0(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=jo(n[0]),a=jo(n[1]);return r==null||a==null?!1:(o.gutter.innerHTML=ar(r),o.content.innerHTML=ar(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=Kh({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=Kh({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=Kh({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 b=this.lastRowCount-y;const w=(S,k)=>{if(!(k<=0||this.fileDiff==null))return this.hunksRenderer.renderDiff(this.fileDiff,{startingLine:S,totalLines:k,bufferBefore:0,bufferAfter:0})},_=w(u,Math.max(f-u,0));if(_==null&&u<f)return!1;const C=w(g,Math.max(p-g,0));if(C==null&&p>g)return!1;const N=(S,k)=>{if(S!=null){if(l==="unified"&&!Array.isArray(d))this.insertPartialHTML(l,d,S,k);else if(l==="split"&&Array.isArray(d))this.insertPartialHTML(l,d,S,k);else throw new Error("FileDiff.applyPartialRender.applyChunk: invalid chunk application");b+=S.rowCount}};return this.cleanupErrorWrapper(),N(_,"afterbegin"),N(C,"beforeend"),this.lastRowCount!==b&&(this.applyRowSpan(l,d,b),this.lastRowCount=b),!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=jo(a?.[0]),d=jo(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=jo(s?.[0]),r=jo(s?.[1]),a=()=>{for(const[l,d]of[[n.gutter,o],[n.content,r]])d!=null&&(l.innerHTML=ar(d));t.rowCount!==this.lastRowCount&&(this.applyRowSpan("unified",n,t.rowCount),this.lastRowCount=t.rowCount)};this.shouldGuardRebuildScroll()?s0(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=jo(n[0]),r=jo(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};$A(h,this.appliedPreAttributes)||(VA(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 my(e,t){return e==null||t==null?e==null&&t==null:Vk(e,t)}function C7({fileDiff:e,oldFile:t,newFile:n}){return e!=null&&e.hunks.length>0||t!=null||n!=null}function k7({fileDiff:e,oldFile:t,newFile:n}){return e!=null||t!=null||n!=null}function j7(e,t,n=!1){return!n&&e==null&&t}function _7(e,t,n=!1){return e==null&&t&&!n}function jo(e){if(!(e==null||e.type!=="element"))return e.children??[]}function N7({fileDiff:e,metrics:t,disableFileHeader:n,hunkSeparators:s,expandUnchanged:o,expandedHunks:r,collapsedContextThreshold:a,canHydratePartialDiff:l}){let d=Or(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=Il({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 b=Xa({type:s,metrics:t,hunkIndex:p,hunkSpecs:f.hunkSpecs})?.totalHeight??0;d+=b,c+=b}d+=f.splitLineCount*t.lineHeight,c+=f.unifiedLineCount*t.lineHeight;const v=T7(f);d+=v.split*t.lineHeight,c+=v.unified*t.lineHeight;const y=p===h?El({fileDiff:e,hunkIndex:p,expandedHunks:u,collapsedContextThreshold:a,errorPrefix:"computeEstimatedDiffHeights"}):void 0;if(y!=null){const b=(y.fromStart+y.fromEnd)*t.lineHeight;if(d+=b,c+=b,y.collapsedLines>0){const w=rr({type:s,metrics:t})?.totalHeight??0;d+=w,c+=w}}else if(p===h&&e.isPartial&&l){const b=rr({type:s,metrics:t})?.totalHeight??0;d+=b,c+=b}}if(e.hunks.length>0){const p=Wk(t);d+=p,c+=p}return{splitHeight:d,unifiedHeight:c}}function T7(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 D7(e,t)}function D7(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 Em=3e3;let I7=-1;var zT=class extends OT{__id=`little-virtualized-file-diff:${++I7}`;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=qh(n)}setMetrics(e,t=!1){const n=qh(e);!t&&Cf(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||!UA(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=!Vu(t,e),s=n&&L7(t,e);super.setOptions(e),s&&this.resetLayoutCache({forceSimpleRecompute:!0,includeEstimatedHeights:O7(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&&Gk(this.renderRange)){const r=E7(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=G7(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=!Hr(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=qh(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=Or(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 Yr({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:b,additionLine:w})=>{const _=l==="split"?w?.splitLineIndex??b?.splitLineIndex:w?.unifiedLineIndex??b?.unifiedLineIndex;if(_==null)throw new Error("VirtualizedFileDiff.getLinePosition: missing line index data");if(v>0){const N=Xa({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 C=this.getLineHeight(_,(w?.noEOFCR??!1)||(b?.noEOFCR??!1));if(_===c)return f={top:p,height:C},!0;if(p+=C,y>0){const N=rr({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??Or(this.metrics,t)+this.cache.fileAnnotationHeight,c;return Yr({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 b=Xa({type:a,metrics:this.metrics,hunkIndex:u,hunkSpecs:h?.hunkSpecs});b!=null&&(d+=b.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 b=rr({type:a,metrics:this.metrics});b!=null&&(d+=b.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=Cm("clone",e,t);if(await Dm(()=>this.primeHighlightCache(n)),!this.enabled||this.fileDiff!==e)return;this.pendingHydratedDiff={expectedDiff:e,nextDiff:n,files:t}}else{if(Cm("merge",e,t),this.setHydratedState(t),await Dm(()=>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 Hk({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=Or(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}=N7({fileDiff:e,metrics:this.metrics,disableFileHeader:t,hunkSeparators:this.getHunkSeparatorType(),expandUnchanged:n,expandedHunks:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:s,canHydratePartialDiff:Rp(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=Im(o,"VirtualizedFileDiff.render"),a=r!=null,l=r?.oldFile,d=r?.newFile,c=a&&(!vy(l,this.deletionFile)||!vy(d,this.additionFile));let u=t??this.fileDiff;t==null&&a&&(c||this.fileDiff==null)&&(u=xo(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&&!Hr(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 C=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(C==null)throw new Error("VirtualizedFileDiff.render: simple virtualizer is not available");C.connect(e,this),this.isVisible=C.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(),b=this.top??0,w=this.computeRenderRangeFromWindow(u,b,y),_=super.render({fileDiff:u,fileContainer:e,renderRange:w,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 z7(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=Rp(e,this.options.loadDiffFiles!=null),a=this.getDiffStyle(),l=this.getHunkSeparatorType(),d=n?!0:this.hunksRenderer.getExpandedHunksMap(),c=P7(this.cache.heightDeltas);let u=Or(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 b=h,w=h+f;let _=A7(b);for(;_<w;){const C=_-b,N=u+(C>0?x:0)+C*this.metrics.lineHeight+M7(y,C)*this.metrics.lineHeight+gy(c,g,g+C);this.cache.checkpoints.push({renderedLineIndex:_,lineIndex:g+C,top:N}),_+=Em}u+=x+f*this.metrics.lineHeight+y.length*this.metrics.lineHeight+gy(c,g,g+f)+v,h=w};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=Il({isPartial:e.isPartial,rangeSize:g.collapsedBefore,expandedHunks:d,hunkIndex:f,collapsedContextThreshold:s}),v=x.collapsedLines>0?Xa({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 b=f===o?El({fileDiff:e,hunkIndex:f,expandedHunks:d,collapsedContextThreshold:s,errorPrefix:"VirtualizedFileDiff"}):void 0,w=b!=null&&b.collapsedLines>0?rr({type:l,metrics:this.metrics})?.totalHeight??0:f===o&&r?rr({type:l,metrics:this.metrics})?.totalHeight??0:0,_=b!=null?b.fromStart+b.fromEnd:0,C=a==="split"?g.splitLineCount:g.unifiedLineCount,N=a==="split"?g.splitLineStart:g.unifiedLineStart;p({rowCount:C,startLineIndex:N,preSeparatorHeight:y,postSeparatorHeight:_===0?w:0,metadataOffsets:R7({diffStyle:a,hunk:g,rowCount:C})}),b!=null&&_>0&&p({rowCount:_,startLineIndex:N+C,postSeparatorHeight:w})}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}=Il({isPartial:e.isPartial,rangeSize:u,expandedHunks:r,hunkIndex:l,collapsedContextThreshold:o});u>0&&(n+=f?u:h+p)}const a=El({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=Rp(e,this.options.loadDiffFiles!=null),p=this.height;let f=this.getLayoutLineCount(e,c);const g=Or(this.metrics,o),x=e.hunks.length>0?Wk(this.metrics):0,{fileAnnotationHeight:v}=this.cache,y=g+v,b=Math.max(0,p-g-v-x),w=this.hasFileAnnotations(e),_=t+g,C=v>0&&w&&_<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),S=Math.ceil(N/l)*l+l,k=S/l,A=k,I=[],E=(n+s)/2,D=this.getLayoutCheckpointBeforeTop(Math.max(0,n-t-S*d*2),l);let T=t+(D?.top??y),H=D?.renderedLineIndex??0,F,O,B;if(Yr({diff:e,diffStyle:c,startingLine:D?.renderedLineIndex??0,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:De,hunk:me,collapsedBefore:$,collapsedAfter:z,deletionLine:de,additionLine:X})=>{const oe=X!=null?X.splitLineIndex:de.splitLineIndex,Z=X!=null?X.unifiedLineIndex:de.unifiedLineIndex,ae=(X?.noEOFCR??!1)||(de?.noEOFCR??!1),be=De===e.hunks.length-1&&me!=null&&(c==="split"?oe===me.splitLineStart+me.splitLineCount-1:Z===me.unifiedLineStart+me.unifiedLineCount-1),ze=($>0?Xa({type:u,metrics:this.metrics,hunkIndex:De,hunkSpecs:me?.hunkSpecs}):void 0)?.totalHeight??0;T+=ze;const Ye=H%l===0,Ve=Math.floor(H/l);if(Ye&&(I[Ve]=T-(t+y+ze),B!=null)){if(B<=0)return!0;B--}const at=this.getLineHeight(c==="split"?oe:Z,ae);if(T>n-at&&T<s&&(F??=Ve),O==null&&T+at>E&&(O=Ve),B==null&&T>=s&&Ye&&(B=A),H++,T+=at,z>0||be&&h){const Ze=rr({type:u,metrics:this.metrics});Ze!=null&&(T<s&&T+Ze.totalHeight>n&&(F??=Ve),O==null&&T+Ze.totalHeight>E&&(O=Ve),T+=Ze.totalHeight)}return!1}}),F==null)if(C)F=0,O=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-g-x};O??=F;const Y=Math.round(O-k/2),U=Math.max(0,Math.ceil(f/l)-k),ee=Math.max(0,Math.min(Y,U)),L=ee*l,Q=Y<0?S+Y*l:S,V=I[ee]??0,ce=L===0?0:v+V,ve=ee+Q/l,_e=ve<I.length?b-I[ve]:b-(T-t-y);return{startingLine:L,totalLines:Q,bufferBefore:ce,bufferAfter:Math.max(0,_e)}}};function E7(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===KA&&(t=Math.max(t??0,o.getBoundingClientRect().height))}return t}function P7(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 gy({lineIndexes:e,prefixTotals:t},n,s){if(n>=s||e.length===0)return 0;const o=xy(e,n);return(t[xy(e,s)]??0)-(t[o]??0)}function xy(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 A7(e){return Math.ceil(e/Em)*Em}function M7(e,t){let n=0;for(const s of e)s<t&&n++;return n}function R7({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 L7(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 O7(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 Rp(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function z7(e){return typeof e=="function"?"custom":e??"line-info"}function vy(e,t){return e==null||t==null?e==null&&t==null:Vk(e,t)}function G7(e,t){const[n,s]=e.split(",").map(Number);return t==="split"?s:n}function GT(e,t){return e==null||t==null?e===t:e.header!==t.header||e.footer!==t.footer?!1:F7(e.items,t.items)}function F7(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 H7(e,t,n){const s=document.createElement("div");return s.style.display="flow-root",e==="header"?(s.setAttribute(qA,""),t.before(s)):(s.setAttribute(YA,""),t.after(s)),n?.observe(s),s}function _i(e){const t=window.devicePixelRatio??1;return Math.round(e*t)/t}const B7=["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"],$7=["theme","disableLineNumbers","overflow","themeType","disableFileHeader","disableVirtualizationBuffers","preferredHighlighter","useCSSClasses","useTokenTransformer","tokenizeMaxLineLength","tokenizeMaxLength","unsafeCSS","lineHoverHighlight","enableTokenInteractionsOnWhitespace","enableGutterUtility","__debugPointerEvents","enableLineSelection","controlledSelection","disableErrorHandling"],by=["renderCustomHeader","renderHeaderPrefix","renderHeaderFilenameSuffix","renderHeaderMetadata","renderAnnotation","renderGutterUtility","onPostRender","onGutterUtilityClick","onLineClick","onLineNumberClick","onLineEnter","onLineLeave","onTokenClick","onTokenEnter","onTokenLeave"],wy=["onLineSelected","onLineSelectionStart","onLineSelectionChange","onLineSelectionEnd"],FT=Symbol("CodeView.itemOptionsState");function yy(e,t){Object.defineProperty(e,FT,{configurable:!1,enumerable:!1,value:t})}function Ma(e){return e[FT]}function Yi(e,t,n){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get(){return n(this)}})}const V7=120,Sy=1,Cy="--diffs-overflow-override",Jx=12e6,HT=1e6,BT=2e6,W7=Jx-BT,ky=Jx-HT;function U7(e){if(e==null)throw new Error("CodeView: createEditor is required for items with edit: true")}const K7=(()=>{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 q7=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=Ea;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:Pi},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??Ea.hunkLineCount,lineHeight:t?.lineHeight??Ea.lineHeight,diffHeaderHeight:t?.diffHeaderHeight??Ea.diffHeaderHeight,hunkSeparatorHeight:t?.hunkSeparatorHeight,spacing:t?.spacing??Ea.spacing,paddingTop:t?.paddingTop,paddingBottom:t?.paddingBottom},this.itemMetricsCache}getSmoothScrollSettings(){return this.options.smoothScrollSettings??ZA}shouldDisablePointerEvents(){return this.options.pointerEventsOnScroll!==!0}shouldValidateItemHeights(){return JA&&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)<Sy||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),K7&&!this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Cy,"hidden"),this.codeOverflowFix=!0),this.scrollInteractionFixTimer=setTimeout(this.restoreScrollInteractions,V7)}restoreScrollInteractions=()=>{this.clearScrollInteractionTimer(),this.pointerEventsDisabled&&(this.stickyContainer.style.removeProperty("pointer-events"),this.pointerEventsDisabled=!1),this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Cy,"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??H7(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(){yf(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(Uk),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))Q7(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 _U()?"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=Y7(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;X7(n,t)&&this.invalidateElementPool(),this.options=t;const r=this.computeMetricsCache(t.itemMetrics),a=!Cf(o,r),l=!Cf(s,this.getLayout());l&&this.syncLayout();const d=a||Z7(n,t);if(d){const u=this.pendingLayoutReset;this.pendingLayoutReset={metrics:a?r:u?.metrics,resetFileLayoutCache:!0,resetDiffLayoutCache:!0,includeEstimatedDiffHeights:u?.includeEstimatedDiffHeights===!0||a||J7(n,t)}}(l||d)&&(this.markLayoutDirtyFromIndex(0),this.scrollDirty=!0),Vu(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?(yf(this.computeRenderRangeAndEmit),this.computeRenderRangeAndEmit()):Bk(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=t9(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 zT(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 QA(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&&eM(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){U7(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()),Nm(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 $7)Yi(t,n,()=>this.options[n]);Yi(t,"stickyHeader",()=>this.options.stickyHeaders),Yi(t,"collapsed",n=>{const s=Ma(n);if(s!=null)return this.getItemOptions(s,"file")?.item.collapsed});for(const n of by)this.defineItemSharedCallback(t,"file",n);for(const n of wy)this.defineItemSelectionCallback(t,"file",n);return t}createDiffOptionsPrototype(){const t={};for(const n of B7)Yi(t,n,()=>this.options[n]);Yi(t,"stickyHeader",()=>this.options.stickyHeaders),Yi(t,"hunkSeparators",()=>this.options.hunkSeparators),Yi(t,"collapsed",n=>{const s=Ma(n);if(s!=null)return this.getItemOptions(s,"diff")?.item.collapsed});for(const n of by)this.defineItemSharedCallback(t,"diff",n);for(const n of wy)this.defineItemSelectionCallback(t,"diff",n);return t}createFileOptions(t){const n=Object.create(this.fileOptionsPrototype);return yy(n,{id:t}),n}createDiffOptions(t){const n=Object.create(this.diffOptionsPrototype);return yy(n,{id:t}),n}updateItemOptionsId(t,n){const s=Ma(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=Ma(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=Ma(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()>ky}getPagedScrollHeight(){return this.shouldRebaseScroll()?Math.min(this.getScrollHeight(),Jx):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=_i(this.clampPagedScrollTop(n)),o=this.clampScrollPageOffset(t-s);return s=_i(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>ky&&n<r,l=s<HT&&n>0;return s<0||s>o||a||l?this.resolveScrollPageWindow(t,l?Math.min(W7,o):BT):{pagedScrollTop:_i(this.clampPagedScrollTop(s)),scrollPageOffset:n}}needsScrollPageUpdate(t){const n=_i(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 ${jy(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 ${jy(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 S=this.resolveAnchoredScrollTop(a);if(S!=null){const k=S-o;o=S,this.scrollAnimation!=null&&(this.scrollAnimation.position+=k)}}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=tM({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 S=p;S<=f;S++){const k=this.items[S];if(k==null)throw new Error(`CodeView.computeRenderRangeAndEmit: No item at index: ${S}`);k.top>u-k.height&&k.top<=h||this.releaseRenderedItem(k)}const g=this.reconcileHeaderFooterHosts();let x;const v=new Set,y=this.findFirstVisibleIndex(u),b=this.findLastVisibleIndex(h);for(let S=y;S<=b;S++){const k=this.items[S];if(k==null)throw new Error("CodeView.computeRenderRangeAndEmit: missing item");const{instance:A}=k;k.element==null?(k.element=this.acquireElement(),Ty(this.stickyContainer,k.element,x),A.virtualizedSetup(),Ny(k,k.element)&&(k.renderedOptionsRevision=this.renderOptionsRevision,v.add(k)),x=k.element):(Ty(this.stickyContainer,k.element,x),Ny(k,void 0,k.renderedOptionsRevision!==this.renderOptionsRevision)&&(k.renderedOptionsRevision=this.renderOptionsRevision,v.add(k)),x=k.element),k.item.edit===!0&&this.attachItemEditor(k)}this.renderState.firstIndex=y<=b?y:-1,this.renderState.lastIndex=b,this.flushSlotCoordinator(),this.flushManagers(v),g&&this.measureMountedHosts(),this.reconcileRenderedItems(v),this.syncContainerHeight(),this.updateStickyPositioning();const w=a!=null?this.resolveAnchoredScrollTop(a):void 0;a===this.pendingLayoutAnchor&&(this.pendingLayoutAnchor=void 0);const _=w!=null?w-o:0;let C=l,N=!1;if(this.pendingScrollTarget!=null){const S=this.advanceScrollAnimation(t,_);S!=null?(C=S,N=!0):C=o}else C=w??l;C!==c&&(this.applyScrollFix(C,c,this.windowSpecs),c=C),N&&this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),this.renderState.scrollTop=_i(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)>=Sy){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=_i(this.clampScrollTop(t)),r=_i(n),{scrollPageOffset:a}=this,l=_i(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:_i(this.getScrollTop())===_i(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);GT(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 Y7(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 X7(e,t){return!Fk(e.theme??Pi,t.theme??Pi)||(e.themeType??"system")!==(t.themeType??"system")||e.unsafeCSS!==t.unsafeCSS}function Z7(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 J7(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 Q7(e){return e instanceof SVGElement?!0:Sf(e)&&(e.hasAttribute("data-core-css")||e.hasAttribute("data-theme-css")||e.hasAttribute("data-unsafe-css"))}function jy(e){const t=_y(e.start,e.side),n=_y(e.end,e.endSide??e.side);return t===n?t:`${t}-${n}`}function _y(e,t){return t==null?`${e}`:`${t==="deletions"?"D":"A"}${e}`}function Ny(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 Ty(e,t,n){if(n==null){e.firstChild!==t&&e.prepend(t);return}n.nextSibling!==t&&n.after(t)}function e9(e){return(e.annotations?.length??0)>0}function t9(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)e9(r.item)&&o.push(r);return o.length>0?o:void 0}function n9({hunkIndex:e,lineIndex:t,conflictIndex:n}){return`merge-conflict-action-${e}-${t}-${n}`}function s9(e,t){const n=t.hunks[e.hunkIndex];if(n!=null)return{hunkIndex:e.hunkIndex,lineIndex:i9(n,e.startContentIndex)}}function i9(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 $T({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:$k,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:oa(v),children:a(v)},y)),t!=null&&d!=null&&h!=null&&t.map(v=>{if(v==null)return;const y=o9(v,e);return i.jsx("div",{slot:y,style:nM,children:d(v,h)},y)}),l!=null&&i.jsx("div",{slot:"gutter-utility-slot",style:sM,children:l(u)})]})}function o9(e,t){const n=s9(e,t);return n!=null?n9({hunkIndex:n.hunkIndex,lineIndex:n.lineIndex,conflictIndex:e.conflictIndex}):void 0}const Dy=typeof window>"u"?m.useEffect:m.useLayoutEffect;function Iy(e){return{instance:void 0,items:void 0,controlled:e,managedOptions:void 0,disableFlushSync:!1,slotCoordinator:void 0}}function r9(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:b,renderHeaderMetadata:w,renderHeaderPrefix:_,selectedLines:C,style:N}=e,S=l!==void 0,k=Kk(),A=m.useContext(qk),I=m.useRef(Iy(S)),E=v!=null,D=f!=null,T=y!=null,H=E||_!=null||b!=null||w!=null,F=H||D||T,O=x!=null,B=g!=null,Y=so($=>{h?.($)}),U=C!==void 0,ee=so($=>{if(k==null)throw new Error("CodeView: EditContext is not attached");const z=k({...r,...$});if(z==null)throw new Error("CodeView: EditProvider.createEditor must return an editor instance");return z}),L=so(($,z,de)=>{d?.($,z,de)}),Q=so(($,z,de)=>{c?.($,z,de)}),V=m.useMemo(()=>c9({options:p,hasCustomHeader:E,hasGutterRenderer:T,hasCodeViewHeader:O,hasCodeViewFooter:B,onSelectedLinesChange:h!=null?Y:void 0,controlledSelection:U,createEditor:k!=null?ee:void 0,onItemEditChange:d!=null?L:void 0,onItemEditComplete:c!=null?Q:void 0}),[k,U,ee,L,Q,Y,B,O,E,T,d,c,h,p]),[ce]=m.useState(()=>d9()),[,ve]=m.useState({}),_e=so($=>{I.current.instance!=null&&($==null||$!==I.current.instance.getContainerElement())&&(I.current.instance.cleanUp(),ce.publish(void 0),I.current=Iy(S)),$!=null&&$!==I.current.instance?.getContainerElement()&&(I.current.instance=new q7(V,o?void 0:A,!0),I.current.instance.setup($)),typeof s=="function"?s($):s!=null&&(s.current=$)}),De=so($=>{I.current.disableFlushSync?ce.publish($):Ks.flushSync(()=>{ce.publish($)})}),me=m.useMemo(()=>{if(!(!H&&!D&&!T&&!O&&!B))return{hasHeaderRenderers:H,hasAnnotationRenderer:D,hasGutterRenderer:T,onSnapshotChange:De}},[De,D,T,H,O,B]);return Dy(()=>u!=null?I.current.instance?.subscribeToScroll(u):void 0),Dy(()=>{const{instance:$,controlled:z,items:de,managedOptions:X,slotCoordinator:oe}=I.current;if($!=null)try{I.current.disableFlushSync=!0;let Z=!1;if(Vu(V,X)||(I.current.managedOptions=V,$.setOptions(V),Z=!0),z!==S){console.error("CodeView: cannot switch between controlled and uncontrolled modes. Remount with a new key instead.");return}if(S)l!==de&&(l9(de,l)?I.current.items=l:a9(de,l)?(I.current.items=l,$.addItems(l.slice(de.length))):(I.current.items=l,$.setItems(l),Z=!0));else if(de==null){const ze=a??[];I.current.items=ze,ze.length>0&&($.setItems(ze),Z=!0)}C!==void 0&&$.setSelectedLines(C,{notify:!1});const ae=$.setSlotCoordinator(me);let be=!1;me!==oe&&((me==null||oe==null)&&(be=!0),I.current.slotCoordinator=me),(Z||ae)&&$.render(!0),ae&&me==null&&ce.publish(void 0),be&&ve({})}finally{I.current.disableFlushSync=!1}}),m.useImperativeHandle(t,()=>({addItems($){const{controlled:z,instance:de}=I.current;Zd(z,"addItems"),de==null?console.error("CodeView.addItems: no valid instance to append items with",$):de.addItems($)},getItem($){const{instance:z}=I.current;if(z==null){console.error("CodeView.getItem: no valid instance exists",$);return}else return z.getItem($)},removeItem($){const{controlled:z,instance:de}=I.current;return Zd(z,"removeItem"),de==null?(console.error("CodeView.removeItem: no valid instance to remove item from",$),!1):de.removeItem($)},updateItem($){const{controlled:z,instance:de}=I.current;return Zd(z,"updateItem"),de==null?(console.error("CodeView.updateItem: no valid instance to update item with",$),!1):de.updateItem($)},updateItemId($,z){const{controlled:de,instance:X}=I.current;return Zd(de,"updateItemId"),X==null?(console.error("CodeView.updateItemId: no valid instance to update item id with",$,z),!1):X.updateItemId($,z)},scrollTo($){const{instance:z}=I.current;z==null?console.error("CodeView.scrollTo: no valid instance to scroll with",$):z.scrollTo($)},setSelectedLines($){const{instance:z}=I.current;z==null?console.error("CodeView.setSelectedLines: no valid instance to update selection with",$):(z.setSelectedLines($,{notify:!1}),Y($))},getSelectedLines(){const{instance:$}=I.current;return $==null?(console.error("CodeView.getSelectedLines: no valid instance exists"),null):$.getSelectedLines()},clearSelectedLines(){const{instance:$}=I.current;$==null?console.error("CodeView.clearSelectedLines: no valid instance to update selection with"):($.clearSelectedLines({notify:!1}),Y(null))},getEditor($){const{instance:z}=I.current;if(z==null){console.error("CodeView.getEditor: no valid instance exists",$);return}return z.getEditor($)},getInstance(){return I.current.instance}}),[Y]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:_e,className:n,style:N}),(F||O||B)&&i.jsx(u9,{managedContentStore:ce,renderCustomHeader:v,renderHeaderPrefix:_,renderHeaderFilenameSuffix:b,renderHeaderMetadata:w,renderAnnotation:f,renderGutterUtility:y,renderCodeViewHeader:x,renderCodeViewFooter:g})]})}const VT=m.forwardRef(r9);function a9(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 l9(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 Zd(e,t){if(e)throw new Error(`CodeView.${t} cannot be used when CodeView is controlled. Use initialItems for imperative item updates.`)}function d9(){let e;const t=new Set;return{getSnapshot(){return e},publish(n){if(!GT(e,n)){e=n;for(const s of t)s()}},subscribe(n){return t.add(n),()=>{t.delete(n)}}}}function c9({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=Jd),n&&(u.renderGutterUtility=Jd),s&&(u.renderCodeViewHeader=Jd),o&&(u.renderCodeViewFooter=Jd),u}const u9=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=>Ks.createPortal(h9({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?Ks.createPortal(d(),p.header):null,[d,p?.header]),m.useMemo(()=>c!=null&&p?.footer!=null?Ks.createPortal(c(),p.footer):null,[c,p?.footer])]})});function h9({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 $T({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 iM({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 Jd(){}const Ey=typeof window>"u"?m.useEffect:m.useLayoutEffect;function p9({fileDiff:e,options:t,editorOptions:n,lineAnnotations:s,selectedLines:o,prerenderedHTML:r,metrics:a,hasGutterRenderUtility:l,hasCustomHeader:d,disableWorkerPool:c,edit:u}){const h=oM(),p=o!==void 0,f=m.useContext(qk),g=Kk(),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 zT(Lp({controlledSelection:p,hasCustomHeader:d,hasGutterRenderUtility:l,options:t}),h,a,c?void 0:f,!0):x.current=new OT(Lp({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 Ey(()=>{const{current:y}=x;if(y==null)return;const b=Lp({controlledSelection:p,hasCustomHeader:d,hasGutterRenderUtility:l,options:t}),w=b!==void 0&&!Vu(y.options,b);y.setOptions(b),y.render({forceRender:w,fileDiff:e,lineAnnotations:s}),o!==void 0&&y.setSelectedLines(o)}),Ey(()=>{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(b){throw y.cleanUp(),b}}},[u]),{ref:v,getHoveredLine:m.useCallback(()=>x.current?.getHoveredLine(),[])}}function Lp({options:e,controlledSelection:t,hasCustomHeader:n,hasGutterRenderUtility:s}){return t||s||n?{...e,controlledSelection:t,renderCustomHeader:n?i0:e?.renderCustomHeader,renderGutterUtility:s?i0:e?.renderGutterUtility}:e}function f9({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:b}=p9({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(Uk,{ref:y,className:a,style:l,children:rM($T({fileDiff:e,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderAnnotation:c,renderGutterUtility:g,lineAnnotations:o,getHoveredLine:b}),d)})}function m9(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 g9(e,t){const n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(s=>e[s]===t[s])}function WT(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 x9(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(b=>b.edits??[]),c=a.flatMap(b=>b.fileChange&&b.fileChange.truncated!==!0?[b.fileChange]:[]),u=[...a].reverse().find(b=>b.writeContent!=null)?.writeContent,h=a.find(b=>b.fileChange)?.fileChange,p=[...a].reverse().find(b=>b.fileChange||b.writeContent!=null||b.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=WT(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 v9={theme:va,diffStyle:"split",lineDiffType:"word",disableFileHeader:!0,preferredHighlighter:"shiki-js",overflow:"wrap"};function Py({path:e,blocks:t,snapshot:n}){const{t:s}=J(),o=e.split("/").pop()||"file",[r,a]=m.useState({kind:"loading"});return m.useEffect(()=>{let l=!0;return n?(a({kind:"loading"}),ra().then(()=>{l&&a({kind:"full",oldText:n.oldText,newText:n.newText})}).catch(()=>{l&&a({kind:"blocks"})}),()=>{l=!1}):(Promise.all([ra(),window.electronAPI.files.read(e)]).then(([,d])=>{if(!l)return;const c=typeof d=="string"?WT(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(Ay,{name:o,oldText:r.oldText,newText:r.newText}):t.map((l,d)=>i.jsx(Ay,{name:o,oldText:l.oldText,newText:l.newText},d))})}function Ay({name:e,oldText:t,newText:n}){const s=rd(v9),o=m.useMemo(()=>{const r=xo({name:e,contents:t},{name:e,contents:n});return r.cacheKey=Yx(e,t,n),r},[e,t,n]);return i.jsx(f9,{fileDiff:o,options:s})}function Pm({hits:e,defaultOpen:t=!1}){const{t:n}=J();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(w9,{hit:s,defaultOpen:t},s.id))})}function b9({view:e}){const{t}=J(),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(Pm,{hits:[e.memory],defaultOpen:!0}):i.jsx(Pm,{hits:e.candidates})]})}function w9({hit:e,defaultOpen:t}){const{t:n}=J(),[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:W("min-w-0 flex-1 font-medium text-foreground text-xs",s?"break-words":"truncate"),children:e.title}),e.unitType&&i.jsx(aa,{variant:"secondary",size:"sm",children:e.unitType}),e.space&&i.jsx(aa,{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:W("mt-0.5 whitespace-pre-wrap break-words text-muted-foreground text-xs leading-relaxed",s?"block":"line-clamp-2"),children:e.content})]})})}const y9={"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 Qx(e){return W("inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",y9[e])}function S9({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(ln,{className:"h-3 w-3"})})}function C9({recipient:e,onRemove:t}){const{t:n}=J();return i.jsxs("span",{className:W(Qx("agent-type"),"mt-0.5 shrink-0"),children:[i.jsx(Vs,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:e.label}),i.jsx(S9,{label:n("Remove Agent recipient"),onRemove:t}),i.jsx("span",{className:"sr-only",children:e.typeKey})]})}const ev=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function UT(e){if(!e)return null;try{const t=JSON.parse(e);return ev(t)?t:null}catch{return null}}function Am(e,t){if(!Array.isArray(e))return null;const n=[];for(const s of e){if(!ev(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 k9(e){const t=UT(e);return t?Am(t.results,"relevance"):null}function j9(e,t){const n=UT(e);if(n?.status==="candidates_found"){const o=Am(n.candidates,"similarity");return o?{written:!1,candidates:o}:null}if(n?.status!=="inserted"||!ev(n.memory)||!t)return null;const s=Am([{...n.memory,content:t}],"relevance")?.[0];return s?{written:!0,deduplicated:n.deduplicated===!0,memory:s}:null}const KT=m.createContext(void 0);function Nd(e){const t=m.useContext(KT);if(t===void 0&&!e)throw new Error(ad(50));return t}const _9=600,qT=300,N9={...lM,instantType:e=>e.instantType,adaptiveOrigin:e=>e.adaptiveOrigin,closeDelay:e=>e.closeDelay};class T9 extends aM{constructor(t,n,s){const o=new hM;super(D9(t,o,n,s),I9(o),N9)}setOpen=(t,n)=>{const{inlineRectCoordsRef:s}=this.context;dM(this,t,n,{onBeforeDispatch(){const o=n.event;t&&n.reason===pM&&n.trigger&&"clientX"in o&&"clientY"in o&&s.current?.element!==n.trigger&&BN(s,n.trigger,o.clientX,o.clientY)}})}}function D9(e,t,n,s=!1){const o={...cM(),instantType:void 0,adaptiveOrigin:void 0,closeDelay:qT,...e};return o.floatingRootContext=uM(t,n,s),o}function I9(e){return{popupRef:m.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e,inlineRectCoordsRef:{current:void 0}}}function My(e){const{open:t,defaultOpen:n=!1,onOpenChange:s,onOpenChangeComplete:o,actionsRef:r,handle:a,triggerId:l,defaultTriggerId:d=null,children:c}=e,u=gM((y,b)=>new T9({open:n,openProp:t,activeTriggerId:d,triggerIdProp:l},y,b));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");xM(u,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:x}=vM(h,u,()=>{u.context.inlineRectCoordsRef.current=void 0});yg(()=>{h&&p==null&&u.set("payload",void 0)},[u,p,h]),m.useImperativeHandle(r,()=>({unmount:x,close:()=>u.setOpen(!1,bM(wM))}),[x,u]);const v=h||f;return i.jsxs(KT.Provider,{value:u,children:[a&&i.jsx(yM,{handle:a,store:u}),v&&i.jsx(E9,{store:u}),typeof c=="function"?c({payload:g}):c]})}function E9({store:e}){const t=e.useState("floatingRootContext"),n=SM(t);return CM(e,{activeTriggerProps:n.reference,inactiveTriggerProps:n.trigger,popupProps:n.floating}),null}const P9=fM(function(t){return Nd(!0)?i.jsx(My,{...t}):i.jsx(mM,{children:i.jsx(My,{...t})})}),YT=m.createContext(void 0);function A9(){const e=m.useContext(YT);if(e===void 0)throw new Error(ad(48));return e}const M9=m.forwardRef(function(t,n){const{keepMounted:s=!1,...o}=t;return Nd().useState("mounted")||s?i.jsx(YT.Provider,{value:s,children:i.jsx(kM,{ref:n,...o})}):null}),R9=jM(function(t,n){const{render:s,className:o,delay:r,closeDelay:a,id:l,payload:d,handle:c,style:u,...h}=t,p=Nd(!0),g=_M(c)??p;if(!g)throw new Error(ad(89));const x=Yk(l),v=g.useState("isTriggerActive",x),y=g.useState("isOpenedByTrigger",x),b=g.useState("floatingRootContext"),w=g.context.inlineRectCoordsRef,_=m.useRef(null),C=r??_9,N=a??qT,{registerTrigger:S,isMountedByThisTrigger:k}=NM(x,_,g,{payload:d,closeDelay:N}),A=TM(b,{mouseOnly:!0,move:!1,handleClose:DM(),delay:()=>({open:C,close:N}),triggerElementRef:_,isActiveTrigger:v,isClosing:()=>g.select("transitionStatus")==="ending"}),I=IM(b,{delay:C}),E={open:y},D=g.useState("triggerProps",k),T=L4(w,y);return ld("a",t,{state:E,ref:[n,S,_],props:[A,I.reference,D,T,{id:x},h],stateAttributesMapping:EM})}),XT=m.createContext(void 0);function L9(){const e=m.useContext(XT);if(e===void 0)throw new Error(ad(49));return e}const O9=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=PM,style:y,...b}=t,w=Nd(),_=A9(),C=AM(),N=w.useState("open"),S=w.useState("mounted"),k=w.useState("floatingRootContext"),A=w.useState("instantType"),I=w.useState("transitionStatus"),E=w.useState("adaptiveOrigin"),D=w.context.inlineRectCoordsRef,T=MM({anchor:r,floatingRootContext:k,positionMethod:a,mounted:S,side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:g,disableAnchorTracking:x,keepMounted:_,nodeId:C,collisionAvoidance:v,adaptiveOrigin:E,inline:O4(D)}),H=T.update;yg(()=>{N&&S&&H()},[N,S,H]);const F={open:N,side:T.side,align:T.align,anchorHidden:T.anchorHidden,instant:A},O=RM(t,F,{styles:T.positionerStyles,transitionStatus:I,props:b,refs:[n,w.useStateSetter("positionerElement")],hidden:!S,inert:!N});return i.jsx(XT.Provider,{value:T,children:i.jsx(LM,{id:C,children:O})})}),z9=m.forwardRef(function(t,n){const{className:s,render:o,style:r,...a}=t,l=Nd(),{side:d,align:c}=L9(),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 OM({open:u,ref:l.context.popupRef,onComplete(){u&&l.context.onOpenChangeComplete?.(!0)}}),zM(g,{closeDelay:x}),ld("div",t,{state:{open:u,side:d,align:c,instant:h,transitionStatus:p},ref:[n,l.context.popupRef,l.useStateSetter("popupElement")],props:[GM,f,HM(p),a],stateAttributesMapping:FM})}),tv=P9;function nv({...e}){return i.jsx(R9,{"data-slot":"preview-card-trigger",...e})}function ZT({className:e,children:t,align:n="center",sideOffset:s=4,...o}){return i.jsx(M9,{children:i.jsx(O9,{align:n,className:"z-50","data-slot":"preview-card-positioner",sideOffset:s,children:i.jsx(z9,{className:W("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 Ry={mask:"text-sky-600 dark:text-sky-400",warn:"text-amber-600 dark:text-amber-400",block:"text-red-600 dark:text-red-400"},G9={mask:Wu,warn:sa,block:Xk},F9={mask:"Mask",warn:"Warn only",block:"Block"},H9={system:"System prompt",user:"Your message",tool_result:"Tool output",tool_args:"Tool arguments",assistant:"Earlier replies",tools:"Tool descriptions"};function B9({report:e}){const{t}=J(),n=BM(e);if(!n)return null;const s=G9[n],o=new Set(e.hits.map(r=>r.token)).size;return i.jsxs(tv,{children:[i.jsxs(nv,{render:i.jsx("span",{className:W("inline-flex shrink-0 items-center gap-0.5 text-[11px]",Ry[n]),"data-privacy-mask":n}),children:[i.jsx(s,{className:"size-3.5"}),i.jsx("span",{className:"tabular-nums",children:o})]}),i.jsxs(ZT,{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:$M(e.hits).map(r=>i.jsxs("li",{className:"flex flex-wrap gap-x-2",children:[i.jsx("span",{className:Ry[r.action],children:t(F9[r.action])}),i.jsx("span",{children:r.kind}),i.jsx("span",{className:"text-muted-foreground",children:t(H9[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 $9=/^\[.+#[0-9A-Fa-f]{4}\]$/;function V9(e){const t=e.indexOf(`
|
|
58
|
-
`),n=t===-1?e:e.slice(0,t);return $9.test(n)?t===-1?"":e.slice(t+1).split(`
|
|
59
|
-
`).map(s=>s.replace(/^\d+:/,"")).join(`
|
|
60
|
-
`):e}const W9={theme:va,disableFileHeader:!0,overflow:"wrap",preferredHighlighter:"shiki-js"};function $c({path:e,contents:t}){const{t:n}=J(),[s,o]=m.useState(!1),r=rd(W9);m.useEffect(()=>{let l=!0;return ra().then(()=>{l&&o(!0)}),()=>{l=!1}},[]);const a=m.useMemo(()=>({name:e.split("/").pop()||"file",contents:V9(t)}),[e,t]);return s?i.jsx(Zk,{file:a,disableWorkerPool:!0,options:r}):i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("Loading...")})}function U9(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 K9={compressed:"Compressed",unchanged:"Unchanged",pending:"Background task started",bypassed:"Bypassed",unavailable:"Unavailable"};function q9({value:e}){const t=u4(e),{t:n}=J();if(!t)return null;const s=U9(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(K9[t.status])}),s&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:n("~{{count}} tokens saved",{count:Jn(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:Jn(t.inputTokens)})}),i.jsx("dt",{children:n("Output estimate")}),i.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:Jn(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 Y9(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 X9(e,t,n=h4){const s=t-e;return s>=n?s:null}const Z9={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"},J9={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 Q9(e){return e?.kind==="deadline"?["background","timeout"]:[]}function eK(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 tK(e,t,n){return t(e)?(n(),!0):!1}let vl=null,bl=null,wl=null,yl=null,Sl=null,Cl=null;function nK(e){return vl=e,()=>{vl===e&&(vl=null)}}function sK(e){return wl=e,()=>{wl===e&&(wl=null)}}function iK(e){return bl=e,()=>{bl===e&&(bl=null)}}function yo(){return wl?(wl(),!0):!1}function oK(e){return Cl=e,()=>{Cl===e&&(Cl=null)}}function rK(e){return Cl?Cl(e):!1}function Jl(e){return vl?(vl(e),!0):!1}function jh(e){return bl?(bl(e),!0):!1}function aK(e){return yl=e,()=>{yl===e&&(yl=null)}}function sv(e,t){return yl?(yl(e,t),!0):!1}function lK(e){return Sl=e,()=>{Sl===e&&(Sl=null)}}function dK(e){return Sl?(Sl(e),!0):!1}function cK(){const[e,t]=m.useState(()=>Date.now());return m.useEffect(()=>{const n=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(n)},[]),e}const Mm=5,Ly=2*Math.PI*Mm;function uK({startedAt:e,deadlineAt:t,output:n}){const{t:s}=J(),o=cK(),r=m.useRef({output:n,at:e??Date.now()});r.current.output!==n&&(r.current={output:n,at:Date.now()});const a=Y9(e,t,o),l=X9(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:Mm,fill:"none",stroke:"currentColor",opacity:"0.25"}),i.jsx("circle",{cx:"6",cy:"6",r:Mm,fill:"none",stroke:"currentColor",strokeDasharray:Ly,strokeDashoffset:Ly*(1-a.fraction),transform:"rotate(-90 6 6)"})]}),Math.ceil(a.remainingMs/1e3),"s"]})]})}function QT(e,t){return e.kind==="exit_nonzero"&&e.exitCode===void 0?t("Failed"):t(Z9[e.kind],{code:e.exitCode??""})}function hK({failure:e}){const{t}=J();return i.jsx("span",{"data-shell-failure":e.kind,className:W("shrink-0 rounded px-1 text-[10px]",e.retryable?"bg-muted text-muted-foreground":"bg-destructive/10 text-destructive"),children:QT(e,t)})}function pK({failure:e,command:t}){const{t:n}=J(),[s,o]=m.useState(!1);if(!e)return null;const r=J9[e.kind],a=Q9(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:QT(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:()=>{tK(eK(l,t,n),jh,yo)},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(Kn,{className:"h-3 w-3"}):i.jsx(Uu,{className:"h-3 w-3"}),n("Copy command")]})]})}function fK(e){return e.startsWith("/skill:")?"skill":e==="/goal"?"goal":"command"}function mK(e){return e.startsWith("/skill:")?e.slice(7):e.replace(/^\//,"")}function Tu(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 gK={skill:Hs,goal:Ta,command:PN},xK={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 eD(e,t=!1){return W("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",xK[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 Du({name:e,className:t,interactive:n=!1,trailing:s}){const o=fK(e),r=gK[o];return i.jsxs("span",{className:W(eD(o,n),t),children:[i.jsx(r,{className:"h-3 w-3"}),mK(e),s]})}function vK({icon:e,state:t}){const n=t==="running"||t==="reviewing";return i.jsxs("span",{className:W("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 tD({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 bK={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 wK({view:e,titles:t}){const{t:n}=J();return i.jsxs("div",{className:"space-y-2 px-3 py-2 text-sm",children:[e.kind==="report"&&e.text&&i.jsx(_s,{text:e.text}),e.kind==="report"&&e.value&&i.jsx(_s,{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(yK,{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 yK({run:e,title:t}){const{t:n}=J(),[s,o]=bK[e.status]??[null,"bg-muted-foreground"],r=e.durationMs===null?"":n("took {{duration}}",{duration:Un(e.durationMs)});return i.jsxs("li",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:W("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 iv=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Oy=e=>typeof e=="string"&&e.trim()?e:null;function Rm(e){if(!iv(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 SK=new Set(["closed","parked","creating"]);function CK(e){if(!iv(e))return null;const{agentId:t,status:n,latestRun:s}=e;return typeof t!="string"||typeof n!="string"?null:(SK.has(n)?null:Rm(s))??{agentId:t,runId:"",status:n,durationMs:null}}function kK(e,t){const n=VM(t);if(!n)return null;const{head:s,value:o}=n;if(e==="report"){const l=Rm(o.run);if(!l)return null;const{text:d,value:c,error:u,...h}=o;return{kind:"report",head:s,runs:[l],text:Oy(d),value:c==null?null:JSON.stringify(c,null,2),error:Oy(u),info:JSON.stringify(h,null,2)}}if(e==="list"){if(!Array.isArray(o.agents))return null;const l=o.agents.flatMap(d=>CK(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(!iv(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=>Rm(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 jK({command:e,output:t,failure:n}){const s=Se(a=>a.terminalTheme),o=Se(a=>a.terminalFontFamily),r=Ku(s)??WM;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:Si(t)}),i.jsx(pK,{failure:n,command:e})]})}function _K(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 nD({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(Kn,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):t.status==="in_progress"?i.jsx(gV,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):i.jsx(Tx,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/50"}),i.jsx("span",{className:W(t.status==="completed"?"text-muted-foreground line-through":t.status==="in_progress"?"font-medium":"text-muted-foreground"),children:t.content})]},t.content))})}function sD({done:e,total:t,className:n}){return i.jsx("div",{className:W("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 zy=new Set;function NK({conversationId:e}){const{t}=J(),n=Se(u=>u.pinUnfinishedTodos),s=se(u=>u.conversations[e]?.messages),o=m.useMemo(()=>n&&s?_K(s):null,[n,s]),[r,a]=m.useState(!1),[,l]=m.useState(0);if(!o||zy.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($n,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx(un,{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:()=>{zy.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(ln,{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(sD,{done:d,total:o.todos.length,className:"mb-2"}),i.jsx(nD,{todos:o.todos})]})]})}const TK=1e3,DK=new Set(["ask_user"]);function iD(e,t){let n=t;for(;n>0&&e[n-1]?.role!=="user";)n--;const s=[];for(let d=n;d<=t&&d<e.length;d++){const c=e[d];if(c.role==="assistant"&&c.timing){const u=c.timing.stepStartMs,h=c.timing.completedMs??(typeof c.duration=="number"?u+c.duration:void 0);if(h!==void 0&&h>u){const p=x=>x!==void 0&&x>u&&x<h?x:void 0,f=p(c.timing.firstTokenMs),g=p(c.timing.thinkingEndMs);s.push({key:`m${d}`,kind:"model",label:"",start:u,end:h,...f!==void 0||g!==void 0?{phases:{...f!==void 0?{firstTokenMs:f}:{},...g!==void 0?{thinkingEndMs:g}:{}}}:{}})}}else if(c.role==="toolResult"&&typeof c.toolDurationMs=="number"&&typeof c.timestamp=="number"){const u=c.toolName??"tool";s.push({key:`t${d}`,kind:DK.has(u)?"wait":"tool",label:u,start:c.timestamp-c.toolDurationMs,end:c.timestamp})}}if(s.length===0||s.length===1&&!s[0].phases)return null;s.sort((d,c)=>d.start-c.start);const o=[];let r=s[0].start;for(const d of s)d.start-r>TK&&o.push({key:`w${d.key}`,kind:"wait",label:"",start:r,end:d.start}),o.push(d),r=Math.max(r,d.end);let a;const l=o.filter(d=>d.kind!=="wait");for(const d of l.length>1?l:[])(!a||d.end-d.start>a.end-a.start)&&(a=d);return{start:o[0].start,end:r,bars:o,...a?{slowest:a.key}:{}}}function IK(e,t){return se(n=>{const s=e?n.conversations[e]:void 0;if(!s)return!1;const o=t-(s.historyBaseIndex??0);return s.messages[o]?.timing?iD(s.messages,o)!==null:!1})}const Op={ttft:"bg-brand/30",thinking:"bg-brand/60",output:"bg-brand"};function EK(e){const{firstTokenMs:t,thinkingEndMs:n}=e.phases??{},s=[];let o=e.start;t!==void 0&&(s.push({phase:"ttft",from:o,to:t}),o=t),n!==void 0&&n>o&&(s.push({phase:"thinking",from:o,to:n}),o=n),s.push({phase:"output",from:o,to:e.end});const r=Math.max(1,e.end-e.start);return s.map(a=>({...a,width:(a.to-a.from)/r*100}))}const Gy=e=>e<1e3?`${Math.round(e)}ms`:Un(e),Fy={ttft:"Waiting for first token",thinking:"Think time",output:"Output"},PK={model:"bg-brand",tool:"bg-info",wait:"bg-muted-foreground/30"};function AK({conversationId:e,messageIndex:t}){const{t:n}=J(),s=se(d=>d.conversations[e]?.messages),o=se(d=>d.conversations[e]?.historyBaseIndex??0),r=m.useMemo(()=>s?iD(s,t-o):null,[s,t,o]);if(!r)return null;const a=Math.max(1,r.end-r.start),l=r.bars.some(d=>d.phases);return i.jsxs("div",{"data-enso":"turn-waterfall",className:"mt-1.5 max-h-64 overflow-auto rounded-lg border border-border/60 px-2.5 py-2 text-[11px]",children:[r.bars.map(d=>{const c=d.key===r.slowest,u=d.kind==="model"?n("Model"):d.label||n("Wait");return i.jsxs("div",{className:"grid grid-cols-[7rem_1fr_3.5rem] items-center gap-2 py-px",children:[i.jsx("span",{className:W("truncate text-muted-foreground",d.kind==="tool"&&"font-mono",c&&"font-medium text-warning"),title:u,children:u}),i.jsx("span",{className:"relative h-2.5",children:i.jsx("span",{className:W("absolute top-0.5 flex h-1.5 min-w-px overflow-hidden rounded-sm",d.phases?c&&"ring-1 ring-warning ring-offset-1 ring-offset-background":c?"bg-warning":PK[d.kind]),style:{left:`${(d.start-r.start)/a*100}%`,width:`${(d.end-d.start)/a*100}%`},children:d.phases&&EK(d).map(h=>i.jsx("span",{className:W("h-full",Op[h.phase]),style:{width:`${h.width}%`},title:`${n(Fy[h.phase])} ${Gy(h.to-h.from)}`},h.phase))})}),i.jsx("span",{className:W("text-right tabular-nums text-muted-foreground",c&&"font-medium text-warning"),children:Gy(d.end-d.start)})]},d.key)}),l&&i.jsx("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-muted-foreground",children:Object.keys(Op).map(d=>i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx("span",{className:W("h-1.5 w-2.5 rounded-sm",Op[d])}),n(Fy[d])]},d))})]})}const MK={report:()=>{},scroller:{current:null}},oD=m.createContext(MK),RK=oD.Provider;function LK(){return m.useContext(oD)}async function OK(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 zK(e){const t=await OK(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 rD({src:e,className:t,frameClassName:n,onError:s}){const{t:o}=J(),[r,a]=m.useState(!1);Qk(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=()=>{zK(e).then(()=>Fe({type:"success",title:o("Image copied")}),d=>Fe({type:"error",title:o("Could not copy image"),description:d instanceof Error?d.message:String(d)}))};return i.jsxs(i.Fragment,{children:[i.jsxs(ho,{children:[i.jsx(po,{render:i.jsx("button",{type:"button",onClick:()=>a(!0),className:W("cursor-zoom-in",n),children:i.jsx("img",{src:e,alt:"",className:t,onError:s})}),onContextMenu:d=>d.stopPropagation()}),i.jsx(fo,{className:"min-w-36",children:i.jsx(Yt,{closeOnClick:!0,onClick:l,children:o("Copy image")})})]}),r&&i.jsx("button",{type:"button",onClick:()=>a(!1),className:W("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 GK=(e,t)=>e===t||!!e&&!!t&&e.runMs===t.runMs&&e.turnMs===t.turnMs&&e.ttftMs===t.ttftMs&&e.tps===t.tps;function FK(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"&&GK(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.live===s.live&&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.tokensAfter===s.tokensAfter&&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;case"discarded-turn":return s.kind==="discarded-turn"&&n.expanded===s.expanded&&n.reason===s.reason&&n.messages.length===s.messages.length&&n.messages.every((o,r)=>o===s.messages[r])}}const HK=/^<(agent-notification|goal-continuation|coworker-hired|coworker-dismissed|background-task-update)>\n?([\s\S]*?)\n?<\/\1>\s*$/,aD=/^<role>\n?([\s\S]*?)\n?<\/role>\s*/,BK=/^<workspace-migrated>\n?([\s\S]*?)\n?<\/workspace-migrated>\s*/;function $K({note:e}){const{t}=J(),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(Mi,{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 lD({note:e}){const{t}=J();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(ga,{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 dD({note:e}){const{t}=J(),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(fR,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):i.jsx(l4,{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 VK({tag:e,body:t}){const n=e==="agent-notification"?Y8(t):null;return n?i.jsx(WK,{notices:n}):i.jsx(UK,{tag:e,body:t})}function WK({notices:e}){const{t}=J(),[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(Vs,{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(un,{className:W("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(_s,{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:Jn(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:Un(o.usage.durationMs)})]})]},r))]})}function UK({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"?Vs:Fo;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:W("min-w-0 flex-1",a?"truncate":"whitespace-pre-wrap"),children:a?o.slice(0,r):o}),a&&i.jsx(un,{className:W("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 cD=/^<message-from-main-agent>\n?([\s\S]*?)\n?<\/message-from-main-agent>\s*$/;function KK(e){const t=aD.exec(e);return cD.test(t?e.slice(t[0].length):e)}function qK({name:e,content:t}){const{t:n}=J();return i.jsxs(vn,{children:[i.jsxs(bR,{className:eD("skill",!0),children:[i.jsx(Hs,{className:"h-3 w-3"}),e]}),i.jsxs(bn,{className:"max-w-lg",children:[i.jsx(wn,{children:i.jsxs(yn,{className:"text-base",children:[n("Skill")," · ",e]})}),i.jsx(Mn,{className:"max-h-[50vh] text-sm",children:i.jsx(_s,{text:t})})]})]})}function Lm({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 YK({blocks:e}){const t=xR(e.rest),n=i.jsx(Lm,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:e.skills.map(s=>i.jsx(qK,{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(lD,{note:t.plan}),t.unattended&&i.jsx(dD,{note:t.unattended}),n]})}function XK({text:e}){const t=ij(e);if(t.names.length>1)return i.jsx(Lm,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:t.names.map(s=>i.jsx(Du,{name:`/skill:${s}`},s))}),extra:t.rest});const n=Tu(e);return n.slash?i.jsx(Lm,{chip:i.jsx(Du,{name:n.slash}),extra:n.rest.trim()}):null}function ZK({preset:e}){const{t}=J();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(Sg,{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 kl({kind:e,label:t,title:n}){const s=e==="file"?wo:e==="chat"?$o:U6;return i.jsxs("span",{className:W(Qx(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 Ra({text:e,searchQuery:t="",activeNth:n=-1}){const s=y4(mR(e)),o={n:0};return i.jsx("span",{className:"whitespace-pre-wrap",children:s.map((r,a)=>r.type==="file"?i.jsx(sj,{path:r.path,children:i.jsx(kl,{kind:"file",label:bh(r.path),title:r.path})},a):r.type==="chat"?i.jsx(kl,{kind:"chat",label:r.label,title:r.sessionFile},a):r.type==="ui-element"?i.jsx(kl,{kind:"ui-element",label:r.label,title:`${r.path}${r.text?` · ${r.text}`:""}`},a):i.jsx("span",{children:t.trim()?gR(r.text,t,n,o):r.text},a))})}function JK({files:e,chats:t}){return i.jsxs("span",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[e.map(n=>i.jsx(sj,{path:n,children:i.jsx(kl,{kind:"file",label:bh(n),title:n})},`f:${n}`)),t.map(n=>i.jsx(kl,{kind:"chat",label:n.label,title:n.sessionFile},`c:${n.sessionFile}`))]})}const Qa="max-w-[82%] rounded-[10px] bg-muted px-3.5 py-[9px] text-(length:--chat-body-size) leading-[1.6]";function el({text:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=J(),o=Wi(),r=!!(o?.speaker||o?.botSession),a=r?nR(e):null;if(a)return i.jsx(A8,{message:a});const l=r?sR(e):e;if(l!==e)return i.jsx(el,{text:l,searchQuery:t,activeNth:n});const d=r?iR(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(el,{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(ha,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:N.title})]},N.id))})]});const c=oR(e);if(c.note){const N=c.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(lD,{note:c.note}),N&&i.jsx(el,{text:N,searchQuery:t,activeNth:n})]})}const u=rR(e);if(u.note){const N=u.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(dD,{note:u.note}),N&&i.jsx(el,{text:N,searchQuery:t,activeNth:n})]})}const h=aR(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(jN,{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:W(Qa,"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(ga,{className:"h-3 w-3"}),s("Plan feedback")]}),i.jsx(Ra,{text:h.feedback,searchQuery:t,activeNth:n})]});const p=lR(e);if(p)return i.jsx(ZK,{preset:p});const f=N4(e);if(f.files.length>0||f.chats.length>0){const N=Tu(f.body);return i.jsxs("div",{className:Qa,children:[N.slash?i.jsxs(i.Fragment,{children:[i.jsx(Du,{name:N.slash}),N.rest.trim()?i.jsx("span",{className:"ml-1.5 align-middle",children:i.jsx(Ra,{text:N.rest.trim(),searchQuery:t,activeNth:n})}):null]}):i.jsx(Ra,{text:f.body,searchQuery:t,activeNth:n}),i.jsx(JK,{files:f.files,chats:f.chats})]})}const x=dR(e);if(x)return i.jsx(YK,{blocks:x});if(Tu(e).slash)return i.jsx(XK,{text:e});const v=BK.exec(e);if(v){const N=e.slice(v[0].length).trim();return i.jsxs(i.Fragment,{children:[i.jsx($K,{note:v[1]}),N&&i.jsx("div",{className:W(Qa,"whitespace-pre-wrap"),children:i.jsx(Ra,{text:N,searchQuery:t,activeNth:n})})]})}const y=HK.exec(e);if(y)return i.jsx(VK,{tag:y[1],body:y[2]});const b=aD.exec(e),w=b?e.slice(b[0].length):e,_=cD.exec(w),C=_?_[1]:w;return i.jsxs("div",{className:W(_?"max-w-[80%] rounded-2xl rounded-bl-md border border-blue-500/20 bg-blue-500/8 px-4 py-2.5 text-sm":W(Qa,"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(Vs,{className:"h-3 w-3"}),s("From main agent")]}),b?.[1]&&!E8(b[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")})," · ",b[1]]}),_?i.jsx(_s,{text:C,searchQuery:t,activeNth:n}):i.jsx(Ra,{text:C,searchQuery:t,activeNth:n})]})}function Hy(e){return e.kind==="tool-group"||e.kind==="thinking"||e.kind==="tool"&&ej(e)}const Td="text-[color:var(--subtle-foreground,var(--muted-foreground))]",Qr="animate-pulse motion-reduce:animate-none";function QK({model:e,at:t,privacyMask:n}){const s=Wi()?.speaker,o=[e,typeof t=="number"?_h(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:W("min-w-0 truncate text-[11.5px]",Td),children:o}),n&&i.jsx(B9,{report:n})]})}const eq=m.memo(function({item:t,onToggleGroup:n,onToggleTurn:s}){const o=UM(),r=o.query,a=o.activeKey===t.key?o.activeNth:-1;switch(t.kind){case"user":{const l=t.text?KK(t.text):!1,d=t.collapsed===!0;return i.jsxs("div",{"data-enso":"message-user",className:W("group/user flex flex-col gap-1.5",l?"items-start":"items-end"),children:[t.images.map((c,u)=>i.jsx(rD,{src:`data:${c.mimeType};base64,${c.data}`,className:"max-h-48 max-w-full rounded-lg border object-contain"},u)),t.text&&i.jsx(el,{text:t.text,searchQuery:r,activeNth:a}),d?i.jsx(dq,{turnKey:t.key,timestamp:t.timestamp,turnDurationMs:t.turnDurationMs,onToggle:s}):i.jsx(cq,{turnKey:t.key,messageIndex:Number(t.key),timestamp:t.timestamp,deliveryState:t.deliveryState,canCollapse:t.canCollapse,onToggleTurn:s})]})}case"text":return i.jsx(uq,{item:t,searchQuery:r,activeNth:a});case"thinking":return i.jsx(fq,{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(KM,{name:t.name,output:t.output,state:t.state}),i.jsx(yq,{item:t}),t.pluginArtifacts?i.jsx(qM,{artifacts:t.pluginArtifacts}):null]});case"tool-group":return i.jsx(vq,{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(hD,{})]});case"task-note":return i.jsx(mq,{item:t});case"compaction":case"compaction-notice":return i.jsx(xq,{item:t});case"compaction-progress":return i.jsx(gq,{state:t.state});case"session-custom":return i.jsx(iq,{entry:t.entry});case"plugin-message":return i.jsx(nq,{item:t});case"discarded-turn":return i.jsx(sq,{item:t,onToggle:n});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"})]})}},FK),By=e=>{if(typeof e=="string")return e;if(e===void 0)return"—";try{return JSON.stringify(e)}catch{return String(e)}};function tq({entry:e}){const{t}=J(),n=R8(),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(Ho,{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 nq({item:e}){const{t}=J();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(qu,{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 sq({item:e,onToggle:t}){const{t:n}=J();return i.jsxs("div",{"data-discarded-turn":e.pluginId,children:[i.jsxs("button",{type:"button",onClick:()=>t?.(e.key),"data-enso":"tool-row",className:W("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",Td),children:[i.jsx(IN,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"shrink-0 text-muted-foreground group-hover/step:text-foreground",children:br("turn_discard",n)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:[e.pluginName,e.reason].filter(Boolean).join(" · ")}),i.jsx(un,{className:W("h-3 w-3 shrink-0 transition-transform",e.expanded&&"rotate-90")})]}),e.expanded&&i.jsxs("div",{className:"t-acc-reveal mt-1 mb-1.5 ml-5 space-y-2 rounded-md border border-dashed border-border bg-muted/20 px-3 py-2 text-xs",children:[i.jsxs("p",{className:"flex items-center gap-1.5 text-muted-foreground",children:[i.jsx(qu,{pluginId:e.pluginId,className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:n("From plugin {{name}}",{name:e.pluginName})})]}),e.messages.map((s,o)=>i.jsx("p",{className:"whitespace-pre-wrap break-words text-foreground",children:s},o))]})]})}function iq({entry:e}){const{t}=J();if(e.kind==="oauth-account-selected")return i.jsx(tq,{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(Vs,{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(Kn,{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})]})]});if(e.kind==="tool-batch-label")return null;const n=e.receipt,s=n.outcome==="succeeded";return i.jsx("div",{className:W("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(Kn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"}):i.jsx(gr,{className:W("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:[By(o.previous)," → ",By(o.value)]})]},o.field))})]})]})})}function Ps(e){const t=e.activeId?e.conversations[e.activeId]:null;return t?t.activeTabId?e.conversations[t.activeTabId]??t:t:null}const uD=()=>()=>{};function hD(){const{t:e}=J(),t=Wi(),n=t?.botControls,s=se(l=>{if(t&&(!t.canRetry||t.botControls))return!1;const d=Ps(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??uD,o,o);return(n?r:s)?i.jsxs("button",{type:"button",title:e("Retry"),onClick:()=>{if(n)return n.retry();const l=Ps(se.getState());l&&se.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(Ho,{className:"h-3 w-3"}),e("Retry")]}):null}function oq(e,t){return vR(Ps(e),t)}const ov="flex items-center gap-1 text-[11px] text-muted-foreground transition-opacity hover:text-foreground";function rq({messageIndex:e}){const{t}=J(),n=Wi();return se(o=>hR(Ps(o),n))?i.jsxs("button",{type:"button",className:ov,title:t("Keep this session and start a parallel one from here"),onClick:()=>{const o=se.getState(),r=Ps(o);if(!r)return;const a=pR(r,e);a!==null&&o.forkFromMessage(r.id,a)},children:[i.jsx(Mi,{className:"h-3 w-3"}),t("Conversation branch")]}):null}function aq({messageIndex:e}){const{t}=J(),n=Wi(),s=se(r=>Ps(r)?.id),o=se(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 cR(l)||a.status==="running"&&uR(l)?l?.deliveryId:void 0});return!s||!o?null:i.jsxs("button",{type:"button",title:t("Withdraw message"),onClick:()=>se.getState().withdrawMessage(s,{kind:"delivery",id:o}),className:"inline-flex items-center gap-1 hover:text-foreground",children:[i.jsx(pa,{className:"h-3 w-3"}),t("Withdraw message")]})}function lq({messageIndex:e}){const{t}=J(),[n,s]=m.useState(!1),[o,r]=m.useState(null),a=Wi(),l=a?.botControls,d=se(x=>{if(a?.botControls)return!1;const v=Ps(x);return oq(x,a)&&!!(v&&Ad(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:Ad(a.sessionId,a.sessionId,x,e)?.entryId??null},u=m.useSyncExternalStore(l?.subscribe??uD,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=Ps(se.getState());if(!v)return;const y=Ad(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 b=se.getState(),w=Ps(b),_=Ad(v,w?.id,b.conversations[v],e,y);_&&b.rewind(_.conversationId,_.entryId,x)},g=[{icon:pa,label:t("Conversation only"),desc:t("Rewind to this message"),restoreFiles:!1,action:()=>p(!1)},{icon:$o,label:t("Conversation + files"),desc:t("Rewind and restore files to before this turn"),restoreFiles:!0,action:()=>p(!0)}];return i.jsxs(gi,{open:n,onOpenChange:s,children:[i.jsxs(xi,{className:ov,title:t("Rewind to this message"),children:[i.jsx(pa,{className:"h-3 w-3"}),t("Rewind")]}),i.jsx(vi,{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(ms,{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 dq({turnKey:e,timestamp:t,turnDurationMs:n,onToggle:s}){const{t:o}=J();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(un,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{children:o("Expand")})]}),typeof t=="number"&&i.jsx("span",{children:_h(t)}),n!==void 0&&i.jsxs("span",{children:["· ",o("took {{duration}}",{duration:Un(n)})]})]})}function cq({turnKey:e,messageIndex:t,timestamp:n,canCollapse:s,deliveryState:o,onToggleTurn:r}){const{t:a}=J(),l=Se(d=>d.autoCollapseTurns);return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/75 select-none",children:[i.jsx(lq,{messageIndex:t}),i.jsx(aq,{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:W(ov,"cursor-pointer opacity-0 group-hover/user:opacity-100"),title:a("Collapse"),children:[i.jsx($n,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{children:a("Collapse")})]}),typeof n=="number"&&i.jsx("span",{children:_h(n)})]})}function uq({item:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=J(),o=Wi(),r=e.perf?pq(e.perf,s,e.turnDurationMs!==void 0):"",a=se(p=>Ps(p)?.id??null),l=Number(e.key.split("-")[0]),d={text:e.text,messageIndex:l,sessionId:o?o.sessionId:a},c=IK(!o&&e.turnEnd&&e.turnDurationMs!==void 0?a:null,l),[u,h]=m.useState(!1);return i.jsxs("div",{"data-enso":"message-assistant",className:"group text-(length:--chat-body-size)",children:[i.jsx(_s,{text:e.text,streaming:e.streaming,searchQuery:t,activeNth:n,leaf:{messageIndex:d.messageIndex,sessionId:d.sessionId}}),e.turnEnd&&!e.streaming&&o?.turnFooter?.(Number(e.key.split("-")[0])),!e.streaming&&i.jsxs("div",{className:W("mt-1 flex items-center gap-2 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",u&&"opacity-100"),children:[i.jsx(o0,{position:"left",...d}),i.jsx(hq,{text:e.text}),i.jsx(o0,{position:"right",...d}),e.turnEnd&&i.jsx(rq,{messageIndex:Number(e.key.split("-")[0])}),e.timestamp&&!e.turnEnd&&i.jsx("span",{children:_h(e.timestamp)}),e.turnDurationMs!==void 0&&(c?i.jsxs("button",{type:"button","aria-expanded":u,onClick:()=>h(p=>!p),className:"flex items-center gap-0.5 transition-colors hover:text-foreground",children:[s("took {{duration}}",{duration:Un(e.turnDurationMs)}),i.jsx(un,{className:W("h-3 w-3 transition-transform",u&&"rotate-90")})]}):i.jsxs("span",{children:[e.timestamp&&!e.turnEnd&&"· ",s("took {{duration}}",{duration:Un(e.turnDurationMs)})]})),r&&i.jsxs("span",{children:["· ",r]})]}),u&&c&&a&&i.jsx(AK,{conversationId:a,messageIndex:l})]})}function hq({text:e}){const{t}=J(),[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(Kn,{className:"h-3 w-3"}):i.jsx(Uu,{className:"h-3 w-3"})})}const $y=e=>String(e).padStart(2,"0"),_h=e=>{const t=new Date(e);return`${$y(t.getHours())}:${$y(t.getMinutes())}`},Vy=e=>{const t=e/1e3;return t<10?String(Math.round(t*10)/10):String(Math.round(t))};function pq(e,t,n=!1){const s=[];return(!n||e.turnMs!==void 0)&&s.push(`${Vy(e.runMs)}s`),e.ttftMs!==void 0&&s.push(`TTFT ${Vy(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:Un(e.turnMs)})),s.join(" · ")}function fq({itemKey:e,text:t,streaming:n,durationMs:s,startedAt:o}){const{t:r}=J(),a=Se(u=>u.expandLiveReasoning),[l,d]=m.useState(null),c=tR(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:W("flex min-h-6 items-center gap-2 text-[13px] transition-colors hover:text-foreground",Td),children:[i.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:i.jsx(YM,{className:W("size-3",n&&"animate-pulse text-brand")})}),n?i.jsx("span",{className:W("text-foreground",Qr),children:r("Thinking…")}):s!==null?i.jsx("span",{children:r("Thought for {{duration}}",{duration:Un(s)})}):i.jsx("span",{children:r("Thought process")}),n&&i.jsx(pD,{itemKey:e,since:o}),i.jsx(un,{className:W("h-3 w-3 transition-transform",c&&"rotate-90")})]}),c&&i.jsx(XM,{text:t,streaming:n,itemKey:e})]})}function mq({item:e}){const{t}=J(),[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(Kn,{className:"h-3 w-3 text-green-600 dark:text-green-500"}),l,i.jsx(un,{className:W("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…"):Si(o??t("(log unavailable)")):t("(no log available)")})]})]})}function gq({state:e}){const{t}=J();return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx(Zt,{className:"h-3 w-3 animate-spin"}),i.jsx("span",{children:t(e==="queued"?"Compacts after this turn":"Compacting…")})]})}function xq({item:e}){const{t}=J(),[n,s]=m.useState(!1),o=e.kind==="compaction",r=e.tokensBefore===null?null:Jn(e.tokensBefore),a=J8(e.tokensBefore,e.tokensAfter),l=a!==null&&e.tokensBefore!==null&&e.tokensAfter!==void 0?t("{{kind}} · {{before}} → {{after}} · freed {{percent}}%",{kind:t(e.memory?"Memory context compacted":e.verified?"Verified context compacted":"Context compacted"),before:Jn(e.tokensBefore),after:Jn(e.tokensAfter),percent: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(d=>!d),className:W("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(I6,{className:"h-3 w-3"}),l,i.jsx(un,{className:W("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 vq({item:e,onToggle:t}){const{t:n}=J(),s=Se(f=>f.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=e.exploring||!!(a&&e.live),u=d?br("explore_fold",n):a?a.workedMs>0?n("Worked for {{duration}}",{duration:Un(a.workedMs)}):n("Activity"):s?e.exploring?n("Exploring"):n("Explored"):n("{{count}} tool calls",{count:e.count}),h=d?[d.goal,n("{{count}} tool calls",{count:e.count})].filter(Boolean):e.summary&&!e.exploring?[e.summary]:a?l:s?r:o,p=i.jsxs("button",{type:"button",onClick:()=>{d?.steps&&t?.(r0(e.key)),t?.(e.key)},title:d?.goal,"data-explore-head":d?"":void 0,"data-enso":"tool-row",className:W("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",Td),children:[i.jsx(tD,{state:e.exploring?"running":"ok"}),i.jsx("span",{className:W("shrink-0 text-muted-foreground group-hover/step:text-foreground",c&&W(Qr,"text-foreground"),e.exploring&&"font-medium"),children:u}),i.jsx("span",{className:W("min-w-0 flex-1 truncate",c&&Qr),children:h.join(" · ")}),i.jsx(un,{className:W("h-3 w-3 shrink-0 transition-transform",e.expanded&&"rotate-90")})]});return!d||!e.expanded?p:i.jsxs(i.Fragment,{children:[p,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(_s,{text:d.report})]}),i.jsxs("button",{type:"button",onClick:()=>t?.(r0(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(un,{className:W("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 La({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:W("max-h-96 overflow-auto [overflow-anchor:none]",t),children:i.jsx("div",{ref:o,children:e})})}function bq(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??""}catch{return String(e)}}function wq({source:e,output:t,view:n}){const s=n?.status==="completed"?bq(n.value):n?.error??t;return i.jsxs("div",{className:"space-y-1 px-3 py-1",children:[e?i.jsx(a0,{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:W("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(a0,{code:s,language:"json"}):i.jsx("pre",{className:"font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:Si(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:Si(n.console)}):null]})}function Wy({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(rD,{src:wf(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 yq({item:e}){const{t}=J(),n=Wi(),s=Se(F=>F.compactReadOnlyTools),o=Se(F=>F.expandLiveEdits),r=s&&e.name!=="bash"&&ej(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=UN[e.name],f=tj(e.name),g=e.state!=="error"&&e.todos?.length===0,x=g?t("Todo list cleared"):e.subagentOp?[t(V4[e.subagentOp]),e.summary].filter(Boolean).join(" · "):e.summary,v=e.nestedPending&&e.state==="running"?`${x} · ${e.nestedPending} pending`:c?.calls.length&&e.state!=="error"?ZM(c.calls):x,y=!g&&!!(e.output||e.source||u||e.ask),b=e.state==="running"&&e.waiting==="subagent"&&!n,w=a||l||d||y||b||h,_=o&&(a||l||h)&&e.state==="running",[C,N]=m.useState(_),[S,k]=m.useState(!1),A=m.useRef(null),I=LK();m.useEffect(()=>{if(!S)return;const F=A.current;if(!F)return;const O=e.key,B=I.report,Y=new IntersectionObserver(([U])=>B(O,U?.isIntersecting===!0),{root:I.scroller.current});return Y.observe(F),()=>{Y.disconnect(),B(O,!1)}},[S,e.key,I]);const E=C&&e.name==="memory_search"?k9(e.output):null,D=C&&e.name==="memory_capture"?j9(e.output,e.memoryContent):null,T=C&&e.name==="subagent"&&e.state!=="error"?kK(e.subagentOp,e.output):null,H=m.useRef(d);return m.useEffect(()=>{const F=JM(e,H.current);H.current=d,(_||o&&F)&&N(!0)},[_,o,d,e]),e.todos&&e.todos.length>0?i.jsx(kq,{todos:e.todos}):e.name.startsWith("goal_")?i.jsx(Sq,{item:e}):e.plan&&e.state!=="error"?i.jsx(Cq,{plan:e.plan}):i.jsxs("div",{ref:A,"data-enso":"tool-row","data-tool-style":r?"compact":"full","data-user-open":S?"true":void 0,children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{type:"button",disabled:!w,onClick:()=>{const F=!C;N(F),k(F),I.report(e.key,F)},className:W("group/step flex min-h-6 min-w-0 flex-1 items-center gap-2 text-left text-[13px]",Td,w&&"cursor-pointer"),children:[i.jsx(tD,{state:e.state}),i.jsx("span",{className:W("shrink-0 text-muted-foreground transition-colors group-hover/step:text-foreground",e.state==="running"&&W(Qr,"text-foreground")),children:p?t(p):f?.tool??e.name}),i.jsx("span",{className:W("min-w-0 flex-1 truncate font-mono text-[12px]",e.state==="error"?"text-destructive":"text-muted-foreground",e.state==="running"&&Qr),children:e.state==="error"&&e.output?x&&e.name==="apply_patch"&&d?`${v} · ${qy(e.output)}`:qy(e.output):x?v: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(hK,{failure:e.shellFailure}),e.state==="reviewing"?i.jsx("span",{className:W("shrink-0 text-[11px] text-foreground",Qr),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(Iq,{callId:e.callId,startedAt:e.startedAt,output:e.output??""}),i.jsx(pD,{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?Un(e.durationMs):null].filter(Boolean).join(" · ")}),w&&i.jsx(un,{className:W("h-3 w-3 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] group-hover/step:opacity-100",C&&"rotate-90 opacity-100")})]}),e.state==="running"&&e.callId&&!n&&i.jsx(jq,{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:()=>nj(),children:i.jsx(Dx,{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(F=>i.jsx(Wy,{path:F,fallback:i.jsx("p",{className:"break-all px-3 py-2 text-xs text-muted-foreground",children:F})},F))}):null,C&&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]}),b&&i.jsx(Dq,{agentIds:e.subagentTitles?Object.keys(e.subagentTitles):void 0}),a&&e.edits&&i.jsx(La,{follow:e.state==="running",children:i.jsx(Py,{path:e.summary,blocks:e.edits})}),d&&e.fileChanges&&i.jsx(La,{follow:e.state==="running",children:e.fileChanges.map((F,O)=>i.jsxs("div",{children:[i.jsxs("div",{className:W("flex items-center gap-2 border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",(O>0||a)&&"border-t"),children:[i.jsx("span",{className:"uppercase",children:F.type}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:F.path,children:F.path}),F.truncated&&i.jsx("span",{children:t("Truncated preview")})]}),i.jsx(Py,{path:F.path,blocks:[F],snapshot:F})]},`${F.type}:${Yx(F.path,F.oldText,F.newText)}`))}),QM(e)&&i.jsx(La,{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:Si(e.output??"")})}),l&&e.writeContent&&i.jsx(La,{follow:e.state==="running",className:W((a||d)&&"border-t border-border/60"),children:i.jsx($c,{path:e.summary,contents:e.writeContent})}),!a&&!l&&!d&&(y||h)&&i.jsxs(La,{follow:e.state==="running",children:[eR(e.name)?i.jsx(wq,{source:e.source,output:e.output,view:c}):e.name==="bash"||e.name==="powershell"?i.jsx(jK,{command:e.summary,output:e.output??"",failure:e.shellFailure}):e.name==="read"&&h&&e.imagePath?i.jsx(Wy,{path:e.imagePath,fallback:i.jsx($c,{path:e.summary,contents:e.output??""})},e.imagePath):e.name==="read"?i.jsx($c,{path:e.summary,contents:e.output??""}):e.name==="subagent"&&e.state!=="error"&&!u&&!T?i.jsx("div",{className:"px-3 py-2 text-sm",children:i.jsx(_s,{text:e.output??""})}):E?i.jsx(Pm,{hits:E}):D?i.jsx(b9,{view:D}):i.jsxs(i.Fragment,{children:[e.ask&&i.jsx(V8,{ask:e.ask,waiting:e.state==="running"}),u&&i.jsx("div",{className:"px-3 py-2 text-sm",children:i.jsx(_s,{text:u})}),T?i.jsx(wK,{view:T,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:Si(e.output)})]}),i.jsx(q9,{value:e.rtk}),i.jsx($8,{value:e.approvalReview})]})]})]})}function Sq({item:e}){const{t}=J(),n=e.name.replace("goal_",""),s=t(n==="complete"?"Goal completed":n==="blocked"?"Goal blocked":"Goal waiting");return i.jsxs("div",{className:W("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(Ta,{className:W("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 Cq({plan:e}){const{t}=J(),[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(ga,{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(un,{className:W("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(_s,{text:e.text})})]})}function kq({todos:e}){const{t}=J(),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(sD,{done:n,total:e.length,className:"mt-1.5 mb-2"}),i.jsx(nD,{todos:e})]})}const Uy=new Map;function jq({callId:e,waiting:t}){const{t:n}=J(),s=se(d=>Ps(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?IN:iV;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 _q=5e3,Nq=[];function Tq(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 Dq({agentIds:e}){const{t}=J(),n=se(l=>Ps(l)?.id??""),s=Kw(l=>l.byConversation[n]??Nq),[o,r]=m.useState(!1);if(m.useEffect(()=>{if(!n)return;let l=!0;const d=p=>{l&&(Kw.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,_q);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:Tq(l,t)}),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:Un(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 pD({itemKey:e,since:t}){const n=Wi(),s=se(d=>Ps(d)?.id??""),o=n?n.sessionId??"":s,r=m.useRef(null);if(r.current===null){const d=`${o}:${e}`;r.current=t??Uy.get(d)??Date.now(),t===void 0&&Uy.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:Un(Date.now()-a)})}function Iq({callId:e,startedAt:t,output:n}){const s=Wi(),o=se(r=>s?void 0:Ps(r)?.toolDeadlineAt?.[e]);return i.jsx(uK,{startedAt:t,deadlineAt:o,output:n})}function Ky(e){return e.kind==="tool-group"?!0:e.kind==="tool"&&!e.todos?.length&&!e.name.startsWith("goal_")}const qy=e=>Si(e.split(`
|
|
73
|
-
`,1)[0]??""),Eq=100;function Pq(e,t,n,s,o=Eq){if(s||!n)return{hiddenSince:t,delayMs:null};const r=t??e;return{hiddenSince:r,delayMs:Math.max(0,o-(e-r))}}const Aq=1e6;function Mq(e,t,n=Aq){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 Rq(e,t){return t}const Lq=new Set(["text","thinking","tool","tool-group"]);function Oq(e,t,n,s){const o=m.useRef(l0),[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?wR(e,t,s,o.current,r):null;o.current=f?.witness??l0;const g=f?.wakeAt??null,x=yR(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 zq=[{icon:PV,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:kN,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:oj,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:$o,title:"Summarize recent changes",hint:"A digest based on git log",prompt:"Summarize the recent changes in this repository based on git log."}];function Gq({onPick:e}){const{t}=J();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:zq.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 ji="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",Yy=1e3;function Xy({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:W("t-stagger",n&&"is-shown",e),children:t})}const Zy=40,Fq={index:"LAST",align:"end"},Hq={top:600,bottom:600},Bq=e=>e?"auto":!1;function $q({style:e,...t}){const n=e?.visibility==="hidden",[s,o]=m.useState(!1),r=m.useRef(null);return m.useEffect(()=>{const a=Pq(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 Nh({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:b=null}){const{t:w}=J(),_=m.useRef(null),[C,N]=m.useState(!0),[S,k]=m.useState(!1),A=m.useRef(!0),I=m.useRef(null),E=m.useRef(0),D=m.useRef(0),T=m.useRef(null),H=m.useRef(!1),F=m.useRef(!1),O=m.useRef(0),[B,Y]=m.useState(null),U=m.useRef(0),ee=m.useCallback(ge=>{cancelAnimationFrame(U.current),U.current=requestAnimationFrame(()=>Y(ge()))},[]);m.useEffect(()=>()=>cancelAnimationFrame(U.current),[]);const[L,Q]=m.useState(new Set),V=m.useRef(new Set),[ce,ve]=m.useState(()=>new Set),_e=m.useCallback((ge,qe)=>{const lt=V.current;qe!==lt.has(ge)&&(qe?lt.add(ge):lt.delete(ge),ve(new Set(lt)))},[]),De=m.useRef({report:_e,scroller:I});De.current.report=_e;const me=m.useCallback(ge=>{Q(qe=>{const lt=new Set(qe);return lt.has(ge)?lt.delete(ge):lt.add(ge),lt})},[]),[$,z]=m.useState(new Map),de=Se(ge=>ge.autoCollapseTurns),X=Se(ge=>ge.collapseCompletedActivity),oe=Se(ge=>ge.collapseLiveActivity),Z=Se(ge=>ge.liveActivityFoldDelaySec),ae=Se(ge=>ge.compactReadOnlyTools),be=Oq(t,o,L,{compact:ae,autoCollapseCompletedTurns:de,collapseCompletedActivity:X,collapseLiveActivity:oe,liveActivityFoldDelaySec:Z,heldOpenTools:ce,turnOverrides:$}),ze=m.useRef({state:k8,collapse:new Map,reveal:new Map}),Ye=m.useMemo(()=>{const ge=ze.current,qe=zt=>I.current?.querySelector(`[data-nav-key="${CSS.escape(zt)}"]`),lt=j8(ge.state,be,(zt,cn)=>{const P=qe(zt)?.getBoundingClientRect().top,M=qe(cn)?.getBoundingClientRect().bottom;return P===void 0||M===void 0?0:M-P}),Tt=Date.now();ge.state=lt.next;for(const{key:zt,...cn}of lt.collapses)ge.collapse.set(zt,{at:Tt,...cn});for(const zt of lt.expands)ge.reveal.set(zt,Tt);return lt.children},[be]),Ve=m.useRef(null),at=m.useRef(0),Ze=m.useRef(null),Et=Mq(Ve.current,be.map(ge=>ge.key));Ve.current=Et.anchor,Et.remount&&(at.current+=1,Ze.current=null);const Gt=Et.firstItemIndex,Pt=m.useCallback((ge,qe)=>{z(lt=>lt.get(ge)===qe?lt:new Map(lt).set(ge,qe))},[]),ne=m.useMemo(()=>{const ge=[];for(let qe=0;qe<t.length;qe++){const lt=t[qe];if(lt.kind!=="user")continue;let Tt="";for(let zt=qe+1;zt<t.length;zt++){const cn=t[zt];if(cn.kind==="user")break;if(cn.kind==="text"){Tt=cn.text;break}}ge.push({key:lt.key,question:lt.text||"[image]",answer:Tt})}return ge},[t]),ie=m.useCallback(()=>{const ge=I.current;ge&&ge.scrollHeight-ge.scrollTop-ge.clientHeight>2&&(H.current=!0,ge.scrollTop=ge.scrollHeight)},[]),He=m.useCallback(()=>{cancelAnimationFrame(E.current);const ge=Date.now()+1200;let qe=null;const lt=()=>{cancelAnimationFrame(E.current),H.current=!1,qe?.removeEventListener("touchstart",lt),qe?.removeEventListener("wheel",lt)},Tt=()=>{if(F.current){lt();return}!qe&&I.current&&(qe=I.current,qe.addEventListener("touchstart",lt,{passive:!0,once:!0}),qe.addEventListener("wheel",lt,{passive:!0,once:!0})),ie(),A.current=!0,N(!0),Date.now()<ge?E.current=requestAnimationFrame(Tt):lt()};Tt(),N(!0),A.current=!0},[ie]);m.useEffect(()=>()=>{cancelAnimationFrame(E.current),cancelAnimationFrame(D.current),window.clearTimeout(O.current)},[]);const St=()=>{F.current=!0,window.clearTimeout(O.current)},it=()=>{window.clearTimeout(O.current),O.current=window.setTimeout(()=>{F.current=!1},400)},je=()=>{St(),it()},ht=()=>{cancelAnimationFrame(E.current),cancelAnimationFrame(D.current),H.current=!1,A.current=!1,N(!1)},$t=m.useCallback(ge=>{if(T.current?.disconnect(),T.current=null,!ge)return;const qe=new ResizeObserver(()=>{if(!A.current&&!H.current)return;cancelAnimationFrame(D.current);let lt=8;const Tt=()=>{ie();const zt=I.current;(zt?zt.scrollHeight-zt.scrollTop-zt.clientHeight:0)<=2||(--lt>0?D.current=requestAnimationFrame(Tt):He())};Tt()});qe.observe(ge),T.current=qe,He()},[ie,He]);m.useEffect(()=>()=>T.current?.disconnect(),[]);const Oe=ge=>be.findIndex(qe=>qe.key===ge||qe.kind==="tool-group"&&fD(qe,ge)),yt=ge=>{if(!p){I.current?.querySelector(`[data-nav-key="${CSS.escape(ge)}"]`)?.scrollIntoView({block:"center"});return}const qe=Oe(ge);qe>=0&&_.current?.scrollToIndex({index:Rq(Gt,qe),align:"center"})},Ht=m.useRef(null),re=ge=>{if(ht(),Oe(ge)>=0){Ht.current=null,yt(ge);return}let qe=null,lt=!1;for(const Tt of t)if(Tt.kind==="user"&&(qe=Tt.key),Tt.key===ge){lt=!0;break}!lt||!qe||(Ht.current=ge,Pt(qe,!1))};m.useLayoutEffect(()=>{const ge=Ht.current;!ge||Oe(ge)<0||(Ht.current=null,yt(ge))},[be]),m.useImperativeHandle(e,()=>({scrollToBottom:He,pinToBottom:ie,isAtBottom:()=>A.current,getScroller:()=>p?null:I.current,scrollToKey:re}));const $e=m.useRef(!1),st=`${v}:${Gt}`,Nt=m.useRef(st);Nt.current!==st&&(Nt.current=st,$e.current=!1);const mt=()=>{!f||$e.current||($e.current=!0,f())};m.useEffect(()=>{p&&!g&&Ze.current===Gt&&mt()},[v,g]);const K=m.useMemo(()=>({query:y,activeKey:b?.key??"",activeNth:b?.nth??-1}),[y,b?.key,b?.nth]),he=(ge,qe)=>{const lt=be[qe+1];if(lt!==void 0&&Ky(ge)&&Ky(lt))return"pb-0";if(!ae)return"pb-4";const Tt=lt!==void 0&&Hy(lt);return Hy(ge)?Tt?"pb-1":"pb-2":ge.kind==="text"&&Tt?"pb-1":"pb-4"},Ie=(ge,qe)=>{const lt=be[qe-1],Tt=lt?.kind==="user"&&!lt.collapsed&&Lq.has(ge.kind)?lt:void 0,zt=Date.now(),cn=ze.current.collapse.get(ge.key),P=cn&&zt-cn.at<Yy?cn:void 0,M=Ye.get(ge.key),R=M&&ze.current.reveal.get(M.group),j=M&&R!==void 0&&zt-R<Yy;return i.jsxs("div",{"data-nav-key":ge.key,"data-fold-collapse":P?P.pair?"pair":"toggle":void 0,style:P?{"--fold-from":`${P.height}px`}:j?{"--fold-i":M.index}:void 0,className:W(ji,he(ge,qe),j&&"t-fold-reveal","[overflow-wrap:anywhere]"),children:[Tt&&i.jsx(QK,{model:Tt.replyModel,at:Tt.replyAt,privacyMask:Tt.replyPrivacyMask}),i.jsx(Yq,{itemKey:ge.key,children:i.jsx(eq,{item:ge,onToggleGroup:me,onToggleTurn:Pt})})]},ge.key)},Ee=m.useRef(!1);x===!0&&(Ee.current=!0);const Be=SR(t.length>0,g,x,Ee.current,!p&&S);m.useLayoutEffect(()=>{if(p){k(!1);return}const ge=I.current;k(!!ge&&CR(x===!0,g,ge.scrollHeight,ge.clientHeight))},[p,x,g,Gt,be.length,t.length]);const Je={pageChrome:Be,onLoadMore:Be==="more"?mt:void 0,busy:n,loading:!!s,since:s?void 0:a??r,error:l,onRetryResume:h};return i.jsx(kR.Provider,{value:K,children:i.jsx(RK,{value:De.current,children:i.jsxs("div",{"data-enso":"timeline",className:"@container relative min-h-0 flex-1",onWheel:je,onKeyDown:je,onTouchStart:St,onTouchEnd:it,onPointerDown:ge=>{ge.target===I.current&&(St(),window.addEventListener("pointerup",it,{once:!0}))},children:[i.jsx(T8,{items:ne,activeKey:B,onJump:re}),t.length===0&&!n?i.jsxs(Xy,{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(C8,{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:w(l)}),h&&i.jsx(fe,{size:"sm",variant:"outline",onClick:h,children:w("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??w("Ask the agent…")}),u&&i.jsx("div",{className:"t-stagger-line t-stagger-line--3 mt-5 w-full",children:i.jsx(Gq,{onPick:u})})]})]}):t.length===0&&l?i.jsxs(Xy,{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:w(l)}),h&&i.jsx(fe,{size:"sm",variant:"outline",onClick:h,children:w("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(Zt,{className:"h-5 w-5 animate-spin text-muted-foreground"}),i.jsx("p",{className:"text-sm text-muted-foreground",children:w("Preparing session…")})]}):p?i.jsx(a8,{ref:_,data:be,defaultItemHeight:80,computeItemKey:(ge,qe)=>qe.key,firstItemIndex:Gt,startReached:mt,followOutput:Bq,atBottomThreshold:Zy,atBottomStateChange:ge=>{if(!ge&&A.current&&!F.current){He();return}N(ge),A.current=ge},increaseViewportBy:Hq,initialTopMostItemIndex:Fq,rangeChanged:({startIndex:ge})=>{Ze.current=ge,ge>Gt+4&&($e.current=!1),ee(()=>{const qe=Math.max(0,ge-Gt);let lt=null;for(let Tt=0;Tt<=Math.min(qe+1,be.length-1);Tt++)be[Tt]?.kind==="user"&&(lt=be[Tt].key);return lt})},scrollerRef:ge=>{I.current=ge instanceof HTMLElement?ge:null},className:"h-full select-text",context:Je,components:Wq,itemContent:(ge,qe)=>Ie(qe,ge-Gt)},at.current):i.jsx("div",{ref:ge=>{I.current=ge},onScroll:ge=>{const qe=ge.currentTarget;if(H.current){H.current=!1,A.current=!0,N(!0);return}if(!F.current){A.current&&ie();return}const lt=qe.scrollHeight-qe.scrollTop-qe.clientHeight<=Zy;lt!==A.current&&(A.current=lt,N(lt)),f&&(qe.scrollTop<80&&!$e.current?($e.current=!0,f()):qe.scrollTop>240&&($e.current=!1))},className:"h-full select-text overflow-y-auto [overflow-anchor:none]",children:i.jsxs("div",{ref:$t,children:[i.jsx(mD,{context:Je}),be.map((ge,qe)=>Ie(ge,qe)),i.jsx(gD,{context:Je})]})}),!C&&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(Yu,{className:"h-3 w-3"}),w("Scroll to bottom")]})]})})})}function fD(e,t){return e.children.some(n=>n.key===t||n.kind==="tool-group"&&fD(n,t))}function Vq({chrome:e,onLoadMore:t}){const{t:n}=J();return e==="none"?i.jsx("div",{className:"h-6"}):i.jsx("div",{className:W(ji,"flex items-center justify-center gap-2 py-3"),children:e==="loading"?i.jsxs(i.Fragment,{children:[i.jsx(Zt,{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 mD({context:e}){return i.jsx(Vq,{chrome:e.pageChrome,onLoadMore:e.onLoadMore})}function gD({context:e}){const{t}=J(),{busy:n,loading:s,since:o,error:r,onRetryResume:a}=e;return i.jsxs("div",{className:W(ji,"pb-6 [overflow-wrap:anywhere]"),children:[n&&i.jsxs("div",{className:"flex min-h-[26px] items-center gap-2 text-[13px]",children:[i.jsx(Uq,{}),i.jsx("span",{className:"animate-pulse text-foreground motion-reduce:animate-none",children:t(s?"Loading…":"Working…")}),o!==void 0&&i.jsx(qq,{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(hD,{}),a&&i.jsx(fe,{size:"sm",variant:"outline",onClick:a,children:t("Retry resume")})]})]})}const Wq={List:$q,Header:mD,Footer:gD};function Uq(){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 Kq=e=>{const t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},qq=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:Kq(Date.now()-t)})});class Yq 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 ea={type:"spring",stiffness:400,damping:30},Iu={type:"tween",duration:.22,ease:[.2,0,0,1]},zp={initial:{height:0,opacity:0},animate:{height:"auto",opacity:1,transition:Iu},exit:{height:0,opacity:0,transition:Iu}};function Xq(e){return e.resizing?!0:e.previousConversationId!==void 0&&e.conversationId!==void 0&&e.previousConversationId!==e.conversationId}function xD(e){return e.skip?{duration:0}:e.cover||e.targetW===0?Iu:ea}const vD=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))}}},Zq={ts:Pa,tsx:Pa,js:Pa,jsx:Pa,mjs:Pa,json:Cg,html:TV,css:d0,scss:d0,md:wo,sh:kf,bash:kf,yml:hi,yaml:hi,toml:hi},Jq={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 Dd(e,t,n=!1){if(t)return n?ni:Cd;const s=e.split(".").pop()?.toLowerCase()??"";return Zq[s]??YV}function Id(e,t){if(t)return"text-amber-500";const n=e.split(".").pop()?.toLowerCase()??"";return Jq[n]??"text-muted-foreground"}const Qq={artifacts:[],media:[]},Gp=new Map,Fp=new Map,eY=new Set(["image","markdown","html","text"]),tY=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`;function nY(e){const t=JSON.stringify(e),[n,s]=m.useState(()=>Gp.get(t)??Qq);return m.useEffect(()=>{if(Gp.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)&&Gp.set(t,a),s(a)}).catch(()=>{}),()=>{o=!1}},[t]),n}function sY(e){const{t}=J();return(n,s)=>{window.electronAPI.bots.artifacts.open({...e,rel:n.rel,action:s}).then(o=>{o.ok||Fe({type:"error",title:o.error==="not-openable"?t("This file type is only shown in Finder"):t("Could not open the file")})})}}function Eu({target:e}){const{artifacts:t,media:n}=nY(e);return i.jsxs(i.Fragment,{children:[n.length>0&&i.jsx(oY,{target:e,media:n}),t.length>0&&i.jsx(lY,{target:e,artifacts:t})]})}function iY(){const{t:e}=J();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 bD(e,t,n){const s=JSON.stringify(e),o=t&&n==="thumb"?Fp.get(t):void 0,[r,a]=m.useState(o?{ok:!0,kind:"image",dataUrl:o}:null);return m.useEffect(()=>{const l=t&&n==="thumb"?Fp.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"&&Fp.set(t,c.dataUrl),d&&a(c)}).catch(()=>d&&a({ok:!1,error:"unavailable"})),()=>{d=!1}},[s,t,n]),r}function oY({target:e,media:t}){const{t:n}=J(),s=iY(),[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(rY,{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(NN,{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(aY,{target:e,item:o,label:o?s(o):"",onClose:()=>r(null)})]})}function rY({target:e,item:t,label:n,onOpen:s}){const o=bD(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(NN,{className:"m-auto h-4 w-4 text-muted-foreground"}):i.jsx(Zt,{className:"m-auto h-4 w-4 animate-spin text-muted-foreground"}),n&&i.jsx("span",{className:W("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 aY({target:e,item:t,label:n,onClose:s}){const{t:o}=J(),r=bD(e,t?.mediaId??null,"full"),a=t?.caption??t?.name??n;return i.jsx(vn,{open:t!==null,onOpenChange:l=>!l&&s(),children:i.jsxs(bn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[i.jsx(wn,{children:i.jsxs(yn,{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(wD,{name:a,content:r})]})})}function lY({target:e,artifacts:t}){const{t:n}=J(),s=sY(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=Dd(a.name,!1),d=eY.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:W("h-3.5 w-3.5 shrink-0",Id(a.name,!1))}),i.jsx("span",{className:"truncate",children:a.name}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:tY(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(rj,{className:"h-3.5 w-3.5"})})]},a.rel)}),i.jsx(dY,{target:e,artifact:o,onOpen:s,onClose:()=>r(null)})]})}function dY({target:e,artifact:t,onOpen:n,onClose:s}){const{t:o}=J(),[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(vn,{open:t!==null,onOpenChange:c=>!c&&s(),children:i.jsxs(bn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[i.jsx(wn,{children:i.jsxs(yn,{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(rj,{className:"h-4 w-4"})})]})]})}),i.jsx(wD,{name:t?.name??"",content:r})]})})}function wD({name:e,content:t}){const{t:n}=J();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(Zt,{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(_s,{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($c,{path:e,contents:t.text})})]})}const yD="enso:design-annotations:v1",SD="enso:annotate-prefs:v1",Jy=TR(e=>e.pageKey),Qy=[],eS=new WeakMap,Do={annotateHovered:!1,annotateEntered:!1,annotateUseCount:0,annotateSendImmediately:!0};function CD(e){try{return typeof localStorage>"u"?null:localStorage.getItem(e)}catch{return null}}function kD(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(e,t)}catch{}}function cY(){const e=CD(SD);if(!e)return Do;try{const t=JSON.parse(e);return{annotateHovered:typeof t.annotateHovered=="boolean"?t.annotateHovered:Do.annotateHovered,annotateEntered:typeof t.annotateEntered=="boolean"?t.annotateEntered:Do.annotateEntered,annotateUseCount:typeof t.annotateUseCount=="number"&&Number.isFinite(t.annotateUseCount)?t.annotateUseCount:Do.annotateUseCount,annotateSendImmediately:typeof t.annotateSendImmediately=="boolean"?t.annotateSendImmediately:Do.annotateSendImmediately}}catch{return Do}}function Oa(e){kD(SD,JSON.stringify(e))}const tS=jR(CD(yD)),uY=cY();function Qd(e,t){kD(yD,NR({queues:e,pages:t}))}const Wn=bg((e,t)=>({...uY,queues:tS.queues,pages:tS.pages,sessions:new Map,familiarity:()=>{const n=t();return _R(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};Oa(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};Oa(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};Oa(o),e({annotateSendImmediately:n})},annotationsFor:(n,s)=>{const o=t().queues.get(n);if(!o||o.items.length===0)return Qy;if(!s)return o.items;let r=eS.get(o.items);r||(r=new Map,eS.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?Qy:l;return r.set(s,d),d},pageKeyOf:n=>t().pages.get(n),setBrowserUrl:(n,s)=>{if(!s)return;const o=aj(s),r=t().pages;if(r.get(n)===o)return;const a=new Map(r);a.delete(n),a.set(n,o),Qd(t().queues,a),e({pages:a})},dispatchQueue:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=Jy(r,s);if(a===r)return;const l=new Map(o.queues);l.delete(n),a.items.length>0&&l.set(n,a),Qd(l,o.pages),e({queues:l})},addAnnotation:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=Jy(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),Qd(l,o.pages);const d=o.annotateUseCount+1;return Oa({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:()=>{Oa(Do),Qd(new Map,new Map),e({...Do,queues:new Map,pages:new Map,sessions:new Map})}})),ta=typeof navigator<"u"&&navigator.platform?navigator.platform.startsWith("Mac"):!0,Om=ta?"⌘⇧D":"Ctrl+Shift+D";function Hp({className:e}){return i.jsx("svg",{viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",className:W("h-3.5 w-3.5 shrink-0",e),children:i.jsx("path",{d:"M14.434 6.765c.793 0 1.076 1.051.388 1.448l-3.593 2.074v4.15c0 .793-1.052 1.075-1.449.387L5.8 7.93c-.299-.517.075-1.164.672-1.164zM13 .875c1.174 0 2.125.951 2.125 2.125v1c0 .345-.28.625-.625.625s-.625-.28-.625-.625V3c0-.483-.392-.875-.875-.875H3c-.483 0-.875.392-.875.875v10c0 .483.392.875.875.875h3c.345 0 .625.28.625.625s-.28.625-.625.625H3C1.826 15.125.875 14.174.875 13V3C.875 1.826 1.826.875 3 .875zm-5.708 7.14 2.687 4.651v-2.565c0-.331.176-.638.462-.803l2.223-1.283z"})})}async function hY(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=Br,o.strokeStyle=Br,o.lineWidth=Nf,o.lineCap="round",o.lineJoin="round";for(const l of e.markup)for(const d of _f(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 pY({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?RR(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 fY({drawing:e,pick:t,markupTool:n,editorOpen:s,onMarkupToolChange:o,onExit:r}){const a=PR({drawing:e,pick:t?{region:t.region}:null,markupToolHeld:n!==null,editorOpen:s}),d=m.useMemo(()=>AR(ta),[])[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($s,{className:"h-3.5 w-3.5"});case"circle":return i.jsx(Tx,{className:"h-3.5 w-3.5"});case"square":return i.jsx(ud,{className:"h-3.5 w-3.5"});case"arrow-right-up":return i.jsx(rV,{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 (${Om})`,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(ln,{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:MR.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:W("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 mY({tabId:e,conversationId:t,active:n,disabled:s,queueOpen:o,onQueueOpenChange:r,onToggleDesignMode:a,onOpenPinFromQueue:l,onSendQueue:d}){const{t:c}=J(),u=Wn(C=>C.familiarity()),h=Wn(C=>C.annotateHovered),p=Wn(C=>C.markHovered),f=Wn(C=>C.annotationsFor(t)),g=Wn(C=>C.annotationsFor(t,e)),x=Wn(C=>C.removeAnnotations),v=Wn(C=>C.clearAnnotations),[y,b]=m.useState(!1),w=n?f:g,_=w.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 (${Om}) — Point at anything and tell the agent what to fix`,onPointerEnter:()=>{p(),u==="never"&&b(!0)},onPointerLeave:()=>b(!1),onClick:()=>{b(!1),a(!0)},className:W("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(Hp,{}),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(Hp,{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(C=>C.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($n,{className:"h-3 w-3"})})]}):i.jsxs("button",{type:"button",onClick:()=>a(!1),"aria-label":"Annotate","aria-pressed":n,title:`Exit Design Mode (${Om})`,className:"flex h-6 items-center gap-1 rounded bg-[#3a96dd]/15 px-2 text-xs font-medium text-[#3a96dd]",children:[i.jsx(Hp,{}),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:w.map(C=>{const N=C.kind==="region"&&C.images[0]?`data:${C.images[0].mimeType};base64,${C.images[0].data}`:null,S=C.kind==="element"&&C.elements.length>1?C.elements.length-1:0,k=C.comment.trim()||(C.kind==="element"&&C.elements[0]?ER(C.elements[0]):C.kind==="region"?`Screenshot region ${Math.round(C.region.rect.width)} × ${Math.round(C.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(C)},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:C.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:k}),S>0&&i.jsxs("span",{className:"shrink-0 rounded bg-muted px-1 py-0.5 text-[10px] text-muted-foreground",children:["+",S]})]}),i.jsx("button",{type:"button","aria-label":"Delete annotation",onClick:()=>x(t,[C.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(Bs,{className:"h-3 w-3"})})]},C.id)})})]})]})}function gY({stage:e,pinned:t,onTogglePinned:n,onClose:s,onStageChange:o}){const[r,a]=m.useState(""),l=m.useMemo(()=>dj(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 XR.filter(p=>ZR(p,{rendersText:e.baseline.rendersText,values:d})&&p.name.includes(h))},[r,e.baseline.rendersText,d]),u=h=>{const p=e2(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(ia,{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:W("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(ln,{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"),b=`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:w=>{w.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:W("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:w=>u({kind:"edit",property:h.name,value:w.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?b:void 0,value:v,disabled:f,onChange:w=>u({kind:"edit",property:h.name,value:w.target.value}),onKeyDown:w=>{if(w.key!=="ArrowUp"&&w.key!=="ArrowDown")return;const _=JR(v,w.key==="ArrowUp"?1:-1,w.shiftKey,h);_!==null&&(w.preventDefault(),w.stopPropagation(),u({kind:"edit",property:h.name,value:_}))},className:W("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:b,children:[h.presets.map(w=>i.jsx("option",{value:w},w)),e.baseline.variables.lengths.map(w=>i.jsx("option",{value:`var(${w.name})`},w.name)),y&&e.baseline.variables.colors.map(w=>i.jsx("option",{value:`var(${w.name})`},w.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(ia,{className:"h-2.5 w-2.5"})})]},h.name)})})]})}function xY({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}=J(),x=Wn(re=>re.annotateSendImmediately),v=Wn(re=>re.setSendImmediately),y=Wn(re=>re.addAnnotation),b=Wn(re=>re.updateAnnotation),w=Wn(re=>re.removeAnnotations),_=Wn(re=>re.annotationsFor(t)),C=m.useMemo(()=>o?_.find(re=>re.id===o.id)??null:null,[_,o]),N=m.useMemo(()=>LR(C?.comment??""),[C?.comment]),[S,k]=m.useState(""),[A,I]=m.useState([]),[E,D]=m.useState(!1),[T,H]=m.useState(!1),[F,O]=m.useState(null),[B,Y]=m.useState({x:0,y:0}),[U,ee]=m.useState(!1),[L,Q]=m.useState(null),[V,ce]=m.useState("move"),[ve,_e]=m.useState(null),De=m.useRef(null),me=m.useRef(null),$=m.useRef(null),z=m.useRef(null),de=m.useId(),X=o?`pin:${o.id}`:s?"draft":"none";m.useEffect(()=>{k(N.prose),I(C?C.images.slice(1):[]),D(!1),O(null),Y({x:0,y:0}),l(!1),window.setTimeout(()=>$.current?.focus(),10)},[X]),m.useEffect(()=>{const re=OR(_.filter($e=>$e.browserId===e));window.electronAPI.browser.previewDesignCss(e,"queue",re)},[_,e]);const oe=m.useMemo(()=>C?C.kind==="element"?C.elements:[]:s?.description.elements??[],[C,s]),Z=oe.length===1?oe[0]:null,ae=m.useCallback(async()=>{if(!Z)return;if(E){D(!1);return}const re=await window.electronAPI.browser.readDesignCss(e,Z.uniqueId);if(!re){Fe({type:"warning",title:g("Could not read CSS for this element")});return}O(zR(re,N.css)),D(!0)},[Z,E,e,N.css,g]);m.useEffect(()=>{if(!s?.region)return;const re=$e=>{if(!(ta?$e.metaKey:$e.ctrlKey)||$e.altKey||$e.key.toLowerCase()!=="z")return;const Nt=document.activeElement===$.current&&S.length>0;if(qR({markCount:s.markup.length+s.redoMarkup.length,toolHeld:r!==null,noteOwnsUndo:Nt}))if($e.preventDefault(),$e.stopPropagation(),$e.shiftKey){const mt=s.redoMarkup.at(-1);if(!mt)return;d({...s,markup:[...s.markup,mt],redoMarkup:s.redoMarkup.slice(0,-1)})}else{const mt=s.markup.at(-1);if(!mt)return;d({...s,markup:s.markup.slice(0,-1),redoMarkup:[...s.redoMarkup,mt]})}};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[s,r,S.length,d]),m.useEffect(()=>{if(!L||!s)return;const re={left:0,top:0,width:n.width,height:n.height},$e=(mt,K)=>{const he=mt.key===" "?"Space":mt.key==="Shift"||mt.key==="Alt"||mt.key==="Escape"?mt.key:null;he&&(he==="Space"&&mt.preventDefault(),Q(Ie=>Ie?f0(Ie,{type:"key",key:he,down:K},re):null))},st=mt=>$e(mt,!0),Nt=mt=>$e(mt,!1);return window.addEventListener("keydown",st,!0),window.addEventListener("keyup",Nt,!0),()=>{window.removeEventListener("keydown",st,!0),window.removeEventListener("keyup",Nt,!0)}},[L,s,n.width,n.height]);const be=m.useMemo(()=>F?dj(F):null,[F]),ze=!!(be&&be.changes.size>0),Ye=S.trim().length>0,Ve=C!==null,at=Ve?S.trim()!==N.prose.trim()||!!be?.isDirty:Ye||ze||(s?.markup.length??0)>0,Ze=m.useMemo(()=>be?c0(S,be.changes):N.css.size>0?c0(S,N.css):S.trim(),[S,be,N.css]),Et=Ve?!0:Ze.length>0||s?.region!==null&&(s?.markup.length??0)>0,Gt=YR({sendImmediately:x,isOnStack:Ve}),Pt=ze&&!Ye?u0[Gt].css:u0[Gt].note,ne=m.useCallback(()=>{const re=oe;if(re.length===0)return;let $e=!1;re.forEach((st,Nt)=>{const mt=`ui-${Date.now()}-${Nt}`,K=jf(st),he=Nt===0&&s?.description.image?{data:s.description.image.data,mimeType:s.description.image.mimeType}:void 0;sv({kind:"ui-element",id:mt,label:K,path:st.path||st.tagName.toLowerCase(),text:(st.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||lj(st),imageId:`img-${mt}`},he)&&($e=!0)}),$e?(yo(),u()):Fe({type:"warning",title:g("No Composer for this selection")})},[oe,s?.description.image,u,g]),ie=m.useCallback(async()=>{if(!(U||!Et)){ee(!0);try{if(Ve&&C){const K=C.images.length>0?[C.images[0],...A]:[...A];b(t,C.id,Ze,K),window.electronAPI.browser.previewDesignCss(e,"draft",{}),h(),x&&p(new Set([C.id]));return}if(!s)return;const re=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ann-${Date.now()}`,$e=Wn.getState().pageKeyOf(e)??"http://localhost/",st=s.description.image,Nt=[];if(st){const K=s.region&&s.markup.length>0?await hY({base64:st.data,markup:s.markup,cropWidth:s.region.width}):st.data;Nt.push({id:`img-${re}`,data:K,mimeType:st.mimeType,name:st.name,width:st.width,height:st.height})}Nt.push(...A);let mt;if(s.region){const K=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"}};mt=y(t,{id:re,kind:"region",comment:Ze,browserId:e,pageKey:$e,images:Nt,region:{rect:s.region,anchor:K,markup:s.markup}})}else mt=y(t,{id:re,kind:"element",comment:Ze,browserId:e,pageKey:$e,images:Nt,elements:s.description.elements});window.electronAPI.browser.previewDesignCss(e,"draft",{}),u(),x&&mt&&p(new Set([mt.id]))}finally{ee(!1)}}},[U,Et,Ve,C,A,b,t,Ze,e,h,x,p,s,y,u]),He=m.useCallback(()=>{if(at&&!a){l(!0);return}l(!1),window.electronAPI.browser.previewDesignCss(e,"draft",{}),Ve?h():u()},[at,a,l,e,Ve,h,u]),St=re=>{for(const $e of re){if(!$e.type.startsWith("image/"))continue;const st=new FileReader;st.onload=()=>{const Nt=st.result,mt=Nt.slice(Nt.indexOf(",")+1);I(K=>[...K,{id:`att-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,data:mt,mimeType:$e.type,name:$e.name}])},st.readAsDataURL($e)}},it=L?L.rect:s?.region??null,je=Math.min(320,Math.max(240,n.width-16)),ht=E?360:148,$t=m.useMemo(()=>{if(o)return GR(o.badge,n,{width:je,height:ht});if(it)return h0({x:it.left,y:it.top,width:it.width,height:it.height},n,je,ht);if(s&&s.elements.length>0){const re=s.elements.map(he=>he.rect.x),$e=s.elements.map(he=>he.rect.y),st=s.elements.map(he=>he.rect.x+he.rect.width),Nt=s.elements.map(he=>he.rect.y+he.rect.height),mt=Math.min(...re),K=Math.min(...$e);return h0({x:mt,y:K,width:Math.max(...st)-mt,height:Math.max(...Nt)-K},n,je,ht)}return{x:16,y:16}},[o,it,s,n,je,ht]),Oe=T?Math.max(8,n.width-je-8):Math.max(8,Math.min($t.x+B.x,n.width-je-8)),yt=T?8:Math.max(8,Math.min($t.y+B.y,n.height-120));if(!s&&!o)return null;const Ht=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:re=>{re.target===re.currentTarget&&He()},children:[s&&it&&i.jsxs(i.Fragment,{children:[Ht&&i.jsx("img",{src:Ht,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%, ${it.left}px 100%, ${it.left}px ${it.top}px, ${it.left+it.width}px ${it.top}px, ${it.left+it.width}px ${it.top+it.height}px, ${it.left}px ${it.top+it.height}px, ${it.left}px 100%, 100% 100%, 100% 0%)`}}),i.jsxs("div",{role:"application","aria-label":"Selected screenshot region",style:{left:it.left,top:it.top,width:it.width,height:it.height,cursor:r!==null?"crosshair":UR(L?L.handle:V,L!==null)},onPointerMove:re=>{const $e=re.currentTarget.getBoundingClientRect(),st={x:re.clientX-$e.left,y:re.clientY-$e.top};if(r!==null){if(!ve||!De.current)return;const Nt={x:Math.max(0,Math.min(it.width,st.x)),y:Math.max(0,Math.min(it.height,st.y))};if(ve.kind==="pen")_e({kind:"pen",points:VR(ve.points,Nt)});else{const mt=re.shiftKey?WR({kind:ve.kind,from:De.current,to:Nt}):Nt;_e({kind:ve.kind,from:De.current,to:mt})}return}if(L){const Nt=re.currentTarget.parentElement?.getBoundingClientRect(),mt={x:re.clientX-(Nt?.left??0),y:re.clientY-(Nt?.top??0)};Q(K=>K?f0(K,{type:"move",point:mt,altKey:re.altKey,shiftKey:re.shiftKey},{left:0,top:0,width:n.width,height:n.height}):null);return}ce(p0(st,it))},onPointerDown:re=>{if(re.button!==0)return;re.preventDefault(),re.stopPropagation(),re.currentTarget.setPointerCapture(re.pointerId);const $e=re.currentTarget.getBoundingClientRect(),st={x:Math.max(0,Math.min(it.width,re.clientX-$e.left)),y:Math.max(0,Math.min(it.height,re.clientY-$e.top))};if(r!==null){De.current=st,f(!0),_e(r==="pen"?{kind:"pen",points:[st]}:{kind:r,from:st,to:st});return}const Nt=re.currentTarget.parentElement?.getBoundingClientRect(),mt={x:re.clientX-(Nt?.left??0),y:re.clientY-(Nt?.top??0)},K=p0(st,it);Q($R({handle:K,point:mt,rect:it,modifiers:{altKey:re.altKey,shiftKey:re.shiftKey}}))},onPointerUp:async()=>{if(ve){const re=FR(s.markup,ve);_e(null),De.current=null,f(!1),re.length!==s.markup.length&&d({...s,markup:re,redoMarkup:[]});return}if(L){const re=HR({rect:L.rect,viewport:n}),$e=BR({markup:s.markup,from:s.region??re,to:re,markupScale:1});Q(null);const st=await window.electronAPI.browser.describeSelection(e,{x:re.left,y:re.top,width:re.width,height:re.height});d({...s,region:re,markup:$e,description:st.image?st: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:it.width,height:it.height,className:"pointer-events-none block h-full w-full overflow-visible",children:[s.markup.map((re,$e)=>_f(re,"complete").map((st,Nt)=>i.jsx("path",{d:st.d,"data-design-markup-stroke":"",fill:st.paint==="fill"?Br:"none",stroke:st.paint==="stroke"?Br:"none",strokeWidth:st.paint==="stroke"?Nf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`${$e}-${Nt}`))),ve&&_f(ve,"active").map((re,$e)=>i.jsx("path",{d:re.d,"data-design-markup-stroke":"active",fill:re.paint==="fill"?Br:"none",stroke:re.paint==="stroke"?Br:"none",strokeWidth:re.paint==="stroke"?Nf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`active-${$e}`))]}),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:Oe,top:yt,width:je},onMouseDown:re=>re.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:re=>{re.button!==0||T||re.target instanceof Element&&re.target.closest("button, input")||(re.preventDefault(),re.currentTarget.setPointerCapture(re.pointerId),me.current={pointerId:re.pointerId,startX:re.clientX,startY:re.clientY,nudgeX:B.x,nudgeY:B.y})},onPointerMove:re=>{const $e=me.current;!$e||$e.pointerId!==re.pointerId||Y({x:$e.nudgeX+(re.clientX-$e.startX),y:$e.nudgeY+(re.clientY-$e.startY)})},onPointerUp:()=>{me.current=null},className:W("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:it||C?.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(it?.width??(C?.kind==="region"?C.region.rect.width:0))," ","×"," ",Math.round(it?.height??(C?.kind==="region"?C.region.rect.height:0))]})]}):oe.map((re,$e)=>{const st=Yh[(re.hueIndex??$e)%Yh.length]??Yh[0],Nt=Xh[(re.hueIndex??$e)%Xh.length]??Xh[0];return i.jsxs("span",{style:{backgroundColor:st.bg,borderColor:Nt.stroke,color:st.border},title:`${KR(re)} — ${re.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:st.border}}),i.jsx("span",{className:"truncate",children:jf(re)})]},re.uniqueId||`${re.tagName}-${$e}`)})}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 rounded-lg bg-muted/50 p-0.5",children:[!Ve&&!it&&oe.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(LV,{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(dd,{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(cj,{className:"h-3 w-3"})})]}),oe.length>0&&i.jsx("button",{type:"button",onClick:ne,title:`Add element to chat (${ta?"⌘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(Lo,{className:"h-3 w-3"})}),Z&&i.jsx("button",{type:"button",onClick:()=>{ae()},"aria-label":"Edit CSS properties","aria-pressed":E,title:"Edit CSS properties",className:W("flex h-5 w-5 items-center justify-center rounded-md transition-colors",E||ze?"bg-[#3a96dd]/15 text-[#3a96dd]":"text-muted-foreground hover:bg-background/80 hover:text-foreground"),children:i.jsx(V6,{className:"h-3 w-3"})}),Ve&&C&&i.jsx("button",{type:"button","aria-label":"Delete annotation",title:"Delete annotation",onClick:()=>{w(t,[C.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(Bs,{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(re=>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:${re.mimeType};base64,${re.data}`,alt:"",className:"h-full w-full object-cover"}),i.jsx("button",{type:"button","aria-label":"Remove attached image",onClick:()=>I($e=>$e.filter(st=>st.id!==re.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(ln,{className:"h-2.5 w-2.5"})})]},re.id))}),i.jsxs("div",{className:"px-3 py-1.5",children:[i.jsx("textarea",{ref:$,rows:2,value:S,onChange:re=>{k(re.target.value),a&&l(!1);const $e=re.currentTarget;$e.style.height="auto",$e.style.height=`${Math.min(144,Math.max(44,$e.scrollHeight))}px`},onPaste:re=>{const $e=Array.from(re.clipboardData.files);$e.length>0&&(re.preventDefault(),St($e))},onKeyDown:re=>{if(re.nativeEvent.isComposing)return;const $e=ta?re.metaKey:re.ctrlKey;if($e&&re.key.toLowerCase()==="l"){re.preventDefault(),re.stopPropagation(),ne();return}if(re.key==="Enter"&&!re.shiftKey){if(Et||$e){re.preventDefault(),re.stopPropagation(),ie();return}if(!Ve&&!it&&oe.length>0){re.preventDefault(),re.stopPropagation(),c("child");return}}if(!Et&&!Ve&&!it&&oe.length>0){if(re.key==="Enter"&&re.shiftKey||re.key==="\\"){re.preventDefault(),re.stopPropagation(),c("parent");return}if(re.key==="Tab"){re.preventDefault(),re.stopPropagation(),c(re.shiftKey?"previous":"next");return}}Ve&&C&&!Ye&&!ze&&(re.key==="Backspace"||re.key==="Delete")&&!re.altKey&&!re.ctrlKey&&!re.metaKey&&!re.repeat&&(re.preventDefault(),re.stopPropagation(),w(t,[C.id]),h())},placeholder:ze?"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"}),ze&&!E&&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(([re,$e])=>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:[re,":"]}),$e.to===null?i.jsx("span",{children:"removed"}):i.jsxs(i.Fragment,{children:[i.jsx("del",{className:"opacity-65",children:$e.from}),i.jsx("span",{className:"opacity-60",children:"→"}),i.jsx("ins",{className:"font-semibold no-underline",children:$e.to})]})]},re))})]}),E&&F&&Z&&i.jsx(gY,{stage:F,pinned:T,onTogglePinned:()=>H(re=>!re),onClose:()=>D(!1),onStageChange:(re,$e)=>{O(re),window.electronAPI.browser.previewDesignCss(e,"draft",{[Z.uniqueId]:$e})}}),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",{}),Ve?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:z,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:re=>{St(Array.from(re.target.files??[])),re.target.value=""}}),i.jsx("button",{type:"button",onClick:()=>z.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(vh,{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:re=>v(!re.target.checked),className:"sr-only"}),i.jsx("span",{"aria-hidden":"true",className:W("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:W("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:U||!Et,"aria-label":Pt,title:`${Pt} (Enter)`,onClick:()=>{ie()},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:[Gt==="add-to-stack"?i.jsx(us,{className:"h-3 w-3"}):Gt==="save-note"?i.jsx(Kn,{className:"h-3 w-3"}):i.jsx(cd,{className:"h-3 w-3"}),i.jsx("span",{children:Pt})]})]})]})]})}function vY({tabId:e,conversationId:t,url:n,designMode:s,onDesignModeState:o}){const{t:r}=J(),[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),[b,w]=m.useState(!1),_=Wn(H=>H.annotationsFor(t,e)),C=Wn(H=>H.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 S=m.useCallback(async H=>{H?Wn.getState().markEntered():(c(null),h(null),f(null),y(!1),l(!1));const F=await window.electronAPI.browser.setDesignMode(e,H);o(F)},[e,o]);m.useEffect(()=>{if(!s||!n)return;const H=aj(n),F=_.filter(O=>O.pageKey===H).map(DR);window.electronAPI.browser.setAnnotationPins(e,H,F)},[s,n,_,e]);const k=m.useCallback(H=>{if(f(H),H!==null&&d&&d.region===null&&d.elements.length>0){const F=d.elements.map(V=>V.rect.x),O=d.elements.map(V=>V.rect.y),B=d.elements.map(V=>V.rect.x+V.rect.width),Y=d.elements.map(V=>V.rect.y+V.rect.height),U=Math.max(0,Math.min(...F)-12),ee=Math.max(0,Math.min(...O)-12),L=Math.max(24,Math.max(...B)-U+12),Q=Math.max(24,Math.max(...Y)-ee+12);c({...d,region:{left:U,top:ee,width:L,height:Q}})}},[d]);m.useEffect(()=>window.electronAPI.browser.onDesignMode(H=>{if(H.tabId===e){if(H.type==="cancelled"){c(null),h(null),f(null),l(!1);return}if(H.type==="drawing"){l(H.drawing);return}if(H.type==="pins"){Wn.getState().setPinnedIds(e,H.ids);return}if(H.type==="pin-click"){c(null),y(!1),H.pin&&h({id:H.id,badge:H.pin});return}if(H.type==="select"){if(l(!1),h(null),y(!1),H.addToChat&&H.description.elements.length>0){H.description.elements.forEach((F,O)=>{const B=`ui-${Date.now()}-${O}`,Y=jf(F),U=O===0&&H.description.image?{data:H.description.image.data,mimeType:H.description.image.mimeType}:void 0;sv({kind:"ui-element",id:B,label:Y,path:F.path||F.tagName.toLowerCase(),text:(F.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||lj(F),imageId:`img-${B}`},U)}),yo(),window.electronAPI.browser.clearSelection(e);return}c({elements:H.elements,region:H.region?{left:H.region.x,top:H.region.y,width:H.region.width,height:H.region.height}:null,viewportWidth:H.viewportWidth,description:H.description,markup:[],redoMarkup:[]})}}}),[e]);const A=m.useCallback(()=>{c(null),f(null),y(!1),window.electronAPI.browser.clearSelection(e)},[e]),I=m.useCallback(()=>{h(null),y(!1),window.electronAPI.browser.openAnnotationPin(e,null,!1)},[e]),E=m.useCallback(async H=>{const F=await window.electronAPI.browser.moveSelection(e,H);F.elements.length!==0&&c(O=>O?{...O,elements:F.elements,description:F.description}:null)},[e]),D=m.useCallback(async H=>{if(H.browserId!==e){Fe({type:"info",title:r("Turn on design mode in this note's browser tab to open it")});return}s||await S(!0);const F=await window.electronAPI.browser.openAnnotationPin(e,H.id,!0);F&&(c(null),h({id:H.id,badge:F}))},[e,s,S,r]),T=m.useCallback(H=>{const F=Wn.getState(),O=F.annotationsFor(t),B=H?O.filter(L=>H.has(L.id)):[...O];if(B.length===0)return;const Y=IR(B,L=>L.pageKey),U=Y.ordered.map(L=>L.id);if(F.removeAnnotations(t,U),!rK({text:Y.text,images:Y.images,mentions:[]})){F.restoreAnnotations(t,Y.ordered),Fe({type:"warning",title:r("Note not sent"),description:r("The note stays in the queue.")});return}F.annotationsFor(t).length===0&&s&&S(!1)},[t,s,S,r]);return m.useEffect(()=>{const H=F=>{if((ta?F.metaKey:F.ctrlKey)&&F.shiftKey&&!F.altKey&&F.key.toLowerCase()==="d"){F.preventDefault(),F.stopPropagation(),S(!s);return}if(!s||F.key!=="Escape")return;const B=F.target instanceof Element?F.target:null,Y=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,U=B?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')!==null;if(b){F.preventDefault(),F.stopPropagation(),w(!1);return}switch(QR({queueOwnsEscape:b,targetOwnsEscape:Y,targetIsInput:U,markupStrokeActive:g,markupToolHeld:p!==null,warningShown:v,draftOpen:d!==null,editorOpen:u!==null})){case"pass-through":return;case"cancel-stroke":F.preventDefault(),F.stopPropagation(),x(!1);return;case"put-down-tool":F.preventDefault(),F.stopPropagation(),f(null);return;case"dismiss-warning":F.preventDefault(),F.stopPropagation(),y(!1);return;case"cancel-draft":F.preventDefault(),F.stopPropagation(),A();return;case"close-editor":F.preventDefault(),F.stopPropagation(),I();return;case"exit":F.preventDefault(),F.stopPropagation(),S(!1);return}};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[s,b,g,p,v,d,u,S,A,I]),{drawing:a,draftPick:d,openPin:u,markupTool:p,warningShown:v,queueOpen:b,allConversationAnnotations:C,setQueueOpen:w,setWarningShown:y,setDraftPick:c,setDesignMode:S,handleMarkupToolChange:k,moveSelection:E,cancelDraft:A,closeOpenPin:I,openPinFromQueue:D,sendQueue:T,setMarkupStrokeActive:x}}const bY=(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,nS=(e,t)=>t.some(n=>bY(e,n)),wY=new Set(["dialog-popup","dialog-viewport","dialog-backdrop","alert-dialog-popup","alert-dialog-viewport","alert-dialog-backdrop"]);function yY(e){if(e.getAttribute("data-enso-float")!==null)return!0;const t=e.getAttribute("data-slot");return t?wY.has(t)||t.endsWith("-popup")||t.endsWith("-positioner"):!1}function sS(e,t){const n=[];for(const s of Array.from(e.querySelectorAll("*"))){if(!yY(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 SY={tabId:null,url:"",title:"",favicon:null,loading:!1,canGoBack:!1,canGoForward:!1,locked:!1,devtoolsOpen:!1,designMode:!1,holder:null},Bp=(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,iS=80,CY=.42;function oS(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=kY(e,t.bottom);return s>0?{...n,radius:s}:n}function kY(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 jY(){const{t:e}=J();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(mo,{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 jD(e){return window.electronAPI.remote?i.jsx(jY,{}):i.jsx(_Y,{...e})}function _Y({conversationId:e,panelApi:t,active:n}){const{t:s}=J(),o=se(L=>t2(L.conversations,e)),r=xn(L=>L.uiByConversation[o]?.open??!1),a=se(L=>L.activeId===o),l=n??(r&&a),[d,c]=m.useState(SY),[u,h]=m.useState(""),[p,f]=m.useState(!1),[g,x]=m.useState(null),[v,y]=m.useState(CY),[b,w]=m.useState({width:800,height:600}),_=m.useRef(null),C=m.useRef(null),N=m.useRef(null),S=m.useRef(void 0),k=m.useRef(!1),A=m.useRef(void 0),I=m.useRef(!1),E=m.useRef(!1);E.current=d.locked;const D=m.useRef(!1);D.current=d.devtoolsOpen;const T=(d.url.startsWith("http")||d.url.startsWith("file:"))&&!d.loading,H=m.useRef(!1);H.current=T;const F=m.useRef(null),O=t.id,B=vY({tabId:O,conversationId:e,url:d.url,designMode:d.designMode,onDesignModeState:c});m.useEffect(()=>{const L=_.current;if(!L)return;const Q=()=>{const ce=L.getBoundingClientRect();ce.width>0&&ce.height>0&&w({width:Math.round(ce.width),height:Math.round(ce.height)})};Q();const V=new ResizeObserver(Q);return V.observe(L),()=>V.disconnect()},[]),m.useEffect(()=>window.electronAPI.browser.onState(L=>{L.tabId===O&&c(L.state)}),[O]),m.useEffect(()=>window.electronAPI.browser.onDesignMode(L=>{if(L.tabId!==O||L.type==="cancelled"||L.type==="select"||L.type==="drawing"||L.type==="pin-click"||L.type==="pins")return;let Q=!1;if(L.type==="annotated")Q=L.image?dK(L.image):!1;else{const V=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ui-${Date.now()}`;Q=sv({kind:"ui-element",id:V,label:L.payload.label||L.payload.tag||"element",path:L.payload.path||L.payload.tag||"element",text:L.payload.text||L.payload.label||L.payload.tag||"element",imageId:`img-${V}`},L.image)}Q?yo():Fe({type:"warning",title:s("No Composer for this selection")})}),[O,s]),m.useEffect(()=>{p||h(d.url)},[d.url,p]),m.useEffect(()=>{const L=d.title.trim()||s("Browser");t.setTitle(L),t.updateParameters({...t.getParameters(),favicon:d.favicon})},[t,d.title,d.favicon,s]),m.useEffect(()=>{let L=0,Q=!1;document.getElementById("root"),uj();const V=()=>{if(Q)return;const ce=l&&t.isActive&&t.isVisible&&document.visibilityState==="visible",ve=ce?oS(_.current):null,_e=ve!==null&&(E.current||nS(ve,sS(document)));(S.current===void 0||!Bp(S.current,ve)||_e!==k.current)&&(S.current=ve,k.current=_e,window.electronAPI.browser.setViewport(O,e,ve,_e).then(c));const De=H.current?ve:null;Bp(F.current,De)||(F.current=De,xn.getState().setBrowserHole(`${O}:guest`,De));const me=ce&&D.current?oS(C.current):null,$=me!==null&&nS(me,sS(document));(A.current===void 0||!Bp(A.current,me)||$!==I.current)&&(xn.getState().setBrowserHole(`${O}:devtools`,me),A.current=me,I.current=$,window.electronAPI.browser.setDevToolsViewport(O,e,me,$).then(c)),L=requestAnimationFrame(V)};return L=requestAnimationFrame(V),()=>{Q=!0,cancelAnimationFrame(L);const{setBrowserHole:ce}=xn.getState();ce(`${O}:guest`,null),ce(`${O}:devtools`,null),F.current=null,S.current!==null&&(S.current=null,window.electronAPI.browser.setViewport(O,e,null)),A.current!==null&&(A.current=null,window.electronAPI.browser.setDevToolsViewport(O,e,null))}},[e,O,t,l]);const Y=async()=>{f(!1);const L=u.trim();if(!L)return;const Q=await window.electronAPI.browser.navigate(O,e,L);x(Q.ok?null:Q.error??s("Navigation failed"))},U=L=>{const Q=_.current,V=C.current;if(!Q||!V)return;L.currentTarget.setPointerCapture(L.pointerId);const ce=L.clientY,ve=Q.getBoundingClientRect().height,_e=V.getBoundingClientRect().height,De=ve+_e,me=z=>{const de=Math.min(De-iS,Math.max(iS,_e-(z.clientY-ce)));y(de/De)},$=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",$)};window.addEventListener("pointermove",me),window.addEventListener("pointerup",$)},ee="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:ee,disabled:d.locked||!d.canGoBack,onClick:()=>{window.electronAPI.browser.goBack(O)},"aria-label":s("Back"),children:i.jsx(dd,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:ee,disabled:d.locked||!d.canGoForward,onClick:()=>{window.electronAPI.browser.goForward(O)},"aria-label":s("Forward"),children:i.jsx(cj,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:ee,disabled:d.locked||!d.tabId,onClick:()=>{window.electronAPI.browser.reload(O)},"aria-label":s("Reload"),children:i.jsx(Mk,{className:W("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:L=>{L.preventDefault(),Y()},children:[i.jsx(mo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("input",{value:u,onChange:L=>h(L.target.value),onFocus:L=>{f(!0),L.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(mY,{tabId:O,conversationId:e,active:d.designMode,disabled:!d.tabId||d.locked||d.devtoolsOpen,queueOpen:B.queueOpen,onQueueOpenChange:B.setQueueOpen,onToggleDesignMode:L=>{B.setDesignMode(L)},onOpenPinFromQueue:L=>{B.openPinFromQueue(L)},onSendQueue:B.sendQueue}),i.jsx("button",{type:"button",className:W(ee,d.devtoolsOpen&&"bg-muted text-foreground"),disabled:!d.tabId,onClick:()=>{window.electronAPI.browser.setDevTools(O,!d.devtoolsOpen).then(c)},"aria-label":s("Toggle Developer Tools"),"aria-pressed":d.devtoolsOpen,children:i.jsx(kN,{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(uw,{className:"h-3 w-3"}),s("Enso is in control")]})]}),d.designMode&&i.jsx(fY,{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:W("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(pY,{active:d.designMode}),d.designMode&&i.jsx(xY,{tabId:O,conversationId:e,stageSize:b,draftPick:B.draftPick,openPin:B.openPin,markupTool:B.markupTool,warningShown:B.warningShown,onWarningShownChange:B.setWarningShown,onDraftPickChange:B.setDraftPick,onMoveSelection:L=>{B.moveSelection(L)},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(mo,{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(uw,{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:U}),i.jsx("div",{ref:C,className:"min-h-0 bg-transparent",style:{flex:`${v} 1 0`}})]})]})]})}function NY({chatId:e,visible:t}){const{t:n}=J(),s=ue(p=>p.browserTabs[e]),o=ue(p=>p.browserTitles),r=ue(p=>p.browserHolders),{openBrowserTab:a,selectBrowserTab:l,closeBrowserTab:d,setBrowserTitle:c}=ue.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:W("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(mo,{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(ln,{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(us,{className:"h-3.5 w-3.5"})})]}),h&&i.jsx(jD,{conversationId:n2(e),panelApi:h,active:t},h.id)]})}const TY=[[0,59],[0,23],[1,31],[1,12],[0,7]],sr=6e4,DY=60*sr,IY=5e4;function $p(e,t,n){if(!/^\d+$/u.test(e))return;const s=Number(e);return s>=t&&s<=n?s:void 0}function EY(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:$p(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=$p(h,t,n),u=p===void 0?a===void 0?c:n:$p(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 Th(e){const t=e.trim().split(/\s+/u);if(t.length!==5)return;const n=t.map((d,c)=>EY(d,...TY[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 PY(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 AY(e,t){let n=Math.floor(t/sr)*sr+sr;for(let s=0;s<IY;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(!PY(e,o))r=new Date(o.getFullYear(),o.getMonth(),o.getDate()+1).getTime();else if(!e.hour.includes(o.getHours()))r=n-o.getMinutes()*sr+DY;else if(!e.minute.includes(o.getMinutes()))r=n+sr;else return n;n=Math.max(r,n+sr)}}const Vp=e=>String(e).padStart(2,"0"),MY=["日","一","二","三","四","五","六"],RY=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function rv(e,t){const n=typeof e=="string"?Th(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=Vp(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=`${Vp(n.hour[0])}:${Vp(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=>MY[p]).join("、")} ${u}`:`Every ${h.map(p=>RY[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 LY=/[A-Za-z0-9._%+-]/,rS=/[A-Za-z0-9_-]/,OY=/```[\s\S]*?(?:```|$)|`[^`\n]*`/g;function _D(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 zY(e,t){if(typeof e!="string")return{ids:[],all:!1};const n=e.normalize("NFC").replace(OY,a=>" ".repeat(a.length)),s=[...t.map(a=>({key:Xc(a.name),id:a.id})),...hj.map(a=>({key:Xc(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&&LY.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&&rS.test(d.at(-1)??"")&&rS.test(u))});l&&(l.id===null?r=!0:o.includes(l.id)||o.push(l.id))}return{ids:o,all:r}}function GY(e,t){const n=_D(t),{ids:s,all:o}=zY(e,n);return o?{ids:[...new Set(n.map(r=>r.id))],all:o}:{ids:s,all:o}}function FY(e,t){const n=Xc(typeof e=="string"?e.replace(/^@/,""):"");return _D(t).filter(s=>Xc(s.name).startsWith(n))}function zm(e,t){return/(?:^|\s)\$([^\s$]*)$/.exec(e.slice(0,t))?.[1]??null}function ND(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 HY(e,t,n){const s=n??t;if(s===null)return[];const o=s.toLowerCase();return ND(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 BY=500,$Y=72,jl=28;function TD({phase:e,heldMs:t,cancelZone:n}){return e!=="recording"&&e!=="starting"?"none":n?"cancel":e==="starting"||t<BY?"too-short":"finish"}function aS(e,t){return e-t>=$Y}function Dh(e,t){const n=[...e,t].slice(-jl);return n.length<jl?[...new Array(jl-n.length).fill(0),...n]:n}const VY=300,WY=12,UY=-50,KY=3;function DD(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 qY(){let e=Number.POSITIVE_INFINITY;return t=>{const n=t.length/Zc*1e3,s=DD(t);return e=Math.min(s,e+KY*n/1e3),s>Math.max(e+WY,UY)}}function YY(e){if(e===Zc)return r=>r;const t=e/Zc;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 XY(e){return Math.min(1,Math.max(0,(DD(e)+55)/45))}const ZY=2e3;function JY(e=ZY){const t=qY();let n=0,s=0;return o=>{const r=o.length/Zc*1e3;return t(o)?(n+=r,s=0):s+=r,n>=VY&&s>=e}}class ID extends Error{}let li=null;function Gm(){return(!li||li.state==="closed")&&(li=new AudioContext),li.state!=="running"&&li.resume().catch(()=>{}),li}async function QY(){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 lS(){const e=li;li=null,e?.close().catch(()=>{})}const Wp={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};async function eX(e){const t=navigator.mediaDevices;if(!e||e===s2)return t.getUserMedia({audio:Wp});try{return await t.getUserMedia({audio:{...Wp,deviceId:{exact:e}}})}catch(n){const s=n instanceof Error?n.name:"";if(s==="NotAllowedError"||s==="SecurityError")throw n;return t.getUserMedia({audio:Wp})}}const tX=5e3;async function nX(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 eX(t.deviceId),await Promise.race([r,new Promise((w,_)=>setTimeout(()=>_(new Error("audio context stayed suspended")),3e3))])}catch(w){for(const _ of l?.getTracks()??[])_.stop();throw a(),w}const d=l.getTracks();if(s.state==="closed"){for(const w of d)w.stop();throw new Error("audio context closed")}const c=s.createMediaStreamSource(l),u=s.createScriptProcessor(4096,1,1),h=YY(s.sampleRate);let p=0,f=()=>{};const g=new Promise(w=>{f=w}),x=setTimeout(f,tX),v=()=>{clearTimeout(x),f()};u.onaudioprocess=w=>{const _=w.inputBuffer.getChannelData(0);for(let N=0;N<_.length;N++)p=Math.max(p,Math.abs(_[N]));p>0&&v(),t.onLevel?.(XY(_));const C=h(new Float32Array(_));C.length>0&&e(C)},c.connect(u),u.connect(s.destination);let y=!1;const b=()=>{if(!y){y=!0,v(),u.onaudioprocess=null,u.disconnect(),c.disconnect();for(const w of d)w.stop();a()}};return{live:g,cancel:b,stop:async()=>{if(b(),p===0)throw new ID("silent recording")}}}const ED="Microphone access denied. Allow it in system settings.",sX={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 PD(e){const t=e?.name;return t==="NotFoundError"||t==="OverconstrainedError"?"No microphone found.":t==="NotAllowedError"||t==="SecurityError"?ED:"Voice input failed."}function AD({startSession:e,requestMicAccess:t,onText:n}){const{t:s}=J(),[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 C=setTimeout(()=>c(null),4e3);return()=>clearTimeout(C)},[d]);const b=m.useCallback(()=>{y.current++,g.current?.cancel(),x.current?.cancel(),g.current=null,x.current=null,h(""),f(!1),r("idle")},[]),w=m.useCallback(async()=>{const C=g.current,N=x.current;if(!(!C||!N)){g.current=null,r("transcribing");try{await C.stop();const S=await N.finish();S.ok?S.text?n(S.text):c(s("No speech detected.")):c(s(sX[S.error]))}catch(S){N.cancel(),c(s(S instanceof ID?ED:"Voice input failed."))}finally{x.current=null,h(""),f(!1),r("idle")}}},[n,s]);return v.current=w,m.useEffect(()=>{if(o!=="recording")return;const C=setInterval(()=>l(N=>N+1),1e3);return()=>clearInterval(C)},[o]),m.useEffect(()=>{o==="recording"&&a>=i2&&w()},[a,w,o]),{phase:o,elapsed:a,error:d,setError:c,partial:u,correcting:p,start:async({autoStop:C=!1,...N}={})=>{if(c(null),!navigator.mediaDevices?.getUserMedia){c(s("Voice input needs a secure (HTTPS) connection."));return}const S=++y.current;h(""),f(!1),l(0),r("starting");let k=null;try{if(t&&!await t())throw new DOMException("microphone denied","NotAllowedError");if(S!==y.current)return;const A=e((D,T)=>{x.current===A&&(h(D),f(T))});k=A,x.current=A;const I=C?JY():null,E=await nX(D=>{A.push(D),I?.(D)&&x.current===A&&v.current()},N);if(S!==y.current){E.cancel();return}if(g.current=E,await E.live,S!==y.current)return;r("recording")}catch(A){if(S!==y.current)return;k?.cancel(),x.current=null,r("idle"),c(s(PD(A)))}},finish:w,cancel:b}}const iX=6,dS=8,oX=448;function rX(e,t){const n=Math.min(oX,t.width*.8);return{left:Math.max(dS,Math.min(e.left,t.width-dS-n)),bottom:t.height-e.top+iX,maxWidth:n}}const cS=120,MD=12,aX=Array.from({length:MD},(e,t)=>`bar-${t}`),uS=Dh([],0),lX=300;function hS(e){const t=e.getBoundingClientRect();return rX(t,{width:window.innerWidth,height:window.innerHeight})}function RD({anchor:e,status:t,children:n}){const[s,o]=m.useState(()=>hS(e));return m.useLayoutEffect(()=>{let r=0;const a=()=>{const l=hS(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]),Ks.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 Fm="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}=J(),{phase:l,elapsed:d,error:c,setError:u,partial:h,correcting:p,start:f,finish:g,cancel:x}=AD({startSession:e,requestMicAccess:t,onText:r}),v=m.useRef(null),[y,b]=m.useState(uS),w=Se(k=>k.voiceInputDevice),_=(k=!1)=>(b(uS),f({autoStop:k,deviceId:w,onLevel:A=>b(I=>Dh(I,A))})),C=m.useRef({phase:l,start:_,finish:g,cancel:x});C.current={phase:l,start:_,finish:g,cancel:x},m.useEffect(()=>{if(!s||n)return;let k=null,A;const I=()=>{clearTimeout(A),A=void 0},E=()=>{A!==void 0&&(I(),s==="space"&&document.execCommand("insertText",!1," "))},D=()=>{if(I(),k===null)return;const F=C.current,O=TD({phase:F.phase,heldMs:performance.now()-k,cancelZone:!1});k=null,O==="finish"?F.finish():O!=="none"&&F.cancel(),O==="too-short"&&u(a("Speech was too short."))},T=F=>{if(F.isComposing||F.keyCode===229)return;if(Pl(F,{allowBare:!0})!==s){E();return}const O=o.current;if(!O||!(F.target instanceof Node)||!O.contains(F.target))return;const B=k===null&&A===void 0;B&&(F.repeat||C.current.phase!=="idle")||(F.preventDefault(),k!==null&&F.stopPropagation(),B&&(A=setTimeout(()=>{A=void 0,k=performance.now(),C.current.start()},lX)))},H=F=>{k===null&&!A||!o2(s,F)||(F.preventDefault(),E(),D())};return window.addEventListener("keydown",T,!0),window.addEventListener("keyup",H,!0),window.addEventListener("blur",D),()=>{window.removeEventListener("keydown",T,!0),window.removeEventListener("keyup",H,!0),window.removeEventListener("blur",D),I(),k!==null&&C.current.cancel()}},[n,s,o,u,a]),m.useEffect(()=>{if(l!=="recording")return;const k=A=>{A.key==="Escape"&&(A.preventDefault(),A.stopPropagation(),x())};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[x,l]);const N=h.length>cS?`…${h.slice(-cS)}`:h,S=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:aX.map((k,A)=>i.jsx("span",{className:"w-[2px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:3+y[jl-MD+A]*11}},k))}),i.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(d/60),":",String(d%60).padStart(2,"0")]}),i.jsx(ud,{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:Fm,children:i.jsx(ln,{className:"h-3.5 w-3.5"})})]}):i.jsx("button",{type:"button",disabled:n||l!=="idle",onClick:()=>{_(!0)},"aria-label":S??a("Voice input"),title:S??(s?`${a("Voice input")} · ${a("Hold {{key}} to talk",{key:mi(s)})}`:a("Voice input")),className:Fm,children:l==="idle"?i.jsx(pj,{className:"h-3.5 w-3.5"}):i.jsx(pr,{className:"h-3.5 w-3.5"})}),v.current&&(c||h)?i.jsx(RD,{anchor:v.current,status:!!c,children:c??(p?i.jsxs("span",{className:"flex items-start gap-1.5",children:[i.jsx(pr,{"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 OD=["agents","members","chats"];function dX(e){return[...OD.flatMap(t=>e[t].map(n=>({candidate:n,group:t}))),...e.files.map(t=>({candidate:t,group:"files"}))]}function zD(e,t){const n=OD.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"}))]:dX(e).map(s=>({type:"item",candidate:s.candidate,group:s.group}))}const cX=20;function uX(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,cX).map(s=>({kind:"chat",id:s.id,label:s.title.split(`
|
|
75
|
-
`)[0].trim()||"Untitled chat",sessionFile:s.sessionFile}))}function hX(e){return e.map(t=>({...t,kind:"agent-type",id:t.typeKey,label:t.displayName}))}function pX(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 fX(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 GD(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=fj(p);h||r(f?hX(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(pX(f))}).catch(()=>{h||l([])})},150);return()=>{h=!0,window.clearTimeout(p)}},[e,t,c]),m.useMemo(()=>t===null?{agents:[],members:[],files:[],chats:[]}:fX(t,o,a,n),[o,a,n,t])}const pS={bot:"Mention a member",all:"Mention a member",chat:"Reference a chat",file:"Files",skill:"Skills"},mX=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 gX({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}=J(),g=m.useRef(null),x=m.useRef(null),v=m.useRef(null),y=m.useRef(!1),[b,w]=m.useState(()=>m0(localStorage,e)),[_,C]=m.useState([]),[N,S]=m.useState(null),[k,A]=m.useState(0),[I,E]=m.useState(!1),D=Se(X=>X.keybindings),{"voice-hold":T,"send-message":H}=Li(D),{text:F}=b,O=X=>w(oe=>({...oe,...X}));m.useEffect(()=>{x.current?.focus()},[]),m.useEffect(()=>{r2(localStorage,e,b)},[e,b]),m.useEffect(()=>a2(X=>{X===e&&w(m0(localStorage,X))}),[e]),m.useLayoutEffect(()=>{const X=x.current;X&&(X.style.height="auto",X.style.height=`${Math.min(X.scrollHeight,220)}px`)},[F]);const B=m.useCallback(X=>window.electronAPI.bots.searchFiles({chatId:e,query:X}).then(oe=>oe.ok?oe.files:[]),[e]),Y=GD(void 0,N?.kind==="at"?N.query:null,[],{searchFiles:B,agents:!1}).files,U=(()=>{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 oe=n?FY(N.query,n).map(Z=>({kind:"bot",bot:Z})):[];return n&&hj.some(Z=>Z.startsWith(X))&&oe.push({kind:"all"}),b.chats.length<l2&&oe.push(...s.filter(Z=>!b.chats.includes(Z.id)&&Z.title.toLowerCase().includes(X)).slice(0,6).map(Z=>({kind:"chat",chat:Z}))),oe.push(...Y.slice(0,8).map(Z=>({kind:"file",path:Z.relativePath,name:Z.label}))),oe})(),ee=(X,oe)=>{const Z=o.length?zm(X,oe):null;if(Z!==null){S({kind:"skill",start:oe-Z.length-1,query:Z}),A(0);return}const ae=/(^|[^A-Za-z0-9._%+-])@([^\s@]*)$/u.exec(X.slice(0,oe));if(!ae)return S(null);S({kind:"at",start:oe-ae[2].length-1,query:ae[2]}),A(0)},L=X=>{if(!N)return;const oe=x.current,Z=oe?.selectionStart??F.length,ae=F.slice(0,N.start),be=F.slice(Z);let ze="";const Ye={};X.kind==="bot"||X.kind==="all"?ze=`@${X.kind==="all"?f("everyone"):X.bot.name} `:X.kind==="file"?(ze=`@${X.path} `,Ye.files=[...new Set([...b.files,X.path])]):X.kind==="chat"?Ye.chats=[...b.chats,X.chat.id]:Ye.skill=X.skill.id,O({...Ye,text:ae+ze+be}),S(null);const Ve=ae.length+ze.length;requestAnimationFrame(()=>{oe?.focus(),oe?.setSelectionRange(Ve,Ve)})},Q=X=>{const oe=x.current,Z=oe?.selectionStart??F.length,ae=oe?.selectionEnd??F.length;O({text:F.slice(0,Z)+X+F.slice(ae)}),requestAnimationFrame(()=>{oe?.focus(),oe?.setSelectionRange(Z+X.length,Z+X.length)})},V=X=>{for(const oe of X){if(!oe.type.startsWith("image/"))continue;const Z=new FileReader;Z.onload=()=>{const ae=Z.result;C(be=>[...be,{data:ae.slice(ae.indexOf(",")+1),mimeType:oe.type}])},Z.readAsDataURL(oe)}},ce=X=>{const oe=x.current,Z=oe?.selectionStart??F.length,ae=oe?.selectionEnd??F.length;window.electronAPI.bots.savePastedText({chatId:e,text:X}).catch(()=>({ok:!1,error:"unavailable"})).then(be=>{const ze=be.ok?`@${be.path} `:X;w(Ye=>({...Ye,text:Ye.text.slice(0,Z)+ze+Ye.text.slice(ae)})),requestAnimationFrame(()=>{oe?.focus(),oe?.setSelectionRange(Z+ze.length,Z+ze.length)})})},ve=new Map(s.map(X=>[X.id,X])),_e=b.skill?o.find(X=>X.id===b.skill||X.name===b.skill):void 0,De=_e&&n?n.filter(X=>GY(F,n).ids.includes(X.id)&&!_e.owners.includes(X.id)):[],me=!a&&!I&&(F.trim().length>0||_.length>0||b.chats.length>0||!!b.skill),$=async()=>{if(!me)return;const X=b,oe=_,Z=X.text.trim();w(d2),C([]),S(null),E(!0);try{await h({text:Z,images:oe,files:X.files.filter(be=>Z.includes(`@${be}`)),chats:X.chats,...X.skill?{skill:_e?.id??X.skill}:{}})||(w(be=>be.text||be.chats.length||be.skill?be:X),C(be=>be.length?be:oe))}finally{E(!1)}},z=X=>{const oe=X.nativeEvent.isComposing||y.current;if(N&&U.length>0&&!oe){if(X.key==="ArrowDown"||X.key==="ArrowUp"){X.preventDefault();const Z=X.key==="ArrowDown"?1:-1;A(ae=>(ae+Z+U.length)%U.length);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),L(U[Math.min(k,U.length-1)]);return}if(X.key==="Escape"){X.preventDefault(),S(null);return}}!oe&&gj(X,H)&&(X.preventDefault(),$())},de=X=>(n??[]).filter(oe=>X.includes(oe.id)).map(oe=>oe.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(),V([...X.dataTransfer.files])},children:[N&&U.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:U.map((X,oe)=>{const Z=pS[X.kind],ae=oe===0||pS[U[oe-1].kind]!==Z;return i.jsxs("div",{children:[ae&&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(),L(X)},onMouseEnter:()=>A(oe),className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",oe===k&&"bg-muted"),children:i.jsx(xX,{item:X,ownerNames:de,grouped:!!n})})]},mX(X))})}),(b.chats.length>0||b.skill)&&i.jsxs("div",{className:"flex flex-wrap gap-1.5 px-3 pt-3",children:[b.skill&&i.jsx(fS,{icon:i.jsx(Hs,{className:"h-3 w-3"}),label:_e?.name??b.skill,tone:"skill",onRemove:()=>O({skill:void 0})}),b.chats.map(X=>i.jsx(fS,{icon:i.jsx(ha,{className:"h-3 w-3"}),label:ve.get(X)?.title??f("Unavailable chat"),onRemove:()=>O({chats:b.chats.filter(oe=>oe!==X)})},X))]}),De.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:De.map(X=>X.name).join(", ")})}),_.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:_.map((X,oe)=>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:()=>C(Z=>Z.filter((ae,be)=>be!==oe)),className:"absolute top-0.5 right-0.5 hidden rounded-full bg-background/90 p-0.5 group-hover:block",children:i.jsx(ln,{className:"h-3 w-3"})})]},oe))}),i.jsx("textarea",{ref:x,value:F,rows:1,disabled:a,placeholder:t,onChange:X=>{O({text:X.target.value}),ee(X.target.value,X.target.selectionStart)},onSelect:X=>ee(X.currentTarget.value,X.currentTarget.selectionStart),onBlur:()=>S(null),onKeyDown:z,onCompositionStart:()=>{y.current=!0},onCompositionEnd:()=>{y.current=!1},onPaste:X=>{const oe=[...X.clipboardData.files].filter(Z=>Z.type.startsWith("image/"));if(oe.length===0){const Z=X.clipboardData.getData("text/plain");if(!mj(Z))return;X.preventDefault(),ce(Z);return}X.preventDefault(),V(oe)},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(vh,{className:"h-4 w-4"})}),i.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:X=>{V([...X.target.files??[]]),X.target.value=""}}),c&&i.jsx(LD,{startSession:c,requestMicAccess:u,disabled:a,holdBinding:T||void 0,holdScope:g,onText:Q}),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(ud,{className:"h-3 w-3 fill-current"})}):i.jsx("button",{type:"button",disabled:!me,onClick:()=>{$()},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(cd,{className:"h-4 w-4"})})]})]})}function xX({item:e,ownerNames:t,grouped:n}){const{t:s}=J();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(sn,{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(ha,{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(wo,{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(Hs,{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 fS({icon:e,label:t,tone:n,onRemove:s}){const{t:o}=J();return i.jsxs("span",{className:W("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(ln,{className:"h-3 w-3"})})]})}const vX={thinking:"Thinking",typing:"Writing reply",tool:"Calling tools",retrying:"Retrying"},mS={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"},bX={running:"Running",done:"Done",error:"Error",denied:"Denied",timeout:"Timed out · denied"},wX={running:"text-primary",done:"text-success",error:"text-destructive",denied:"text-warning",timeout:"text-warning"},yX=e=>e<1e4?`${(Math.max(0,e)/1e3).toFixed(1)}s`:go(e);function FD({conversationId:e,leading:t,trailing:n,className:s}){const{t:o}=J(),r=ue(p=>e?p.sessions[e]:void 0),a=ue(p=>e?p.queue.find(f=>f.conversationId===e):void 0),l=m.useMemo(()=>c2(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(vX[l.state]):o(a?.reason&&Object.hasOwn(mS,a.reason)?mS[a.reason]:"Queued"):null;return i.jsxs("div",{className:W("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:go(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:br(p.name,o)}),p.detail&&i.jsx("span",{className:"truncate font-mono",children:p.detail}),i.jsx("span",{className:W("shrink-0",wX[p.status]),children:o(p.status==="timeout"&&p.name==="ask_user"?"Timed out · no answer":bX[p.status])}),f!==void 0&&i.jsx("span",{className:"shrink-0 tabular-nums",children:yX(f)})]},p.id)})]})]})}const SX=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),CX=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),kX=[],jX={auto:"Automatic",delegator:"By delegator",human:"Manual"};function Ih({state:e,interrupted:t,autoRetry:n}){const{t:s}=J();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:W("rounded px-1.5 text-[11px]",o),children:r[e]??e})}function HD({check:e,className:t}){const{t:n}=J();return i.jsxs("div",{className:W("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:W("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 Ed(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 _X(e,t){window.electronAPI.bots.cancelDelegation(e).then(n=>{n.ok||Fe({type:"error",title:t("Cancel failed"),description:n.error}),ue.getState().refreshDelegations()})}function _l(e,t,n){window.electronAPI.bots.retryDelegation(e,n).then(s=>{s.ok?s.warning&&Fe({type:"warning",title:s.warning}):Fe({type:"error",title:t("Retry failed"),description:s.error}),ue.getState().refreshDelegations()})}function Eh(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 NX({record:e,delegations:t}){const{t:n}=J(),s=h2(e);if(!s)return null;const o=bj(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:p2(e)?n("Retrying automatically · attempt {{n}}",{n:o}):n("Retry #{{n}} · {{source}}",{n:o,source:n(jX[s])})})}function Ph({record:e,entry:t,retried:n,append:s,taskSeq:o,fill:r,bots:a,onOpenConversation:l}){const{t:d}=J(),c=ue(H=>H.delegations)??kX,u=e?.state??t?.state??"queued",h=Eh(!s&&Al(u)),p=a.get(e?.parentBotId??t?.from??""),f=a.get(e?.targetBotId??t?.to??""),g=f2(s?"completed":u),x=u2(e),v=!s&&x&&Al(u),y=!s&&u==="blocked"?e?.blocked:void 0,b=ue(H=>y&&e?.taskId?H.delegations.some(F=>F.taskId===e.taskId&&F.createdAt>e.createdAt):!1),w=ue(H=>H.openTask),_=!!t?.taskId&&!s,[C,N]=m.useState(!_),S=e?xj(e,c):!1,k=!s&&e?.chatId&&e.resultSeq!==void 0?{chatId:e.chatId,seq:e.resultSeq}:void 0,A=s||k?void 0:e?u==="completed"?e.result:u==="blocked"?void 0:Ed(e,d):t?.summary,I=d("{{from}} → {{to}} · Delegation",{from:p?.name??d("Deleted member"),to:f?.name??d("Deleted member")}),E=i.jsxs(i.Fragment,{children:[_&&i.jsx(un,{"aria-hidden":!0,className:W("size-3.5 shrink-0 transition-transform",C&&"rotate-90")}),i.jsx(sn,{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(sn,{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(vj,{info:x}):i.jsx(Ih,{state:u,interrupted:e?.failure==="interrupted",autoRetry:S}),e&&!s&&i.jsx(NX,{record:e,delegations:c}),e&&!s&&i.jsx("span",{children:go((e.finishedAt??h)-e.createdAt)}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:SX(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:W("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":C,"aria-label":d(C?"Collapse delegation result":"Expand delegation result"),className:W(D,"w-full rounded text-left hover:text-foreground"),onClick:()=>N(H=>!H),children:E}):i.jsx("div",{className:D,children:E}),!C&&T&&i.jsx("div",{className:"mt-1 truncate text-muted-foreground text-xs",children:T}),C&&T&&i.jsx("div",{className:"mt-1.5 line-clamp-3 text-sm [overflow-wrap:anywhere]",children:T}),C&&i.jsxs(i.Fragment,{children:[e?.check&&!s&&i.jsx(HD,{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:b?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")})]}),S&&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:CX(e.autoRetryAt),n:bj(e,c)+1})}),k&&i.jsx("button",{type:"button",onClick:()=>ue.getState().focusSeq(k.chatId,k.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(fe,{size:"xs",variant:"ghost",onClick:()=>l(e.childConversationId,I),children:d("View process")}),y&&!b&&e.chatId&&e.taskId&&i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>e.chatId&&e.taskId&&w(e.chatId,e.taskId),children:d("Reply")}),g.cancel&&i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>_X(e.id,d),children:d("Cancel")}),g.retry&&!n&&i.jsx(fe,{size:"xs",variant:"outline",title:S?d("Skip the wait and retry now. The scheduled automatic retry is canceled."):void 0,onClick:()=>_l(e.id,d),children:d(S?"Retry now":"Retry")}),g.resumeOrRestart&&!n&&i.jsxs(i.Fragment,{children:[i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>_l(e.id,d,"resume"),children:d("Continue")}),i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>_l(e.id,d,"restart"),children:d("Start over")})]})]})]})]})}function BD(e){const t=ue(c=>c.chats.find(u=>u.id===e)),n=ue(c=>c.sessions),s=ue(c=>c.queue),o=ue(c=>c.silences),r=ue(c=>c.delegations),a=ue(c=>c.browserHolders),l=ue(c=>c.browserTabs[t?.parentId??e]?.tabs),d=ue(c=>g2(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 TX(e,t){const n=BD(e);return m.useMemo(()=>m2(t,n),[t,n])}function DX(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 $D(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 za({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 VD({info:e,bot:t}){const{t:n}=J(),s=ue(d=>e.delegation?d.bots.find(c=>c.id===e.delegation?.parentBotId):void 0),o=e.delegation,r=DX(e,n),a=ue(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(ZT,{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(vj,{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(za,{label:n("Task"),children:i.jsx("span",{className:"line-clamp-2",children:o.task})}),i.jsx(za,{label:n("From"),children:s?.name??n("Deleted member")}),i.jsx(za,{label:n("Time"),children:go((o.finishedAt??Date.now())-o.createdAt)})]}),r&&i.jsx(za,{label:n("Waiting on"),children:r}),a&&i.jsx(za,{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:go(Date.now()-e.quietSince)})}),o&&e.state==="stuck"&&o.state==="failed"&&i.jsx("div",{className:"text-muted-foreground",children:Ed(o,n)}),o&&e.state==="done"&&o.result&&i.jsx("div",{className:"line-clamp-3 text-muted-foreground",children:o.result}),l&&i.jsx(fe,{size:"xs",className:"mt-1 self-start",onClick:()=>$D(l),children:n("Go handle it")})]})]})}function WD({chatId:e,botId:t,bot:n,size:s="sm"}){const{t:o}=J(),r=TX(e,t);return i.jsxs(tv,{children:[i.jsxs(nv,{render:i.jsx("span",{className:"relative inline-flex shrink-0"}),children:[i.jsx(sn,{bot:n,size:s,presence:r.state}),i.jsx("span",{className:"sr-only",children:Tf(r,o)})]}),i.jsx(VD,{info:r,bot:n})]})}function IX({chatId:e,memberIds:t,bots:n,onOpenLive:s}){const{t:o}=J(),r=BD(e),a=m.useMemo(()=>x2(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=v2(d),p=b2(d);return i.jsxs(tv,{children:[i.jsxs(nv,{render:i.jsx("button",{type:"button",onClick:()=>p?.kind==="pending"?$D(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(sn,{bot:c,size:"xs",presence:d.state}),h?i.jsx("span",{className:"max-w-56 truncate pr-1.5",children:[u,Tf(d,o),h].join(" · ")}):i.jsx("span",{className:"sr-only",children:`${u} · ${Tf(d,o)}`})]}),i.jsx(VD,{info:d,bot:c})]},l)})})}const UD=[137,80,78,71,13,10,26,10];function fa(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}let ec=null;function EX(e){if(!ec){ec=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;ec[n]=s>>>0}}let t=4294967295;for(const n of e)t=ec[(t^n)&255]^t>>>8;return(t^4294967295)>>>0}function KD(e){return UD.every((t,n)=>e[n]===t)?"png":e[0]===255&&e[1]===216&&e[2]===255?"jpeg":fa(e.subarray(0,4))==="RIFF"&&fa(e.subarray(8,12))==="WEBP"?"webp":null}function qD(e){if(KD(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=fa(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?fa(e.data.subarray(0,t)):null};function gS(e,t){const n=qD(e)?.find(s=>YD(s)===t);return n?fa(n.data.subarray(t.length+1)):null}function xS(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,EX(n.subarray(4,8+t.length))),n}function PX(e,t,n,s=[]){const o=qD(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(UD),...a.map(h=>h.raw),xS("tEXt",l),xS("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 AX(e){return btoa(fa(new TextEncoder().encode(e)))}function MX(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 RX(e){return{budgetCost:e?.dailyCostUsd!==void 0?String(e.dailyCostUsd):"",budgetTokens:e?.dailyTokens!==void 0?String(e.dailyTokens):""}}function XD(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 LX(e){return{delegationTimeout:e.delegationTimeoutMinutes!==void 0?String(e.delegationTimeoutMinutes):"",maxTurnTokens:e.maxTokensPerTurn!==void 0?String(e.maxTokensPerTurn):""}}function av(e){const t=e.delegationTimeout.trim()?Number(e.delegationTimeout):null,n=e.maxTurnTokens.trim()?Number(e.maxTurnTokens):null;return t!==null&&!w2(t)||n!==null&&!y2(n)?{ok:!1}:{ok:!0,delegationTimeoutMinutes:t,maxTokensPerTurn:n}}function vS(e){return[...e.normalize("NFC").trim().replace(/\s+/gu,"_").replace(/[^\p{L}\p{N}_-]/gu,"").replace(/_+/gu,"_").replace(/^_+|_+$/gu,"")].slice(0,C2).join("")}const Io=e=>typeof e=="string"?e.trim():"",Up=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function bS(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 OX(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 zX(e){return{...typeof e.title=="string"?{title:e.title.trim()}:{},...Io(e.scope)?{scope:Io(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}:{},...S2.includes(e.approvalMode)?{approvalMode:e.approvalMode}:{},...typeof e.memory=="boolean"?{memoryEnabled:e.memory}:{}}}function GX(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=Up(n.data)?n.data:n,o=Io(s.name);if(!o)return{ok:!1,error:"not-a-card"};const r=Up(s.extensions)?s.extensions.enso:void 0;if(Up(r)){const c=typeof s.description=="string"?s.description:"";return{ok:!0,draft:{name:vS(o),title:"",scope:bS(c),persona:c,...zX(r)}}}const a=c=>c.replace(/\{\{char\}\}/giu,o).replace(/\{\{user\}\}/giu,"the user"),l=a(Io(s.description)),d=[l,Io(s.personality)&&`Personality: ${a(Io(s.personality))}`,Io(s.scenario)&&`Scenario: ${a(Io(s.scenario))}`].filter(Boolean);return{ok:!0,draft:{name:vS(o),title:"",scope:bS(l),persona:d.join(`
|
|
81
|
-
|
|
82
|
-
`)}}}const Ir=256,wS=4;function ZD({hasImage:e,nested:t=!1,disabled:n=!1,onPick:s,onRemove:o}){const{t:r}=J(),a=m.useRef(null),[l,d]=m.useState(null);return i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[i.jsxs(fe,{size:"xs",variant:"outline",disabled:n,onClick:()=>a.current?.click(),children:[i.jsx(vh,{}),r("Upload avatar")]}),e&&i.jsxs(fe,{size:"xs",variant:"ghost",disabled:n,onClick:o,children:[i.jsx(ln,{}),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&&k2(u).then(d,()=>Fe({type:"error",title:r("This image cannot be used as an avatar.")}))}}),i.jsx(FX,{source:l,nested:t,onCancel:()=>d(null),onDone:c=>{d(null),s(c)}})]})}function FX({source:e,nested:t=!1,onCancel:n,onDone:s}){const{t:o}=J(),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?Ir/Math.min(l.w,l.h)*v:1,p=v=>{if(!l)return v;const y=h(v.zoom),b=(l.w*y-Ir)/2,w=(l.h*y-Ir)/2;return{zoom:v.zoom,x:Math.max(-b,Math.min(b,v.x)),y:Math.max(-w,Math.min(w,v.y))}},f=v=>u(y=>p({...y,zoom:Math.max(1,Math.min(wS,v))})),g=()=>{const v=r.current;if(!v||!l)return;const y=h(c.zoom),b=Ir/y;s(_2(v,l.w/2-b/2-c.x/y,l.h/2-b/2-c.y/y,b))},x=h(c.zoom);return i.jsx(vn,{open:e!==null,onOpenChange:v=>!v&&n(),children:i.jsxs(bn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:o("Crop avatar")}),i.jsx(As,{children:o("Drag to move, scroll to zoom.")})]}),i.jsxs(Mn,{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:Ir,height:Ir},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(b=>p({...b,x:b.x+v.clientX-y.x,y:b.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:()=>{Fe({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(j2,{min:1,max:wS,step:.01,value:c.zoom,"aria-label":o("Zoom"),onValueChange:v=>f(Array.isArray(v)?v[0]:v)})]}),i.jsxs(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(fe,{size:"sm",disabled:!l,onClick:g,children:o("Use this avatar")})]})]})})}const HX=["tools","approvalMode","skillIds","mcpServerIds","canDelegateTo","acceptFrom"],BX=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every(n=>t.includes(n)):e===t;function yS(e,t){return HX.flatMap(n=>{const s=t[n];return!s||BX(e[n],s.value)?[]:[{field:n,from:e[n],to:s.value,reason:s.reason}]})}function $X(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 JD={tools:"all",approvalMode:"auto-edits",skillIds:[],mcpServerIds:[],canDelegateTo:"any",acceptFrom:"any",memoryEnabled:!0,budgetCost:"",budgetTokens:"",delegationTimeout:"",maxTurnTokens:""};function QD({value:e,onChange:t,profile:n,botId:s,zIndex:o}){const{t:r}=J(),l=ue(d=>d.bots).filter(d=>d.id!==s&&!d.archivedAt);return i.jsxs("div",{className:"space-y-4",children:[i.jsx(VX,{value:e,onApply:t,profile:n,botId:s}),i.jsxs("div",{children:[i.jsx(Xt,{children:r("Tools")}),i.jsx(kg,{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(Xt,{children:r("Approval mode")}),i.jsx(wj,{value:e.approvalMode,onChange:d=>t({approvalMode:d}),zIndex:o})]}),i.jsx(eI,{value:e,onChange:t}),i.jsx(SS,{label:r("Can delegate to"),value:e.canDelegateTo,bots:l,onChange:d=>t({canDelegateTo:d})}),i.jsx(SS,{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(ci,{checked:e.memoryEnabled,onCheckedChange:d=>t({memoryEnabled:d})})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:r("Daily budget")}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsx(Jt,{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(Jt,{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(Xt,{children:r("Per-turn token limit")}),i.jsx(Jt,{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(Xt,{children:r("Delegation time limit (minutes)")}),i.jsx(Jt,{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 Ah(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 VX({value:e,onApply:t,profile:n,botId:s}){const{t:o,locale:r}=J(),[a,l]=m.useState(!1),[d,c]=m.useState(null),[u,h]=m.useState([]),p=d?yS(e,d):[],f=async()=>{if(![n.name,n.title,n.scope,n.persona].some(x=>x.trim())){Fe({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){Fe({type:"error",title:Ah(x,o),...x.detail?{description:x.detail}:{}});return}if(yS(e,x.suggestion).length===0){Fe({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=$X(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(fe,{size:"xs",variant:"outline",disabled:a,onClick:()=>{f()},children:[a?i.jsx(Zt,{className:"animate-spin"}):i.jsx(Hs,{}),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(hd,{className:"mt-0.5",checked:!u.includes(x.field),onCheckedChange:v=>h(y=>v?y.filter(b=>b!==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:WX(x.field,o)}),i.jsx(UX,{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(fe,{size:"xs",variant:"outline",onClick:()=>c(null),children:o("Cancel")}),i.jsx(fe,{size:"xs",disabled:p.every(x=>u.includes(x.field)),onClick:g,children:o("Apply")})]})]})]})}function WX(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 UX({change:e}){const{t}=J(),n=Se(p=>p.skills),s=Se(p=>p.mcpServers),o=ue(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(Ml[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 eI({value:e,onChange:t}){const{t:n}=J(),s=Se(a=>a.skills),o=Se(a=>a.mcpServers),r=(a,l)=>a.includes(l)?a.filter(d=>d!==l):[...a,l];return i.jsxs(i.Fragment,{children:[i.jsx(g0,{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:v0(e.skillIds,a,l)}),placeholder:n("Filter skills..."),renderDetail:a=>i.jsx(x0,{rows:[[n("Source"),a.source],[n("Path"),a.path],[n("Description"),a.description]]})}),i.jsx(g0,{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:v0(e.mcpServerIds,a,l)}),placeholder:n("Filter MCP servers..."),renderDetail:a=>i.jsx(x0,{rows:[[n("Source"),a.source],["Transport",a.transport],["URL",a.url]]})})]})}function SS({label:e,value:t,bots:n,onChange:s}){const{t:o}=J();return i.jsxs("div",{children:[i.jsx(Xt,{children:e}),i.jsx(kg,{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(hd,{checked:t.includes(r.id),onCheckedChange:a=>s(a?[...t,r.id]:t.filter(l=>l!==r.id))}),i.jsx(sn,{bot:r,size:"xs"}),r.name]},r.id))]})]})}function KX({bot:e}){const{t}=J(),n=ue(r=>r.usage?.bots[e.id]);if(m.useEffect(()=>{ue.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:Zh(a.tokens)}),i.jsx("div",{className:"truncate text-muted-foreground text-xs tabular-nums",children:Jh(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&&`${Zh(n.today.tokens)} / ${Zh(o.dailyTokens)} tokens`,o.dailyCostUsd!==void 0&&`${Jh(n.today.cost??0)} / ${Jh(o.dailyCostUsd)}`].filter(Boolean).join(" · "),n.exhausted&&` · ${t("Today's budget is used up")}`]})]})}function tI({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(Zt,{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(qX,{item:r,onDeleted:()=>s(a=>a?.filter(l=>l.id!==r.id)??null)},r.id))})}function qX({item:e,onDeleted:t}){const{t:n}=J(),[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}):Fe({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):Fe({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(Jt,{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(fe,{size:"xs",variant:"ghost",disabled:r,onClick:()=>o(null),children:n("Cancel")}),i.jsxs(fe,{size:"xs",disabled:r||!s.content.trim(),onClick:()=>{d()},children:[r&&i.jsx(Zt,{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(Zt,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx($s,{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():Fe({type:"error",title:c.error??n("Delete failed")})})},className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive",children:i.jsx(Bs,{className:"h-3.5 w-3.5"})})]})]})}function nI({target:e,emptyText:t}){const{t:n}=J(),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}Fe({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(fe,{size:"xs",variant:"ghost",disabled:c,onClick:()=>d(null),children:n("Cancel")}),i.jsx(fe,{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(fe,{size:"xs",variant:"outline",onClick:()=>d(r.content),children:n("Edit notes")})]}):i.jsx(Zt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}function sI({value:e,onApply:t}){const{t:n,locale:s}=J(),[o,r]=m.useState(!1),a=async()=>{if(!e.name.trim()||!e.title.trim()){Fe({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){Fe({type:"error",title:Ah(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}:{}}),Fe({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(fe,{size:"xs",variant:"ghost",className:"-my-1 h-6 text-muted-foreground",disabled:o,onClick:()=>{a()},children:[o?i.jsx(Zt,{className:"animate-spin"}):i.jsx(Hs,{}),n("Generate with AI")]})}function CS(e){const t=Th(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 YX(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 XX(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 ZX(e){return e.status==="review"&&!!(e.delegationId&&e.assigneeBotId)}function JX(e,t){return e.filter(n=>n.chatId===t).sort((n,s)=>n.createdAt-s.createdAt)}const tc=e=>e.finishedAt??e.createdAt;function QX(e,t){const n=e.filter(o=>o.chatId===t),s=o=>Al(o.state)||xj(o,e);return{active:n.filter(s).sort((o,r)=>o.createdAt-r.createdAt),completed:n.filter(o=>o.state==="completed").sort((o,r)=>tc(r)-tc(o)),failed:n.filter(o=>["failed","canceled","blocked"].includes(o.state)&&!s(o)).sort((o,r)=>tc(r)-tc(o))}}function eZ(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 tZ(e,t){const n=N2(e);if(!n)return;const s=t.find(r=>r.id===e.delegationId);if(n.reason==="failed"){const r=yj(e);return{reason:"failed",...s?{record:s}:{},since:r?.finishedAt??s?.finishedAt??e.updatedAt}}const o=(e.blockedStreak?.[e.assigneeBotId??""]??0)>=T2;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 nZ=["0 9 * * *","0 9 * * 1-5","0 9 * * 1","0 * * * *"];function sZ(e,t,n){const s=Th(e);if(s)return{source:s.source,description:rv(s,t),next:AY(s,n)}}function iZ(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 oZ(e){return e.title.trim()?e.prompt.trim()?Th(e.schedule)?e.chatId?null:"chat":"schedule":"prompt":"title"}function Pu(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 ma("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?ma(n,t):t("This routine is blocked. Fix the problem and enable it again.");default:return e}}function ma(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 iI(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 lv(){const{t:e}=J(),[t,n]=m.useState(!1),s=async(r,a,l)=>{n(!0);try{const d=await a();d.ok?l&&Fe({type:"success",title:l}):Fe({type:"error",title:r,description:Pu(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 oI({routine:e}){const{t,locale:n}=J(),s=ue(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:[rv(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 rZ({alert:e}){const{t}=J(),n=ue(p=>p.bots),s=ue(p=>p.chats),o=ue(p=>p.setView),{busy:r,review:a,resume:l,run:d}=lv(),{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(sn,{bot:u,size:"sm"}),i.jsx("span",{className:"text-foreground",children:u?.name??t("Deleted member")}),h?.kind==="group"&&i.jsxs("span",{children:["· ",Ss(h,n,t)]}),i.jsx(dv,{routine:c})]}),i.jsx(oI,{routine:c}),e.kind==="blocked"&&i.jsx("div",{className:"mt-1 text-destructive text-xs",children:ma(c.blockedReason,t)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[h&&i.jsx(fe,{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(fe,{size:"xs",variant:"outline",disabled:r,onClick:()=>d(c,!0),children:t("Dry run")}),i.jsx(fe,{size:"xs",variant:"outline",disabled:r,onClick:()=>a(c,!1),children:t("Reject")}),i.jsx(fe,{size:"xs",disabled:r,onClick:()=>a(c,!0),children:t("Approve")})]}):i.jsx(fe,{size:"xs",disabled:r,onClick:()=>l(c),children:t("Enable again")})]})]})}function dv({routine:e}){const{t}=J(),[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:W("rounded px-1.5 text-[11px]",s),children:n})}function aZ({text:e,target:t}){const{t:n}=J(),s=ue(l=>l.routines.find(d=>d.id===t.id&&d.botId===t.botId)),{busy:o,review:r,run:a}=lv();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(dv,{routine:s}):i.jsx("span",{className:"text-[11px]",children:n("Routine removed")})]}),s&&i.jsx(oI,{routine:s}),s?.status==="draft"&&i.jsxs("div",{className:"mt-2 flex justify-end gap-1.5",children:[i.jsx(fe,{size:"xs",variant:"ghost",disabled:o,onClick:()=>a(s,!0),children:n("Dry run")}),i.jsx(fe,{size:"xs",variant:"outline",disabled:o,onClick:()=>r(s,!1),children:n("Reject")}),i.jsx(fe,{size:"xs",disabled:o,onClick:()=>r(s,!0),children:n("Approve")})]})]})}const cv=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function rI(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 lZ(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 dZ(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 aI({botId:e,chatId:t}){const{t:n,locale:s}=J(),o=ue(w=>w.chats),r=ue(w=>w.bots),[a,l]=m.useState(null),[d,c]=m.useState(null),[u,h]=m.useState(null),[p,f]=m.useState(null),g=lv(),x=m.useCallback(async()=>{const w=await window.electronAPI.bots.routines.list(e?{botId:e}:{}).catch(()=>null),_=w?.ok?w.routines:[];l(t?JX(_,t):_)},[e,t]);m.useEffect(()=>(l(null),x(),window.electronAPI.bots.onEvent(w=>{w.kind==="routine"&&x()})),[x]);const v=async(w,_)=>{const{id:C,title:N,prompt:S,schedule:k}=w,A=await window.electronAPI.bots.routines.save({botId:w.botId,id:C,title:N,prompt:S,schedule:k,chatId:w.chatId,enabled:_});A.ok?A.routine.status==="blocked"&&Fe({type:"error",title:n("Routine blocked"),description:ma(A.routine.blockedReason,n)}):Fe({type:"error",title:n("Routine not saved"),description:Pu(A.error,n)}),x()},y=async w=>{h(null);const _=await window.electronAPI.bots.routines.remove({botId:w.botId,id:w.id});_.ok||Fe({type:"error",title:n("Routine not deleted"),description:Pu(_.error,n)}),x()};if(a===null)return i.jsx(Zt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const b=w=>r.find(_=>_.id===w)?.name??n("Deleted member");return i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs(fe,{size:"xs",variant:"outline",onClick:()=>c("new"),children:[i.jsx(us,{}),n("New routine")]}),a.length===0&&i.jsx("p",{className:"text-muted-foreground text-xs",children:n("No routines yet")}),a.map(w=>{const _=o.find(k=>k.id===w.chatId),C=w.status==="draft",N=D2(w)&&(w.status==="enabled"||w.status==="paused"),S=_?n("Posts to {{chat}}",{chat:Ss(_,r,n)}):n("Target chat missing");return i.jsxs("div",{"data-slot":"bot-card",className:W("rounded-lg border bg-card px-2.5 py-2 text-xs",w.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:w.title}),i.jsx(dv,{routine:w}),!C&&i.jsx(ci,{checked:w.status==="enabled",onCheckedChange:k=>{v(w,k)},title:w.status==="enabled"?n("Enabled"):n("Paused")})]}),i.jsx("div",{className:"mt-0.5 text-muted-foreground",children:[t?b(w.botId):"",rv(w.schedule,s),w.doneBy?n("Done by {{name}}",{name:b(w.doneBy)}):"",t?"":S].filter(Boolean).join(" · ")}),w.proposedBy&&C&&i.jsx("div",{className:"mt-0.5 text-warning",children:n("Proposed by {{name}}, waiting for your approval",{name:b(w.proposedBy)})}),w.status==="blocked"&&i.jsx("div",{className:"mt-0.5 text-destructive",children:ma(w.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:w.lastRunAt?n("Last run {{time}} · {{result}}",{time:cv(w.lastRunAt),result:iI(w.lastResult,n)}):n("Never run")}),w.missed?i.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-warning",children:n("Missed {{n}} times",{n:w.missed})}):null,!w.catchUp&&i.jsx("span",{children:n("No catch-up")})]}),i.jsxs("div",{className:"mt-1.5 flex flex-wrap justify-end gap-1",children:[C?i.jsxs(i.Fragment,{children:[i.jsx(fe,{size:"xs",variant:"ghost",disabled:g.busy,onClick:()=>{g.review(w,!1)},children:n("Reject")}),i.jsx(fe,{size:"xs",disabled:g.busy,onClick:()=>{g.review(w,!0)},children:n("Approve")})]}):i.jsxs(fe,{size:"xs",variant:"ghost",disabled:!N||g.busy,onClick:()=>{g.run(w,!1)},children:[i.jsx(jg,{}),n("Run now")]}),i.jsxs(fe,{size:"xs",variant:"ghost",disabled:g.busy,title:n("Run once without affecting the schedule"),onClick:()=>{g.run(w,!0)},children:[i.jsx(oj,{}),n("Dry run")]}),i.jsxs(fe,{size:"xs",variant:p===w.id?"secondary":"ghost",onClick:()=>f(p===w.id?null:w.id),children:[i.jsx($o,{}),n("History")]}),i.jsxs(fe,{size:"xs",variant:"ghost",onClick:()=>c(w),children:[i.jsx($s,{}),n("Edit")]}),i.jsxs(fe,{size:"xs",variant:"ghost",onClick:()=>h(w),children:[i.jsx(Bs,{}),n("Delete")]})]}),p===w.id&&i.jsx(cZ,{routine:w})]},w.id)}),d&&i.jsx(pZ,{botId:e,chatId:t,routine:d==="new"?void 0:d,onClose:w=>{c(null),w&&x()}}),i.jsx(ms,{open:u!==null,onOpenChange:w=>!w&&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 cZ({routine:e}){const{t}=J(),n=ue(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(Zt,{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:cv(l.startedAt)}),i.jsx("span",{children:lZ(l.trigger,t)}),i.jsxs("span",{className:W(l.result==="ok"&&"text-success",(l.result==="error"||l.result==="blocked"||l.result==="budget")&&"text-destructive"),children:[iI(l.result,t),dZ(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"?ma(l.error,t):l.error})]},l.runId))})}const uZ=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],kS=e=>String(e).padStart(2,"0");function hZ({value:e,onChange:t}){const{t:n,locale:s}=J(),o=CS(e),[r,a]=m.useState(!o),[l,d]=m.useState(o??{kind:"daily",days:[1],hour:9,minute:0}),c=sZ(e,s,Date.now()),u=f=>{d(f);const g=YX(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=CS(e);f?d(f):u(l),a(!1)};return i.jsxs("div",{children:[i.jsx(Xt,{hint:r?n("cron: minute hour day month weekday, local time"):void 0,action:i.jsx(fe,{size:"xs",variant:"ghost",onClick:p,children:n(r?"Simple":"Advanced (cron)")}),children:n("Schedule")}),r?i.jsx(Jt,{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(vs,{items:h,value:l.kind,onValueChange:f=>u({...l,kind:f,days:l.days.length?l.days:[1]}),children:[i.jsx(bs,{className:"w-32",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:h.map(f=>i.jsx(os,{value:f.value,children:f.label},f.value))})]}),l.kind==="weekly"&&uZ.map((f,g)=>{const x=l.days.includes(g);return i.jsx(fe,{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(Jt,{type:"time",className:"w-28",value:`${kS(l.hour)}:${kS(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:W("mt-1 text-xs",c?"text-muted-foreground":"text-destructive"),children:c?`${c.description} · ${c.next?n("Next run {{time}}",{time:cv(c.next)}):n("Never runs")}`:rI("schedule",n)})]})}function pZ({botId:e,chatId:t,routine:n,onClose:s}){const{t:o}=J(),r=ue(B=>B.chats),a=ue(B=>B.bots),l=m.useMemo(()=>(r.find(Y=>Y.id===t)?.members??[]).flatMap(Y=>{const U=a.find(ee=>ee.id===Y&&ee.archivedAt===void 0);return U?[U]:[]}),[r,a,t]),[d,c]=m.useState(n?.botId??e??l[0]?.id??""),u=m.useMemo(()=>iZ(r,d),[r,d]),[h,p]=m.useState(n?.title??""),[f,g]=m.useState(n?.prompt??""),[x,v]=m.useState(n?.schedule??nZ[0]),[y,b]=m.useState(n?.chatId??t??u[0]?.id??""),[w,_]=m.useState(n?.doneBy??""),[C,N]=m.useState(n?.catchUp??!0),[S,k]=m.useState(null),[A,I]=m.useState(!1),E=B=>{const Y=r.find(U=>U.id===B);return Y?`${Ss(Y,a,o)} · ${Y.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(Y=>Y.id===y)?.members??[]).flatMap(Y=>{const U=a.find(ee=>ee.id===Y&&ee.archivedAt===void 0);return U&&U.id!==d?[U]:[]}),[r,a,y,d]),H=[{value:"",label:o("The member itself")},...T.map(B=>({value:B.id,label:B.name}))],F=T.some(B=>B.id===w)?w:"",O=async()=>{if(!d)return k(o("Choose a member."));const B=oZ({title:h,prompt:f,schedule:x,chatId:y});if(B)return k(rI(B,o));I(!0),k(null);try{const Y=await window.electronAPI.bots.routines.save({botId:d,title:h,prompt:f,schedule:x,chatId:y,catchUp:C,doneBy:F||null,...n?{id:n.id,enabled:n.status!=="paused"}:{}});Y.ok?s(!0):k(Pu(Y.error,o))}finally{I(!1)}};return i.jsx(vn,{open:!0,onOpenChange:B=>!B&&s(!1),children:i.jsxs(bn,{className:"max-h-[85vh] max-w-lg",children:[i.jsx(wn,{children:i.jsx(yn,{children:o(n?"Edit routine":"New routine")})}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Xt,{children:o("Routine title")}),i.jsx(Jt,{value:h,onChange:B=>p(B.target.value)})]}),i.jsxs("div",{children:[i.jsx(Xt,{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(hZ,{value:x,onChange:v}),t?i.jsxs("div",{children:[i.jsx(Xt,{children:o("Member")}),i.jsxs(vs,{items:l.map(B=>({value:B.id,label:B.name})),value:d,disabled:!!n,onValueChange:B=>c(B),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:l.map(B=>i.jsx(os,{value:B.id,children:B.name},B.id))})]})]}):i.jsxs("div",{children:[i.jsx(Xt,{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(vs,{items:D.map(B=>({value:B,label:E(B)})),value:y,onValueChange:B=>b(B),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:D.map(B=>i.jsx(os,{value:B,children:E(B)},B))})]})]}),T.length>0&&i.jsxs("div",{children:[i.jsx(Xt,{hint:o("Another member of the target chat runs it, as a delegation"),children:o("Done by")}),i.jsxs(vs,{items:H,value:F,onValueChange:B=>_(B),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:H.map(B=>i.jsx(os,{value:B.value,children:B.label},B.value||"self"))})]})]}),i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx(Xt,{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(ci,{checked:C,onCheckedChange:N})]}),S&&i.jsx("p",{className:"text-destructive text-sm",children:S})]}),i.jsxs(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>s(!1),children:o("Cancel")}),i.jsxs(fe,{size:"sm",disabled:A,onClick:()=>{O()},children:[A&&i.jsx(Zt,{className:"animate-spin"}),o("Save")]})]})]})})}function Kp(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,...RX(e.budget),...LX(e)}}function fZ(e){const t=XD(e),n=av(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 mZ(e,t){const n=Jc(e),s=n?await fetch(n).then(r=>r.blob()).then(jj).catch(()=>null):null,o=PX(I2(s??await E2(e.name,e.avatar.color)),"chara",AX(JSON.stringify(OX(e,t))),["ccv3"]);if(!o)throw new Error("png");P2(new Blob([new Uint8Array(o)],{type:"image/png"}),`${e.name}.png`)}function gZ({botId:e,chat:t,onOpenHistory:n}){const{t:s}=J(),o=ue(E=>E.bots.find(D=>D.id===e)),r=ue(E=>E.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),b=m.useCallback(async()=>{const E=await window.electronAPI.bots.get(e);E.ok&&(ue.getState().upsertBot(E.bot),l(E.persona),c(Kp(E.bot,E.persona)),h(!1))},[e]);m.useEffect(()=>{l(null),c(null),b()},[b]);const w=m.useMemo(()=>o&&a!==null?Kp(o,a):null,[o,a]),_=u&&!!(d&&w&&JSON.stringify(d)!==JSON.stringify(w));if(m.useEffect(()=>{!u&&w&&c(w)},[o?.version]),!o||!d)return i.jsx("div",{className:"flex flex-1 items-center justify-center",children:i.jsx(Zt,{className:"h-4 w-4 animate-spin text-muted-foreground"})});const C=E=>{c(D=>D&&{...D,...E}),h(!0)},N=_g(d.name,r,s,o.id),S=async E=>{x(!0);try{await kj(o.id,E)||Fe({type:"error",title:s("Avatar update failed")})}finally{x(!1)}},k=()=>{mZ(o,a??"").then(()=>Fe({type:"success",title:s('Persona embedded in the PNG. Restore it in a new member via "Import character card".')})).catch(()=>Fe({type:"error",title:s("Export failed")}))},A=async()=>{const E=fZ(d);if(!E){Fe({type:"error",title:av(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:E});if(D.ok){ue.getState().upsertBot(D.bot),l(d.persona),c(Kp(D.bot,d.persona)),h(!1);return}Fe({type:"error",title:ol(D.reason,D.error,s),...D.reason==="conflict"?{actions:[{label:s("Refresh"),onClick:()=>{b()}}]}:{}})}finally{f(!1)}},I=async()=>{const E=v;if(y(null),E==="archive"){const T=await window.electronAPI.bots.archive(o.id,!0);T.ok?ue.getState().upsertBot(T.bot):Fe({type:"error",title:ol(T.reason,T.error,s)});return}const D=await window.electronAPI.bots.remove(o.id);if(D.ok){ue.getState().setView(null),await Promise.all([ue.getState().refreshCatalog(),ue.getState().refreshChats()]);return}if(D.reason==="boss"){const T=ue.getState().chats,H=(D.chatIds??[]).map(F=>T.find(O=>O.id===F)).filter(F=>!!F).map(F=>Ss(F,r,s));Fe({type:"warning",title:s("{{name}} owns group chats",{name:o.name}),description:s("Choose another owner in {{groups}} first.",{groups:H.join("、")})});return}Fe({type:"error",title:ol(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(sn,{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(Df,{children:[i.jsxs(If,{render:i.jsx(fe,{size:"xs",variant:"outline",onClick:k}),children:[i.jsx(od,{}),s("Export character card")]}),i.jsx(Ef,{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(ZD,{hasImage:!!o.avatar.image,disabled:g,onPick:E=>{S(E)},onRemove:()=>{S(null)}})]})]})]}),i.jsxs(Xu,{defaultValue:"profile",className:"mt-3 flex min-h-0 flex-1 flex-col",children:[i.jsxs(Zu,{variant:"underline",className:"shrink-0 px-2",children:[i.jsx(Is,{value:"profile",children:s("Profile")}),i.jsx(Is,{value:"abilities",children:s("Abilities")}),i.jsx(Is,{value:"memory",children:s("Memory")}),i.jsx(Is,{value:"routines",children:s("Routines")}),i.jsx(Is,{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(KX,{bot:o}),i.jsxs("div",{children:[i.jsx(Xt,{hint:s("Used for @ in groups; must be unique"),children:s("Name")}),i.jsx(Jt,{value:d.name,onChange:E=>C({name:E.target.value})}),N&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:N})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:s("Title")}),i.jsx(Jt,{value:d.title,onChange:E=>C({title:E.target.value})})]}),i.jsxs("div",{children:[i.jsx(Xt,{hint:s("Used for routing and the delegation directory"),children:s("Responsibilities")}),i.jsx(ei,{rows:2,value:d.scope,onChange:E=>C({scope:E.target.value})})]}),i.jsxs("div",{children:[i.jsx(Xt,{action:i.jsx(sI,{value:d,onApply:C}),children:s("Persona")}),i.jsx(ei,{rows:8,value:d.persona,onChange:E=>C({persona:E.target.value})})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:s("Avatar color")}),i.jsx(Sj,{value:d.color,onChange:E=>C({color:E})})]}),i.jsxs("div",{className:"flex gap-2 border-t pt-3",children:[i.jsxs(fe,{size:"xs",variant:"outline",onClick:()=>y("archive"),children:[i.jsx(Ai,{}),s("Archive member")]}),i.jsxs(fe,{size:"xs",variant:"destructive-outline",onClick:()=>y("delete"),children:[i.jsx(Bs,{}),s("Delete permanently")]})]})]}),i.jsxs(oo,{value:"abilities",className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Xt,{children:s("Model")}),i.jsx(Cj,{engine:d.engine,onChange:E=>C({engine:E})})]}),i.jsx(QD,{value:d,onChange:C,profile:d,botId:o.id})]}),i.jsxs(oo,{value:"memory",children:[i.jsxs("div",{className:"mb-4",children:[i.jsx(Xt,{hint:s("Injected into every new conversation"),children:s("Core notes")}),i.jsx(nI,{target:{botId:o.id},emptyText:s("No notes yet. Key preferences and facts are summarized here automatically after memories are organized.")})]}),i.jsx(tI,{spaceId:`bot:${o.id}`,emptyText:s("No memories yet")})]}),i.jsx(oo,{value:"routines",children:i.jsx(aI,{botId:o.id})}),i.jsx(oo,{value:"history",children:i.jsx(xZ,{chat:t,botId:o.id,onOpen:E=>n(E,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(fe,{size:"sm",variant:"outline",onClick:()=>{w&&c(w),h(!1)},children:s("Discard")}),i.jsxs(fe,{size:"sm",disabled:p||!!N,onClick:()=>{A()},children:[p&&i.jsx(Zt,{className:"animate-spin"}),s("Save")]})]}),i.jsx(ms,{open:v!==null,onOpenChange:E=>!E&&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:()=>{I()}})]})}function xZ({chat:e,botId:t,onOpen:n}){const{t:s}=J(),[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(Zt,{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 Au(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 lI(e,t,n,s){const o=await window.electronAPI.bots.tasks.reply({chatId:e,id:t,text:n}),r=ue.getState();return r.refreshTasks(e),r.refreshDelegations(),r.refreshInbox(),o.ok||Fe({type:"error",title:s("Reply not sent"),description:Au(o.error,s)}),o.ok}function uv({placeholder:e,onSend:t,className:n}){const{t:s}=J(),[o,r]=m.useState(""),[a,l]=m.useState(!1),d=Li(Se(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:W("mt-1.5 flex items-end gap-1",n),children:[i.jsx(ei,{value:o,rows:1,size:"sm",maxLength:Ng,placeholder:e,"aria-label":e,title:d?`${s("Send")} ${mi(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&&gj(u,d)&&(u.preventDefault(),c())}}),i.jsx(fe,{size:"icon-sm",variant:o.trim()?"default":"ghost","aria-label":s("Send reply"),disabled:!o.trim()||a,onClick:()=>{c()},children:a?i.jsx(Zt,{className:"animate-spin"}):i.jsx(Ax,{})})]})}function dI(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 cI=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),uI=(e,t)=>e.ok===void 0?t("Processing"):e.ok?t("Delivered"):t("Not delivered");function vZ({appends:e}){const{t}=J();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:cI(n.at)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",title:n.text,children:n.text}),i.jsx("span",{className:W("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:uI(n,t)})]},n.deliveryId))})}function bZ({runs:e,bots:t,onOpenConversation:n}){const{t:s}=J(),o=ue(f=>f.delegations),r=Eh(e.some(f=>Al(f.state))),[a,l]=m.useState(!1),[d,c]=m.useState(null),u=eZ(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"?Ed(g??f,s):void 0,y=g?.appends??[];return i.jsxs("li",{className:W(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(sn,{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"):dI(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:go(x.ms)})}):i.jsxs(i.Fragment,{children:[i.jsx(Ih,{state:f.state,interrupted:f.failure==="interrupted"}),i.jsx("span",{children:go(x.ms)})]}),f.appends&&i.jsx("button",{type:"button","aria-expanded":d===f.id,disabled:!y.length,title:y.map(b=>`${cI(b.at)} ${b.text} · ${uI(b,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(fe,{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(vZ,{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(fe,{size:"xs",variant:"ghost",onClick:()=>l(!0),children:s("Show all ({{n}})",{n:u.length})})]})}const Hm=5,wZ=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}=J(),[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(fe,{size:"xs",variant:"ghost",className:"mt-1",onClick:()=>a(!0),children:o("Show all ({{n}})",{n:t})})]})}function yZ({chat:e,onOpenConversation:t}){const{t:n}=J(),s=ue(k=>k.tasks[e.id]),o=ue(k=>k.bots),r=ue(k=>k.delegations),[a,l]=m.useState(null),[d,c]=m.useState(null),[u,h]=m.useState(null),p=ue(k=>k.taskFocus),[f,g]=m.useState(null),x=m.useRef(null),v=Eh(!!s?.some(k=>k.status==="blocked")),y=m.useMemo(()=>new Map(o.map(k=>[k.id,k])),[o]),b=e.members.flatMap(k=>{const A=y.get(k);return A&&A.archivedAt===void 0?[A]:[]});m.useEffect(()=>{ue.getState().refreshTasks(e.id)},[e.id]),m.useEffect(()=>{!p||p.chatId!==e.id||!s||(ue.getState().clearTaskFocus(p.nonce),s.some(k=>k.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 k=setTimeout(()=>g(null),2e3);return()=>clearTimeout(k)},[f]);const w=async(k,A)=>{const I=await k();I.ok||Fe({type:"error",title:A,description:Au(I.error??"",n)}),ue.getState().refreshTasks(e.id)},_=window.electronAPI.bots.tasks,C=k=>({chatId:e.id,id:k.id});if(!s)return i.jsx(Zt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const N=XX(s),S=k=>i.jsx(SZ,{task:k,bots:y,members:b,onOpenConversation:t,block:tZ(k,r),now:v,highlighted:f===k.id,onEdit:()=>l(k),onAssign:A=>{w(()=>_.assign({...C(k),botId:A}),n("Task not assigned"))},onComplete:()=>{w(()=>_.complete(C(k)),n("Task not updated"))},onAccept:()=>{w(()=>_.review({...C(k),accept:!0}),n("Task not updated"))},onReturn:A=>h({task:k,rework:A}),onCancel:()=>{w(()=>_.cancel(C(k)),n("Task not updated"))},onDelete:()=>c(k),onReply:A=>lI(e.id,k.id,A,n)},k.id);return i.jsxs("div",{ref:x,children:[i.jsxs(fe,{size:"xs",variant:"outline",className:"mb-3",onClick:()=>l("new"),children:[i.jsx(us,{}),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(S)}),N.doing.length>0&&i.jsx(io,{title:n("Doing"),count:N.doing.length,children:()=>N.doing.map(S)}),N.blocked.length>0&&i.jsx(io,{title:n("Stuck tasks"),count:N.blocked.length,children:()=>N.blocked.map(S)}),N.review.length>0&&i.jsx(io,{title:n("Awaiting review"),count:N.review.length,children:()=>N.review.map(S)}),N.done.length>0&&i.jsx(io,{title:n("Completed"),count:N.done.length,limit:Hm,children:k=>N.done.slice(0,k).map(S)}),N.canceled.length>0&&i.jsx(io,{title:n("Canceled"),count:N.canceled.length,limit:0,children:k=>N.canceled.slice(0,k).map(S)}),a&&i.jsx(jZ,{chatId:e.id,task:a==="new"?void 0:a,onClose:k=>{l(null),k&&ue.getState().refreshTasks(e.id)}}),u&&i.jsx(kZ,{task:u.task,assignee:y.get(u.task.assigneeBotId??"")?.name??n("Deleted member"),rework:u.rework,onClose:()=>h(null),onReturn:k=>_.review({...C(u.task),accept:!1,reason:k,...u.rework?{rework:!0}:{}}).then(A=>(A.ok&&(h(null),ue.getState().refreshTasks(e.id)),A.ok?null:Au(A.error,n)))}),i.jsx(ms,{open:d!==null,onOpenChange:k=>!k&&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 k=d;c(null),k&&w(()=>_.remove(C(k)),n("Task not deleted"))}})]})}function SZ({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}=J(),v=e.status==="todo"||e.status==="doing"||e.status==="blocked",y=e.status==="review",b=yj(e),w=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:W("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(xh,{className:"h-3.5 w-3.5"})}),i.jsxs($i,{align:"end",children:[i.jsxs(fn,{onClick:o,children:[i.jsx($s,{}),x("Edit")]}),v&&(!e.delegationId||e.status==="blocked"||b)&&n.length>0&&i.jsxs(Nj,{children:[i.jsxs(Tj,{children:[i.jsx($l,{}),e.assigneeBotId?x("Reassign to"):x("Assign to")]}),i.jsx(Dj,{children:n.map(C=>i.jsxs(fn,{disabled:C.id===e.assigneeBotId,onClick:()=>r(C.id),children:[i.jsx(sn,{bot:C,size:"xs"}),C.name]},C.id))})]}),v&&!b&&i.jsxs(fn,{onClick:a,children:[i.jsx(Kn,{}),x("Mark done")]}),(v||y)&&i.jsxs(fn,{onClick:c,children:[i.jsx(ln,{}),x("Cancel task")]}),i.jsx(ba,{}),i.jsxs(fn,{variant:"destructive",onClick:u,children:[i.jsx(Bs,{}),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:W("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(CZ,{block:p,now:f,assignee:w,bots:t,members:n,assigneeBotId:e.assigneeBotId,onRetry:()=>b&&_l(b.id,x),onAssign:r,onCancel:c,onReply:h}),!p&&(y||e.status==="doing"&&e.delegationId)&&i.jsx(uv,{placeholder:x(y?"Comment…":"Add to the current run…"),onSend:h}),e.check&&i.jsx(HD,{check:e.check,className:"mt-1"}),y&&i.jsxs("div",{className:"mt-1.5 flex gap-1.5",children:[i.jsxs(fe,{size:"xs",onClick:l,children:[i.jsx(Kn,{}),x("Accept result")]}),i.jsxs(fe,{size:"xs",variant:"outline",onClick:()=>d(!1),children:[i.jsx(pa,{}),x("Return")]}),ZX(e)&&i.jsxs(fe,{size:"xs",variant:"outline",onClick:()=>d(!0),children:[i.jsx(Tg,{}),x("Return for rework")]})]}),i.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-muted-foreground",children:[w||e.assigneeBotId?i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(sn,{bot:w,size:"xs"}),w?.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:wZ(e.updatedAt)})]}),e.runs&&e.runs.length>0&&i.jsx(bZ,{runs:e.runs,bots:t,onOpenConversation:s})]})}function CZ({block:e,now:t,assignee:n,assigneeBotId:s,bots:o,members:r,onRetry:a,onAssign:l,onCancel:d,onReply:c}){const{t:u}=J(),h=n?.name??u("Deleted member"),p=u("Stuck for {{time}}",{time:go(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(uv,{placeholder:u("Answer {{name}}; they continue after your reply…",{name:h}),onSend:c})]})}const f=e.record?.state==="failed"&&Ed(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(fe,{size:"xs",variant:"outline",onClick:a,children:[i.jsx(ia,{}),u("Retry")]}),r.length>0&&i.jsxs(Hi,{children:[i.jsxs(Bi,{render:i.jsx(fe,{size:"xs",variant:"outline"}),children:[i.jsx($l,{}),u("Reassign")]}),i.jsx($i,{align:"start",children:r.map(g=>i.jsxs(fn,{disabled:g.id===s,onClick:()=>l(g.id),children:[i.jsx(sn,{bot:g,size:"xs"}),g.name]},g.id))})]}),i.jsxs(fe,{size:"xs",variant:"outline",onClick:d,children:[i.jsx(ln,{}),u("Cancel task")]})]})]})}function kZ({task:e,assignee:t,rework:n,onClose:s,onReturn:o}){const{t:r}=J(),[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(vn,{open:!0,onOpenChange:f=>!f&&s(),children:i.jsxs(bn,{className:"max-w-lg",children:[i.jsx(wn,{children:i.jsx(yn,{children:n?r("Return task #{{n}} for rework",{n:e.seq}):r("Return task #{{n}}",{n:e.seq})})}),i.jsxs(Mn,{className:"space-y-2",children:[i.jsx(Xt,{children:r("Reason for returning")}),i.jsx(ei,{rows:4,autoFocus:!0,value:a,maxLength:Ng,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(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:s,children:r("Cancel")}),i.jsxs(fe,{size:"sm",disabled:u,onClick:()=>{p()},children:[u&&i.jsx(Zt,{className:"animate-spin"}),r(n?"Return for rework":"Return")]})]})]})})}function jZ({chatId:e,task:t,onClose:n}){const{t:s}=J(),[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(Au(x.error,s))}finally{f(!1)}};return i.jsx(vn,{open:!0,onOpenChange:x=>!x&&n(!1),children:i.jsxs(bn,{className:"max-w-lg",children:[i.jsx(wn,{children:i.jsx(yn,{children:t?s("Edit task #{{n}}",{n:t.seq}):s("New task")})}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Xt,{children:s("Task title")}),i.jsx(Jt,{value:o,maxLength:A2,onChange:x=>r(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:s("Details")}),i.jsx(ei,{rows:4,value:a,maxLength:Ng,onChange:x=>l(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:s("Acceptance check (optional)")}),i.jsx(Jt,{value:d,maxLength:M2,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(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsxs(fe,{size:"sm",disabled:p,onClick:()=>{g()},children:[p&&i.jsx(Zt,{className:"animate-spin"}),s("Save")]})]})]})})}function _Z({chat:e,onOpenConversation:t}){const{t:n}=J(),s=ue(d=>d.delegations),o=ue(d=>d.bots),r=m.useMemo(()=>new Map(o.map(d=>[d.id,d])),[o]),a=m.useMemo(()=>QX(s,e.id),[s,e.id]),l=d=>i.jsx(Ph,{record:d,retried:_j(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:Hm,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:Hm,children:d=>a.failed.slice(0,d).map(l)})]})}const NZ=(e,t)=>e.workspace.kind===t.kind&&(t.kind!=="project"||e.workspace.kind==="project"&&e.workspace.projectId===t.projectId);function hI({chat:e,className:t}){const{t:n}=J(),s=Se(f=>f.projects),o=ue(f=>f.bots),r=ue(f=>f.upsertChat),[a,l]=m.useState(!1),[d,c]=m.useState(null),u=Ij(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")},...Ju(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):Fe({type:"error",title:Ns(g.error,n)})};return i.jsxs(i.Fragment,{children:[i.jsxs(gi,{open:a,onOpenChange:l,children:[i.jsxs(xi,{className:W("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(Cd,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:u}),i.jsx($n,{className:"h-3 w-3 shrink-0 opacity-60"})]}),i.jsxs(vi,{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||Fe({type:"error",title:Ns(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=NZ(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(Kn,{className:"h-3.5 w-3.5 shrink-0 text-brand"})]},f.input.kind==="project"?f.input.projectId:f.input.kind)})})]})]}),i.jsx(ms,{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 Zo({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 qp({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 pI(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 z2(e,t,n,new Date().toISOString())}async function TZ(e,t){const n=await pI(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 DZ(e,t){const n=await pI(e,t),s=n&&R2(L2(n.team));return s?O2(o=>({...o,teams:G2(o.teams,s,crypto.randomUUID())})):!1}function IZ({chat:e,thread:t=e,onOpenConversation:n}){const{t:s}=J(),o=ue(T=>T.bots),r=ue(T=>T.runtime[t.id]),a=ue(T=>T.upsertChat),l=ue(T=>T.openDirect),d=Se(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),[b,w]=m.useState("info"),_=ue(T=>T.taskFocus);m.useEffect(()=>{_?.chatId===e.id&&w("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 C=async T=>{const H=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,...T});H.ok?a(H.chat):(Fe({type:"error",title:Ns(H.error,s)}),ue.getState().refreshChats())},N=e.members.map(T=>({id:T,bot:c.get(T)})),S=e.routing.muted??[],k=o.filter(T=>!T.archivedAt&&!e.members.includes(T.id)),A=T=>T?c.get(T)?.name??"?":"—",I=e.workspace.kind==="project"?d.find(T=>e.workspace.kind==="project"&&T.id===e.workspace.projectId):void 0,E=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(Xu,{value:b,onValueChange:T=>w(String(T)),className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs(Zu,{variant:"underline",className:"shrink-0 px-2 pt-2",children:[i.jsx(Is,{value:"info",children:s("Group info")}),i.jsx(Is,{value:"board",children:s("Task board")}),i.jsx(Is,{value:"delegations",children:s("Delegations")}),i.jsx(Is,{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(yZ,{chat:e,onOpenConversation:n})}),i.jsx(oo,{value:"delegations",children:i.jsx(_Z,{chat:t,onOpenConversation:n})}),i.jsx(oo,{value:"routines",children:i.jsx(aI,{chatId:e.id})}),i.jsxs(oo,{value:"info",children:[i.jsx(Jt,{className:"mt-2",value:u,placeholder:s("Group name"),onChange:T=>h(T.target.value),onBlur:()=>u.trim()!==e.title&&void C({title:u.trim()}),onKeyDown:T=>T.key==="Enter"&&T.currentTarget.blur()}),i.jsxs(Zo,{title:s("Members"),children:[N.map(({id:T,bot:H})=>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(WD,{chatId:t.id,botId:T,bot:H}),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:H?.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")}),S.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(cw,{className:"h-2.5 w-2.5"}),s("Muted")]})]}),i.jsx("div",{className:"truncate text-muted-foreground text-xs",children:H?.scope||H?.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(xh,{className:"h-3.5 w-3.5"})}),i.jsxs($i,{align:"end",children:[i.jsxs(fn,{disabled:e.bossBotId===T,onClick:()=>{C({bossBotId:T})},children:[i.jsx(Ej,{}),s("Make owner")]}),i.jsxs(fn,{disabled:e.bossBotId===T,onClick:()=>{C({routing:{muted:S.includes(T)?S.filter(F=>F!==T):[...S,T]}})},children:[i.jsx(cw,{}),S.includes(T)?s("Unmute"):s("Mute")]}),i.jsxs(fn,{disabled:e.bossBotId===T||e.members.length<=2,onClick:()=>{C({members:e.members.filter(F=>F!==T)})},children:[i.jsx(o4,{}),s("Remove from group")]})]})]})]},T)),i.jsxs(gi,{open:v,onOpenChange:y,children:[i.jsxs(xi,{disabled:k.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(us,{className:"h-3.5 w-3.5"}),s("Add member")]}),i.jsx(vi,{side:"bottom",align:"start",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:k.map(T=>i.jsxs("button",{type:"button",onClick:()=>{y(!1),C({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(sn,{bot:T,size:"sm"}),i.jsx("span",{className:"min-w-0 truncate",children:T.name})]},T.id))})]})]}),i.jsxs(Zo,{title:s("Reply queue"),children:[i.jsx(qp,{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(qp,{label:s("Waiting"),value:r?.queue.length?r.queue.map(T=>A(T)).join("、"):"—"}),i.jsx(qp,{label:s("Per-member limit"),value:s("{{n}} replies",{n:e.routing.maxTurnsPerBot})})]}),i.jsx(Zo,{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(hI,{chat:e,className:"w-full max-w-none"}),i.jsxs("p",{className:"mt-1.5 text-muted-foreground text-xs",children:[I?`${I.path} · `:"",s("Shared by all members")]})]})}),i.jsxs(Zo,{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(vs,{items:D,value:e.routing.mode,onValueChange:T=>{T!==e.routing.mode&&C({routing:{mode:T}})},children:[i.jsx(bs,{size:"sm",className:"w-40",children:i.jsx(ws,{})}),i.jsx(ys,{children:D.map(T=>i.jsx(os,{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(Jt,{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(Jt,{type:"number",min:1,max:10,value:g,onChange:T=>x(T.target.value)})]})]}),E&&i.jsx(fe,{size:"xs",className:"mt-2",onClick:()=>{C({routing:{maxHops:Math.round(Number(p))||e.routing.maxHops,maxTurnsPerBot:Math.round(Number(g))||e.routing.maxTurnsPerBot}})},children:s("Save")})]}),i.jsx(Zo,{title:s("Group notes"),children:i.jsx(nI,{target:{chatId:e.id},emptyText:s("No group notes yet. Group conventions and decisions are summarized here automatically after memories are organized.")})}),i.jsx(Zo,{title:s("Group memory"),children:i.jsx(tI,{spaceId:`chat:${e.id}`,emptyText:s("No group memories yet")})}),i.jsxs(Zo,{title:s("Team"),children:[i.jsxs(fe,{size:"xs",variant:"outline",onClick:()=>{TZ(e,o).then(T=>T||Fe({type:"error",title:s("Export failed")}))},children:[i.jsx(od,{}),s("Export team")]}),i.jsxs(fe,{size:"xs",variant:"outline",className:"ml-1.5",onClick:()=>{DZ(e,o).then(T=>Fe(T?{type:"success",title:s("Saved as team template")}:{type:"error",title:s("Could not save as team template")}))},children:[i.jsx(uV,{}),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 EZ(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 PZ(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 AZ(e,t){const n=String(t),s=`${n}-`;return e.find(o=>o.key===n||o.key.startsWith(s))?.key}function MZ(e){return e.earliest===void 0?"wait":e.target>=e.earliest?"scroll":e.loading?"wait":e.hasOlder?"load":"give-up"}function RZ(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 LZ(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 OZ({chatId:e,bots:t}){const{t:n}=J(),s=ue(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(fe,{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||Fe({type:"error",title:d.error})}catch{Fe({type:"error",title:n("Failed to send")})}finally{r(null)}}},children:n("Insert into {{name}}’s current task",{name:l})})]},a.deliveryId)})}const zZ=(e,t)=>t?e.find(n=>n.conversationId===t):void 0,GZ=(e,t)=>Math.max(0,Math.floor((t-e)/1e3));function fI({since:e}){const{t}=J(),[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:GZ(e,n)})})}function mI({conversationId:e,className:t}){const n=ue(s=>zZ(s.silences,e)?.since);return n===void 0?null:i.jsx("span",{className:t??"shrink-0 text-warning",children:i.jsx(fI,{since:n})})}const Vc=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),FZ={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 HZ({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}=J(),g=m.useRef(null),x=m.useRef(!0),v=m.useRef(h);v.current=h;const y=m.useCallback((ae,be)=>v.current(ae,be),[]),b=m.useRef(null),w=m.useRef(!1),_=n?.entries??[],C=m.useRef({chatId:e.id,loaded:_,delegations:o});C.current={chatId:e.id,loaded:_,delegations:o};const N=m.useCallback(ae=>{const{chatId:be,loaded:ze,delegations:Ye}=C.current,Ve=$2(ze,ae);if(Ve!==void 0)return ue.getState().focusSeq(be,Ve);const at=Ye.find(Ze=>Ze.id===ae);Fe({type:"info",title:at&&at.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]),S=EZ(_,e.epochSeq??0),k=n?.history,A=e.epochSeq??0,[I,E]=m.useState(!1);m.useEffect(()=>E(!1),[e.id,A]);const D=A>0&&!I&&!k,T=m.useMemo(()=>D?_.filter(ae=>ae.seq>=A):_,[_,D,A]),H=m.useMemo(()=>V2(T),[T]),F=()=>{D&&n?.hasOlder&&!n.loading&&!_.some(ae=>ae.seq<A)&&(_e(),l()),E(D)},O=m.useMemo(()=>{const ae=new Map;if(!k)for(const be of H)be.kind==="entry"&&be.entry.kind==="bot"&&!be.continued&&ae.set(be.entry.botId,be.entry.id);return new Set(ae.values())},[H,k]),B=m.useMemo(()=>new Map(o.map(ae=>[ae.id,{record:ae,retried:_j(ae,o)}])),[o]),Y=m.useMemo(()=>Aj(o,e.id),[o,e.id]),U=m.useMemo(()=>W2(T,U2(Y)),[T,Y]),ee=ue(ae=>ae.tasks[e.id]),L=Y.some(ae=>ae.appends?.length);m.useEffect(()=>{L&&!ee&&ue.getState().refreshTasks(e.id)},[L,ee,e.id]);const Q=({key:ae,record:be,append:ze})=>i.jsx(Ph,{record:be,append:ze,taskSeq:ze&&ee?.find(Ye=>Ye.id===be.taskId)?.seq,fill:!0,bots:t,onOpenConversation:h},ae),V=s?.current?t.get(s.current):void 0,ce=s?.current?e.sessions[s.current]?.conversationId:void 0,ve=ue(ae=>ce?ae.sessions[ce]?.messages.length:void 0);m.useLayoutEffect(()=>{const ae=g.current;ae&&(ae.scrollTop=ae.scrollHeight),x.current=!0},[e.id]);const _e=()=>{const ae=g.current;if(!ae)return;const be=ae.getBoundingClientRect().top;for(const ze of ae.querySelectorAll("[data-seq]")){const Ye=ze.getBoundingClientRect();if(!(Ye.bottom<=be)){b.current={seq:Number(ze.dataset.seq),top:Ye.top-be};return}}};m.useLayoutEffect(()=>{const ae=g.current;if(!ae)return;const be=b.current;!n?.loading&&!n?.loadingNewer&&(b.current=null);const Ye=w.current&&!k;w.current=!!k;const Ve=be&&ae.querySelector(`[data-seq="${be.seq}"]`);if(be&&Ve){ae.scrollTop+=Ve.getBoundingClientRect().top-ae.getBoundingClientRect().top-be.top;return}Ye&&(x.current=!0),x.current&&!k&&(ae.scrollTop=ae.scrollHeight)},[T,k,n?.loading,n?.loadingNewer,Y.length,V?.id,ve,s?.routing]);const De=()=>{const ae=g.current;if(!ae||!n)return;const be=ae.scrollHeight-ae.scrollTop-ae.clientHeight;x.current=be<40,b.current&&_e(),!(T.length===0||D&&(_[0]?.seq??0)<=A)&&(ae.scrollTop<80&&n.hasOlder&&!n.loading&&(_e(),l()),be<80&&k&&!n.loadingNewer&&(_e(),d()))},[me,$]=m.useState(null),z=m.useRef(null),[de,X]=m.useState(null);m.useLayoutEffect(()=>{if(!r||z.current===r.nonce)return;if(D&&r.seq<A){E(!0);return}const ae=T[0]?.seq,be=T.at(-1)?.seq,ze=de?.nonce===r.nonce?de:null,Ye=RZ({target:r.seq,range:n?ae===void 0||be===void 0?null:[ae,be]:void 0,loading:!!(ze&&!ze.done),jumped:!!ze?.done});if(Ye!=="wait"){if(Ye==="jump"){const Ve=r.nonce;x.current=!1,b.current=null,X({nonce:Ve,done:!1}),c(r.seq).finally(()=>X(at=>at?.nonce===Ve?{nonce:Ve,done:!0}:at));return}z.current=r.nonce,a?.(r.nonce),Ye==="scroll"&&(x.current=!1,b.current=null,$(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 ae=window.setTimeout(()=>$(null),2500);return()=>window.clearTimeout(ae)},[me]);const oe=()=>{x.current=!0,b.current=null,u()},Z=k&&n?n.lastSeq-k.sinceSeq:0;return i.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[i.jsx("div",{ref:g,onScroll:De,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:W(ji,"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(Zt,{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(Zt,{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.")}),U.head.map(Q),H.map(ae=>ae.kind==="day"?i.jsx("div",{className:"py-1 text-center text-[11px] text-muted-foreground",children:new Date(ae.at).toLocaleDateString()},ae.key):i.jsxs(m.Fragment,{children:[A>0&&!k&&ae.entry.seq===A&&i.jsxs("button",{type:"button",onClick:F,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(un,{className:"h-3.5 w-3.5"}):i.jsx($n,{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":ae.entry.seq,className:W("-mx-2 flex flex-col rounded-lg px-2 transition-colors duration-500",me===ae.entry.seq&&"bg-brand/10"),children:i.jsx(BZ,{chatId:e.id,entry:ae.entry,continued:ae.continued,latest:O.has(ae.entry.id),retryable:S.has(ae.entry.id)&&e.archivedAt===void 0,retryBusy:!!(s?.current||s?.routing),bots:t,records:B,onOpenConversation:y,onLocateDelegation:N})}),U.after.get(ae.entry.id)?.map(Q)]},ae.key)),n?.loadingNewer&&i.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:i.jsx(Zt,{className:"h-4 w-4 animate-spin"})}),!k&&!V&&s?.routing&&i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(jS,{}),f("Choosing who replies…")]}),!k&&i.jsx(OZ,{chatId:e.id,bots:t}),!k&&V&&i.jsxs("button",{type:"button",disabled:!ce,title:f("View live"),onClick:()=>ce&&p(ce,V.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(sn,{bot:V,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:V.name}),f("Replying")]}),i.jsx(FD,{conversationId:ce,leading:i.jsx(jS,{}),trailing:i.jsxs(i.Fragment,{children:[i.jsx(mI,{conversationId:ce}),ce&&i.jsx("span",{className:"shrink-0 underline-offset-2 hover:underline",children:f("View live")})]})})]})]})]})})}),k&&i.jsxs("button",{type:"button",onClick:oe,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(Yu,{className:"h-3 w-3"}),Z>0?f("Back to latest · {{n}} new",{n:Z}):f("Back to latest")]})]})}function jS(){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 BZ=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}=J(),[p,f]=m.useState(!1),g=async()=>{if(!p){f(!0);try{const x=await window.electronAPI.bots.retry(t,n.id);x.ok||Fe({type:"error",title:h("Retry failed"),description:Ns(x.error,h)})}catch{Fe({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")," · ",Vc(n.at),i.jsx("div",{className:"h-px flex-1 bg-border"})]}):n.routine?i.jsx(aZ,{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(fe,{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:W(Qa,"whitespace-pre-wrap break-words"),children:i.jsx(Wc,{text:n.text,bots:r})}),n.images?.length?i.jsx(Eu,{target:{chatId:t,entryId:n.id}}):null,(n.refs?.skill||n.refs?.chats?.length)&&i.jsx(UZ,{refs:n.refs}),!s&&i.jsx("span",{className:"mt-0.5 text-[11px] text-muted-foreground",children:Vc(n.at)})]});case"progress":return i.jsx(VZ,{chatId:t,entry:n,bots:r,failed:a.get(n.delegationId)?.record.state==="failed"});case"delegation":return i.jsx(Ph,{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:W("flex w-full gap-2.5",s&&"-mt-1.5"),children:[s?i.jsx("span",{className:"w-6 shrink-0"}):o?i.jsx(WD,{chatId:t,botId:n.botId,bot:x}):i.jsx(sn,{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} · `:"",Vc(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(FZ[n.routedBy])})]}),i.jsx("div",{className:"text-sm",children:i.jsx(_s,{text:n.text})}),i.jsx(Eu,{target:{chatId:t,entryId:n.id}}),i.jsx(WZ,{entry:n,onOpen:()=>l(n.conversationId,x?.name??"")})]})]})}}}),$Z={started:{icon:vV,className:"border-brand/50 text-brand"},blocked:{icon:gr,className:"border-warning/60 text-warning"},failed:{icon:F2,className:"border-destructive/60 text-destructive"},delivered:{icon:wg,className:"border-success/60 text-success"}};function VZ({chatId:e,entry:t,bots:n,failed:s}){const{t:o}=J(),r=ue(u=>u.openTask),a=n.get(t.botId),l=$Z[t.phase==="blocked"&&s?"failed":t.phase],d=l.icon,c=PZ(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(sn,{bot:a,size:"sm"}),i.jsxs("div",{className:W("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(Wc,{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(Wc,{text:c[2],bots:n})]}):i.jsx(Wc,{text:t.text,bots:n})]}),i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:Vc(t.at)})]})]})}function Wc({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 Pk(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:W(Qx("file"),"mx-0.5 leading-4"),title:s.path,children:[i.jsx(wo,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:Pj})]},o):i.jsx("span",{className:"font-medium underline underline-offset-2",children:s.part},o))})}function WZ({entry:e,onOpen:t}){const{t:n}=J(),[s,o]=m.useState(!1),[r,a]=m.useState(null);m.useEffect(()=>{if(!s||r)return;let d=!0;const c=h=>{const p=H2(h,e.text);if(d){if(!p)return a({error:n("No process recorded.")});a({steps:B2(h.slice(p.start,p.end)),exact:p.exact})}},u=ue.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?$n:un;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(Zt,{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:W("truncate",d.error&&"text-destructive"),children:[d.error?"✗":"·"," ",br(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 UZ({refs:e}){const{t}=J(),n=ue(a=>a.chats),s=ue(a=>a.bots),o=Se(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:W(r,"bg-info/15 text-info"),children:[i.jsx(Hs,{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:W(r,"bg-muted"),title:t("Referenced chat"),children:[i.jsx(ha,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:l?Ss(l,s,t):t("Unavailable chat")})]},a)})]})}function Mh({retry:e,onCancel:t}){const{t:n}=J(),[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(Ho,{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(ln,{className:"h-3.5 w-3.5"})})]})}function gI(e){const{t}=J(),n=ue(r=>r.delegations),s=e?K2(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:dI(r.trigger,t)})})),[o,t])}const KZ=2500;function xI({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=MZ({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"?AZ(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),KZ);return()=>window.clearTimeout(h)},[d]),{searchQuery:d?.query??"",activeHit:d?{key:d.key,nth:0}:null}}function vI({conversationId:e,speaker:t,emptyTitle:n,emptyDescription:s,className:o,focus:r,onFocusDone:a,turnFooter:l,controls:d,runDividers:c,dataSlot:u}){const h=ue(S=>S.sessions[e]),p=ue(S=>!!S.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(()=>()=>{ue.getState().loadOlderSession(e)},[e]),y=xI({focus:r,timelineRef:f,items:x,baseIndex:h?.historyBaseIndex??0,hasMessages:(h?.messages.length??0)>0,loading:p,loadOlder:v,onDone:a}),{name:b,color:w,image:_}=t,C=m.useMemo(()=>({sessionId:e,canRewind:!!d,canRetry:!!d,canFork:!1,speaker:{name:b,color:w,image:_},turnFooter:l,...d?{botControls:d}:{}}),[e,b,w,_,l,d]),N=(h?.historyBaseIndex??0)>0;return i.jsx(kh.Provider,{value:C,children:i.jsxs("div",{"data-slot":u,className:W("@container flex min-h-0 flex-1 flex-col",o),children:[i.jsx(Nh,{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?()=>{ue.getState().loadOlderSession(e)}:void 0,searchQuery:y.searchQuery,activeHit:y.activeHit},e),h?.retry&&i.jsx("div",{className:ji,children:i.jsx(Mh,{retry:h.retry})})]})})}function qZ({conversationId:e,title:t,speaker:n,emptyTitle:s,emptyDescription:o,footer:r,onClose:a}){const l=gI(e);return i.jsx(vn,{open:e!==null,onOpenChange:d=>!d&&a(),children:i.jsxs(bn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[i.jsx(wn,{children:i.jsx(yn,{children:t})}),e&&i.jsx(vI,{className:"border-t",conversationId:e,speaker:n,emptyTitle:s??t,emptyDescription:o,runDividers:l}),r&&i.jsx("div",{className:ji,children:r})]})})}function hv({conversationId:e,title:t,speaker:n,focus:s,turnFooter:o,read:r,botSession:a=!0,onClose:l}){const{t:d}=J(),[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(E=>r?r(E):window.electronAPI.bots.sessionHistory({conversationId:e??"",...E!==void 0?{beforeIndex:E}:{}}),[e,r]);m.useEffect(()=>{if(u(null),p(void 0),!e)return;let E=!0;return y().then(D=>{E&&(D.ok?u({messages:D.messages,baseIndex:D.baseIndex}):p(D.code==="not-found"?d("This conversation has no history yet."):D.error))}),()=>{E=!1}},[e,y,d]);const b=m.useCallback(async()=>{if(!(!e||!c||c.baseIndex<=0||x.current)){x.current=!0,g(!0);try{const E=await y(c.baseIndex);E.ok&&E.baseIndex+E.messages.length===c.baseIndex&&u({messages:[...E.messages,...c.messages],baseIndex:E.baseIndex})}finally{x.current=!1,g(!1)}}},[e,y,c]),w=gI(e),_=m.useMemo(()=>c?xr(c.messages,!1,[],void 0,{historyBaseIndex:c.baseIndex,runDividers:w}):[],[c,w]),C=m.useCallback(()=>{b()},[b]),N=xI({focus:s,timelineRef:v,items:_,baseIndex:c?.baseIndex??0,hasMessages:!!c?.messages.length,loading:f||c===null,loadOlder:C}),S=n?.name,k=n?.color,A=n?.image,I=m.useMemo(()=>({sessionId:e,canRewind:!1,canRetry:!1,botSession:a,speaker:S&&k?{name:S,color:k,image:A}:void 0,turnFooter:o}),[a,e,S,k,A,o]);return i.jsx(vn,{open:e!==null,onOpenChange:E=>!E&&l(),children:i.jsxs(bn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[i.jsx(wn,{children:i.jsx(yn,{children:t})}),i.jsx(kh.Provider,{value:I,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(Nh,{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?()=>{b()}:void 0,searchQuery:N.searchQuery,activeHit:N.activeHit})})})]})})}function zo(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 Bm="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 YZ({group:e,thread:t}){const{t:n}=J(),s=ue(k=>k.chats),o=ue(k=>k.sessions),r=ue(k=>k.timelines),a=ue(k=>k.queue),l=ue(k=>k.reads),d=ue(k=>k.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(k=>[k.id,k.name])),[d]),y=k=>k.threadTitle??(k.parentId?n("New topic"):n("Main topic")),b=F4(s,e).map(k=>{const A=Dg(k,{sessions:o,timeline:r[k.id],queue:a,names:v});return{id:k.id,title:y(k),preview:A.preview,activityAt:Math.max(A.activityAt,k.createdAt),unread:k.id!==t.id&&Za(A.marker,l[A.key]),running:A.running,canRename:!x,canDelete:!!k.parentId}}),w=VN(b,{currentId:t.id,rootId:e.id}),_=b.length-w.length,C=k=>ue.getState().openThread(e.id,k),N=async()=>{await ue.getState().createThread(e.id)||Fe({type:"error",title:n("Could not create topic")})},S=async k=>{const A=await window.electronAPI.bots.deleteThread(k);A.ok||Fe({type:"error",title:Ns(A.error,n)}),ue.getState().refreshChats()};return i.jsxs(i.Fragment,{children:[i.jsxs(Hi,{children:[i.jsxs(Bi,{className:W(Bm,"max-w-56 @max-[28rem]:max-w-32 @max-[21rem]:max-w-24"),children:[i.jsx("span",{className:"truncate",children:y(t)}),b.some(k=>k.unread)&&i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-info"}),i.jsx($n,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs($i,{align:"end",className:"w-72",children:[i.jsxs(Ig,{children:[i.jsx(Eg,{children:n("Topics")}),w.map(k=>i.jsxs(fn,{onClick:()=>C(k.id),children:[i.jsx(Kn,{className:W(k.id!==t.id&&"invisible")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:k.title}),i.jsx(pv,{entry:k})]},k.id))]}),i.jsx(ba,{}),_>0&&i.jsxs(fn,{onClick:()=>u(!0),children:[i.jsx(Ex,{}),n("All topics ({{n}})",{n:b.length})]}),i.jsxs(fn,{disabled:x,onClick:()=>{N()},children:[i.jsx(Lo,{}),n("New topic")]}),i.jsxs(fn,{disabled:x,onClick:()=>p({id:t.id,title:y(t)}),children:[i.jsx($s,{}),n("Rename topic")]}),t.parentId&&i.jsxs(fn,{variant:"destructive",onClick:()=>g(t.id),children:[i.jsx(Bs,{}),n("Delete topic")]})]})]}),i.jsxs("button",{type:"button",disabled:x,onClick:()=>{N()},className:W(Bm,"shrink-0"),title:n("New topic"),"aria-label":n("New topic"),children:[i.jsx(Lo,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New topic")})]}),c&&i.jsx(bI,{heading:n("Topics"),placeholder:n("Search topics..."),empty:n("No matching topics"),filters:!0,entries:b,currentId:t.id,onClose:()=>u(!1),onOpen:k=>{C(k),u(!1)},onRename:k=>p({id:k.id,title:k.title}),onDelete:k=>g(k.id)}),i.jsx(ms,{open:f!==null,onOpenChange:k=>!k&&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 S(f),zIndexLevel:c?"nested":"base"}),h!==null&&i.jsx(XZ,{initial:h.title,nested:c,onClose:()=>p(null),onSave:async k=>{const A=await window.electronAPI.bots.renameThread(h.id,k);if(!A.ok){Fe({type:"error",title:Ns(A.error,n)});return}ue.getState().upsertChat(A.chat),p(null)}})]})}function pv({entry:e}){const{locale:t}=J();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:zo(e.activityAt,t)})]})}function bI({heading:e,placeholder:t,empty:n,filters:s=!1,entries:o,currentId:r,onClose:a,onOpen:l,onRename:d,onDelete:c}){const{t:u}=J(),[h,p]=m.useState(""),[f,g]=m.useState("all"),x=Sw(o,h,f),v=b=>Sw(o,"",b).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(vn,{open:!0,onOpenChange:b=>!b&&a(),children:i.jsxs(bn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(wn,{children:[i.jsxs(yn,{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(eh,{children:i.jsx(ti,{})}),i.jsx(th,{autoFocus:!0,value:h,placeholder:t,onChange:b=>p(b.target.value)})]}),s&&i.jsx(Xu,{value:f,onValueChange:b=>g(b),children:i.jsxs(Zu,{children:[i.jsx(Is,{value:"all",children:u("All")}),i.jsxs(Is,{value:"unread",children:[u("Unread"),v("unread")>0&&i.jsx("span",{className:"tabular-nums",children:v("unread")})]}),i.jsxs(Is,{value:"running",children:[u("In progress"),v("running")>0&&i.jsx("span",{className:"tabular-nums",children:v("running")})]})]})})]}),i.jsxs(Mn,{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(b=>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(b.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(Kn,{className:W("h-3.5 w-3.5 shrink-0",b.id!==r&&"invisible")}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-sm",children:b.title}),b.preview&&i.jsx("span",{className:"block truncate text-muted-foreground text-xs",children:b.preview})]}),i.jsx(pv,{entry:b})]}),d&&b.canRename&&i.jsx("button",{type:"button",className:y,onClick:()=>d(b),title:u("Rename topic"),"aria-label":u("Rename topic"),children:i.jsx($s,{className:"h-3.5 w-3.5"})}),c&&b.canDelete?i.jsx("button",{type:"button",className:W(y,"hover:text-destructive"),onClick:()=>c(b),title:u("Delete topic"),"aria-label":u("Delete topic"),children:i.jsx(Bs,{className:"h-3.5 w-3.5"})}):c?i.jsx("span",{className:"w-5.5 shrink-0","aria-hidden":!0}):null]},b.id))]})]})})}function XZ({initial:e,nested:t,onClose:n,onSave:s}){const{t:o}=J(),[r,a]=m.useState(e),l=()=>{r.trim()&&s(r.trim())};return i.jsx(vn,{open:!0,onOpenChange:d=>!d&&n(),children:i.jsxs(bn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[i.jsx(wn,{children:i.jsx(yn,{children:o("Rename topic")})}),i.jsx(Mn,{children:i.jsx(Jt,{value:r,autoFocus:!0,maxLength:80,onChange:d=>a(d.target.value),onKeyDown:d=>d.key==="Enter"&&l()})}),i.jsxs(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(fe,{size:"sm",disabled:!r.trim(),onClick:l,children:o("Save")})]})]})})}function ZZ({chat:e,botId:t,running:n,onView:s}){const{t:o}=J(),[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(w=>{w.ok&&a(w.sessions.filter(_=>_.botId===t))})},[e.id,t]);m.useEffect(p,[p,h,n]);const f=r.map(w=>{const _=w.conversationId===h;return{id:w.conversationId,title:w.title??o(_?"New conversation":"Untitled conversation"),preview:_||w.resumable?"":o("Workspace changed; view only"),activityAt:w.activityAt??(_?Date.now():0),unread:!1,running:_&&n,resumable:w.resumable}}),g=VN(f,{currentId:h??"",rootId:h??""}),x=f.length-g.length,v=f.find(w=>w.id===h)?.title??o("New conversation"),y=async w=>{const _=await window.electronAPI.bots.switchSession(e.id,w);_.ok||Fe({type:"error",title:Ns(_.error,o)}),await ue.getState().refreshChats(),p()},b=w=>{const _=f.find(C=>C.id===w);!_||w===h||(_.resumable?n?u(w):y(w):s(w,_.title))};return f.length<2?null:i.jsxs(i.Fragment,{children:[i.jsxs(Hi,{onOpenChange:w=>w&&p(),children:[i.jsxs(Bi,{className:W(Bm,"max-w-56"),children:[i.jsx("span",{className:"truncate",children:v}),i.jsx($n,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs($i,{align:"end",className:"w-72",children:[i.jsxs(Ig,{children:[i.jsx(Eg,{children:o("Conversations")}),g.map(w=>i.jsxs(fn,{onClick:()=>b(w.id),children:[i.jsx(Kn,{className:W(w.id!==h&&"invisible")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:w.title}),!w.resumable&&w.id!==h&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:o("Read-only")}),i.jsx(pv,{entry:w})]},w.id))]}),x>0&&i.jsxs(i.Fragment,{children:[i.jsx(ba,{}),i.jsxs(fn,{onClick:()=>d(!0),children:[i.jsx(Ex,{}),o("All conversations ({{n}})",{n:f.length})]})]})]})]}),l&&i.jsx(bI,{heading:o("Conversations"),placeholder:o("Search conversations..."),empty:o("No matching conversations"),entries:f,currentId:h??"",onClose:()=>d(!1),onOpen:w=>{d(!1),b(w)}}),i.jsx(ms,{open:c!==null,onOpenChange:w=>!w&&u(null),title:o("Switch conversation?"),description:o("The reply in progress will be stopped."),confirmLabel:o("Switch"),onConfirm:()=>c&&void y(c)})]})}function wI(e){const{t}=J(),n=ya(),s=Se(d=>d.virtualModels);if(!e?.engine)return t("Default model");const{providerId:o,modelId:r}=e.engine,a=Gj(s,e.engine);return a?a.name:n.find(d=>d.id===o)?.models.find(d=>d.id===r)?.label??r}function JZ({chat:e,group:t=e}){const{t:n}=J(),s=ue(je=>je.bots),o=ue(je=>je.chats),r=ue(je=>je.sessions),a=ue(je=>je.queue),l=ue(je=>je.delegations),d=ue(je=>je.timelines[e.id]),c=ue(je=>je.runtime[e.id]),u=ue(je=>je.markRead),h=ue(je=>je.panelOpen),p=ue(je=>je.panelTab),f=ue(je=>je.browserTabs[t.id]?.tabs.length??0),g=ue(je=>je.panelWidth),x=Se(je=>je.skills),v=Se(je=>je.voiceInputEnabled),y=Se(je=>je.voiceModel),{status:b}=Mj(v),w=v&&b?.state!=="unsupported"&&b?.models.find(je=>je.id===y)?.state==="ready",[_,C]=m.useState(!1),[N,S]=m.useState(0),k=wa(),A=m.useRef(null);m.useEffect(()=>{const je=A.current?.parentElement;if(!je)return;const ht=()=>S(je.clientWidth);ht();const $t=new ResizeObserver(ht);return $t.observe(je),()=>$t.disconnect()},[]);const I=k?N:zj(g,N),E=h?I:0,D=m.useCallback(je=>{const ht=A.current?.parentElement;ht&&ue.getState().nudgePanelWidth(-je,ht.clientWidth)},[]),[T,H]=m.useState(null),[F,O]=m.useState(),[B,Y]=m.useState(null),U=ue(je=>je.focus?.chatId===e.id?je.focus:null),ee=ue(je=>je.clearFocus),L=m.useMemo(()=>new Map(s.map(je=>[je.id,je])),[s]),Q=m.useMemo(()=>Object.fromEntries(s.map(je=>[je.id,je.name])),[s]),V=e.members.map(je=>L.get(je)).filter(je=>!!je),ce=V.map(je=>`${je.id}:${je.skillIds.join(",")}`).join("|"),ve=m.useMemo(()=>x.flatMap(je=>{const ht=V.filter($t=>$t.skillIds.includes(je.id)).map($t=>$t.id);return ht.length?[{id:je.id,name:je.name,description:je.description,owners:ht}]:[]}),[x,ce]),_e=m.useMemo(()=>o.filter(je=>je.id!==t.id&&!je.parentId&&je.archivedAt===void 0).map(je=>({id:je.id,title:Ss(je,s,n),kind:je.kind})),[o,t.id,s,n]),De=Dg(e,{sessions:r,timeline:d,queue:a,names:Q}),me=ue(je=>je.reads[De.key]),$=e.kind==="group"?q2(d,me):De.marker,z=m.useMemo(()=>l.filter(je=>je.chatId===e.id),[l,e.id]),de=m.useMemo(()=>Rj(r,Lj(o,l),e.id),[r,o,l,e.id]),oe=T?(je=>{const ht=z.find(yt=>yt.childConversationId===je);if(ht)return L.get(ht.targetBotId);const $t=Object.entries(e.sessions).find(([,yt])=>yt.conversationId===je)?.[0],Oe=d?.entries.find(yt=>yt.kind==="bot"&&yt.conversationId===je);return L.get($t??(Oe?.kind==="bot"?Oe.botId:e.kind==="direct"?e.members[0]:""))})(T.id):void 0,Z=B?L.get(B.botId):void 0,ae=B?de.filter(je=>je.conversationId===B.id):[],be=B?.title??Z?.name??n("Deleted member"),ze=B&&l.find(je=>je.childConversationId===B.id)?.state==="queued",Ye=m.useCallback((je,ht)=>{const $t=Y2(ue.getState().delegations,je);$t?(ue.getState().sessions[je]||ue.getState().trackSession(je),Y({id:je,botId:$t.botId,title:ht})):H({id:je,title:ht})},[]);m.useEffect(()=>{u(De.key,$)},[u,De.key,$]),m.useEffect(()=>{if(e.kind==="group"){const je=ue.getState();je.timelines[e.id]?.history&&je.focus?.chatId!==e.id?je.jumpLatest(e.id):je.loadLatest(e.id),ue.getState().refreshRuntime(e.id)}},[e.id,e.kind]);const Ve=e.kind==="direct"?V[0]:void 0,at=Ve?e.sessions[Ve.id]?.conversationId:void 0,Ze=U?.locator,Et=U&&Ze?.kind==="session"&&Ze.conversationId===at?{messageIndex:Ze.messageIndex,query:U.query,nonce:U.nonce}:void 0,Gt=U&&Ze?.kind==="timeline"?{seq:Ze.seq,query:U.query,nonce:U.nonce}:void 0;m.useEffect(()=>{U?.locator.kind==="session"&&U.locator.conversationId!==at&&(H({id:U.locator.conversationId,title:n("History")}),O({messageIndex:U.locator.messageIndex,query:U.query,nonce:U.nonce}),ee(U.nonce))},[U,at,ee,n]);const Pt=T?.id,ne=m.useCallback(je=>e.kind==="direct"&&Pt?i.jsx(Eu,{target:{chatId:e.id,conversationId:Pt,messageIndex:je}}):null,[e.id,e.kind,Pt]),ie=e.archivedAt!==void 0,He=c?.current?L.get(c.current):void 0,St=(()=>{if(ie)return n("This chat is archived. Restore it before sending.");if(e.kind==="group"){const je=e.routing.mode==="smart"?n("Without @, the best-fit member is picked to reply"):n("Without @, the group owner replies");return He?`${je} · ${n("{{name}} is replying; new messages are routed after they finish",{name:He.name})}`:je}return De.running&&Ve?n("{{name}} is working; your message joins the current turn",{name:Ve.name}):null})(),it=async({text:je,images:ht,...$t})=>{const Oe=await ue.getState().send(e.id,je,ht,$t);return Oe.ok?(Oe.queued&&Fe({type:"info",title:n("Queued until a session slot frees up")}),ue.getState().timelines[e.id]?.history&&ue.getState().jumpLatest(e.id),!0):(Fe({type:"error",title:n("Message not sent"),description:Ns(Oe.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:[Ve?i.jsx(sn,{bot:Ve,busy:De.running}):i.jsx(rl,{bots:V,busy:De.running}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate font-semibold text-sm",children:Ss(e,s,n)}),i.jsx("div",{className:"truncate text-muted-foreground text-xs",children:Ve?i.jsx(eJ,{bot:Ve,running:De.running,queued:De.queued,conversationId:e.sessions[Ve.id]?.conversationId}):n("{{n}} members · Owner {{name}}",{n:V.length,name:L.get(e.bossBotId??"")?.name??"—"})})]}),i.jsx("div",{className:"flex-1"}),i.jsx(hI,{chat:t}),Ve?i.jsxs(i.Fragment,{children:[i.jsx(ZZ,{chat:e,botId:Ve.id,running:De.running,onView:(je,ht)=>H({id:je,title:ht})}),i.jsxs("button",{type:"button",disabled:ie,onClick:()=>{window.electronAPI.bots.newSession(e.id).then(je=>{je.ok?ue.getState().refreshChats():Fe({type:"error",title:Ns(je.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(Lo,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New conversation")})]})]}):i.jsx(YZ,{group:t,thread:e})]}),Ve?i.jsxs(i.Fragment,{children:[i.jsx(QZ,{items:Aj(z,e.id),bots:L,onOpenConversation:Ye}),i.jsx(nJ,{chat:e,bot:Ve,focus:Et,onFocusDone:ee})]}):i.jsx(HZ,{chat:e,bots:L,timeline:d,runtime:c,delegations:z,focus:Gt,onFocusDone:ee,onLoadOlder:()=>{ue.getState().loadOlder(e.id)},onLoadNewer:()=>{ue.getState().loadNewer(e.id)},onLoadAround:je=>ue.getState().loadAround(e.id,je),onJumpLatest:()=>{ue.getState().jumpLatest(e.id)},onOpenConversation:Ye,onOpenLive:(je,ht)=>Y({id:je,botId:ht,title:L.get(ht)?.name??n("Deleted member")})}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:W(ji,"pb-4"),children:[Ve&&(De.running||De.queued)&&i.jsx(FD,{conversationId:e.sessions[Ve.id]?.conversationId,className:"mb-2 rounded-lg border bg-muted/30 px-3 py-2"}),i.jsx(_S,{items:de,bots:L,showNames:e.kind==="group"}),e.kind==="group"&&i.jsx(IX,{chatId:e.id,memberIds:e.members,bots:L,onOpenLive:(je,ht)=>Y({id:je,botId:ht,title:L.get(ht)?.name??n("Deleted member")})}),i.jsx(gX,{chatId:e.id,placeholder:Ve?n("Message {{name}}…",{name:Ve.name}):n("@ a member, or just say it…"),members:e.kind==="group"?V:void 0,chatOptions:_e,skills:ve,voice:w?vD:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,running:De.running||!!(c?.current||c?.routing),disabled:ie,hint:St,toolbar:Ve?i.jsx(tJ,{bot:Ve}):null,onSend:it,onStop:()=>{ue.getState().stop(e.id)}},e.id)]})})]}),h&&!k&&i.jsx(Cu,{onResize:D,onResizingChange:C}),i.jsx(Rs.aside,{ref:A,initial:!1,animate:{width:E},style:k?void 0:{maxWidth:`max(0px, calc(100% - ${Oj+Pg}px))`},transition:xD({skip:_,cover:k,targetW:E}),className:W("flex min-h-0 shrink-0 flex-col overflow-hidden bg-background",k?"absolute inset-y-0 right-0 z-10":"relative"),children:i.jsxs("div",{className:W("flex h-full min-h-0 flex-col",!h&&"invisible"),style:{width:I},children:[i.jsx("div",{className:"flex h-10 shrink-0 items-center gap-1 border-b px-2",children:["info","browser"].map(je=>i.jsxs("button",{type:"button",onClick:()=>ue.getState().setPanelTab(je),className:W("flex h-7 items-center gap-1.5 rounded-md px-2.5 text-xs transition-colors",p===je?"bg-brand/10 font-medium text-foreground dark:bg-brand/15":"text-muted-foreground hover:text-foreground"),children:[je==="info"?i.jsx(nh,{className:"h-3.5 w-3.5"}):i.jsx(mo,{className:"h-3.5 w-3.5"}),n(je==="info"?Ve?"Member":"Group info":"Browser"),je==="browser"&&f>0&&i.jsx("span",{className:"text-muted-foreground tabular-nums",children:f})]},je))}),p==="browser"?i.jsx(NY,{chatId:t.id,visible:h}):Ve?i.jsx(gZ,{botId:Ve.id,chat:e,onOpenHistory:Ye}):i.jsx(IZ,{chat:t,thread:e,onOpenConversation:Ye})]})}),i.jsx(hv,{conversationId:T?.id??null,title:T?.title??"",speaker:oe?{name:oe.name,color:oe.avatar.color,image:Jc(oe)}:void 0,focus:F,turnFooter:ne,onClose:()=>{H(null),O(void 0)}}),i.jsx(qZ,{conversationId:B?.id??null,title:be,speaker:{name:Z?.name??be,color:Z?.avatar.color??"#64748b",image:Z?Jc(Z):void 0},emptyTitle:ze?n("Queued and has not started yet"):void 0,emptyDescription:ze?"":void 0,footer:Z&&ae.length>0?i.jsx(_S,{items:ae,bots:L,showNames:!1}):void 0,onClose:()=>Y(null)})]})}function QZ({items:e,bots:t,onOpenConversation:n}){const{t:s}=J();return e.length===0?null:i.jsx("div",{className:"shrink-0 border-b bg-muted/30",children:i.jsxs("div",{className:W(ji,"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(Ph,{record:o,bots:t,onOpenConversation:n},o.id))})]})})}function eJ({bot:e,running:t,queued:n,conversationId:s}){const{t:o}=J(),r=wI(e),a=o(t?"Working":n?"Queued":"Idle");return i.jsxs(i.Fragment,{children:[[e.title,r,a].filter(Boolean).join(" · "),t&&i.jsx(mI,{conversationId:s,className:"ml-1.5 text-warning"})]})}function tJ({bot:e}){const{t}=J(),n=wI(e),s=Ml[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(Hs,{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(Wu,{className:"h-3 w-3"}),t(s.labelKey)]})]})}function nJ({chat:e,bot:t,focus:n,onFocusDone:s}){const{t:o}=J(),r=e.sessions[t.id]?.conversationId,a=e.archivedAt!==void 0,l=m.useMemo(()=>{if(a||!r)return;const c=u=>{u.ok||Fe({type:"error",title:Ns(u.error??"unavailable",o)})};return{subscribe:ue.subscribe,projection:()=>ue.getState().sessions[r],rewind:(u,h)=>{ue.getState().rewind(e.id,u,h).then(c)},retry:()=>{ue.getState().retry(e.id).then(c)}}},[e.id,r,a,o]),d=m.useCallback(c=>r?i.jsx(Eu,{target:{chatId:e.id,conversationId:r,messageIndex:c}}):null,[e.id,r]);return r?i.jsx(vI,{conversationId:r,speaker:{name:t.name,color:t.avatar.color,image:Jc(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(sn,{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 _S({items:e,bots:t,showNames:n}){const{t:s}=J(),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(sn,{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(Vl,{approvals:u,onRespond:(p,f)=>{window.electronAPI.agent.respondApproval(r,p,f)}}),i.jsx(wh,{asks:h,onAnswer:(p,f)=>{window.electronAPI.agent.respondAsk(r,p,f)}})]},r)})})}function sJ(e,t){const n={pending:[],budgets:[],routines:[],silences:[],interrupted:[],blocked:[],count:0};for(const s of X2(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 iJ({write:e,bot:t,chatName:n}){const{t:s}=J(),o=Z2(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(sn,{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(fe,{size:"xs",variant:"outline",disabled:r,onClick:()=>c("reject"),children:s("Reject")}),i.jsx(fe,{size:"xs",disabled:r,onClick:()=>c("approve"),children:s("Approve")})]})]})}function oJ(){const{t:e}=J(),t=ue(p=>p.inbox),n=ue(p=>p.chats),s=ue(p=>p.bots),o=ue(p=>p.delegations),r=ue(p=>p.routines),[a,l]=m.useState(null),d=m.useMemo(()=>sJ(t,{routines:r,delegations:o}),[t,r,o]),c=J2(),u=m.useMemo(()=>new Map(s.map(p=>[p.id,p])),[s]),h=p=>{const f=n.find(g=>g.id===p);return f?Ss(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(Ix,{className:"h-6 w-6"}),i.jsx("p",{className:"text-sm",children:e("Nothing needs your attention")})]}),d.pending.map(p=>i.jsx(cJ,{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(aJ,{item:p,bot:u.get(p.botId??"")},p.key)),c.map(p=>i.jsx(iJ,{write:p,bot:p.botId?u.get(p.botId):void 0,chatName:h(p.chatId)},p.id)),d.routines.map(p=>i.jsx(rZ,{alert:p},p.routine.id)),d.silences.map(p=>i.jsx(rJ,{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(lJ,{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(dJ,{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(hv,{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 rJ({item:e,bot:t,chatName:n}){const{t:s}=J(),o=ue(l=>l.setView),r=ue(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(sn,{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(fI,{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(fe,{size:"xs",variant:"ghost",onClick:()=>{r(e.key)},children:s("Dismiss")}),e.chatId&&i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>e.chatId&&o({kind:"chat",chatId:e.chatId}),children:s("Go to chat")})]})]})}function aJ({item:e,bot:t}){const{t:n}=J(),s=ue(a=>a.dismissInbox),o=ue(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(sn,{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(fe,{size:"xs",variant:"ghost",onClick:()=>{s(e.key)},children:n("Dismiss")}),t&&i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>{o(t.id)},children:n("Go to chat")})]})]})}function lJ({inboxKey:e,record:t,bots:n,chatName:s}){const{t:o}=J(),r=ue(g=>g.openTask),a=ue(g=>g.dismissInbox),l=Eh(!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(sn,{bot:d,size:"xs"}),i.jsx("span",{className:"text-foreground",children:c}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx(Ih,{state:t.state}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:o("Stuck for {{time}}",{time:go(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(uv,{placeholder:o("Answer {{name}}; they continue after your reply…",{name:c}),onSend:g=>lI(p,f,g,o)})]}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(fe,{size:"xs",variant:"ghost",onClick:()=>{a(e)},children:o("Dismiss")}),p&&f&&i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>r(p,f),children:o("Open task card")})]})]})}function dJ({inboxKey:e,record:t,bots:n,chatName:s,onOpen:o}){const{t:r}=J(),a=ue(p=>p.setView),l=ue(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(sn,{bot:d,size:"xs"}),i.jsx("span",{className:"text-foreground",children:u}),i.jsx("span",{children:"→"}),i.jsx(sn,{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(Ih,{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:Ed(t,r)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(fe,{size:"xs",variant:"ghost",onClick:()=>{l(e)},children:r("Dismiss")}),t.chatId&&i.jsx(fe,{size:"xs",variant:"ghost",onClick:()=>t.chatId&&a({kind:"chat",chatId:t.chatId}),children:r("Go to chat")}),i.jsx(fe,{size:"xs",variant:"outline",onClick:()=>o(r("{{from}} → {{to}} · Delegation",{from:u,to:h})),children:r("View conversation")}),i.jsx(fe,{size:"xs",onClick:()=>_l(t.id,r),children:r("Retry")})]})]})}function cJ({item:e,bot:t,owner:n,chatName:s}){const{t:o}=J(),r=ue(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(sn,{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:WN(e.request.protected,o)})]}),e.kind==="approval"?i.jsxs("div",{className:"mt-2 text-sm",children:[br(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(fe,{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(fe,{size:"xs",variant:"outline",disabled:d,onClick:()=>h("deny"),children:o("Deny")}),!e.request.protected&&i.jsx(fe,{size:"xs",variant:"outline",disabled:d,onClick:()=>h("allowSession"),children:o("Always allow in this session")}),i.jsx(fe,{size:"xs",disabled:d,onClick:()=>h("allow"),children:o("Allow")})]}):i.jsxs(i.Fragment,{children:[e.request.options?.map(g=>i.jsx(fe,{size:"xs",variant:"outline",disabled:d,onClick:()=>p(g),children:g},g)),i.jsx(Jt,{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(fe,{size:"xs",disabled:d||!a.trim(),onClick:()=>p(a),children:o("Reply")})]})]})]})}function uJ(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=Q2({locale:l.locale}),y=m.useMemo(()=>l.filter!==void 0?l.filter:v.contains,[l.filter,v]),b=String(u?n:h).trim(),w=m.useMemo(()=>r!=="both"?c?null:y:y===null?null:(N,S,k)=>y(N,b,k),[y,r,b,c]);function _(N,S){g(""),u||p(N),o?.(N,S)}function C(N,S){e.onItemHighlighted?.(N,S),S.reason!==tL&&g(d&&N!=null?nL(N,a):"")}return i.jsx(eL,{...l,itemToStringLabel:a,openOnInputClick:t,selectionMode:"none",fillInputOnItemPress:!0,filter:w,autoComplete:r,inputValue:x,defaultInputValue:s,onInputValueChange:_,onItemHighlighted:C})}const hJ=sL,pJ="",fJ=200;function mJ(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 gJ(){const e=iL(),t=m.useRef(null);return m.useEffect(()=>{if(oL)return;const n=t.current;if(n==null)return;const s=mJ(n);if(s==null)return;const o=s.data,r=`${o}${pJ}`;return s.nodeValue=r,e.start(fJ,()=>{s.nodeValue===r&&(s.nodeValue=o)}),()=>{e.clear(),s.nodeValue===r&&(s.nodeValue=o)}},[t,e]),t}const yI=m.createContext(void 0);function xJ(){const e=m.useContext(yI);if(e===void 0)throw new Error(ad(18));return e}const vJ=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=ld("div",t,{ref:n,props:[{role:"group","aria-labelledby":d},l]}),p=i.jsx(yI.Provider,{value:u,children:h});return a?i.jsx(rL,{items:a,children:p}):p}),bJ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,id:a,...l}=t,{setLabelId:d}=xJ(),c=Yk(a);return yg(()=>(d(c),()=>{d(h=>h===c?void 0:h)}),[c,d]),ld("div",t,{ref:n,props:[{id:c},l]})}),wJ=aL,yJ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,children:a,...l}=t,{filteredItems:d}=lL(),c=dL(),u=gJ(),h=d.length===0?a:null;return ld("div",t,{ref:[n,c.state.emptyRef,u],props:[{children:h,role:"status","aria-live":"polite","aria-atomic":!0},l]})}),fv=uJ,Yp=new WeakMap;function Er(e,t){const n=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(e));return Number.isFinite(n)?n:t}function $m(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 SJ(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=Yp.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=Er("--clear-dur",1e3),d=Er("--clear-out-dur",400),c=Er("--clear-in-dur",400),u=Er("--clear-out-fly",12),h=Er("--clear-in-fly",12),p=Er("--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="",Yp.delete(t),$m(t)},Math.max(l,d,c));Yp.set(t,y)}function mv({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&&$m(l.current)},[r.value]),i.jsxs("div",{ref:l,className:"t-clear autocomplete-clear-dissolve relative w-full",onInput:d=>$m(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(cL,{className:W(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(Jt,{size:a}),...r}),i.jsx("div",{"aria-hidden":"true",className:W("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:W("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(_J,{className:W("-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(Fj,{})}),n&&i.jsx(jJ,{className:W("-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(ln,{})})]})}function SI({className:e,children:t,sideOffset:n=4,zIndex:s,...o}){return i.jsx(uL,{children:i.jsx(hL,{className:"z-[55] select-none",style:s?{zIndex:s}:void 0,"data-slot":"autocomplete-positioner",sideOffset:n,children:i.jsx("span",{className:W("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(pL,{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 gv({className:e,children:t,...n}){return i.jsx(wJ,{className:W("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 CJ({className:e,...t}){return i.jsx(vJ,{className:W("[[role=group]+&]:mt-1.5",e),"data-slot":"autocomplete-group",...t})}function kJ({className:e,...t}){return i.jsx(bJ,{className:W("px-2 py-1.5 font-medium text-muted-foreground text-xs",e),"data-slot":"autocomplete-group-label",...t})}function xv({className:e,...t}){return i.jsx(yJ,{className:W("not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",e),"data-slot":"autocomplete-empty",...t})}function vv({className:e,...t}){return i.jsx(fL,{scrollbarGutter:!0,scrollFade:!0,children:i.jsx(mL,{className:W("not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3",e),"data-slot":"autocomplete-list",...t})})}function jJ({className:e,onClickCapture:t,onPointerDownCapture:n,...s}){return i.jsx(gL,{className:W("-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||SJ(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(ln,{})})}function _J({className:e,...t}){return i.jsx(hJ,{className:e,"data-slot":"autocomplete-trigger",...t})}const CI=m.createContext({inputRef:null}),kI=xL,NJ=vL;function TJ({className:e,...t}){return i.jsx(yL,{className:W("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 DJ({className:e,...t}){return i.jsx(SL,{className:W("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 jI({className:e,children:t,...n}){const s=m.useRef(null);return i.jsxs(NJ,{children:[i.jsx(bL,{}),i.jsx(TJ,{}),i.jsx(DJ,{children:i.jsx(wL,{className:W("-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(CI.Provider,{value:{inputRef:s},children:t})})})]})}function _I({autoHighlight:e="always",keepHighlight:t=!0,open:n=!0,...s}){return i.jsx(fv,{autoHighlight:e,keepHighlight:t,open:n,...s})}function NI({className:e,placeholder:t=void 0,endAddon:n,...s}){const{inputRef:o}=m.useContext(CI);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(mv,{className:W("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 TI({className:e,...t}){return i.jsx(vv,{className:W("not-empty:scroll-py-2 not-empty:p-2",e),"data-slot":"command-list",...t})}function DI({className:e,...t}){return i.jsx(xv,{className:W("not-empty:py-6",e),"data-slot":"command-empty",...t})}function II({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 Pr({className:e,...t}){return i.jsx(CJ,{className:e,"data-slot":"command-group",...t})}function Ar({className:e,...t}){return i.jsx(kJ,{className:e,"data-slot":"command-group-label",...t})}function ir({className:e,...t}){return i.jsx(gv,{className:W("py-1.5",e),"data-slot":"command-item",...t})}function NS({className:e,...t}){return i.jsx("span",{className:W("ms-auto font-medium text-muted-foreground/72 text-xs tracking-widest",e),"data-slot":"command-shortcut",...t})}function EI({className:e,...t}){return i.jsx("div",{className:W("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 TS=e=>e.locator.kind==="timeline"?`${e.chatId}:${e.locator.seq}`:`${e.chatId}:${e.locator.conversationId}:${e.locator.messageIndex}`;function PI({className:e}){const{t}=J(),n=Se(r=>r.keybindings),s=Li(n)["search-workspace"],o=t("Search messages");return i.jsx("button",{type:"button",className:e,onClick:()=>ue.getState().setSearchOpen(!0),title:s?`${o} (${mi(s)})`:o,children:i.jsx(ti,{className:"h-4 w-4"})})}function IJ(){const{t:e,locale:t}=J(),n=ue(v=>v.searchOpen),s=ue(v=>v.setSearchOpen),o=ue(v=>v.bots),r=ue(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(b=>{v||c(b.ok?{key:u,hits:b.hits,truncated:b.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(kI,{open:n,onOpenChange:s,children:i.jsx(jI,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:g,children:i.jsxs(_I,{children:[i.jsx(NI,{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(),ue.getState().focusHit(y,u))}}),i.jsxs(II,{children:[u&&f&&f.hits.length===0&&i.jsx(DI,{children:e("No matching messages")}),i.jsxs(TI,{children:[f?.hits.map(v=>{const y=p.get(v.chatId),b=(y?.members??[]).map(C=>h.get(C)).filter(C=>C!==void 0),w=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(ir,{value:TS(v),className:"items-start gap-2.5",onClick:()=>ue.getState().focusHit(v,u),children:[i.jsx("span",{className:"mt-0.5 shrink-0",children:v.chatKind==="direct"?i.jsx(sn,{bot:b[0]}):i.jsx(rl,{bots:b})}),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?Ss(y,o,e):e("Deleted chat")}),i.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[w,_]})]}),i.jsx("p",{className:"line-clamp-2 break-words text-muted-foreground text-xs",children:LZ(v.snippet,v.ranges).map((C,N)=>C.match?i.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:C.text},N):i.jsx("span",{children:C.text},N))})]}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:v.at?zo(v.at,t,x):""})]},TS(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(EI,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(Hj,{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 EJ({chat:e,onOpenChange:t}){const{t:n}=J(),s=ue(f=>f.bots),o=ue(f=>f.chats),r=Se(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(CL(n("{{title}} copy",{title:Ss(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){Fe({type:"error",title:Ns(g.error,n)});return}const x=ue.getState();x.upsertChat(g.chat),x.setView({kind:"chat",chatId:g.chat.id}),x.loadLatest(g.chat.id),Fe({type:"success",title:n("Cloned. The chat history is empty.")}),t(!1)}finally{c(!1)}}};return i.jsx(vn,{open:!0,onOpenChange:t,children:i.jsxs(bn,{className:"max-w-md",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:n("Clone group chat")}),i.jsx(As,{children:n("Copies the setup of “{{title}}”. The original stays as is; replies in progress are not stopped.",{title:Ss(e,s,n)})})]}),i.jsxs(Mn,{className:"space-y-4 text-sm",children:[i.jsxs("div",{children:[i.jsx(Xt,{children:n("Group name")}),i.jsx(Jt,{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(Xt,{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:Ij(e,r,s,n)}):n("A new empty folder, separate from the original")]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(Xt,{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(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsx(fe,{size:"sm",disabled:!a.trim()||d,onClick:()=>{p()},children:n("Clone")})]})]})})}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 PJ({width:e,onCollapse:t,onNewMember:n,onNewGroup:s,onNewTeam:o,onStartFromGoal:r}){const{t:a,locale:l}=J(),d=[{label:a("Start from a goal"),icon:Ta,onClick:r},{label:a("New member"),icon:$l,onClick:n},{label:a("New group chat"),icon:la,onClick:s},{label:a("Create team from template"),icon:Pf,onClick:o}],c=ue(ne=>ne.bots),u=ue(ne=>ne.chats),h=ue(ne=>ne.queue),p=ue(ne=>ne.sessions),f=ue(ne=>ne.delegations),g=ue(ne=>ne.timelines),x=ue(ne=>ne.reads),v=ue(ne=>ne.view),y=ue(ne=>ne.setView),b=ue(ne=>ne.openDirect),w=ue(ne=>ne.upsertChat),_=ue(ne=>ne.upsertBot),[C,N]=m.useState(!1),[S,k]=m.useState(""),[A,I]=m.useState(null),[E,D]=m.useState(null),T=m.useMemo(()=>new Map(c.map(ne=>[ne.id,ne])),[c]),H=m.useMemo(()=>Object.fromEntries(c.map(ne=>[ne.id,ne.name])),[c]),F=m.useMemo(()=>Rj(p,Lj(u,f)),[p,u,f]),O=m.useMemo(()=>{const ne=new Set,ie=new Set;for(const He of f)Al(He.state)&&(He.chatId&&ne.add(He.chatId),ie.add(He.targetBotId));return{chatIds:ne,botIds:ie}},[f]),B=m.useMemo(()=>kL(u.map(ne=>{const ie=Dg(ne,{sessions:p,timeline:g[ne.id],queue:h,names:H});return{chat:ne,summary:{...ie,running:ie.running||(ne.kind==="group"?O.chatIds.has(ne.id):O.botIds.has(ne.members[0])),pending:F.filter(He=>He.chatId===ne.id).length}}}),x),[u,p,g,h,H,F,O,x]),Y=B.filter(ne=>!ne.chat.archivedAt),U=jL(Y.filter(ne=>ne.chat.kind==="group"&&ne.chat.settledAt===void 0)),ee=new Map(Y.filter(ne=>ne.chat.kind==="direct").map(ne=>[ne.chat.members[0],ne])),L=c.filter(ne=>ne.archivedAt===void 0&&ee.get(ne.id)?.chat.settledAt===void 0).map(ne=>({bot:ne,row:ee.get(ne.id)})).sort((ne,ie)=>{const He=Number(ie.row?.chat.pinned??!1)-Number(ne.row?.chat.pinned??!1),St=(ne.row?.chat.pinOrder??Number.POSITIVE_INFINITY)-(ie.row?.chat.pinOrder??Number.POSITIVE_INFINITY);return He||(ne.row?.chat.pinned&&St?St:0)||(ie.row?.summary.activityAt??ie.bot.updatedAt)-(ne.row?.summary.activityAt??ne.bot.updatedAt)}),Q=Y.filter(ne=>ne.chat.settledAt!==void 0&&(ne.chat.kind==="group"||T.get(ne.chat.members[0])?.archivedAt===void 0)).sort((ne,ie)=>(ie.chat.settledAt??0)-(ne.chat.settledAt??0)),V=U.filter(ne=>ne.chat.pinned).map(ne=>ne.chat.id),ce=L.flatMap(({row:ne})=>ne?.chat.pinned?[ne.chat.id]:[]),[ve,_e]=m.useState(null),[De,me]=m.useState(!0),$=B.filter(ne=>ne.chat.archivedAt!==void 0),z=c.filter(ne=>ne.archivedAt!==void 0),de=$.length+z.length,X=S.trim().toLowerCase(),oe=(...ne)=>!X||ne.some(ie=>ie.toLowerCase().includes(X)),Z=$.filter(({chat:ne,summary:ie})=>oe(Ss(ne,c,a),ie.preview??"")).sort((ne,ie)=>(ie.chat.archivedAt??0)-(ne.chat.archivedAt??0)),ae=z.filter(ne=>oe(ne.name,ne.title,ne.scope)).sort((ne,ie)=>(ie.archivedAt??0)-(ne.archivedAt??0)),be=Ag(),ze=v?.kind==="chat"?v.chatId:null,Ye=async(ne,ie)=>{const He=await window.electronAPI.bots.updateChat({chatId:ne.id,...ie});He.ok?w(He.chat):Fe({type:"error",title:Ns(He.error,a)})},Ve=ne=>Ye(ne,ne.pinned?{pinned:!1}:{pinned:!0,pinOrder:Math.max(-1,...u.filter(ie=>ie.pinned).map(ie=>ie.pinOrder??0))+1}),at=(ne,ie,He)=>{const St=Object.fromEntries(u.map(it=>[it.id,it.pinOrder]));for(const it of TL(ne,ie,He,St)){const je=u.find(ht=>ht.id===it.chatId);je&&Ye(je,{pinOrder:it.pinOrder})}},Ze=(ne,ie)=>{const He=ie.indexOf(ne.id),St=B.find(it=>it.chat.id===ne.id)?.summary;return{onSettle:()=>{Ye(ne,{settled:ne.settledAt===void 0})},onSnooze:it=>{Ye(ne,{snoozedUntil:it})},onMarkUnread:St&&ze!==ne.id&&!Za(St.marker,x[St.key])&&_L(St.marker)!==void 0?()=>ue.getState().markUnread(ne.id):void 0,onMoveUp:He>0?()=>at(ie,ne.id,He-1):void 0,onMoveDown:He>=0&&He<ie.length-1?()=>at(ie,ne.id,He+1):void 0}},Et=(ne,ie)=>ne?.pinned?{draggable:!0,onDragStart:He=>{He.dataTransfer.effectAllowed="move",_e(ne.id)},onDragEnd:()=>_e(null),onDragOver:He=>{ve&&ve!==ne.id&&ie.includes(ve)&&He.preventDefault()},onDrop:He=>{He.preventDefault(),ve&&ie.includes(ve)&&at(ie,ve,ie.indexOf(ne.id)),_e(null)}}:{},Gt=async(ne,ie)=>{const He=await window.electronAPI.bots.archive(ne.id,ie);He.ok?_(He.bot):Fe({type:"error",title:He.error})},Pt=ne=>ne?ne.running?a("Working"):ne.queued?a("Queued"):ne.activityAt?zo(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(Xp,{title:a("Group chats"),onAdd:s,addLabel:a("New group chat")}),U.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No group chats yet")}),U.map(({chat:ne,summary:ie})=>i.jsx(Jp,{chat:ne,onPin:()=>{Ve(ne)},onArchive:()=>{Ye(ne,{archived:!0})},onDelete:()=>I(ne),onClone:()=>D(ne),manage:Ze(ne,V),children:i.jsx(Zp,{...Et(ne,V),active:ze===ne.id,avatar:i.jsx(rl,{bots:ne.members.map(He=>T.get(He)),busy:ie.running}),title:Ss(ne,c,a),pinned:ne.pinned,meta:Pt(ie),preview:ie.preview,unread:Za(ie.marker,x[ie.key]),pending:ie.pending,onClick:()=>y({kind:"chat",chatId:ne.id})})},ne.id)),i.jsx(Xp,{title:a("Members"),onAdd:n,addLabel:a("New member")}),L.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No members yet")}),L.map(({bot:ne,row:ie})=>i.jsx(Jp,{chat:ie?.chat,onPin:ie?()=>{Ve(ie.chat)}:void 0,onArchive:ie?()=>{Ye(ie.chat,{archived:!0})}:void 0,onArchiveMember:()=>{Gt(ne,!0)},manage:ie?Ze(ie.chat,ce):void 0,children:i.jsx(Zp,{...Et(ie?.chat,ce),active:!!(ie&&ze===ie.chat.id),avatar:i.jsx(sn,{bot:ne,busy:ie?.summary.running||O.botIds.has(ne.id)}),title:ne.name,pinned:ie?.chat.pinned,meta:O.botIds.has(ne.id)?a("Working"):Pt(ie?.summary),preview:ie?.summary.preview||ne.title||ne.scope,unread:!!(ie&&Za(ie.summary.marker,x[ie.summary.key])&&ze!==ie.chat.id),pending:ie?.summary.pending??0,onClick:()=>{b(ne.id)}})},ne.id)),Q.length>0&&i.jsx(Xp,{title:`${a("Settled")} · ${Q.length}`,onToggle:()=>me(ne=>!ne)}),De&&Q.map(({chat:ne,summary:ie})=>{const He=ne.kind==="direct"?T.get(ne.members[0]):void 0;return i.jsx(Jp,{chat:ne,onPin:()=>{Ve(ne)},onArchive:()=>{Ye(ne,{archived:!0})},onClone:ne.kind==="group"?()=>D(ne):void 0,manage:Ze(ne,[]),children:i.jsx(Zp,{className:"opacity-75",active:ze===ne.id,avatar:He?i.jsx(sn,{bot:He,busy:ie.running}):i.jsx(rl,{bots:ne.members.map(St=>T.get(St)),busy:ie.running}),title:He?He.name:Ss(ne,c,a),meta:ne.snoozedUntil!==void 0?a("Remind {{time}}",{time:zo(ne.snoozedUntil,l)}):Pt(ie),preview:ie.preview,unread:Za(ie.marker,x[ie.key])&&(ne.kind==="group"||ze!==ne.id),pending:ie.pending,onClick:()=>He?void b(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:Jo,title:a("Collapse sidebar"),children:i.jsx(Px,{className:"h-4 w-4"})}):i.jsx("span",{}),i.jsxs("div",{className:"flex items-center",children:[i.jsx(PI,{className:Jo}),d.map(({label:ne,icon:ie,onClick:He})=>i.jsx("button",{type:"button",className:W(Jo,"hidden @min-[18.5rem]:flex"),onClick:He,title:ne,children:i.jsx(ie,{className:"h-4 w-4"})},ne)),i.jsxs(Hi,{children:[i.jsx(Bi,{className:W(Jo,"@min-[18.5rem]:hidden"),title:a("More actions"),children:i.jsx(xh,{className:"h-4 w-4"})}),i.jsx($i,{align:"end",side:"top",children:d.map(({label:ne,icon:ie,onClick:He})=>i.jsxs(fn,{onClick:He,children:[i.jsx(ie,{}),ne]},ne))})]}),(be>0||v?.kind==="inbox")&&i.jsxs("button",{type:"button",className:W(Jo,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(Ix,{className:"h-4 w-4"}),be>0&&i.jsx(Rh,{count:be,className:"-top-0.5 -right-1 absolute"})]}),de>0&&i.jsx("button",{type:"button",className:Jo,onClick:()=>{k(""),N(!0)},title:`${a("Archived")} (${de})`,children:i.jsx(Ai,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:Jo,onClick:()=>{window.electronAPI.window.openSettings()},title:a("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})})]})]}),i.jsx(vn,{open:C,onOpenChange:N,children:i.jsxs(bn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(wn,{children:[i.jsxs(yn,{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(eh,{children:i.jsx(ti,{})}),i.jsx(th,{value:S,placeholder:a("Search conversations..."),onChange:ne=>k(ne.target.value)})]})]}),i.jsxs(Mn,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[Z.length+ae.length===0&&i.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:S.trim()?a("No matching conversations"):a("Nothing archived")}),Z.length>0&&i.jsx(DS,{title:a("Chat threads"),count:Z.length,children:Z.map(({chat:ne,summary:ie})=>i.jsx(IS,{avatar:ne.kind==="group"?i.jsx(rl,{bots:ne.members.map(He=>T.get(He))}):i.jsx(sn,{bot:T.get(ne.members[0])}),title:Ss(ne,c,a),preview:ie.preview,onOpen:()=>{y({kind:"chat",chatId:ne.id}),N(!1)},onRestore:()=>{Ye(ne,{archived:!1})},onDelete:ne.kind==="group"?()=>I(ne):void 0},ne.id))}),ae.length>0&&i.jsx(DS,{title:a("Members"),count:ae.length,children:ae.map(ne=>i.jsx(IS,{avatar:i.jsx(sn,{bot:ne}),title:ne.name,preview:ne.title||ne.scope,onRestore:()=>{Gt(ne,!1)}},ne.id))})]})]})}),i.jsx(ms,{open:A!==null,onOpenChange:ne=>!ne&&I(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;I(null),ne&&window.electronAPI.bots.deleteChat(ne.id).then(ie=>{ie.ok?(ze===ne.id&&y(null),ue.getState().refreshChats()):Fe({type:"error",title:Ns(ie.error,a)})})}}),i.jsx(EJ,{chat:E,onOpenChange:ne=>!ne&&D(null)})]})}function Rh({count:e,className:t}){return i.jsx("span",{className:W("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 DS({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 IS({avatar:e,title:t,preview:n,onOpen:s,onRestore:o,onDelete:r}){const{t:a}=J(),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(Bl,{className:"h-3.5 w-3.5"})}),r&&i.jsx("button",{type:"button",className:W(l,"hover:text-destructive"),onClick:r,title:a("Delete"),children:i.jsx(Bs,{className:"h-3.5 w-3.5"})})]})}function Xp({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(us,{className:"h-3.5 w-3.5"})})]})}function Zp({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:W("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(Rh,{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 Jp({chat:e,children:t,onPin:n,onArchive:s,onDelete:o,onArchiveMember:r,onClone:a,manage:l}){const{t:d}=J(),c=u=>l?.onSnooze(NL(Date.now())[u]);return i.jsxs(ho,{children:[i.jsx(po,{render:t}),i.jsxs(fo,{className:"min-w-40",children:[n&&i.jsxs(Yt,{onClick:n,children:[e?.pinned?i.jsx(yu,{}):i.jsx(di,{}),e?.pinned?d("Unpin"):d("Pin")]}),l?.onMoveUp&&i.jsxs(Yt,{onClick:l.onMoveUp,children:[i.jsx(cd,{}),d("Move up")]}),l?.onMoveDown&&i.jsxs(Yt,{onClick:l.onMoveDown,children:[i.jsx(Yu,{}),d("Move down")]}),l&&i.jsxs(Yt,{onClick:l.onSettle,children:[e?.settledAt!==void 0?i.jsx(ia,{}):i.jsx(wg,{}),e?.settledAt!==void 0?d("Back to in progress"):d("Settle")]}),l&&i.jsxs(Bj,{children:[i.jsxs($j,{children:[i.jsx(eV,{}),d("Remind me later")]}),i.jsxs(Vj,{className:"min-w-36",children:[i.jsx(Yt,{onClick:()=>c("hour"),children:d("In 1 hour")}),i.jsx(Yt,{onClick:()=>c("later"),children:d("In 3 hours")}),i.jsx(Yt,{onClick:()=>c("tomorrow"),children:d("Tomorrow 9:00")})]})]}),l?.onMarkUnread&&i.jsxs(Yt,{onClick:l.onMarkUnread,children:[i.jsx(C6,{}),d("Mark as unread")]}),a&&i.jsxs(Yt,{onClick:a,children:[i.jsx(Uu,{}),d("Clone group chat")]}),s&&i.jsxs(Yt,{onClick:s,children:[i.jsx(Ai,{}),d("Archive chat")]}),r&&i.jsxs(Yt,{onClick:r,children:[i.jsx(Bl,{}),d("Archive member")]}),o&&i.jsxs(i.Fragment,{children:[i.jsx(Mg,{}),i.jsxs(Yt,{variant:"destructive",onClick:o,children:[i.jsx(Bs,{}),d("Delete group chat")]})]})]})]})}const AJ=30;function ES({onPick:e}){const{t,locale:n}=J(),s=n==="zh"?"zh":"en",o=Wj(),r=ue(_=>_.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:C,name:N,title:S,scope:k})=>({id:C,name:N,title:S,scope:k}))}:{},templates:o.slice(0,AJ).map(({id:C,data:N})=>({id:C,title:N.title,summary:N.summary}))});if(!_.ok){h(Ah(_,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(fe,{size:"sm",disabled:!a.trim()||d,onClick:()=>{v()},children:[d?i.jsx(Zt,{className:"animate-spin"}):i.jsx(Hs,{}),t("Recommend")]})})]});const b=p.kind==="team"?o.find(_=>_.id===p.templateId)?.data:void 0,w=p.kind==="existing"?r.find(_=>_.id===p.botId):p.kind==="member"?{...p.member,avatar:{color:tr[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(Ta,{className:"h-3.5 w-3.5"}),p.kind==="team"?t("Recommended: a team"):t("Recommended: one member")]}),w?i.jsxs("div",{className:"flex items-start gap-2.5",children:[i.jsx(sn,{bot:w}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("p",{className:"font-medium text-sm",children:[w.name,i.jsx("span",{className:"ml-2 font-normal text-muted-foreground text-xs",children:w.title})]}),w.scope&&i.jsx("p",{className:"text-muted-foreground text-xs",children:w.scope})]})]}):b&&i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"-space-x-1.5 flex",children:b.members.map(_=>i.jsx(sn,{size:"sm",bot:{name:_.name,avatar:{color:_.color}}},_.key))}),i.jsx("p",{className:"font-medium text-sm",children:b.title}),i.jsx("p",{className:"text-muted-foreground text-xs",children:b.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(fe,{size:"sm",variant:"ghost",disabled:d,onClick:()=>{f(null),h(null)},children:[i.jsx(dd,{}),t("Back")]}),i.jsxs("div",{className:"flex gap-2",children:[p.kind==="existing"&&i.jsx(fe,{size:"sm",variant:"outline",disabled:d,onClick:()=>{y({firstMessage:g})},children:t("Create new instead")}),i.jsx(fe,{size:"sm",disabled:d||p.kind==="existing"&&!w,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 nc=e=>({...JD,name:"",title:"",scope:"",persona:"",color:e,engine:null});function MJ({open:e,onOpenChange:t,seed:n,onCreated:s}){const{t:o}=J(),r=ue(D=>D.bots),a=DL(),l=m.useRef(null),[d,c]=m.useState({kind:"template",id:"pm"}),[u,h]=m.useState(()=>nc(tr[0])),[p,f]=m.useState(null),[g,x]=m.useState(null),[v,y]=m.useState(!1),[b,w]=m.useState(!1),[_,C]=m.useState(!1),N=()=>{c({kind:"blank"}),h(nc(tr[r.length%tr.length])),f(null),x(null)},S=D=>{if(!D)return N();const T=IL(D.data);c({kind:"template",id:D.id}),h({...JD,name:T.name??"",title:T.title??"",scope:T.scope??"",persona:T.persona??"",color:T.avatar?.color??tr[0],engine:null,approvalMode:T.approvalMode??"auto-edits",tools:T.tools??"all"}),f(null),x(null)};m.useEffect(()=>{e&&(n?(c({kind:"blank"}),h({...nc(tr[r.length%tr.length]),...n}),f(null),x(null)):S(a[0]),y(!1),w(!1),C(!1))},[e]);const k=D=>{h(T=>({...T,...D})),x(null)},A=async D=>{const T=new Uint8Array(await D.arrayBuffer()),H=KD(T)==="png",F=H?MX(gS(T,"chara")??gS(T,"ccv3")??""):new TextDecoder().decode(T),O=F?GX(F):{ok:!1,error:"not-a-card"};if(!O.ok){x(O.error==="invalid-json"&&!H?o("This file is not valid JSON."):o("This file is not a SillyTavern character card."));return}const{color:B,memoryEnabled:Y,...U}=O.draft;c({kind:"import"}),h({...nc(B??u.color),...U,...Y!==void 0?{memoryEnabled:Y}:{}}),f(H?await jj(D).catch(()=>null):null),y(!0),x(null)},I=_g(u.name,r,o),E=async()=>{if(y(!0),I)return;const D=XD(u);if(!D.ok){x(o("Budget must be a positive number"));return}const T=av(u);if(!T.ok){x(o("Check the per-turn token limit and delegation time limit"));return}w(!0);try{const H=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(!H.ok){x(ol(H.reason,H.error,o));return}ue.getState().upsertBot(H.bot),p&&!await kj(H.bot.id,p)&&Fe({type:"error",title:o("Avatar update failed")}),t(!1);const F=await ue.getState().openDirect(H.bot.id);F&&s?.(F)}finally{w(!1)}};return i.jsx(vn,{open:e,onOpenChange:t,children:i.jsxs(bn,{className:"max-h-[85vh] max-w-3xl",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:o("New member")}),i.jsx(As,{children:o("Members have their own persona, model, tools and memory. Their name is how you @ them in groups.")})]}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsx(fe,{size:"sm",variant:d.kind==="template"?"default":"outline",disabled:a.length===0,onClick:()=>S(a[0]),children:o("From template")}),i.jsx(fe,{size:"sm",variant:d.kind==="blank"?"default":"outline",onClick:N,children:o("Blank")}),i.jsxs(fe,{size:"sm",variant:d.kind==="import"?"default":"outline",onClick:()=>l.current?.click(),children:[i.jsx(Cg,{}),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:()=>S(D),className:W("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(sn,{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(us,{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(Xt,{hint:o("Used for @ in groups; must be unique"),children:o("Name")}),i.jsx(Jt,{value:u.name,onChange:D=>k({name:D.target.value}),onBlur:()=>y(!0)}),v&&I&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:I})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:o("Title")}),i.jsx(Jt,{value:u.title,onChange:D=>k({title:D.target.value})})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:o("Model")}),i.jsx(Cj,{engine:u.engine,onChange:D=>k({engine:D}),zIndex:kn.DROPDOWN_IN_MODAL})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:o("Avatar color")}),i.jsxs("div",{className:"flex items-start gap-2.5",children:[i.jsx(sn,{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(Sj,{value:u.color,onChange:D=>k({color:D})}),i.jsx(ZD,{nested:!0,hasImage:!!p,onPick:f,onRemove:()=>f(null)})]})]})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(Xt,{hint:o("Used for routing and the delegation directory"),children:o("Responsibilities")}),i.jsx(Jt,{value:u.scope,onChange:D=>k({scope:D.target.value})})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(Xt,{action:i.jsx(sI,{value:u,onApply:k}),children:o("Persona")}),i.jsx(ei,{rows:4,value:u.persona,onChange:D=>k({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:()=>C(D=>!D),children:[i.jsx(un,{className:W("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(QD,{value:u,onChange:k,profile:u,zIndex:kn.DROPDOWN_IN_MODAL})})]})]}),g&&i.jsx("p",{className:"text-destructive text-sm",children:g})]}),i.jsxs(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),i.jsxs(fe,{size:"sm",disabled:b||v&&!!I,onClick:()=>{E()},children:[b&&i.jsx(Zt,{className:"animate-spin"}),o("Create and start chatting")]})]})]})})}function AI({projectId:e,onChange:t}){const{t:n}=J(),s=Se(p=>p.projects),o=Se(p=>p.addProject),r=m.useMemo(()=>Ju(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:Uj(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){Fe({type:"error",title:n("Failed to add project"),description:g instanceof Error&&g.message||void 0})}};return i.jsxs(fv,{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(mv,{placeholder:n("Search Code projects or recent folders..."),showClear:!!d,showTrigger:!0})}),i.jsx(fe,{type:"button",variant:"outline",onClick:()=>{window.electronAPI.dialog.selectDirectory().then(p=>{p&&h(p)})},children:n("Browse")})]}),i.jsxs(SI,{zIndex:kn.DROPDOWN_IN_MODAL,children:[i.jsx(xv,{children:n("No matching projects found")}),i.jsx(vv,{children:p=>i.jsxs(gv,{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 RJ({open:e,onOpenChange:t}){const{t:n}=J(),s=ue(E=>E.bots),o=m.useMemo(()=>s.filter(E=>E.archivedAt===void 0),[s]),r=Ju(Se(E=>E.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(Tr.maxHops)),[b,w]=m.useState(String(Tr.maxTurnsPerBot)),[_,C]=m.useState(!1),[N,S]=m.useState(null);m.useEffect(()=>{e&&(l(""),c([]),h(null),f(r.length>0?"project":"chat-home"),x(r[0]?.id??""),y(String(Tr.maxHops)),w(String(Tr.maxTurnsPerBot)),C(!1),S(null))},[e]);const k=(E,D)=>{const T=D?[...d,E]:d.filter(H=>H!==E);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),I=async()=>{if(A){C(!0);try{const E=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))||Tr.maxHops,maxTurnsPerBot:Math.round(Number(b))||Tr.maxTurnsPerBot}});if(!E.ok){S(Ns(E.error,n));return}const D=ue.getState();D.upsertChat(E.chat),D.setView({kind:"chat",chatId:E.chat.id}),D.loadLatest(E.chat.id),t(!1)}finally{C(!1)}}};return i.jsx(vn,{open:e,onOpenChange:t,children:i.jsxs(bn,{className:"max-h-[85vh] max-w-xl",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:n("New group chat")}),i.jsx(As,{children:n("One member replies at a time. Without @, the best-fit member is picked to reply.")})]}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Xt,{children:n("Group name")}),i.jsx(Jt,{value:a,onChange:E=>l(E.target.value)})]}),i.jsxs("div",{children:[i.jsx(Xt,{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(E=>{const D=d.includes(E.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(hd,{checked:D,onCheckedChange:T=>k(E.id,T===!0)}),i.jsx(sn,{bot:E,size:"sm"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-sm",children:[E.name,E.title&&i.jsx("span",{className:"ml-1.5 text-muted-foreground text-xs",children:E.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===E.id,onChange:()=>h(E.id),className:"accent-primary"}),n("Owner")]})]},E.id)})})]}),i.jsxs("div",{children:[i.jsx(Xt,{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:W("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:W("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(AI,{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(nh,{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(Xt,{children:n("@ relay limit (per message of yours)")}),i.jsx(Jt,{type:"number",min:1,max:20,value:v,onChange:E=>y(E.target.value)})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:n("Max replies per member")}),i.jsx(Jt,{type:"number",min:1,max:10,value:b,onChange:E=>w(E.target.value)})]})]}),N&&i.jsx("p",{className:"text-destructive text-sm",children:N})]}),i.jsxs(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsxs(fe,{size:"sm",disabled:!A||_,onClick:()=>{I()},children:[_&&i.jsx(Zt,{className:"animate-spin"}),n("Create")]})]})]})})}const PS={skillIds:[],mcpServerIds:[]};function LJ({open:e,onOpenChange:t,seedTemplateId:n,onCreated:s}){const{t:o,locale:r}=J(),a=ue(Q=>Q.bots),l=Wj(),d=Ju(Se(Q=>Q.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),[b,w]=m.useState(null),[_,C]=m.useState({}),[N,S]=m.useState(null),[k,A]=m.useState(!1);m.useEffect(()=>{if(!e)return;h(null),x(d[0]?.id??""),y(!1),w(null),C({}),S(null);const Q=l.find(V=>V.id===n);Q&&I({team:b0(Q.data)})},[e]);const I=async Q=>{y(!0),w(null);try{const V=await window.electronAPI.bots.previewTeam(Q);if(!V.ok){w(EL(V.error,o));return}h({team:V.team,renamed:V.renamed,picked:V.team.members.map(ce=>ce.key)}),C({}),S(null),f(V.team.workspace==="project"&&d.length>0?"project":"chat-home")}finally{y(!1)}},E=Q=>h(V=>V&&{...V,team:Q(V.team)}),D=(Q,V)=>E(ce=>({...ce,members:ce.members.map(ve=>ve.key===Q?{...ve,...V}:ve)})),T=m.useMemo(()=>u?PL(u.team,u.picked):null,[u]),H=m.useMemo(()=>{const Q=new Map;if(!T)return Q;const V=[...a,...T.members.map(ce=>({id:`team:${ce.key}`,name:ce.name}))];for(const ce of T.members){const ve=_g(ce.name,V,o,`team:${ce.key}`);ve&&Q.set(ce.key,ve)}return Q},[T,a,o]),F=T!==null&&H.size===0&&(p==="chat-home"||!!g)&&!v&&!k,O=Q=>_[Q]??PS,B=(Q,V)=>C(ce=>({...ce,[Q]:{...ce[Q]??PS,...V}})),Y=async()=>{if(T){A(!0);try{const Q=r==="zh"?"zh":"en",V=await Promise.all(T.members.map(async $=>{try{const z=await window.electronAPI.bots.suggestAbilities({name:$.name,title:$.title,scope:$.scope,persona:$.persona,language:Q});return{key:$.key,result:z}}catch{return{key:$.key,result:null}}}));let ce=0,ve=0,_e;const De={..._},me=new Map;for(const{key:$,result:z}of V){if(!z?.ok){ve++,z&&!_e&&(_e=Ah(z,o));continue}const{suggestion:de}=z,X={};de.tools&&(X.tools=de.tools.value),de.approvalMode&&(X.approvalMode=de.approvalMode.value),Object.keys(X).length>0&&me.set($,X);const oe=de.skillIds?.value??O($).skillIds,Z=de.mcpServerIds?.value??O($).mcpServerIds;De[$]={skillIds:[...oe],mcpServerIds:[...Z]},(oe.length+Z.length>0||me.has($))&&ce++}C(De),me.size>0&&E($=>({...$,members:$.members.map(z=>({...z,...me.get(z.key)}))})),ve>0&&Fe({type:"error",title:o("Suggestions failed for {{n}} members",{n:ve}),..._e?{description:_e}:{}}),ve<V.length&&Fe({type:ce>0?"success":"info",title:ce>0?o("Configured abilities for {{n}} members",{n:ce}):o("Current abilities already match the suggestion.")})}finally{A(!1)}}},U=async()=>{if(!(!T||!F)){y(!0),w(null);try{const Q=Object.fromEntries(T.members.map(ve=>[ve.key,O(ve.key)]).filter(([,ve])=>ve.skillIds.length+ve.mcpServerIds.length>0)),V=await window.electronAPI.bots.createTeam({team:{...T,title:T.title.trim()},workspace:p==="project"?{kind:"project",projectId:g}:{kind:"chat-home"},...Object.keys(Q).length>0?{assets:Q}:{}});if(!V.ok){w(ol(V.error,Ns(V.error,o),o));return}const ce=ue.getState();for(const ve of V.bots)ce.upsertBot(ve);ce.upsertChat(V.chat),ce.setView({kind:"chat",chatId:V.chat.id}),ce.loadLatest(V.chat.id),t(!1),s?.(V.chat.id)}finally{y(!1)}}},ee=r==="zh"?"zh":"en",L=Q=>u?.team.members.find(V=>V.key===Q)?.name??Q;return i.jsx(vn,{open:e,onOpenChange:t,children:i.jsxs(bn,{className:"max-h-[85vh] max-w-2xl",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:o("Create team from template")}),i.jsx(As,{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(Mn,{className:"space-y-4",children:[u?i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx(Xt,{children:o("Group name")}),i.jsx(Jt,{value:u.team.title,onChange:Q=>{const V=Q.target.value;E(ce=>({...ce,title:V}))}})]}),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(fe,{size:"xs",variant:"outline",disabled:!T||k||v,onClick:()=>{Y()},children:[k?i.jsx(Zt,{className:"animate-spin"}):i.jsx(Hs,{}),o("AI auto-configure")]})]}),i.jsx("div",{className:"space-y-1.5",children:u.team.members.map(Q=>{const V=u.picked.includes(Q.key),ce=Q.key===u.team.bossKey,ve=u.renamed.find(de=>de.key===Q.key),_e=V?H.get(Q.key):void 0,De=Q.delegation.canDelegateTo,me=De==="any"?[]:De.filter(de=>u.picked.includes(de)),$=O(Q.key),z=V&&N===Q.key;return i.jsxs("div",{className:W("flex items-start gap-2.5 rounded-lg border px-2.5 py-2",!V&&"opacity-60"),children:[i.jsx(hd,{className:"mt-1.5",checked:V,disabled:ce,onCheckedChange:de=>h({...u,picked:de===!0?[...u.picked,Q.key]:u.picked.filter(X=>X!==Q.key)})}),i.jsx(sn,{bot:Q,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(Jt,{className:"h-7 w-36",value:Q.name,disabled:!V,onChange:de=>{const X=de.target.value;E(oe=>({...oe,members:oe.members.map(Z=>Z.key===Q.key?{...Z,name:X}:Z)}))}}),i.jsx("span",{className:"truncate text-muted-foreground text-xs",children:Q.title}),ce&&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(Ej,{className:"h-3 w-3"}),o("Owner")]})]}),i.jsx("p",{className:"text-muted-foreground text-xs",children:Q.scope}),ve&&ve.to===Q.name&&i.jsx("p",{className:"text-warning text-xs",children:o('"{{from}}" is taken, renamed to "{{to}}"',ve)}),_e&&i.jsx("p",{className:"text-destructive text-xs",children:_e}),i.jsxs("button",{type:"button",disabled:!V,onClick:()=>S(z?null:Q.key),className:"flex items-start gap-1 text-left text-[11px] text-muted-foreground hover:text-foreground disabled:pointer-events-none",children:[z?i.jsx($n,{className:"mt-px h-3 w-3 shrink-0"}):i.jsx(un,{className:"mt-px h-3 w-3 shrink-0"}),i.jsxs("span",{children:[Q.tools==="readonly"?o("Read-only"):o("All tools")," · ",o(Ml[Q.approvalMode].labelKey),me.length>0&&` · ${o("Delegates to {{names}}",{names:me.map(L).join(ee==="zh"?"、":", ")})}`," · ",$.skillIds.length+$.mcpServerIds.length===0?o("No skills or MCP"):o("{{n}} skills · {{m}} MCP",{n:$.skillIds.length,m:$.mcpServerIds.length})]})]}),z&&i.jsxs("div",{className:"space-y-3 rounded-lg bg-muted/40 p-2.5",children:[i.jsxs("div",{children:[i.jsx(Xt,{children:o("Tools")}),i.jsx(kg,{value:Q.tools,options:[{value:"all",label:o("All tools")},{value:"readonly",label:o("Read-only")}],onChange:de=>D(Q.key,{tools:de})})]}),i.jsxs("div",{children:[i.jsx(Xt,{children:o("Approval mode")}),i.jsx(wj,{value:Q.approvalMode,onChange:de=>D(Q.key,{approvalMode:de}),zIndex:kn.DROPDOWN_IN_MODAL})]}),i.jsx(w0,{label:o("Can delegate to"),value:Q.delegation.canDelegateTo,options:u.picked.filter(de=>de!==Q.key),nameOf:L,onChange:de=>D(Q.key,{delegation:{...Q.delegation,canDelegateTo:de}})}),i.jsx(w0,{label:o("Accepts delegation from"),value:Q.delegation.acceptFrom,options:u.picked.filter(de=>de!==Q.key),nameOf:L,onChange:de=>D(Q.key,{delegation:{...Q.delegation,acceptFrom:de}})}),i.jsx(eI,{value:$,onChange:de=>B(Q.key,de)})]})]})]},Q.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(Xt,{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:W("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:W("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(AI,{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(nh,{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:Q,data:V})=>i.jsxs("button",{type:"button",disabled:v,onClick:()=>{I({team:b0(V)})},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:V.members.map(ce=>i.jsx(sn,{size:"sm",bot:{name:ce.name,avatar:{color:ce.color}}},ce.key))}),i.jsx("span",{className:"font-medium text-sm",children:V.title}),i.jsx("span",{className:"text-muted-foreground text-xs",children:V.summary})]},Q))}),i.jsxs(fe,{size:"sm",variant:"outline",disabled:v,onClick:()=>c.current?.click(),children:[i.jsx(Cg,{}),o("Import team (JSON)")]}),i.jsx("input",{ref:c,type:"file",accept:".json,application/json",hidden:!0,onChange:Q=>{const V=Q.target.files?.[0];Q.target.value="",V&&V.text().then(ce=>I({text:ce}))}})]}),b&&i.jsx("p",{className:"text-destructive text-sm",children:b})]}),i.jsxs(rs,{children:[u&&i.jsxs(fe,{variant:"ghost",size:"sm",className:"mr-auto",onClick:()=>{h(null),w(null)},children:[i.jsx(dd,{}),o("Back")]}),i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),u&&i.jsxs(fe,{size:"sm",disabled:!F,onClick:()=>{U()},children:[v&&i.jsx(Zt,{className:"animate-spin"}),o("Create team")]})]})]})})}const _o="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function OJ({sidebarWidth:e,collapsed:t,onToggleCollapse:n,onResize:s}){const o=sh()==="mobile",{t:r}=J(),a=ue(T=>T.view),l=ue(T=>T.chats),d=ue(T=>T.bots),c=ue(T=>T.loaded),u=ue(T=>T.setView),[h,p]=m.useState(!1),[f,g]=m.useState(!1),[x,v]=m.useState(!1),[y,b]=m.useState(!1),[w,_]=m.useState(null),C=m.useRef(""),N=Ag(),S=a?.kind==="chat"?l.find(T=>T.id===a.chatId):void 0,k=S?.kind==="group"?H4(l,S):void 0;m.useEffect(()=>{c&&a?.kind==="chat"&&!S&&u(null)},[c,a,S,u]);const A=async T=>{if(T.botId){const H=ue.getState();if(!H.bots.some(O=>O.id===T.botId))throw new Error("Member not found");const F=await H.openDirect(T.botId);if(!F)throw new Error("Could not open chat");y0(F,T.firstMessage.trim()),b(!1);return}b(!1),_(T),C.current=T.firstMessage.trim(),T.templateId?v(!0):p(!0)},I=T=>{C.current&&y0(T,C.current),C.current=""},E=()=>{_(null),C.current="",p(!0)},D=()=>{_(null),C.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(PI,{className:_o}),i.jsx("button",{type:"button",className:_o,onClick:()=>b(!0),title:r("Start from a goal"),children:i.jsx(Ta,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:_o,onClick:E,title:r("New member"),children:i.jsx($l,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:_o,onClick:()=>g(!0),title:r("New group chat"),children:i.jsx(la,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:_o,onClick:D,title:r("Create team from template"),children:i.jsx(Pf,{className:"h-4 w-4"})}),(N>0||a?.kind==="inbox")&&i.jsxs("button",{type:"button",className:W(_o,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(Ix,{className:"h-4 w-4"}),N>0&&i.jsx(Rh,{count:N,className:"-top-0.5 -right-1 absolute"})]}),i.jsx("div",{className:"flex-1"}),i.jsx("button",{type:"button",className:_o,onClick:()=>{window.electronAPI.window.openSettings()},title:r("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})}),o&&i.jsx("button",{type:"button",className:_o,onClick:n,title:r("Expand sidebar"),children:i.jsx(TN,{className:"h-4 w-4"})})]}):i.jsxs(i.Fragment,{children:[i.jsx(PJ,{width:e,onCollapse:o?n:void 0,onNewMember:E,onNewGroup:()=>g(!0),onNewTeam:D,onStartFromGoal:()=>b(!0)}),i.jsx(Cu,{onResize:s})]}),a?.kind==="inbox"?i.jsx(oJ,{}):S?i.jsx(JZ,{chat:k??S,group:S},k?.id??S.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(Vs,{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(ES,{onPick:A}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(fe,{size:"sm",variant:d.length===0?"outline":"default",onClick:E,children:[i.jsx($l,{}),r("New member")]}),d.length>=2&&i.jsxs(fe,{size:"sm",variant:"outline",onClick:()=>g(!0),children:[i.jsx(la,{}),r("New group chat")]}),i.jsxs(fe,{size:"sm",variant:"outline",onClick:D,children:[i.jsx(Pf,{}),r("Create team from template")]})]})]}),i.jsx(MJ,{open:h,onOpenChange:p,seed:w?.member,onCreated:I}),i.jsx(RJ,{open:f,onOpenChange:g}),i.jsx(IJ,{}),i.jsx(LJ,{open:x,onOpenChange:v,seedTemplateId:w?.templateId,onCreated:I}),i.jsx(vn,{open:y,onOpenChange:b,children:i.jsxs(bn,{className:"max-w-xl",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:r("Start from a goal")}),i.jsx(As,{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(Mn,{className:"flex justify-center pb-4",children:y&&i.jsx(ES,{onPick:A})})]})})]})}const AS="enso-mode",co=bg()(e=>({mode:localStorage.getItem(AS)==="bot"?"bot":"code",setMode:t=>{localStorage.setItem(AS,t),e({mode:t})}}));function sc(){return Se.getState().botModeEnabled&&is.getState().activeNodeId==="local"&&co.getState().mode==="bot"}function zJ(){const e=Se(s=>s.botModeEnabled),t=is(s=>s.activeNodeId==="local"),n=co(s=>s.mode);return e&&t&&n==="bot"}async function GJ(e){if(!Se.getState().botModeEnabled)return;const t=typeof e.chatId=="string"?e.chatId:void 0,n=typeof e.conversationId=="string"?e.conversationId:void 0,s=ue.getState();t||await s.refreshDelegations(),is.getState().activeNodeId!=="local"&&is.getState().switchNode("local"),co.getState().setMode("bot");const o=AL({chatId:t,conversationId:n},ue.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 MI(){is.getState().activeNodeId!=="local"&&is.getState().switchNode("local"),co.getState().setMode("code")}const Ga=[{value:"code",label:"Code",Icon:Fo},{value:"bot",label:"Bot",Icon:ML}],FJ={ArrowLeft:-1,ArrowUp:-1,ArrowRight:1,ArrowDown:1},HJ={duration:.26,ease:[.22,1,.36,1]},BJ={duration:.5,ease:[.34,1.36,.64,1]},$J={duration:.18,ease:[.4,0,.2,1]};function VJ({className:e}){const{t}=J(),n=co(h=>h.mode),s=co(h=>h.setMode),o=Ag(),r=Li(Se(h=>h.keybindings))["toggle-app-mode"],a=r?`${t("Switch between Code and Bot")} (${mi(r)})`:void 0,l=J$()??!1,d=m.useId(),c=m.useRef({}),u=h=>{const p=FJ[h.key];if(!p)return;h.preventDefault();const f=Ga.findIndex(x=>x.value===n),g=Ga[(f+p+Ga.length)%Ga.length].value;s(g),c.current[g]?.focus()};return i.jsx("div",{role:"radiogroup","aria-label":t("Switch mode"),onKeyDown:u,className:W("flex h-7 shrink-0 rounded-lg bg-muted/60 p-0.5 text-xs",e),children:Ga.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:W("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(Rs.span,{layoutId:d,"aria-hidden":!0,className:"absolute inset-0 rounded-md bg-background shadow-xs",transition:l?{duration:0}:ea}),i.jsx(f,{className:"relative h-3.5 w-3.5"}),i.jsx("span",{className:"relative",children:p}),i.jsx(fl,{children:x&&i.jsx(Rs.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:HJ,children:i.jsx(Rs.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:$J},transition:BJ,children:i.jsx(Rh,{count:o,className:"block"})})})})]},h)})})}const Ql="enso:open-chat-find";let Vm;function RI(e){Vm=e,window.dispatchEvent(new Event(Ql))}function MS(){const e=Vm;return Vm=void 0,e}function WJ({query:e,onQueryChange:t,current:n,total:s,onPrev:o,onNext:r,onClose:a}){const{t:l}=J(),d=m.useRef(null);return m.useEffect(()=>{const c=()=>{d.current?.focus(),d.current?.select()};return c(),window.addEventListener(Ql,c),()=>window.removeEventListener(Ql,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(Jt,{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(fe,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:o,"aria-label":l("Previous match"),children:i.jsx(Kj,{className:"h-3.5 w-3.5"})}),i.jsx(fe,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:r,"aria-label":l("Next match"),children:i.jsx($n,{className:"h-3.5 w-3.5"})}),i.jsx(fe,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a,children:i.jsx(ln,{className:"h-3.5 w-3.5"})})]})}function UJ(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&&OL(e.child,s.child)}function KJ({request:e,conversationId:t}){const{t:n}=J(),s=se(l=>l.conversations[t]),o=RL({onDone:()=>{zL()}}),r=e.host,a=UJ(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(LL,{flow:o,providerLabel:r.providerLabel})]})}function qJ(e){const{t}=J(),n=e?.startsWith("bot:")?e.slice(4):void 0,s=ue(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=fj(l)?.candidates.find(c=>c.typeKey===e);a&&r(d?.displayName)}).catch(()=>{}),()=>{a=!1}},[e,n,s]),!!n)return s??o??t("Member")}function YJ(e,t){return e?null:t?"empty":"hydrating"}function XJ(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 ZJ(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:Rg(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:qj(n)}}function JJ(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt}function QJ(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:JJ(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 eQ(e){return JSON.stringify(e)}let Xi=null;function bv(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=QJ(o,Rg({status:o.status??"idle",spawning:o.spawning,subagents:o.subagents,coworkerIds:o.coworkerIds,backgroundTasks:o.backgroundTasks},e));t[s]=r,n.push(`${s}:${eQ(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 Fa=null;function tQ(e){if(Fa?.source===e)return Fa.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=Fa?.print===n?Fa.value:t;return Fa={source:e,print:n,value:s},s}const nQ=[],RS=new WeakMap;function sQ(e,t){const n=e[t];if(!n)return nQ;const s=RS.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 RS.set(n,{source:e,print:r,value:a}),a}function iQ(){const[e,t]=m.useState([]);return m.useEffect(()=>{let n=!0;const s=window.electronAPI.elevation.onChanged(o=>t(o));return window.electronAPI.elevation.pending().then(o=>{n&&t(o)}),()=>{n=!1,s()}},[]),e}function oQ(){const e=iQ(),t=e[0];return t?i.jsx(rQ,{request:t,total:e.length},t.id):null}function rQ({request:e,total:t}){const{t:n}=J(),[s,o]=m.useState(""),[r,a]=m.useState(!1),l=Mx(e.expiresAt),d=r||l!==void 0&&l<=0,c=u=>{a(!0),o(""),window.electronAPI.elevation.answer(e.id,u)};return i.jsxs("form",{"data-enso":"approval",className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",onSubmit:u=>{u.preventDefault(),s&&!d&&c(s)},children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx(GL,{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:n("Run as administrator")}),i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[i.jsx(Rx,{remainingMs:l,expiredLabel:"Timed out · denied"}),t>1&&i.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["1/",t]})]})]}),i.jsx("pre",{className:"mt-1.5 max-h-24 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted/60 px-2 py-1.5 font-mono text-xs",children:e.command}),i.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[i.jsx("input",{type:"password",autoFocus:!0,autoComplete:"off",value:s,disabled:d,placeholder:n("Login password"),"aria-invalid":e.retry||void 0,onChange:u=>o(u.currentTarget.value),className:W("h-7 min-w-0 flex-1 rounded-md border bg-background px-2 text-xs outline-none focus-visible:border-ring",e.retry?"border-destructive/60":"border-border/60")}),i.jsx("button",{type:"button",disabled:d,onClick:()=>c(null),className:"rounded-md px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50",children:n("Deny")}),i.jsx("button",{type:"submit",disabled:d||!s,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:n("Allow")})]}),i.jsx("p",{className:W("mt-1 text-[11px]",e.retry?"text-destructive":"text-muted-foreground"),children:e.retry?n("Incorrect password. Try again."):n("Applies to this command only. The password is never shown to the AI.")})]})}function aQ(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 lQ(e,t){const n=Se(r=>r.openChangesOnFileEdit),s=m.useRef(void 0),o=m.useRef(new Set);m.useEffect(()=>{const r=aQ(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&&nj()},[t,n,e])}function Ha(e,t){const n=e.trim().toLowerCase();return n?t.some(s=>s?.toLowerCase().includes(n)):!0}function dQ(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 cQ=[],uQ=[],hQ=typeof window<"u"&&!!window.electronAPI?.remote;function LI({conversationId:e,cwd:t,emptyTitle:n,onSuggestion:s,timelineRef:o}){const r=se(V=>V.conversations[e]?.projectId),a=se(V=>V.conversations[e]?.messages??cQ),l=se(V=>V.conversations[e]?.customEntries??uQ),d=se(V=>V.conversations[e]?.status==="running"),c=se(V=>V.conversations[e]?.compaction),u=se(V=>V.conversations[e]?.compactionNoticeAt),h=se(V=>V.conversations[e]?.occupancy?.compactionTokensAfter),p=se(V=>V.conversations[e]?.historyBaseIndex??0),f=se(V=>V.conversations[e]?.toolOutputs),g=se(V=>V.conversations[e]?.toolStartedAt),x=se(V=>V.conversations[e]?.pendingApprovals),v=se(V=>V.conversations[e]?.runStartedAt),y=se(V=>V.conversations[e]?.lastOutputAt),b=se(V=>V.conversations[e]?.error),w=se(V=>V.conversations[e]?.started===!0),_=se(V=>V.conversations[e]?.sessionFile),C=se(V=>V.conversations[e]?.status),N=se(V=>V.conversations[e]?.spawning===!0),S=se(V=>V.conversations[e]?.historyLoadAttempted),k=se(V=>!!V.conversations[e]?.historyLoading),A=m.useRef({conversationId:"",items:[]}),I=m.useMemo(()=>{A.current.conversationId!==e&&(A.current={conversationId:e,items:[]});const ce=FL(A.current.items,a,d,p)??xr(a,d,l,t,{compaction:c,compactionNoticeAt:u,compactionTokensAfter:h,historyBaseIndex:p,toolOutputs:f,toolStartedAt:g,pendingApprovals:x});return A.current.items=ce,ce},[c,u,h,e,t,l,p,a,x,d,f,g]);lQ(I,e);const E=HL({started:w,sessionFile:_,messages:a,spawning:N,status:C,historyLoadAttempted:S,historyLoading:k}),[D,T]=m.useState(!1),[H,F]=m.useState(""),[O,B]=m.useState(0),Y=m.useMemo(()=>D?dQ(I,H):[],[D,H,I]);m.useEffect(()=>{const V=()=>{const ce=MS();T(!0),ce&&(F(ce),B(0))};return window.addEventListener(Ql,V),()=>window.removeEventListener(Ql,V)},[]),m.useEffect(()=>{const V=MS();if(B(0),V){F(V),T(!0);return}e&&(F(""),T(!1))},[e]),m.useEffect(()=>{if(!D||Y.length===0)return;const V=Math.min(O,Y.length-1);o.current?.scrollToKey(Y[V].key)},[D,O,Y,o]);const U=m.useCallback(V=>{Y.length!==0&&B(ce=>(ce+V+Y.length)%Y.length)},[Y.length]);m.useEffect(()=>{if(!D)return;const V=ce=>{if(ce.key==="Escape"){ce.preventDefault(),T(!1);return}const ve=Pl(ce);ve==="mod+g"?(ce.preventDefault(),U(1)):ve==="mod+shift+g"&&(ce.preventDefault(),U(-1))};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[D,U]);const ee=m.useMemo(()=>r?{conversationId:e,projectId:r,...t?{cwd:t}:{}}:null,[e,t,r]),L=m.useRef(null),Q=m.useCallback(()=>{const V=o.current?.getScroller();L.current=V?{height:V.scrollHeight,top:V.scrollTop}:null,se.getState().loadOlderHistory(e)},[e,o]);return m.useLayoutEffect(()=>{const V=o.current?.getScroller(),ce=L.current;!V||!ce||(L.current=null,V.scrollTop=ce.top+(V.scrollHeight-ce.height))},[p]),i.jsxs(Lg.Provider,{value:ee,children:[D&&i.jsx(WJ,{query:H,onQueryChange:V=>{F(V),B(0)},current:Y.length===0?0:Math.min(O,Y.length-1)+1,total:Y.length,onPrev:()=>U(-1),onNext:()=>U(1),onClose:()=>{T(!1),F("")}}),i.jsx(Nh,{virtualize:!hQ,ref:o,items:I,busy:E!==null,loading:E==="loading",running:d,runStartedAt:v,lastOutputAt:y,error:BL(a,b),emptyTitle:n,onSuggestion:s,onRetryResume:!w&&_&&C==="failed"?()=>{se.getState().resumeConversation(e)}:void 0,historyLoading:k,hasOlder:p>0,olderCursor:p,onStartReached:p>0?Q:void 0,searchQuery:D?H:"",activeHit:D?Y[O]??null:null},e)]})}const pQ=/-([0-9a-f]{8})$/i;function LS(e){const t=e.title?.trim();return t||e.name.replace(pQ,"").trim()||e.name}const fQ={sm:"size-2",md:"size-2.5"},mQ={sm:"h-3 w-3",md:"h-3.5 w-3.5"};function Lh({tone:e,size:t="sm",title:n,className:s,"data-enso":o,"data-status":r}){const{t:a}=J();if(e==="waiting"){const l=a("Waiting for your answer");return i.jsx("span",{role:"img","aria-label":l,title:l,"data-slot":"conversation-status","data-tone":e,"data-enso":o,"data-status":r,className:W("flex shrink-0 items-center text-amber-500",s),children:i.jsx(wV,{className:W(mQ[t],"stroke-[2.5]"),"aria-hidden":!0})})}return i.jsx("span",{"data-slot":"conversation-status","data-tone":e,"data-enso":o,"data-status":r,title:n,className:W("shrink-0 rounded-full",fQ[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 gQ({parentId:e,coworkerIds:t}){const{t:n,locale:s}=J(),o=Se(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=se(y=>y.pendingChildRun),g=m.useCallback(()=>{const y=++h.current;return window.electronAPI.agent.listChildRuns(e).then(b=>{y===h.current&&a(b.ok?b.items:[])})},[e]);m.useEffect(()=>{g()},[g,p]);const x=m.useCallback(y=>{const b=c?.childId;return b?window.electronAPI.agent.readChildRun(e,b,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)){se.getState().selectTab(e,y.childId);return}u(y)}};return m.useEffect(()=>{if(!f||f.parentId!==e)return;const y=r.find(b=>b.childId===f.childId);if(y&&(se.setState({pendingChildRun:null}),!!y.available)){if(d(!1),y.live&&t.includes(y.childId)){se.getState().selectTab(e,y.childId);return}u(y)}},[f,r,e,t]),i.jsxs(i.Fragment,{children:[r.length>0&&i.jsxs(gi,{open:l,onOpenChange:y=>{d(y),y&&g()},children:[i.jsxs(xi,{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($o,{className:"size-3.5"}),i.jsx("span",{className:"text-[11px] tabular-nums leading-none",children:r.length})]}),i.jsx(vi,{align:"end",className:"w-96 [&_[data-slot=popover-viewport]]:p-1",children:i.jsx("ul",{className:"flex flex-col",children:r.map(y=>{const b=LS(y);return i.jsx("li",{children:i.jsxs("button",{type:"button",disabled:!y.available,title:b,className:W("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:b}),y.agentType&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Yj(y.agentType,o)}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:zo(y.startedAt,s)}),y.live&&i.jsx(Lh,{tone:"running",size:"sm",title:n("Running")})]})},y.childId)})})})]}),i.jsx(hv,{conversationId:c?.childId??null,title:c?LS(c):"",read:x,botSession:!1,onClose:()=>u(null)})]})}const xQ=[{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"}],vQ={"/goal":xQ};function bQ(e,t){if(!e)return null;const n=t.trimStart();return n?n.search(/\s/)>=0?null:n:""}function wQ(e,t){if(!e)return[];const n=vQ[e]??[],s=t.trim().toLowerCase();return s?n.filter(o=>o.name.toLowerCase().startsWith(s)||o.aliases.some(r=>r.toLowerCase().startsWith(s))):n}function yQ(e){return e.filter(t=>t.state==="enabled").flatMap(t=>(t.statusItems??[]).filter(n=>n.visible&&n.text.trim().length>0).map(n=>({...n,pluginId:t.id,pluginName:t.name})))}let OI=[];const Wm=new Set;function OS(e){OI=e;for(const t of Wm)t()}function SQ(e){return Wm.add(e),()=>Wm.delete(e)}const zS=()=>OI,CQ={neutral:"text-muted-foreground",accent:"text-primary",success:"text-emerald-600 dark:text-emerald-400",warning:"text-amber-600 dark:text-amber-400",danger:"text-red-600 dark:text-red-400"};function kQ({sessionId:e}){const t=m.useSyncExternalStore(SQ,zS,zS);return t.length===0?null:i.jsx(i.Fragment,{children:t.map(n=>{const s=n.command?Xj().find(a=>a.pluginId===n.pluginId&&a.id===n.command):void 0,o=W("shrink-0 truncate px-1 text-[11px]",CQ[n.tone]),r=n.tooltip?`${n.tooltip} · ${n.pluginName}`:n.pluginName;return s?i.jsx("button",{type:"button",title:r,className:W(o,"rounded hover:bg-accent"),onClick:()=>{Og(s,e).then(a=>{a&&Fe({title:a})})},children:n.text},`${n.pluginId}:${n.id}`):i.jsx("span",{title:r,className:o,children:n.text},`${n.pluginId}:${n.id}`)})})}const zI=50,jQ=64,_Q=120,NQ=32*1024,TQ=120,ic=[];function GS(e){return/(?:^|\s)#([^\s#]*)$/.exec(e)?.[1]??null}function DQ(e,t,n){if(!Array.isArray(n))return[];const s=[];for(const o of n){if(s.length>=zI)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,jQ),...typeof l=="string"&&l?{detail:l.slice(0,_Q)}:{}}})}return s}function IQ(e){const t=typeof e=="string"?e:typeof e=="object"&&e!==null?e.text:null;return typeof t=="string"&&t.length<=NQ?t:null}let GI=[];const Um=new Set;function FS(e){GI=e;for(const t of Um)t()}function EQ(e){return Um.add(e),()=>Um.delete(e)}const HS=()=>GI;function PQ(e,t){const n=m.useSyncExternalStore(EQ,HS,HS),[s,o]=m.useState(ic);return m.useEffect(()=>{if(e===null||n.length===0){o(ic);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?DQ(l,d,c.value):ic})).then(l=>{r||o(l.flat().slice(0,zI))})},TQ);return()=>{r=!0,clearTimeout(a)}},[e,n,t]),e===null?ic:s}async function AQ(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?IQ(n.value):null}const Uc="composer-drop",FI="pinned-drop",wv="project-group:__ungrouped__",Km="project:",qm="project-group:",Kc="selector-group:",Ym="pinned-chat:",HI=e=>`${Km}${e}`,BI=e=>`${qm}${e}`,yv=e=>`${Kc}${e}`,MQ=e=>`chat:${e}`,$I=e=>`${Ym}${e}`,RQ=e=>`active-chat:${e}`;function LQ(e){return e.split(`
|
|
84
|
-
`)[0].trim()||"Untitled chat"}function BS(e){if(e===wv||e===`${Kc}__ungrouped__`)return null;if(e.startsWith(qm)){const t=e.slice(qm.length);return t==="__all__"?void 0:t}if(e.startsWith(Kc)){const t=e.slice(Kc.length);return t==="__all__"?void 0:t}}function OQ(e,t,n,s){if(!t)return null;if(e.type==="project-group"){const o=BS(t);return!o||o===e.groupId?null:{kind:"reorder-groups",activeId:e.groupId,overId:o}}if(e.type==="project"){if(t===Uc)return{kind:"insert-file-mention",path:e.path,label:e.name};const o=BS(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(Km)){const r=t.slice(Km.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===Uc?{kind:"insert-file-mention",path:e.relativePath,label:e.name}:null;if(t===Uc)return!e.sessionFile||e.conversationId===n?null:{kind:"insert-chat-mention",conversationId:e.conversationId,label:LQ(e.title),sessionFile:e.sessionFile};if(t===FI)return e.pinned?null:{kind:"pin-conversation",conversationId:e.conversationId};if(t.startsWith(Ym)){const o=t.slice(Ym.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 $S=200,zQ=Array.from({length:jl},(e,t)=>`bar-${t}`),VS=Dh([],0);function GQ({active:e,disabled:t,onChange:n}){const{t:s}=J(),[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}Gm(),r(!0);try{await QY(),n(!0)}catch(h){l(s(PD(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:Fm,children:o?i.jsx(pr,{className:"h-3.5 w-3.5"}):e?i.jsx($L,{className:"h-3.5 w-3.5"}):i.jsx(pj,{className:"h-3.5 w-3.5"})}),a&&d.current?i.jsx(RD,{anchor:d.current,status:!0,children:a}):null]})}let WS;function FQ({startSession:e,disabled:t,onText:n}){const{t:s}=J(),{phase:o,elapsed:r,error:a,setError:l,partial:d,correcting:c,start:u,finish:h,cancel:p}=AD({startSession:e,onText:n}),[f,g]=m.useState(VS),[x,v]=m.useState(!1),[y,b]=m.useState(!1),w=m.useRef(null);m.useEffect(()=>(clearTimeout(WS),()=>{WS=setTimeout(lS,0)}),[]),m.useEffect(()=>{const S=window.visualViewport;if(!x||!S)return;const k=()=>{w.current&&(w.current.shifted=!0)};return S.addEventListener("resize",k),S.addEventListener("scroll",k),()=>{S.removeEventListener("resize",k),S.removeEventListener("scroll",k)}},[x]);const _=S=>{t||w.current||o!=="idle"||S.pointerType==="mouse"&&S.button!==0||(S.preventDefault(),document.activeElement?.blur(),S.currentTarget.setPointerCapture(S.pointerId),w.current={id:S.pointerId,y:S.clientY,at:performance.now(),shifted:!1},v(!0),b(!1),g(VS),u({context:Gm(),onLevel:k=>g(A=>Dh(A,k))}))},C=(S,k)=>{const A=w.current;if(!A||A.id!==S.pointerId)return;w.current=null,v(!1),b(!1);const I=TD({phase:o,heldMs:performance.now()-A.at,cancelZone:k||!A.shifted&&aS(A.y,S.clientY)});I==="finish"?h():I!=="none"&&p(),lS(),Gm(),I==="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:S=>{const k=w.current;k?.id===S.pointerId&&(k.shifted&&(k.y=S.clientY,k.shifted=!1),b(aS(k.y,S.clientY)))},onPointerUp:S=>C(S,!1),onPointerCancel:S=>C(S,!0),onContextMenu:S=>S.preventDefault(),className:W("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(HQ,{phase:o,cancelling:y,elapsed:r,levels:f,partial:d,correcting:c}):null]})}function HQ({phase:e,cancelling:t,elapsed:n,levels:s,partial:o,correcting:r}){const{t:a}=J(),l=e==="transcribing",d=o.length>$S?`…${o.slice(-$S)}`:o;return Ks.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:W("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(pr,{"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:zQ.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:W("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(ln,{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:W("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 US=e=>e.startsWith("/skill:");function BQ(e,t){return!US(t)||!e.every(US)?[t]:e.includes(t)?[...e]:[...e,t]}function $Q(e){const t=ij(e);if(t.names.length>0)return{slashes:t.names.map(s=>`/skill:${s}`),rest:t.rest};const n=Tu(e);return{slashes:n.slash?[n.slash]:[],rest:n.rest}}function VQ(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=$Q(t.text??"");return{slashes:o.slashes,segments:o.rest?[{type:"text",text:o.rest}]:[],images:[...n?e.images:[],...t.images??[]]}}const WQ={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>'},UQ='<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>',KQ={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 Qp(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=W("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",KQ[e.type]);const n=document.createElement("span");n.className="shrink-0 inline-flex",n.innerHTML=e.type==="file"&&/[\\/]$/.test(e.path)?UQ:WQ[e.type],t.appendChild(n);const s=document.createElement("span");return s.className="truncate",s.textContent=e.type==="file"?e.label??bh(e.path):e.label,t.appendChild(s),t}function VI(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 ef(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=VI(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 tf(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 qQ(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 oc(e){return e instanceof HTMLElement&&!!e.dataset.mentionKind}function tl(e){return e instanceof Text&&!/[^\s\u00a0]/.test(e.textContent??"")}function YQ(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(;tl(u);)u=u.previousSibling;return oc(u)?u:null}if(/[^\s\u00a0]/.test(d.slice(o)))return null;let c=s.nextSibling;for(;tl(c);)c=c.nextSibling;return oc(c)?c:null}const r=s.childNodes;if(t==="before"){let d=o-1;for(;d>=0&&tl(r[d]);)d-=1;const c=d>=0?r[d]:null;return oc(c)?c:null}let a=o;for(;a<r.length&&tl(r[a]);)a+=1;const l=r[a];return oc(l)?l:null}function XQ(e,t){const n=e.nextSibling;tl(n)&&n.remove();const s=e.previousSibling;if(e.remove(),s){WI(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 WI(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.setStartAfter(e),n.collapse(!0),t.removeAllRanges(),t.addRange(n)}const ZQ=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 b=()=>{const w=f.current;if(!w||document.activeElement!==w)return;const _=window.getSelection();if(!_||_.rangeCount===0||!_.isCollapsed)return;const C=_.anchorNode;if(C&&(C===w||w.contains(C))){const k=qQ(w,_);k?(_.removeAllRanges(),_.addRange(k)):C.nodeType===Node.TEXT_NODE&&(g.current={node:C,offset:_.anchorOffset});return}const N=g.current,S=document.createRange();N?.node.isConnected&&w.contains(N.node)?(S.setStart(N.node,Math.min(N.offset,N.node.length)),S.collapse(!0)):(S.selectNodeContents(w),S.collapse(!0)),_.removeAllRanges(),_.addRange(S)};return document.addEventListener("selectionchange",b),()=>document.removeEventListener("selectionchange",b)},[]);const x=m.useCallback(()=>{const b=f.current;if(!b)return;const w=ef(b),_=w.map(E=>E.type==="text"?E.text:"").join(""),C=w.some(E=>E.type!=="text");let N=null,S=null,k=null,A=null;const I=tf(b);if(I){const E=I.node.textContent?.slice(0,I.offset)??"";N=mw(E,E.length),N===null&&(k=zm(E,E.length)),N===null&&k===null&&(A=GS(E)),N===null&&I.node===b.firstChild&&/^\/[^\s]*$/.test(E)&&(S=E.slice(1))}o({plainText:_,hasMentions:C,segments:w,mentionQuery:N,slashQuery:S,skillQuery:k,pluginQuery:A})},[o]),v=m.useCallback(b=>{const w=f.current;if(!w)return null;const _=tf(w);if(!_)return null;const C=_.node.textContent?.slice(0,_.offset)??"";if(b==="#"){const N=GS(C);return N===null?null:{node:_.node,start:C.length-N.length-1,end:_.offset}}if(b==="@"||b==="$"){const N=b==="@"?mw(C,C.length):zm(C,C.length);return N===null?null:{node:_.node,start:C.length-N.length-1,end:_.offset}}return _.node!==w.firstChild||!/^\/[^\s]*$/.test(C)?null:{node:_.node,start:0,end:_.offset}},[]),y=m.useCallback((b,w)=>{const _=f.current;if(!_)return;_.focus();const C=document.createRange(),N=w?v("@"):null;if(N)C.setStart(N.node,N.start),C.setEnd(N.node,N.end),C.deleteContents();else{const A=tf(_);A?(C.setStart(A.node,A.offset),C.collapse(!0)):(C.selectNodeContents(_),C.collapse(!1))}const S=b();C.insertNode(S);const k=document.createTextNode(" ");S.parentNode?.insertBefore(k,S.nextSibling),WI(k),x()},[v,x]);return m.useImperativeHandle(p,()=>({focus:()=>f.current?.focus(),isEmpty:()=>{const b=f.current;return b?!ef(b).some(_=>_.type!=="text"||_.text.trim().length>0):!0},getSegments:()=>f.current?ef(f.current):[],setSegments:b=>{const w=f.current;if(w){w.textContent="";for(const _ of b)_.type==="text"?w.appendChild(document.createTextNode(_.text)):w.appendChild(Qp(_));x()}},clear:()=>{const b=f.current;b&&(b.textContent="",x())},insertMention:b=>{const w=b.kind==="file"?{type:"file",path:b.relativePath}:b.kind==="chat"?{type:"chat",label:b.label,sessionFile:b.sessionFile}:{type:"ui-element",id:b.id,label:b.label,path:b.path,text:b.text,imageId:b.imageId};y(()=>Qp(w),b.kind!=="ui-element")},consumeToken:b=>{const w=v(b);if(!w)return;const _=document.createRange();_.setStart(w.node,w.start),_.setEnd(w.node,w.end),_.deleteContents(),x()},insertFileChip:(b,w)=>{y(()=>Qp({type:"file",path:b,...w?{label:w}:{}}),!1)},insertText:b=>{y(()=>document.createTextNode(b),!1)},getMentionAnchorRect:()=>{const b=v("@");if(!b)return null;const w=document.createRange();return w.setStart(b.node,b.start),w.setEnd(b.node,Math.min(b.start+1,b.node.length)),w.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:b=>{if(!b.nativeEvent.isComposing&&(b.key==="Backspace"||b.key==="Delete")){const w=f.current,_=w&&YQ(w,b.key==="Backspace"?"before":"after");if(_&&w){b.preventDefault(),XQ(_,w),x();return}}r(b)},onClick:b=>{if(!u)return;const w=b.target;if(!(w instanceof Element))return;const _=w.closest("[data-mention-kind]");if(!(_ instanceof HTMLElement)||!f.current?.contains(_))return;const C=VI(_);C&&u(C)},onKeyUp:b=>{b.key!=="Escape"&&x()},onMouseUp:x,onPaste:b=>{if(b.clipboardData.files.length>0){a(b);return}b.preventDefault();const w=b.clipboardData.getData("text/plain");w&&(l?.(w)||document.execCommand("insertText",!1,w))},onCompositionStart:d,onCompositionEnd:()=>{c(),x()},className:W("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)})}),JQ=/[\\/]/;function QQ(e){return e.split(JQ).filter(t=>t.length>0)}function eee(e){const t=new Map,n=e.map(QQ),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 tee({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}=J(),f=m.useMemo(()=>zD(e,t),[e,t]),g=m.useMemo(()=>eee(e.files.map(S=>S.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 b={agents:p("Agents"),members:p("Members"),chats:p("Chats")},w={agents:Vs,members:la,chats:$o},_=o?e[o]:[];let C=0;const N=(S,k)=>{const A=e[S];if(A.length===0)return null;const I=S==="files"?p("Files"):b[S];return i.jsxs("div",{role:"group","aria-label":I,children:[i.jsx("p",{className:W("px-2 pb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",k?"pt-2":"pt-1.5"),children:I}),A.map(E=>{const D=C++;return i.jsx(KS,{ref:T=>{T?x.current.set(D,T):x.current.delete(D)},id:`${c}-option-${D}`,candidate:E,active:D===n,pathLabel:E.kind==="file"?g.get(E.relativePath):void 0,onHover:()=>{s(D),y&&a(null)},onSelect:()=>d(E)},`${S}:${E.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(S=>S.type==="folder").map(S=>{const k=C++,A=w[S.id];return i.jsxs("button",{ref:I=>{I?x.current.set(k,I):x.current.delete(k)},id:`${c}-option-${k}`,type:"button",role:"option","aria-selected":n===k,onClick:()=>{s(k),a(S.id),l(0)},onMouseMove:()=>{s(k),o!==S.id&&(a(S.id),l(0))},className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",n===k&&"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:b[S.id]}),i.jsx(un,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},`folder:${S.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":b[o],"data-slot":"mention-flyout",className:W("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((S,k)=>i.jsx(KS,{ref:A=>{A?v.current.set(k,A):v.current.delete(k)},id:`${c}-sub-${k}`,candidate:S,active:k===r,onHover:()=>l(k),onSelect:()=>d(S)},`sub:${S.id}`))})]})}function KS({ref:e,id:t,candidate:n,active:s,pathLabel:o,onHover:r,onSelect:a}){const{t:l}=J(),d=nee(n),c=n.kind==="agent-type"?n.source==="bot"?la:Vs:n.kind==="chat"?$o:d?Cd:wo;return i.jsxs("button",{ref:e,id:t,type:"button",role:"option","aria-selected":s,onClick:a,onMouseMove:r,className:W("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(aa,{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(aa,{variant:"secondary",className:"px-1 py-0 text-[9px]",children:l("Locked")})]}),i.jsx("span",{className:W("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 nee(e){return e.kind==="file"&&/[\\/]$/.test(e.relativePath)}const qS=new Map,see=()=>!!window.electronAPI?.remote&&window.matchMedia?.("(pointer: coarse)").matches===!0;function Sv({cwd:e,commands:t,running:n,busy:s,focusKey:o,pluginPresetId:r=null,autoFocus:a=!window.electronAPI?.remote,enterToSend:l=!see(),toolbar:d,locked:c=!1,injectedDraft:u,injectedImages:h,injectedDraftAppend:p,onDraftConsumed:f,initialRecipient:g,onInitialRecipientConsumed:x,chatCandidates:v,onActivate:y,onSend:b,onAbort:w,queuedCount:_=0,onSteerQueued:C,isolated:N=!1,placeholder:S,planMode:k=!1,voice:A,requestMicAccess:I,voiceMode:E="click",savePastedText:D}){const{t:T}=J(),H=wa(),[F,O]=m.useState(!1),B=E==="hold"?A:void 0,Y=Se(le=>le.keybindings),U=Se(le=>le.privacyMasking),ee=Li(Y)["send-message"],L=Li(Y)["voice-hold"],Q=m.useId(),[V,ce]=m.useState([]),[ve,_e]=m.useState([]),[De,me]=m.useState(g),$=m.useRef(o),[z,de]=m.useState(!1),{setNodeRef:X,isOver:oe}=vd({id:N?`isolated-composer:${o??"side"}`:Uc,disabled:N}),[Z,ae]=m.useState(null),[be,ze]=m.useState(null),Ye=m.useRef(new Set),Ve=m.useRef(b);Ve.current=b;const at=m.useRef(U);at.current=U,m.useEffect(()=>{if(N)return;const le=nK(ye=>Ze.current?.insertMention(ye)),Te=iK(ye=>Ze.current?.insertText(ye)),Ae=sK(()=>Ze.current?.focus()),Ge=aK((ye,ke)=>{ke&&ce(Me=>[...Me,{...ke,id:ye.imageId}]),Ze.current?.insertMention(ye),Ze.current?.focus()}),Qe=lK(ye=>{ce(ke=>[...ke,{data:ye.data,mimeType:ye.mimeType}]),Ze.current?.focus()}),et=oK(ye=>{if(ne.current)return!1;const ke=at.current,Me=ke.enabled?Qh(ye.text,ke).blocked:[];return Me.length>0?(Fe({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):Ve.current(ye)!==!1});return()=>{le(),Te(),Ae(),Ge(),Qe(),et()}},[N,T]);const Ze=m.useRef(null),Et=m.useRef(null),Gt=m.useRef(null),Pt=m.useRef(!1),ne=m.useRef(c);ne.current=c,m.useEffect(()=>{if(!(N||!o))return VL({key:o,segments:()=>Ze.current?.getSegments()??[],insertText:le=>Ze.current?.insertText(le),setText:le=>Ze.current?.setSegments(le?[{type:"text",text:le}]:[]),busy:()=>Pt.current||ne.current||!Ze.current})},[N,o]);const[ie,He]=m.useState({left:0,flyoutSide:"right"}),[St,it]=m.useState(""),[je,ht]=m.useState(!1),[$t,Oe]=m.useState(null),yt=GD(e,$t,v),Ht=m.useMemo(()=>zD(yt,$t??""),[yt,$t]),[re,$e]=m.useState(null),[st,Nt]=m.useState(null),[mt,K]=m.useState(null),he=PQ(mt,o??null),[Ie,Ee]=m.useState(0),[Be,Je]=m.useState(null),[ge,qe]=m.useState(0),lt=m.useRef(null),Tt=m.useCallback(le=>{(le.plainText.trim()||le.hasMentions)&&y?.(),it(le.plainText),ht(le.hasMentions);const Te=new Set(le.segments.filter(Ge=>Ge.type==="ui-element"&&Ge.imageId).map(Ge=>Ge.type==="ui-element"?Ge.imageId:"")),Ae=[...Ye.current].filter(Ge=>!Te.has(Ge));Ye.current=Te,Ae.length>0&&(ce(Ge=>WL(Ge,Ae)),ae(Ge=>Ge&&Ae.includes(Ge.imageId)?null:Ge)),Oe(Ge=>(Ge!==le.mentionQuery&&(Ee(0),Je(null),qe(0)),le.mentionQuery)),$e(le.slashQuery),Nt(le.skillQuery),K(le.pluginQuery)},[y]);m.useEffect(()=>{const le=$.current;if(le!==o){le&&qS.set(le,{segments:Ze.current?.getSegments()??[],images:V,slashes:ve,recipient:De});const Te=o?qS.get(o):void 0,Ae=o?UL(o):void 0;Ze.current?.setSegments(Ae?[{type:"text",text:Ae}]:Te?.segments??[]),Ye.current=new Set((Te?.segments??[]).filter(Ge=>Ge.type==="ui-element"&&Ge.imageId).map(Ge=>Ge.type==="ui-element"?Ge.imageId:"")),ce(Te?.images??[]),_e(Te?.slashes??[]),me(Te?.recipient),$.current=o,Oe(null),$e(null),Nt(null),Ee(0),Je(null),qe(0)}a&&Ze.current?.focus()},[o]),m.useEffect(()=>{g&&(me(g),x?.())},[g,x]),m.useEffect(()=>{if(!u&&!h?.length)return;const le=VQ({segments:Ze.current?.getSegments()??[],images:V,slashes:ve},{text:u,images:h},p);_e(le.slashes),ce(le.images),Ze.current?.setSegments(le.segments),f?.(),window.setTimeout(()=>Ze.current?.focus(),0)},[u,h,p]);const zt=ve.length===1?ve[0]:null,cn=bQ(zt,St.replaceAll("","")),P=HY(t,re,st),M=re===null&&st===null&&cn!==null?wQ(zt,cn):[];m.useEffect(()=>{Ee(0)},[re,st,cn,mt]),m.useEffect(()=>{lt.current?.children[Ie]?.scrollIntoView({block:"nearest"})},[Ie]);const R=m.useCallback(le=>{if(le.kind==="agent-type"){Ze.current?.consumeToken("@"),me(le),Oe(null);return}Ze.current?.insertMention(le),Oe(null)},[]),j=m.useCallback(le=>{K(null),AQ(le,o??null).then(Te=>{const Ae=Ze.current;Ae&&(Ae.consumeToken("#"),Te&&Ae.insertText(Te))})},[o]),G=$t!==null&&Ht.length>0?"mention":mt!==null&&he.length>0?"plugin":P.length>0?"slash":M.length>0?"slash-sub":null;m.useLayoutEffect(()=>{if(G!=="mention")return;const le=Et.current;if(!le)return;const Te=()=>{const Ae=le.getBoundingClientRect(),Ge=le.querySelector('[data-slot="mention-picker"]'),Qe=Ge?.querySelector('[role="listbox"]'),et=Ge?.querySelector('[data-slot="mention-flyout"]'),ye=Ze.current?.getMentionAnchorRect(),ke=m4({anchorLeft:ye?ye.left-Ae.left:0,containerWidth:Ae.width,popupWidth:Qe instanceof HTMLElement?Qe.offsetWidth:280,flyoutWidth:et instanceof HTMLElement?et.offsetWidth:252,flyoutGap:4});He(Me=>Me.left===ke.left&&Me.flyoutSide===ke.flyoutSide?Me:ke)};return Te(),window.addEventListener("resize",Te),()=>window.removeEventListener("resize",Te)},[$t,St,Be,G]);const pe=G==="mention"?Ht.length:G==="plugin"?he.length:G==="slash-sub"?M.length:P.length,xe=m.useCallback((le,Te)=>{const Ae=[{type:"text",text:le}];if(Ze.current?.setSegments(Ae),!Te)return;const Ge=vw({segments:Ae,slashes:ve,images:V,recipient:De});b(Ge)!==!1&&(Ze.current?.clear(),ce([]),_e([]),me(void 0),Oe(null),$e(null),Nt(null))},[V,b,De,ve]),Pe=m.useCallback(le=>{Ze.current?.consumeToken(st!==null?"$":"/"),$e(null),Nt(null);const Te=KL(le);if(!Te){_e(Ae=>BQ(Ae,le));return}Og(Te,N?null:o??null).then(Ae=>{Ae&&Fe({type:"error",title:T("Plugin command failed"),description:Ae})})},[st,N,o,T]),Ke=m.useCallback((le=!1)=>{if(G==="mention"){if(Be){const Ae=yt[Be][ge];Ae&&R(Ae);return}const Te=Ht[Ie];Te?.type==="item"&&R(Te.candidate)}else if(G==="plugin"){const Te=he[Ie];Te&&j(Te)}else if(G==="slash"){const Te=P[Ie];Te&&Pe(Te.name)}else if(G==="slash-sub"){const Te=M[Ie];if(!Te)return;xe(Te.name,le)}},[Ie,ge,Be,yt,Ht,R,j,he,G,P,Pe,M,xe]),ut=St.replaceAll("","").trim(),nt=!!(ut||ve.length>0||V.length>0||je),Kt=De!==void 0,dt=s&&!Kt,_t={sessionId:N?null:o??null,draft:St.replaceAll("",""),busy:c,pluginPresetId:r},Dt=n&&_>0&&C!==void 0&&l&&!!ee,At=Dt&&!nt&&!Kt&&!c,Ct=m.useMemo(()=>U.enabled&&ut?Qh(ut,U):null,[ut,U]),xt=()=>{if(!nt)return;const le=vw({segments:Ze.current?.getSegments()??[],slashes:ve,images:V,recipient:De}),Te=U.enabled?Qh(le.text,U).blocked:[];if(Te.length>0){Fe({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}b(le)!==!1&&(Ze.current?.clear(),ce([]),_e([]),me(void 0),Oe(null),$e(null),Nt(null))},kt=m.useCallback(le=>{for(const Te of le){if(Te.type.startsWith("image/")){const Qe=new FileReader;Qe.onload=()=>{const et=Qe.result,ye=et.slice(et.indexOf(",")+1);ce(ke=>[...ke,{data:ye,mimeType:Te.type}])},Qe.readAsDataURL(Te);continue}const Ae=window.electronAPI.files.pathForFile(Te),Ge=window.electronAPI.remote;if(!Ae&&Ge){Ge.upload(Te).then(Qe=>{Qe&&Ze.current?.insertFileChip(Qe)}).catch(()=>{});continue}Ae&&Ze.current?.insertFileChip(Ae)}},[]),It=le=>{const Te=le.nativeEvent.isComposing||Pt.current;if(G){const Ge=G==="mention"?Ht[Ie]:void 0,Qe=g4({key:le.key,shiftKey:le.shiftKey,isComposing:Te,activeIndex:Ie,itemCount:pe,folderOpen:G==="mention"&&Be!==null,activeIsFolder:G==="mention"&&Ge?.type==="folder",folderIndex:ge,folderItemCount:Be?yt[Be].length:0});if(Qe.type==="move"){le.preventDefault(),Ee(Qe.index),Je(null);return}if(Qe.type==="move-folder"){le.preventDefault(),qe(Qe.index);return}if(Qe.type==="open-folder"){le.preventDefault(),Ge?.type==="folder"&&Je(Ge.id),qe(0);return}if(Qe.type==="close-folder"){le.preventDefault(),Je(null);return}if(Qe.type==="pick"){le.preventDefault(),Ke(G==="slash-sub"&&le.key==="Enter");return}if(Qe.type==="close"){le.preventDefault(),Oe(null),$e(null),Nt(null),K(null),Je(null);return}}if(Te)return;const Ae=Pl(le);if(!N&&Ae&&Ae===Li(Se.getState().keybindings)["switch-model"]){le.preventDefault(),qL();return}if(le.key==="Backspace"&&ve.length>0&&ut.length===0&&!je){le.preventDefault(),_e(Ge=>Ge.slice(0,-1));return}if(le.key==="Backspace"&&De&&Ze.current?.isEmpty()&&ve.length===0){le.preventDefault(),me(void 0);return}l&&!G&&Pl(le,{allowBare:!0})===ee&&(le.preventDefault(),At?C?.():xt())};return i.jsxs("div",{ref:Et,className:"relative",children:[G==="mention"&&i.jsx(tee,{id:Q,groups:yt,query:$t??"",activeIndex:Ie,onActiveIndexChange:Ee,openFolderId:Be,folderIndex:ge,onOpenFolderIdChange:Je,onFolderIndexChange:qe,onSelect:R,left:ie.left,flyoutSide:ie.flyoutSide}),G==="plugin"&&i.jsx("div",{ref:lt,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:he.map((le,Te)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Te===Ie,onMouseDown:Ae=>Ae.preventDefault(),onClick:()=>j(le),onMouseMove:()=>Ee(Te),className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Te===Ie&&"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:le.item.label}),le.item.detail&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:le.item.detail})]},le.key))}),(G==="slash"||G==="slash-sub")&&i.jsx("div",{ref:lt,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:(G==="slash"?P:M).map((le,Te)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Te===Ie,onClick:()=>{Ee(Te),G==="slash"?Pe(le.name):xe(le.name,!1)},onMouseMove:()=>Ee(Te),className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Te===Ie&&"bg-foreground/10"),children:[i.jsx(PN,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-mono font-medium",children:st!==null?`$${le.name.slice(7)}`:le.name}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:T(le.description)})]},le.name))}),i.jsxs("div",{ref:X,"data-slot":"composer","data-enso":"composer",className:W("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)]",(z||oe)&&"border-brand/50 bg-brand/5",(Kt||k)&&"border-primary/35 shadow-primary/5"),onDragOver:le=>{le.dataTransfer.types.includes("Files")&&(le.preventDefault(),de(!0))},onDragLeave:le=>{le.currentTarget.contains(le.relatedTarget)||de(!1)},onDrop:le=>{const Te=Array.from(le.dataTransfer.files);Te.length!==0&&(le.preventDefault(),de(!1),kt(Te))},children:[V.filter(le=>!le.id).length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:V.filter(le=>!le.id).map((le,Te)=>i.jsxs("div",{className:"group relative",children:[i.jsx("button",{type:"button",onClick:()=>ze(le),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:${le.mimeType};base64,${le.data}`,alt:"",className:"h-16 w-16 rounded-md border object-cover"})}),i.jsx("button",{type:"button",onClick:()=>ce(Ae=>Ae.filter((Ge,Qe)=>Qe!==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(ln,{className:"h-3 w-3"})})]},Te))}),i.jsxs("div",{className:W("flex items-start gap-1.5 px-4",V.length>0?"pt-1.5":"pt-3.5"),children:[De&&i.jsx(C9,{recipient:De,onRemove:()=>me(void 0)}),ve.map(le=>i.jsx(Du,{name:le,className:"mt-0.5 shrink-0",trailing:i.jsx("button",{type:"button",onClick:()=>_e(Te=>Te.filter(Ae=>Ae!==le)),className:"rounded-sm opacity-70 hover:opacity-100","aria-label":T("Remove"),children:i.jsx(ln,{className:"h-3 w-3"})})},le)),i.jsx(ZQ,{ref:Ze,placeholder:ve.length>0?"":c?T("Resolve the pending approval to continue"):Kt?T("Message the selected Agent…"):Dt?T("Press {{key}} to steer the next queued message into this round…",{key:mi(ee)}):S||T(n?"Message will queue until this round finishes…":"Type @ to choose a file or Agent"),disabled:c,onStateChange:Tt,onChipActivate:le=>{le.type==="ui-element"&&ae({kind:"ui-element",id:le.id,label:le.label,path:le.path,text:le.text,imageId:le.imageId})},onKeyDown:It,onPasteText:le=>!D||!mj(le)?!1:(D(le).catch(()=>({ok:!1,error:"unavailable"})).then(Te=>{const Ae=Ze.current;Te.ok?Ae?.insertFileChip(Te.path,`${Pj} · ${T("{{count}} chars",{count:Te.chars.toLocaleString()})}`):Ae?.insertText(le)}),!0),onPaste:le=>{const Te=Array.from(le.clipboardData.files);Te.length!==0&&(le.preventDefault(),kt(Te))},onCompositionStart:()=>{Pt.current=!0},onCompositionEnd:()=>{Pt.current=!1},ariaProps:{role:"combobox","aria-autocomplete":"list","aria-expanded":G!==null,"aria-controls":G==="mention"?Q:void 0,"aria-activedescendant":G==="mention"?Be?`${Q}-sub-${ge}`:`${Q}-option-${Ie}`:void 0}})]}),Kt&&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:W("flex min-w-0 flex-1 items-center gap-1",H?"overflow-x-auto [scrollbar-width:none]":"overflow-hidden"),children:[i.jsx("input",{ref:Gt,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:le=>{kt(Array.from(le.target.files??[])),le.target.value=""}}),i.jsx("button",{type:"button",disabled:c,onClick:()=>Gt.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(vh,{className:"h-3.5 w-3.5"})}),i.jsx(S0,{side:"left",..._t}),B?i.jsx(GQ,{active:F,disabled:c,onChange:le=>{O(le),le?document.activeElement?.blur():Ze.current?.focus()}}):A?i.jsx(LD,{startSession:A,requestMicAccess:I,disabled:c,holdBinding:L||void 0,holdScope:Et,onText:le=>{Ze.current?.insertText(le),Ze.current?.focus()}}):null,d,!N&&i.jsx(kQ,{sessionId:_t.sessionId}),i.jsx(S0,{side:"right",..._t}),Ct&&(Ct.blocked.length>0||Ct.masked>0)&&i.jsxs("span",{className:W("flex shrink-0 items-center gap-1 text-[11px]",Ct.blocked.length>0?"text-red-600 dark:text-red-400":"text-sky-600 dark:text-sky-400"),"data-privacy-precheck":!0,children:[Ct.blocked.length>0?i.jsx(Xk,{className:"size-3.5"}):i.jsx(Wu,{className:"size-3.5"}),Ct.blocked.length>0?T("Will be blocked: {{kinds}}",{kinds:Ct.blocked.join(", ")}):T("{{count}} will be masked",{count:Ct.masked})]})]}),dt&&!nt?i.jsx(fe,{variant:"outline",size:"icon",className:"size-8 shrink-0 rounded-full",onClick:w,"aria-label":T("Stop"),children:i.jsx(SV,{className:"h-4 w-4"})}):i.jsx(fe,{size:"icon",className:"size-8 shrink-0 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-35",onClick:xt,disabled:!nt||c,"aria-label":T(Kt?"Send only to the selected Agent":"Send"),title:Kt?T("Send only to the selected Agent"):l&&ee?`${T("Send")} ${mi(ee)}`:T("Send"),children:i.jsx(cd,{className:"h-4 w-4"})})]})]}),B&&F?i.jsx(FQ,{startSession:B,disabled:c,onText:le=>{Ze.current?.insertText(le),document.activeElement?.blur()}}):null,i.jsx(vn,{open:Z!==null,onOpenChange:le=>!le&&ae(null),children:i.jsxs(bn,{className:"max-w-md",children:[i.jsx(wn,{children:i.jsx(yn,{children:Z?.label??T("Selected UI element")})}),i.jsx(Mn,{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 le=V.find(Te=>Te.id===Z.imageId);return le?i.jsx("img",{src:`data:${le.mimeType};base64,${le.data}`,alt:"",className:"max-h-72 w-full rounded-md border object-contain"}):null})()]})})]})}),i.jsx(vn,{open:be!==null,onOpenChange:le=>!le&&ze(null),children:i.jsxs(bn,{className:"max-w-3xl",children:[i.jsx(wn,{children:i.jsx(yn,{children:T("Preview")})}),i.jsx(Mn,{children:be&&i.jsx("img",{src:`data:${be.mimeType};base64,${be.data}`,alt:"",className:"max-h-[80vh] w-full rounded-md object-contain"})})]})})]})}function UI({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:W("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 KI(e,t){const n=await se.getState().reloadConversation(e);n&&Fe({type:"error",title:t("Failed to reload conversation"),description:n})}async function iee(e,t){const n=await se.getState().restartConversation(e);n&&Fe({type:"error",title:t("Failed to restart conversation"),description:n})}function oee({parentId:e,displayedId:t,trailing:n}){const{t:s}=J(),o=se(p=>p.conversations[e]?.title??""),r=se(p=>p.conversations[e]?.started===!0),a=se(p=>p.conversations[e]?.reloading===!0),l=se(p=>!!p.conversations[e]?.spawning),d=se(p=>sQ(p.conversations,e)),[c,u]=m.useState(!1),h=p=>W("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(Zj,{"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(YS,{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:()=>se.getState().selectTab(e,void 0)}),d.map(p=>{const f=YL({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(YS,{id:p.id,label:p.title||p.child?.agentInstanceName||p.coworkerName||p.id,className:W(h(t===p.id),t!==p.id&&"group-hover/tab:bg-muted/50"),leading:p.mode==="task"?i.jsx(zg,{className:"h-3 w-3 shrink-0"}):i.jsx(Vs,{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(Lh,{tone:f,size:"sm"})}),reloadDisabled:p.reloading||p.spawning,reloading:p.reloading,onSelect:()=>se.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."))&&se.getState().dismissCoworkerFromUI(e,p.id)},children:i.jsx(ln,{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(us,{className:"h-3.5 w-3.5"})})]}),n,c&&i.jsx(ree,{parentId:e,onClose:()=>u(!1)})]})}function YS({id:e,label:t,className:n,leading:s,trailing:o,reloadDisabled:r,reloading:a,onSelect:l}){const{t:d}=J(),[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(UI,{title:t,className:"max-w-48 text-xs",onCommit:p=>{se.getState().renameConversation(e,p),u(!1)},onCancel:()=>u(!1)}):i.jsx("span",{className:"max-w-48 truncate",children:t}),o]});return i.jsxs(ho,{children:[i.jsx(po,{render:h}),i.jsxs(fo,{className:"min-w-36",children:[i.jsxs(Yt,{onClick:()=>u(!0),children:[i.jsx($s,{}),d("Rename")]}),i.jsxs(Yt,{disabled:r,onClick:()=>{KI(e,d)},children:[i.jsx(Ho,{className:a?"animate-spin":void 0}),d("Reload conversation")]})]})]})}function ree({parentId:e,onClose:t}){const{t:n}=J(),s=Se(x=>x.agentTypes),o=Se(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=[...XL.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 se.getState().hireCoworker(e,r.trim(),l||void 0);x?u(x):t()};return i.jsx(vn,{open:!0,onOpenChange:x=>!x&&t(),children:i.jsxs(bn,{className:"max-w-sm",children:[i.jsx(wn,{children:i.jsx(yn,{children:n("Hire coworker")})}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsxs(Os,{children:[i.jsx(zs,{children:n("Name (slug)")}),i.jsx(Jt,{value:r,onChange:x=>a(x.target.value),placeholder:"reviewer",autoFocus:!0})]}),i.jsxs(Os,{children:[i.jsx(zs,{children:n("Agent type")}),i.jsxs(vs,{items:f,value:l,onValueChange:x=>d(x??""),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:f.map(x=>i.jsx(os,{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(rs,{children:[i.jsx(fe,{variant:"ghost",onClick:t,children:n("Cancel")}),i.jsx(fe,{onClick:()=>{g()},disabled:!r.trim(),children:n("Hire")})]})]})})}function aee(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 lee={active:"bg-green-500 animate-pulse",paused:"bg-amber-500",waiting:"bg-amber-500",blocked:"bg-destructive",completed:"bg-blue-500"};function dee({conversationId:e,goal:t}){const{t:n}=J(),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(Ta,{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:W("h-1.5 w-1.5 shrink-0 rounded-full",lee[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:()=>se.getState().pauseGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(R6,{className:"h-3.5 w-3.5"})}):t.status!=="completed"?i.jsx("button",{type:"button",title:n("Resume goal"),onClick:()=>se.getState().resumeGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(jg,{className:"h-3.5 w-3.5"})}):null,i.jsx("button",{type:"button",title:n("Clear goal"),onClick:()=>se.getState().clearGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-destructive",children:i.jsx(ln,{className:"h-3.5 w-3.5"})})]})}function cee(e,t){return e.trim().length>0||t>0}function XS(e,t){return e>0?`${e} ${t}`:null}function qI({conversationId:e,queued:t}){const{t:n}=J(),[s,o]=m.useState(null),[r,a]=m.useState("");if(t.length===0)return null;const l=d=>{cee(r,d.images?.length??0)&&se.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]"}),XS(d.images?.length??0,n("attachments"))&&i.jsxs("span",{title:XS(d.images?.length??0,n("attachments"))??void 0,className:"flex shrink-0 items-center gap-0.5 text-muted-foreground",children:[i.jsx(x6,{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(Kn,{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:()=>se.getState().withdrawMessage(e,{kind:"queue",id:d.id}),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(pa,{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($s,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Send now"),onClick:()=>se.getState().sendQueuedNow(e,d.id),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(Ax,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Interrupt and send now"),onClick:()=>{se.getState().interruptAndSendQueued(e,d.id)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(X6,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Remove"),onClick:()=>se.getState().removeQueuedMessage(e,d.id),className:"rounded p-0.5 text-muted-foreground hover:text-destructive",children:i.jsx(ln,{className:"h-3.5 w-3.5"})})]})]},d.id))})}const YI="mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2 text-xs";function XI({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(_s,{text:e.text})})}function uee({conversationId:e,planState:t,approvalMode:n}){const s=Jj(t);return s==="awaiting_review"&&t?.pending?i.jsx(hee,{conversationId:e,doc:t.pending,approvalMode:n},t.pending.planId):s==="executing"&&t?.executing?i.jsx(pee,{conversationId:e,doc:t.executing},t.executing.planId):null}function hee({conversationId:e,doc:t,approvalMode:n}){const{t:s}=J(),o=ZL(),[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 b=se.getState();y&&y!==n&&b.setApprovalMode(e,y);const w=await b.respondPlan(e,t.planId,v,v==="revise"?c.trim():void 0);w&&(g(!1),Fe({type:"error",title:s("Plan response failed"),description:w}))};return i.jsxs("div",{className:YI,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ga,{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(un,{className:W("h-3 w-3 shrink-0 transition-transform",r&&"rotate-90")})]})]}),r&&i.jsx(XI,{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(Ml[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(gi,{open:h,onOpenChange:p,children:[i.jsx(xi,{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($n,{className:"h-3.5 w-3.5"})}),i.jsxs(vi,{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")}),JL.map(v=>{const y=Ml[v],b=y.icon,w=v==="assistant"&&!o;return i.jsxs("button",{type:"button",disabled:w,onClick:()=>{p(!1),x("approve",v)},className:W("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",w&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[i.jsx(b,{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 pee({conversationId:e,doc:t}){const{t:n}=J(),[s,o]=m.useState(!1);return i.jsxs("div",{className:W(YI,"py-1.5"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(jN,{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(un,{className:W("h-3 w-3 shrink-0 transition-transform",s&&"rotate-90")})]}),i.jsx("button",{type:"button",title:n("Finish plan"),onClick:()=>{se.getState().respondPlan(e,t.planId,"finish")},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(ln,{className:"h-3.5 w-3.5"})})]}),s&&i.jsx(XI,{doc:t})]})}function fee({active:e,onToggle:t}){const{t:n}=J();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:W("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(ga,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"hidden @min-[28rem]:inline",children:n("Plan")})]})}function mee({presetId:e,onSelect:t,onModel:n,disabled:s}){const{t:o}=J(),r=Se(h=>h.presets),a=QL(),[l,d]=m.useState(!1),c=[{id:e5,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:t5(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(Qc,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:u.name})]}):i.jsxs(gi,{open:l,onOpenChange:d,children:[i.jsxs(xi,{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(Qc,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:u.name}),i.jsx($n,{className:"h-3 w-3 shrink-0"})]}),i.jsx(vi,{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=n5(f??h.id,a);g&&n?.(g),d(!1)},className:W("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(Kn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},h.id)})})]})}const gee=[];function xee({projectId:e,conversationId:t}){const{t:n}=J(),s=Se(p=>p.projects.find(f=>f.id===e)?.trustedProjectCode??gee),o=Se(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(sa,{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(ln,{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(sa,{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(fe,{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(ln,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}const vee=70,ZI=80,JI={system:"bg-brand",memory:"bg-warning",tools:"bg-info",skills:"bg-success",files:"bg-foreground/70",results:"bg-foreground/40",chat:"bg-muted-foreground/70"};function QI({segments:e,highlight:t,className:n}){return i.jsx("span",{"aria-hidden":!0,className:W("flex h-1 w-16 shrink-0 gap-px overflow-hidden rounded-full bg-muted-foreground/15",n),children:e.map(s=>i.jsx("span",{className:W("block h-full transition-opacity",JI[s.kind],t&&t!==s.kind&&"opacity-25"),style:{width:`${s.width}%`}},s.kind))})}function bee({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:W("block h-full rounded-full",t?"bg-destructive":e>=vee?"bg-warning":"bg-muted-foreground/70"),style:{width:`${e}%`}})})}const wee={system:"System prompt",memory:"Enabled instructions",tools:"Tool definitions",skills:"Enabled skills",files:"Files read",results:"Tool results",chat:"Conversation"};function yee({conversationId:e}){const{t}=J(),n=se(r=>r.conversations[e]?.compaction);if(!se(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:()=>se.getState().compact(e),children:o})}function See({occupancy:e,conversationId:t,cwd:n,onNavigate:s}){const{t:o}=J(),[r,a]=m.useState(),[l,d]=m.useState();if(!e)return i.jsx("p",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:o("Context occupancy unavailable until the session starts")});const c=e.contextWindow,u=IT(e),h=(e.percent??0)>=ZI,p=[...u].filter(g=>Zw(e.parts,g.kind).length>0).sort((g,x)=>x.tokens-g.tokens)[0]?.kind,f=l===void 0?p:l;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:[Jn(e.used),c?` / ${Jn(c)}`:" · ?",e.percent!==void 0&&i.jsx("span",{className:W(h&&"text-warning"),children:` · ${e.percent}%`})]}),i.jsx("span",{className:"text-muted-foreground",children:o("Estimate")})]}),u.length>0&&i.jsx(QI,{segments:u,highlight:r,className:"h-1.5 w-full"}),h&&c!==void 0&&i.jsx("p",{className:"text-[11px] text-warning",children:o("About {{tokens}} left",{tokens:Jn(Math.max(0,c-e.used))})}),e.compactionModelMismatch&&i.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("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:o("{{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:()=>{se.getState().forkFromEntry(t,e.compactionEntryId)},children:o("Conversation branch")})]}),i.jsx("ul",{className:"flex flex-col gap-1",onMouseLeave:()=>a(void 0),children:u.map(({kind:g,tokens:x})=>{const v=e.used>0?Math.round(x/e.used*100):0,y=Zw(e.parts,g),b=f===g&&y.length>0;return i.jsxs("li",{onMouseEnter:()=>a(g),children:[i.jsxs("button",{type:"button",disabled:y.length===0,"aria-expanded":y.length>0?b:void 0,onClick:()=>d(b?null:g),className:"flex w-full items-center gap-1.5 rounded-sm text-left text-[11px] enabled:hover:bg-muted/60",children:[i.jsx(un,{className:W("h-3 w-3 shrink-0 text-muted-foreground transition-transform",b&&"rotate-90",y.length===0&&"invisible")}),i.jsx("span",{className:"w-24 shrink-0 truncate text-muted-foreground",children:o(wee[g])}),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:W("block h-full",JI[g]),style:{width:`${v}%`}})})}),i.jsx("span",{className:"w-10 shrink-0 text-right tabular-nums",children:Jn(x)}),i.jsxs("span",{className:"w-8 shrink-0 text-right text-muted-foreground tabular-nums",children:[v,"%"]})]}),b&&i.jsx("ul",{className:"mt-0.5 ml-1.5 flex flex-col gap-0.5 border-l border-border pl-2",children:y.map(w=>{const _=Z8(w),C=Q8(g,w,n),N=S=>{if(S.type==="file"){if(!t)return;s5(t,S.rel)}else window.electronAPI.window.openSettings(S.link);s?.()};return i.jsxs("li",{className:"group/item flex items-center gap-2 rounded-sm text-[11px] text-muted-foreground hover:bg-muted/60 hover:text-foreground",children:["raw"in _?i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono",title:_.raw,children:_.raw}):i.jsx("span",{className:"min-w-0 flex-1 truncate",children:o(_.key,_.vars)}),C&&(C.type==="settings"||t)?i.jsx("button",{type:"button",onClick:()=>N(C),className:"hidden shrink-0 rounded-sm border border-border bg-background px-1.5 text-[10px] leading-4 text-muted-foreground hover:text-foreground group-hover/item:block focus-visible:block",children:o(C.type==="file"?"Open":"Settings")}):null,i.jsx("span",{className:W("shrink-0 tabular-nums",C&&"group-hover/item:hidden"),children:Jn(w.tokens)})]},`${w.tag}-${w.name}`)})})]},g)})}),t&&i.jsx(yee,{conversationId:t})]})}function Cee(e){return e?e.used:null}const Cv=90;function eE(e,t){const n=Cee(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 kee(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 jee(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:`${Jn(a)} · ${l}%`,percent:l,critical:l>=Cv}}else n.context={compact:`${Jn(r)}·?`,full:`${Jn(r)} · ?`}}const s=[],o=[];return t.ttftAvgMs!==void 0&&(s.push(Un(t.ttftAvgMs)),o.push(e("First token avg {{duration}}",{duration:Un(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:`↑${Jn(t.inputTokens)} ↓${Jn(t.outputTokens)}`,full:e("Input {{input}} tok · Output {{output}} tok",{input:Jn(t.inputTokens),output:Jn(t.outputTokens)})}),t.cacheHitPercent!==void 0&&(n.cache={compact:`${t.cacheHitPercent}%`,full:e("Cache hit {{percent}}%",{percent:t.cacheHitPercent})}),n}function _ee(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:nf(t.bytes),full:`${nf(t.bytes)} / ${nf(t.limitBytes)} · ${n}% · ${s}`,critical:t.blocked||n>=Cv}}function nf(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 Nee({className:e,orientation:t="horizontal",...n}){return i.jsx(i5,{className:W("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 Tee={minimal:"Minimal",default:"Default",full:"Full"};function Dee({icons:e,values:t}){const{t:n}=J(),s=Se(x=>x.statusLineSegments),o=m.useMemo(()=>tE(s),[s]),r=Se(x=>x.toggleStatusLineSegment),a=Se(x=>x.setStatusLineSegments),[l,d]=m.useState(null),[c,u]=m.useState(null),h=o5(o),p=Qj.filter(x=>!o.includes(x)),f=()=>{d(null),u(null)},g=()=>{if(l!==null&&c!==null){const x=c>l?c-1:c,v=d5(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:r5.map(x=>i.jsx(fe,{variant:h===x?"secondary":"ghost",size:"xs",onClick:()=>a([...a5[x]]),children:n(Tee[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],b=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:w=>{if(l===null)return;w.preventDefault();const _=w.currentTarget.getBoundingClientRect(),C=w.clientY<_.top+_.height/2;u(C?v:v+1)},onDrop:w=>{w.preventDefault(),g()},className:W("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:w=>{w.dataTransfer.effectAllowed="move",w.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(l5,{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(Mu[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:b?.full||n("No data yet")})]})]}),i.jsx(ci,{checked:!0,onCheckedChange:w=>r(x,w)})]})]},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(Nee,{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(Mu[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:y?.full||n("No data yet")})]})]}),i.jsx(ci,{checked:!1,onCheckedChange:b=>r(x,b)})]},x)})]})]})]})}function tE(e){const t=Array.isArray(e)?e:u5,n=new Set(Qj),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 Mu={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"},Iee={minimal:"Min",low:"Low",medium:"Med",high:"High",xhigh:"Extra",max:"Max"},Eee={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"},Pee={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},Aee={supervised:m5,"auto-edits":Wu,full:f5,assistant:Hs},Mee={model:zV,context:x5,requestBody:g5,turns:G6,duration:_N,sessionTime:h6,speed:zg,tokens:IV,cache:FV,cwd:ni,sessionName:J6,coworkers:la,usage:c4};function Ree(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 Lee(e){return e.split(/[\\/]+/).filter(Boolean).at(-1)??e}function rc(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function ZS(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 JS(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 Oee(e){return{...Mee,approval:Aee[e.approvalMode??"full"]}}function zee(e,t){const[n,s]=m.useState(()=>{if(!e)return;const o=C0.get(e);return o?{key:e,data:o.data}:void 0});return m.useEffect(()=>{if(!e)return;let o=!1;const r=C0.get(e);if(r&&Date.now()-r.fetchedAt<h5){s({key:e,data:r.data});return}return p5(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 Gee(e,t,n,s,o,r,a){const l=F8(n),d={model:void 0,requestBody:_ee(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,...jee(e,kee(H8(l),eE(t.occupancy,t.contextWindow)))};if(t.lastModelId){const b=s.find(_=>_.id===t.lastProviderId)?.models.find(_=>_.id===t.lastModelId)?.label??t.lastModelId,w=t.reasoningEnabled?t.thinkingLevel:void 0;d.model={compact:w?`${b} · ${e(Iee[w])}`:b,full:w?`${b} · ${e(Eee[w])}`:b}}l.steps>0&&(d.turns={compact:`${l.turns}·${l.steps}`,full:e("{{turns}} turns · {{steps}} steps",{turns:l.turns,steps:l.steps})});const c=Ree(t,n,r),u=l.llmMs+c.llm,h=l.toolMs+c.tool,p=[],f=[];u>=1e3&&(p.push(Un(u)),f.push(e("LLM {{duration}}",{duration:Un(u)}))),h>=1e3&&(p.push(Un(h)),f.push(e("Tool calls {{duration}}",{duration:Un(h)}))),p.length>0&&(d.duration={compact:p.join(" · "),full:f.join(" · ")});const g=Math.max(0,r-t.createdAt);d.sessionTime={compact:JS(g),full:JS(g)};const x=o.find(y=>y.id===t.projectId);if(x){const y=Lee(x.path);d.cwd={compact:y,full:x.path}}t.title.trim().length>0&&(d.sessionName={compact:rc(t.title,16),full:rc(t.title,60)}),d.approval={compact:"",full:e(Pee[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,b=Math.max(...y.map(S=>S.usedPercent)),w=y[0],_=rc(w.label,24),C=w.resetsAt!==void 0?ZS(w.resetsAt-r):void 0,N=y.length>1?` +${y.length-1}`:"";d.usage={compact:`${_} ${Math.round(w.usedPercent)}%${C?`·${C}`:""}${N}`,full:y.map(S=>{const k=S.resetsAt!==void 0?` · ${e("resets in {{remaining}}",{remaining:ZS(S.resetsAt-r)})}`:"";return`${rc(S.label,24)} ${Math.round(S.usedPercent)}%${k}`}).join(" · "),critical:b>=Cv}}return d}function nE({conversationId:e,cwd:t}){const{t:n}=J(),s=se(I=>I.conversations[e]),o=s?.messages??[],r=ya(),a=Se(I=>I.virtualModels),l=m.useMemo(()=>a.length===0?r:[...r,{id:e_,models:a.map(I=>({id:I.id,label:I.name}))}],[r,a]),d=Se(I=>I.projects),c=Se(I=>I.statusLineSegments),u=m.useMemo(()=>tE(c),[c]),[h,p]=m.useState(null),[f,g]=m.useState(!1),x=m.useMemo(()=>{if(u.includes("usage"))return Gg(r,s)?.accountKey},[u,r,s]),[v,y]=m.useState(()=>Date.now()),b=s?.status==="running"&&u.includes("duration"),w=u.includes("sessionTime"),_=u.includes("usage")&&x!==void 0;m.useEffect(()=>{if(!b&&!w&&!_)return;const I=setInterval(()=>y(Date.now()),1e3);return()=>clearInterval(I)},[b,w,_]);const C=zee(x,v),N=m.useMemo(()=>s?Oee(s):null,[s]),S=m.useMemo(()=>s?Gee(n,s,o,l,d,v,C):null,[n,s,o,l,d,v,C]);if(!s||!N||!S)return null;const k=s.occupancy?IT(s.occupancy):[],A=u.filter(I=>S[I]);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:[A.length>0&&i.jsx("div",{className:"flex min-w-0 flex-nowrap items-center gap-3 overflow-hidden",children:A.map((I,E)=>{const D=S[I];if(!D)return null;const T=N[I],H=i.jsxs("span",{title:`${n(Mu[I])} · ${D.full}`,onMouseEnter:()=>p(I),onMouseLeave:()=>p(F=>F===I?null:F),className:W("relative flex items-center gap-1 text-[11px] tabular-nums",D.critical?"text-destructive":I==="context"&&D.percent!==void 0&&D.percent>=ZI?"text-warning":"text-subtle-foreground"),children:[I==="context"&&D.percent!==void 0?k.length>0?i.jsx(QI,{segments:k}):i.jsx(bee,{percent:D.percent,critical:!!D.critical}):i.jsx(T,{className:"h-3 w-3 shrink-0 opacity-75"}),D.compact&&i.jsx("span",{className:"truncate",children:D.compact}),h===I&&I!=="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:n(Mu[I])}),i.jsx("span",{className:"ml-1 break-words text-muted-foreground",children:D.full})]})]});return i.jsx("span",{className:W("shrink-0 items-center",f||c5(I,E)?"flex":"hidden group-focus-within:flex group-hover:flex"),children:I==="context"?i.jsxs(gi,{open:f,onOpenChange:g,children:[i.jsx(xi,{className:"rounded-sm outline-none",children:H}),i.jsx(vi,{side:"top",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:i.jsx(See,{occupancy:s.occupancy,conversationId:s.id,cwd:t,onNavigate:()=>g(!1)})})]}):H},I)})}),i.jsxs(gi,{children:[i.jsx(xi,{"aria-label":n("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(t_,{className:"h-3.5 w-3.5"})}),i.jsx(vi,{side:"top",align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:i.jsx(Dee,{icons:N,values:S})})]})]})}const Fee=["pattern","query","path","file_path"],Hee=["path","file_path","query","pattern"],Bee=["command","cmd","script"],$ee=["path","file_path","pattern","query","command","url","description","summary"],QS=120;function Ba(e){const t=e.replace(/\s+/g," ").trim();return t.length>QS?`${t.slice(0,QS-1)}…`:t}function Vee(e){const t=e.toLowerCase();return t.includes("search")||t.includes("grep")||t==="find"?Fee:t==="read"||t.endsWith("_read")?Hee:t==="bash"||t.includes("shell")||t.includes("terminal")?Bee:$ee}function Wee(e,t){const n=t.trim();if(!n)return"";let s;try{s=JSON.parse(n)}catch{return Ba(n)}if(s===null)return"";if(typeof s!="object"||Array.isArray(s))return Ba(JSON.stringify(s)??String(s));const o=n_(e,s);if(o.summary!==void 0)return Ba(o.summary);if(!o.args||typeof o.args!="object")return"";const r=o.args;for(const l of Vee(o.name)){const d=r[l];if(typeof d=="string"&&d.trim())return Ba(d)}const a=JSON.stringify(r);return a==="{}"?"":Ba(a)}function Uee(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}const sE=new Map,Kee=e=>{const t=sE.get(e);return t?new Set(t):new Set},eC=(e,t)=>(sE.set(e,t),t),Xm=new Map,qee=(e,t)=>{const n=Xm.get(e)??new Set;Xm.set(e,n);for(const s of t)n.add(s);return n};function kv({sessionId:e,tasks:t,subagents:n,readOnly:s}){const o=Se(b=>b.virtualModels),{t:r}=J(),[a,l]=m.useState(()=>Kee(e)),[d,c]=m.useState(null),u=se(b=>b.pendingAgentOpen);m.useEffect(()=>{!u||u.sessionId!==e||(c(u.agentId),se.setState({pendingAgentOpen:null}))},[u,e]);const h=qee(e,[...t.filter(b=>b.status==="running").map(b=>b.taskId),...n.filter(b=>b.status==="running").map(b=>b.id)]),p=(b,w)=>!a.has(b)&&(w==="running"||h.has(b)),f=t.filter(b=>p(b.taskId,b.status)),g=n.filter(b=>p(b.id,b.status));if(m.useEffect(()=>{const b=Xm.get(e),w=[...t.filter(C=>C.status!=="running").map(C=>C.taskId),...n.filter(C=>C.status!=="running").map(C=>C.id)].filter(C=>b?.has(C)&&!a.has(C)&&C!==d);if(w.length===0)return;const _=setTimeout(()=>{l(C=>{const N=new Set(C);for(const S of w)N.add(S);return eC(e,N)})},5e3);return()=>clearTimeout(_)},[e,t,n,a,d]),f.length===0&&g.length===0)return null;const x=b=>{l(w=>eC(e,new Set(w).add(b))),d===b&&c(null)},v=f.find(b=>b.taskId===d)??null,y=g.find(b=>b.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?` · ${Af(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(ln,{className:"h-3.5 w-3.5"})})]}),v&&i.jsx(nte,{tail:v.tail}),y&&i.jsx(Yee,{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(b=>i.jsx(tC,{icon:Fo,status:b.status,meta:i.jsx(tte,{task:b}),open:d===b.taskId,onToggle:()=>c(d===b.taskId?null:b.taskId),stopTitle:r("Stop task"),onStop:s?void 0:()=>{window.electronAPI.agent.stopTask(e,b.taskId)},onDismiss:()=>x(b.taskId),children:i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground",title:b.command,children:b.command})},b.taskId)),g.map(b=>i.jsxs(tC,{icon:Vs,status:b.status,meta:i.jsx(ete,{agent:b}),open:d===b.id,onToggle:()=>c(d===b.id?null:b.id),stopTitle:r("Stop subagent"),onStop:s?void 0:()=>{window.electronAPI.agent.stopSubagent(e,b.id)},onDismiss:()=>x(b.id),children:[b.agentType&&i.jsx("span",{className:"shrink-0 font-medium",children:b.agentType}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:[b.description,b.modelId&&i.jsxs("span",{className:"text-muted-foreground/60",children:[" ","· ",Af(o,b.modelId)]}),b.status==="running"&&b.currentActivity&&i.jsxs("span",{className:"text-muted-foreground/60",children:[" · ",b.currentActivity]})]})]},b.id))]})]})}function tC({icon:e,status:t,meta:n,open:s,onToggle:o,stopTitle:r,onStop:a,onDismiss:l,children:d}){const{t:c}=J();return i.jsxs("div",{className:"flex min-h-[30px] min-w-0 items-center gap-2 px-1 text-[13px]",children:[i.jsx(vK,{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($n,{className:W("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(ud,{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(ln,{className:"h-3 w-3"})})]})}function Yee({agent:e}){const{t}=J(),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=Uee(r.currentTarget)},children:[n.map(r=>i.jsx(Xee,{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:W("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(_s,{text:e.resultText})]})]})}function Xee({activity:e}){const{t}=J(),[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(Qee,{text:e.text,markdown:!0})]});const o=Wee(e.toolName,e.argumentsText),r=n_(e.toolName,e.argumentsText).name,a=tj(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(Zee,{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(Jee,{status:e.status,label:t(e.status)}),i.jsx(un,{"aria-hidden":"true",className:W("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:Si(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:Si(e.outputText)})]})]})]})}function Zee({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(wo,{"aria-hidden":"true",className:n}):t==="bash"||t==="exec"||t==="codemode"||t.includes("shell")||t.includes("terminal")?i.jsx(kf,{"aria-hidden":"true",className:n}):i.jsx(Tg,{"aria-hidden":"true",className:n})}function Jee({status:e,label:t}){const n="h-3.5 w-3.5";return i.jsx("span",{role:"status","aria-label":t,title:t,className:W("shrink-0",e==="failed"?"text-destructive":"text-muted-foreground"),children:e==="running"?i.jsx(Zt,{"aria-hidden":"true",className:W(n,"animate-spin")}):e==="done"?i.jsx(Kn,{"aria-hidden":"true",className:n}):e==="failed"?i.jsx(gr,{"aria-hidden":"true",className:n}):i.jsx(lV,{"aria-hidden":"true",className:n})})}function Qee({text:e,label:t,markdown:n=!1}){const{t:s}=J(),o=e.length>800||e.split(`
|
|
91
|
-
`).length>16,r=n?i.jsx(_s,{text:e}):i.jsx("pre",{className:"overflow-x-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:Si(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 ete({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"?Un(Date.now()-e.startedAt):e.status]})}function tte({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"?Un(Date.now()-e.startedAt):e.exitCode!==void 0?`exit ${e.exitCode}`:e.status})}function nte({tail:e}){const{t}=J(),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:Si(e)||t("(no output yet)")})}function jv(e){return e==="darwin"?"Open in Finder":e==="win32"?"Open in File Explorer":"Open in File Manager"}async function _v(e,t){try{const n=await window.electronAPI.projects.reveal(e);n.ok||Fe({type:"error",title:t("Could not complete the file action."),description:n.error})}catch(n){Fe({type:"error",title:t("Could not complete the file action."),description:String(n)})}}const ste="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 ite({project:e,conversationId:t,path:n,branch:s,openDisabled:o,children:r}){const{t:a}=J(),[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=>{_v({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(Cd,{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) ${ste}`,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(Mi,{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($i,{align:"end",className:"min-w-48",children:[c&&i.jsxs(i.Fragment,{children:[i.jsxs(fn,{disabled:o,onClick:()=>f(),children:[i.jsx(ni,{}),a(jv(window.electronAPI.env.platform))]}),i.jsx(nC,{label:a("Editors"),apps:g,fallback:i.jsx(um,{}),disabled:o,onOpen:f}),i.jsx(nC,{label:a("Terminals"),apps:x,fallback:i.jsx(Fo,{}),disabled:o,onOpen:f}),i.jsx(ba,{})]}),i.jsxs(fn,{onClick:()=>{navigator.clipboard.writeText(n)},children:[i.jsx(Uu,{}),a("Copy Path")]})]})]})}function nC({label:e,apps:t,fallback:n,disabled:s,onOpen:o}){return t.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx(ba,{}),i.jsxs(Ig,{children:[i.jsx(Eg,{children:e}),t.map(r=>i.jsxs(fn,{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 ote({conversationId:e}){const{t}=J(),n=se(r=>r.conversations[e]),s=se(r=>r.rebuildWorktree),o=se(r=>r.fallbackToMainWorkspace);return!n?.worktreeMissing||!n.worktree?null:i.jsx(s_,{open:!0,children:i.jsxs(i_,{className:"sm:max-w-md",children:[i.jsxs(o_,{children:[i.jsx(r_,{className:"text-base",children:t("Isolated worktree is missing")}),i.jsx(a_,{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(l_,{variant:"bare",children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>{o(e)},children:t("Fall back to main working tree")}),i.jsx(fe,{size:"sm",onClick:()=>{s(e).then(r=>{r&&Fe({type:"error",title:t("Failed to rebuild worktree"),description:r})})},children:t("Rebuild worktree")})]})]})})}function Ru(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 rte({initialName:e,data:t,busy:n,disabled:s,error:o,returnFocus:r,onSubmit:a,onClose:l}){const{t:d}=J(),[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?Ru(t.blockedReason,d):t&&!t.headCommit?d("Create a commit before creating a branch from HEAD."):null;return i.jsx(vn,{open:!0,onOpenChange:v=>{!v&&!n&&l()},children:i.jsxs(bn,{className:"max-w-sm",initialFocus:h,finalFocus:r,showCloseButton:!n,children:[i.jsxs(wn,{children:[i.jsx(yn,{children:d("Create branch")}),i.jsx(As,{children:d("Creates a branch from the current HEAD and switches every conversation in this workspace to it.")})]}),i.jsxs(Mn,{children:[i.jsx(Jt,{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(rs,{children:[i.jsx(fe,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:l,children:d("Cancel")}),i.jsxs(fe,{type:"button",size:"sm",disabled:!!g,onClick:()=>{g||a(c.trim())},children:[n&&i.jsx(Zt,{className:"h-3.5 w-3.5 animate-spin"}),d("Create and switch")]})]})]})})}function ate({data:e,loading:t,error:n,disabled:s,query:o,searchRef:r,onQueryChange:a,onSelect:l,onCreate:d,onRetry:c}){const{t:u}=J(),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(Jt,{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:Ru(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(Zt,{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:W("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(Lo,{className:"h-3.5 w-3.5 shrink-0"}):i.jsx(Mi,{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(Kn,{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(us,{className:"h-3.5 w-3.5 shrink-0"}),u("Create branch from HEAD…")]})]})}function qc(e){return e.name?.trim()||e.branch}function lte(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 dte(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 Zm(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[qc(e),e.branch,e.path,s].join(`
|
|
93
|
-
`)}function cte({worktree:e,status:t}){const{t:n}=J();return i.jsx("span",{"data-slot":"worktree-label",title:Zm(e,t,n),className:"flex shrink-0 items-center",children:i.jsx(Mi,{className:W("size-2.75",t?.exists===!1?"text-destructive":t?.dirty?"text-warning":(t?.ahead??0)>0?"text-info":"text-subtle-foreground")})})}function iE({entity:e,onClose:t}){const{t:n}=J(),s=se(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?Fe({type:"error",title:n("Failed to rename worktree"),description:c}):t()}catch(c){Fe({type:"error",title:n("Failed to rename worktree"),description:String(c)})}finally{l(!1)}}};return i.jsx(vn,{open:e!==null,onOpenChange:c=>{!c&&!a&&t()},children:i.jsxs(bn,{className:"max-w-sm",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:n("Rename worktree")}),i.jsx(As,{children:n("Only the display name changes, for all sessions in this worktree. Leave empty to use the branch name.")})]}),i.jsx(Mn,{children:i.jsx(Jt,{"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(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",disabled:a,onClick:t,children:n("Cancel")}),i.jsxs(fe,{size:"sm",disabled:a,onClick:()=>{d()},children:[a&&i.jsx(Zt,{className:"h-3.5 w-3.5 animate-spin"}),n("Save")]})]})]})})}function ute({conversationId:e,onBranchChange:t}){const{t:n}=J(),s=se(Oe=>Oe.conversations[e]),o=se(Oe=>Oe.moveConversationToWorktree),r=se(Oe=>Oe.cleanupWorktree),a=se(Oe=>Oe.refreshWorktreeStatuses),l=se(Oe=>Oe.conversations),d=se(Oe=>Oe.worktreeStatuses),c=se(Oe=>Oe.attachConversationToWorktree),u=se(Oe=>Oe.newConversation),h=se(Oe=>Oe.switchWorkspaceBranch),p=se(Oe=>Oe.workspaceRevisionByConversation[e]??0),[f,g]=m.useState(null),x=m.useMemo(()=>lte(l,s?.projectId??"",d),[l,s?.projectId,d]),[v,y]=m.useState(!1),[b,w]=m.useState(!1),[_,C]=m.useState(!1),[N,S]=m.useState(null),[k,A]=m.useState(!1),I=Se(Oe=>s?Oe.projects.find(yt=>yt.id===s.projectId):void 0),E=!!(s&&!s.parentId&&!s.child&&I?.kind!=="ssh"&&I?.kind!=="scratch"),D=`${e}\0${s?.worktree?.path??I?.path??""}`,T=m.useRef(D);T.current=D;const H=m.useRef(0),F=m.useRef(!1),O=m.useRef(null),B=m.useRef(null),Y=m.useRef(null);m.useEffect(()=>{v&&(b?B:Y).current?.focus()},[v,b]);const[U,ee]=m.useState(null),L=U?.key===D?U.data:null,Q=L?.currentBranch??void 0;m.useEffect(()=>{t?.(Q)},[t,Q]);const[V,ce]=m.useState(!0),[ve,_e]=m.useState(null),[De,me]=m.useState(""),[$,z]=m.useState(null),[de,X]=m.useState(null),oe=$===D;m.useEffect(()=>{y(!1),w(!1),me(""),z(null),X(null)},[D]);const Z=m.useCallback(async(Oe=!1)=>{if(!E)return;const yt=++H.current;ce(!0),_e(null);try{const Ht=await window.electronAPI.worktree.branches(e);if(yt!==H.current||T.current!==D)return;if(Ht.ok)ee({key:D,data:Ht.value});else{const re=Ru(Ht.code,n);_e(re),Oe&&Fe({type:"error",title:n("Failed to load branches"),description:re})}}catch(Ht){if(yt!==H.current||T.current!==D)return;_e(n("Failed to load branches")),Oe&&Fe({type:"error",title:n("Failed to load branches"),description:String(Ht)})}finally{yt===H.current&&T.current===D&&ce(!1)}},[e,E,n,D]);if(m.useEffect(()=>{Z();const Oe=()=>{F.current||Z()};return window.addEventListener("focus",Oe),()=>{H.current+=1,window.removeEventListener("focus",Oe)}},[Z,p]),!s||s.parentId||s.child||I?.kind==="ssh")return null;const ae=!!s.worktree,be=_||s.spawning||s.status==="running"||!!(s.workspaceMigrating||s.reloading),ze=s.worktreeMissing||d[e]?.exists===!1,Ye=dte(s),Ve=L?L.currentBranch:s.worktree?.branch,at=Ve??(L?.headCommit?n("Detached HEAD"):""),Ze=s.worktree?qc(s.worktree):n("Local"),Et=at&&at!==Ze&&(!L?.defaultBranch||Ve!==L.defaultBranch)?`${Ze} · ${at}`:Ze,Gt=be||ze||V||!!ve||!L||!!L.blockedReason,Pt=async(Oe,yt=!1,Ht)=>{if(Gt||F.current)return;F.current=!0,H.current+=1,C(!0),X(null);const re=n(Ht?"Failed to create conversation":"Failed to switch branch");try{if(Ht){await u(s.projectId,{worktreeFromConversationId:Ht})?T.current===D&&y(!1):Fe({type:"error",title:re});return}const $e=await h(e,Oe,yt);if(T.current!==D)return;if($e.ok)ee({key:D,data:$e.value}),_e(null),z(null),y(!1);else{const st=Ru($e.code,n);X(st),Fe({type:"error",title:re,description:$e.code==="git-error"?`${st}
|
|
94
|
-
${$e.error}`:st}),Z()}}catch($e){if(T.current!==D)return;X(String($e)),Fe({type:"error",title:re,description:String($e)})}finally{F.current=!1,C(!1)}},ne=Oe=>{Oe.name===L?.currentBranch||Oe.occupied&&!Oe.worktreeConversationId||Pt(Oe.name,!1,Oe.occupied?Oe.worktreeConversationId:void 0)},ie=async Oe=>{if(be)return;C(!0);const yt=n(Oe?"Failed to use worktree":"Failed to create conversation");try{if(Oe){const Ht=await c(e,Oe);Ht&&Fe({type:"error",title:yt,description:Ht})}else await u(s.projectId,{worktreeFromConversationId:e})||Fe({type:"error",title:yt})}catch(Ht){Fe({type:"error",title:yt,description:String(Ht)})}finally{C(!1)}},He=async()=>{C(!0);try{const Oe=await r(e);Oe?Fe({type:"error",title:n("Failed to clean up worktree"),description:Oe}):a()}catch(Oe){Fe({type:"error",title:n("Failed to clean up worktree"),description:String(Oe)})}finally{C(!1)}},St=async(Oe=!1)=>{C(!0);try{const yt=await o(e,{allowDirtyMainTree:Oe});yt===d_?A(!0):yt?Fe({type:"error",title:n("Failed to move to worktree"),description:yt}):a()}catch(yt){Fe({type:"error",title:n("Failed to move to worktree"),description:String(yt)})}finally{C(!1)}},it=async()=>{C(!0);try{const Oe=await window.electronAPI.worktree.status(e);if(Oe.ok&&Tc(Oe.value)){S(Oe.value);return}await He()}catch(Oe){Fe({type:"error",title:n("Failed to clean up worktree"),description:String(Oe)})}finally{C(!1)}},je=[{id:"local",selected:!ae,icon:i.jsx(hw,{className:"h-3.5 w-3.5 shrink-0"}),name:n("Local workspace"),hint:n("Work directly in the main working tree"),onSelect:()=>{ae&&it()}},{id:"worktree",selected:ae,icon:i.jsx(Mi,{className:"h-3.5 w-3.5 shrink-0"}),name:s.worktree?qc(s.worktree):n("New isolated worktree"),hint:ae?s.worktree?.branch:n("Run this session on its own git worktree"),onSelect:()=>{ae||St()}}],ht=i.jsx(ms,{open:k,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),St(!0)}}),$t=()=>{const Oe=[];return N?.dirty&&Oe.push(n("Uncommitted changes")),N&&N.ahead>0&&Oe.push(n("{{n}} unmerged commits (branch is kept)",{n:N.ahead})),Oe.join("; ")};return i.jsxs(i.Fragment,{children:[i.jsxs(gi,{open:v,onOpenChange:Oe=>{_||(y(Oe),Oe&&(w(!1),me(""),Z()))},children:[i.jsxs(xi,{ref:O,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?`${Et}
|
|
95
|
-
${Zm(s.worktree,d[e],n)}`:Et,children:[_?i.jsx(Zt,{className:"h-3 w-3 shrink-0 animate-spin"}):ae?i.jsx(Mi,{className:"h-3 w-3 shrink-0"}):i.jsx(hw,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:Et}),i.jsx($n,{className:"h-3 w-3 shrink-0"})]}),i.jsx(vi,{side:"top",align:"start",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",initialFocus:Y,finalFocus:oe||f!==null?!1:O,children:b?i.jsxs(i.Fragment,{children:[i.jsxs("button",{type:"button",onClick:()=>w(!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(dd,{className:"h-3.5 w-3.5 shrink-0"}),n("Local branches")]}),i.jsx(ate,{data:L,loading:V,error:ve,disabled:be||ze,query:De,searchRef:B,onQueryChange:me,onSelect:ne,onRetry:()=>{Z(!0)},onCreate:()=>{Gt||!L?.headCommit||(X(null),z(D),y(!1))}})]}):i.jsxs(i.Fragment,{children:[je.map(Oe=>i.jsxs("button",{ref:Oe.id==="local"?Y:void 0,type:"button",disabled:be,onClick:()=>{Oe.onSelect(),y(!1)},className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",Oe.selected?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[Oe.icon,i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:Oe.name}),Oe.hint&&i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:Oe.hint})]}),Oe.selected&&i.jsx(Kn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},Oe.id)),Ye&&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:Oe,worktree:yt})=>i.jsxs("button",{type:"button",disabled:be,title:Zm(yt,d[Oe],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),ie(Oe)},children:[i.jsx(Mi,{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:qc(yt)}),i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:yt.path})]})]},yt.path))})]}),s.worktree&&i.jsxs("div",{className:"mt-1 border-t pt-1",children:[i.jsxs("button",{type:"button",disabled:be||ze,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),ie()},children:[i.jsx(Lo,{className:"h-3.5 w-3.5"}),n("New conversation in this worktree")]}),i.jsxs("button",{type:"button",disabled:be||ze,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($s,{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:()=>w(!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(Mi,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"flex-1",children:n("Switch branch")}),i.jsx(un,{className:"h-3.5 w-3.5 shrink-0"})]})})]})})]}),i.jsx(ms,{open:N!==null,onOpenChange:Oe=>{Oe||S(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:$t()}),confirmLabel:n("Clean up"),onConfirm:()=>{S(null),He()}}),oe&&i.jsx(rte,{initialName:De.trim(),data:L,busy:_,disabled:Gt,error:de,returnFocus:O,onSubmit:Oe=>{Pt(Oe,!0)},onClose:()=>z(null)},D),ht,i.jsx(iE,{entity:f,onClose:()=>g(null)})]})}function hte(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 pte=e=>{jh(e)&&yo()};function fte(){const{t:e}=J(),t=v5(),n=ya(),s=Se(ie=>ie.virtualModels),o=Se(ie=>ie.agentTypes),r=Se(ie=>ie.defaultModel),a=Se(ie=>ie.projects),l=Se(ie=>ie.projectGroups),d=Se(ie=>ie.voiceInputEnabled),c=Se(ie=>ie.voiceModel),u=Se(ie=>ie.presets),{status:h}=Mj(d),p=d&&h?.state!=="unsupported"&&h?.models.find(ie=>ie.id===c)?.state==="ready",f=m.useSyncExternalStore(ie=>se.persist?.onFinishHydration?.(ie)??(()=>{}),()=>se.persist?.hasHydrated?.()??!0),g=se(Mf(ZJ)),x=se(ie=>ie.conversations[g?.parentId??""]?.coworkerIds),v=b5(g?.presetId,ie=>u.find(He=>He.id===ie)).pluginPresetId??null,y=qJ(g?.displayedParentId?g.agentType:void 0),b=Fi(ie=>ie.snapshot),w=Fg(),_=se(ie=>tQ(ie.conversations)),C=g?.parentId,N=g?.parentProjectId,S=m.useMemo(()=>C!==void 0&&N!==void 0?uX(_,N,C):[],[_,C,N]),k=m.useMemo(()=>a.find(ie=>ie.id===g?.projectId),[g?.projectId,a]),A=m.useMemo(()=>a.find(ie=>ie.id===g?.parentProjectId),[g?.parentProjectId,a]),I=m.useMemo(()=>eu(k,l),[k,l]),E=m.useMemo(()=>eu(A,l),[A,l]),D=m.useMemo(()=>Rl({defaultModel:r,...I,lastProviderId:g?.lastProviderId,lastModelId:g?.lastModelId,providers:n,credentials:da(b),virtualModels:s}),[g?.lastModelId,g?.lastProviderId,I,r,b,n,s]),T=m.useMemo(()=>Rl({defaultModel:r,...E,lastProviderId:g?.parentLastProviderId,lastModelId:g?.parentLastModelId,providers:n,credentials:da(b),virtualModels:s}),[r,b,g?.parentLastModelId,g?.parentLastProviderId,E,n,s]),H=T.source==="none"?null:{providerId:T.providerId,modelId:T.modelId},F=D.source==="none"?void 0:w.find(ie=>ie.id===D.providerId),O=D.source==="none"?"":D.modelId,B=D.source==="none"?"":Rf(D)?D.providerId:F?.id??"",Y=se(ie=>Rf(D)&&g?.id?hte(ie.conversations[g.id]?.messages):void 0),U=se(Mf(ie=>Gg(n,g?.id?ie.conversations[g.id]:void 0))),ee=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."):w.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."),L=a.find(ie=>ie.id===g?.projectId),Q=g?.id,[V,ce]=m.useState(),ve=m.useCallback(ie=>ce(Q&&ie?{id:Q,branch:ie}:void 0),[Q]),_e=g?.parentWorktreeBranch??(V?.id===g?.parentId?V?.branch:void 0),De=Se(ie=>ie.skills),me=Se(ie=>ie.loadLocalSkills),$=Se(ie=>w5(ie.disabledBuiltinTools,ie.projects,g?.projectId,"plan")),[z,de]=m.useState([]),X=me?L?.path??"":"",oe=g?.presetId;m.useEffect(()=>{let ie=!1;return window.electronAPI.assets.listProjectSkills(X,oe).then(He=>{ie||de(He)}).catch(()=>{ie||de([])}),()=>{ie=!0}},[X,oe]);const Z=g?.commands,ae=y5(),be=m.useMemo(()=>{if(!Z)return[];const ie={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])")},St={name:"/plan",description:e("Plan mode: research read-only, then approve a plan (/plan [task] · off)")},it=De.filter(ht=>ht.enabled!==!1).map(ht=>({name:`/skill:${ht.name}`,description:ht.description})),je=z.map(ht=>({name:`/skill:${ht.name}`,description:ht.description}));return ND([ie,He,...$?[St]:[],...it,...je,...Z,...ae])},[e,De,z,Z,ae,$]),ze=m.useRef(null),Ye=!g?.displayedParentId&&["planning","awaiting_review"].includes(Jj(g?.planState)),Ve=g?.status==="running",at=g?.busy===!0,Ze=g?.parentWorktreePath??L?.path,Et=m.useMemo(()=>(g?.pendingCapabilityAsks??[]).map(ie=>({requestId:ie.requestId,tool:ie.capabilityId,kind:"mcp",summary:ie.summary})),[g?.pendingCapabilityAsks]),Gt=m.useCallback(()=>{g&&!g.parentStarted&&g.parentSessionFile&&!g.parentWorktreeMissing&&g.parentStatus!=="failed"&&se.getState().resumeConversation(g.parentId)},[g]);m.useEffect(()=>{const ie=g?.compactionError;!ie||!g||(Fe({type:"error",title:e("Compaction failed"),description:ie}),se.getState().clearCompactionError(g.id))},[g,e]);const Pt=YJ(g,f);if(!g)return i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",...Pt==="hydrating"?{"data-timeline-loading":""}:{},children:[t&&i.jsx(Zj,{"data-enso":"title-bar"}),Pt==="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(gte,{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(ote,{conversationId:g.parentId}),i.jsx(oee,{parentId:g.parentId,displayedId:g.id,trailing:i.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-1",children:[i.jsx(gQ,{parentId:g.parentId,coworkerIds:x??[]}),L?i.jsx(ite,{project:L,conversationId:g.parentId,path:g.parentWorktreePath??L.path,branch:_e,openDisabled:g.parentWorktreeMissing,children:ne}):i.jsx("div",{className:"flex min-w-0 shrink-0 items-center",children:ne})]})}),i.jsx(LI,{conversationId:g.id,cwd:Ze,emptyTitle:L?.name??"EnsoCode",onSuggestion:L?pte:void 0,timelineRef:ze}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:ji,children:[L&&L.kind!=="ssh"&&L.kind!=="scratch"&&!g.displayedParentId&&i.jsx(xee,{projectId:L.id,conversationId:g.id}),g.retry&&i.jsx(Mh,{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(Zt,{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(Lg.Provider,{value:{conversationId:g.id,projectId:g.projectId,...Ze?{cwd:Ze}:{}},children:i.jsx(kv,{sessionId:g.id,tasks:g.backgroundTasks??[],subagents:g.subagents??[]},g.id)}),i.jsx(Vl,{approvals:Et,allowSession:!1,handoff:!1,onRespond:(ie,He)=>{He!=="allow"&&He!=="deny"||se.getState().respondCapabilityAsk(g.id,ie,He)}},Et[0]?.requestId??"no-capability-approval"),i.jsx(Vl,{approvals:g.pendingApprovals??[],allowSession:g.childLockedProfileId===void 0,onRespond:(ie,He)=>{window.electronAPI.agent.respondApproval(g.id,ie,He)}}),i.jsx(oQ,{}),i.jsx(wh,{asks:g.pendingAsks??[],onAnswer:(ie,He)=>{window.electronAPI.agent.respondAsk(g.id,ie,He)}}),g.activeOauthAsk&&i.jsx(KJ,{request:g.activeOauthAsk,conversationId:g.id},g.activeOauthAsk.requestId),!g.displayedParentId&&i.jsx(uee,{conversationId:g.id,planState:g.planState,approvalMode:g.approvalMode??"full"}),i.jsx(qI,{conversationId:g.id,queued:g.queuedMessages??[]}),g.goal&&i.jsx(dee,{conversationId:g.id,goal:g.goal}),i.jsx(NK,{conversationId:g.id},g.id),!g.displayedParentId&&ee&&i.jsx("div",{role:"status",className:"rounded-md border border-dashed px-3 py-2 text-muted-foreground text-xs",children:ee}),i.jsx(Sv,{cwd:L?.path,chatCandidates:S,commands:be,running:Ve,busy:at,locked:(g.pendingApprovals??[]).length>0||Et.length>0||!!(g.rewinding||g.restoringFiles),focusKey:g.id,pluginPresetId:v,planMode:Ye,savePastedText:L?.kind==="ssh"?void 0:ie=>window.electronAPI.files.savePastedText({conversationId:g.id,text:ie}),voice:p?vD:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,placeholder:Ye?e("Describe the task — a plan comes first"):void 0,injectedDraft:g.draftText,injectedImages:g.draftImages,injectedDraftAppend:g.draftAppend,onDraftConsumed:()=>se.getState().clearDraft(g.id),queuedCount:g.queuedMessages?.length??0,onSteerQueued:()=>se.getState().steerQueued(g.id),initialRecipient:g.prefillAgentTypeKey===tu?mte:void 0,onInitialRecipientConsumed:()=>se.getState().clearAgentPrefill(g.id),toolbar:i.jsxs(i.Fragment,{children:[!g.displayedParentId&&i.jsxs(i.Fragment,{children:[i.jsx(mee,{presetId:g.presetId??"default",disabled:g.started,onSelect:ie=>se.getState().setPreset(g.id,ie),onModel:ie=>se.getState().setModel(g.id,ie.providerId,ie.modelId)}),i.jsx(ute,{conversationId:g.id,onBranchChange:ve}),($||g.planState?.active)&&i.jsx(fee,{active:g.planState?.active??!1,onToggle:ie=>se.getState().setPlanMode(g.id,ie)}),i.jsx(S5,{mode:g.approvalMode??"full",autoReject:g.autoRejectApprovals===!0,onSelect:ie=>se.getState().setApprovalMode(g.id,ie),onToggleAutoReject:ie=>se.getState().setAutoRejectApprovals(g.id,ie)}),i.jsx(ih,{listenHotkey:!0,refreshAllModels:!0,providers:w,virtualModels:s,routedModelLabel:Y,activeAccount:U,providerId:B,modelId:O,reasoningEnabled:g.reasoningEnabled??!1,thinkingLevel:g.thinkingLevel??"medium",onSelect:(ie,He)=>se.getState().setModel(g.id,ie,He),onReasoningChange:ie=>se.getState().setReasoning(g.id,ie),onThinkingChange:ie=>se.getState().setThinking(g.id,ie)})]}),g.displayedParentId&&i.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[y??(g.agentType?Yj(g.agentType,o):"coworker"),g.lastModelId?` · ${Af(s,g.lastModelId)}`:""]})]}),onActivate:Gt,onSend:ie=>!ie.recipient&&!L||!ie.recipient&&!g.displayedParentId&&(!B||!O)?!1:(aee(ie,{dispatchAgent:(He,St)=>{se.getState().dispatchAgent(He,St,H)},sendCoding:(He,St)=>{L&&(ze.current?.scrollToBottom(),se.getState().send(He,{providerId:B,modelId:O,cwd:L.path},St))}}),!0),onAbort:()=>{se.getState().abort()}}),i.jsx(nE,{conversationId:g.id,cwd:Ze})]})})]})}const mte={kind:"agent-type",id:tu,typeKey:tu,label:"Enso",displayName:"Enso",description:"EnsoCode system agent for product capabilities and team setup",source:"system",locked:!0,canDisable:!1,canEdit:!1};function gte({status:e,pendingAskCount:t=0,hasRunningChild:n=!1}){const s=Hg({status:e,pendingAskCount:t,hasRunningChild:n});return i.jsx(Lh,{tone:s,title:e})}function oE(e,t,n){const s=e.slice();return s.splice(n<0?s.length+n:n,0,s.splice(t,1)[0]),s}function xte(e,t){return e.reduce((n,s,o)=>{const r=t.get(s);return r&&(n[o]=r),n},Array(e.length))}function ac(e){return e!==null&&e>=0}function vte(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 bte(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const lc={scaleX:1,scaleY:1},wte=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=yte(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,...lc}:null}return a>o&&a<=r?{x:-l.width-d,y:0,...lc}:a<o&&a>=r?{x:l.width+d,y:0,...lc}:{x:0,y:0,...lc}};function yte(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 rE=e=>{let{rects:t,activeIndex:n,overIndex:s,index:o}=e;const r=oE(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}},dc={scaleX:1,scaleY:1},sC=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,...dc}:null}const d=Ste(r,o,n);return o>n&&o<=a?{x:0,y:-l.height-d,...dc}:o<n&&o>=a?{x:0,y:l.height+d,...dc}:{x:0,y:0,...dc}};function Ste(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 aE="Sortable",lE=Ne.createContext({activeIndex:-1,containerId:aE,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:rE,disabled:{draggable:!1,droppable:!1}});function Jm(e){let{children:t,id:n,items:s,strategy:o=rE,disabled:r=!1}=e;const{active:a,dragOverlay:l,droppableRects:d,over:c,measureDroppableContainers:u}=xd(),h=md(aE,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),b=!vte(f,y.current),w=v!==-1&&x===-1||b,_=bte(r);bi(()=>{b&&g&&u(f)},[b,f,g,u]),m.useEffect(()=>{y.current=f},[f]);const C=m.useMemo(()=>({activeIndex:x,containerId:h,disabled:_,disableTransforms:w,items:f,overIndex:v,useDragOverlay:p,sortedRects:xte(f,d),strategy:o}),[x,h,_.draggable,_.droppable,w,f,v,d,p,o]);return Ne.createElement(lE.Provider,{value:C},t)}const Cte=e=>{let{id:t,items:n,activeIndex:s,overIndex:o}=e;return oE(n,s,o).indexOf(t)},kte=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},jte={duration:200,easing:"ease"},dE="transform",_te=zi.Transition.toString({property:dE,duration:0,easing:"linear"}),Nte={roleDescription:"sortable"};function Tte(e){let{disabled:t,index:n,node:s,rect:o}=e;const[r,a]=m.useState(null),l=m.useRef(n);return bi(()=>{if(!t&&n!==l.current&&s.current){const d=o.current;if(d){const c=ka(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 Oh(e){let{animateLayoutChanges:t=kte,attributes:n,disabled:s,data:o,getNewIndex:r=Cte,id:a,strategy:l,resizeObserverConfig:d,transition:c=jte}=e;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:g,sortedRects:x,overIndex:v,useDragOverlay:y,strategy:b}=m.useContext(lE),w=Dte(s,f),_=u.indexOf(a),C=m.useMemo(()=>({sortable:{containerId:h,index:_,items:u},...o}),[h,o,_,u]),N=m.useMemo(()=>u.slice(u.indexOf(a)),[u,a]),{rect:S,node:k,isOver:A,setNodeRef:I}=vd({id:a,data:C,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...d}}),{active:E,activatorEvent:D,activeNodeRect:T,attributes:H,setNodeRef:F,listeners:O,isDragging:B,over:Y,setActivatorNodeRef:U,transform:ee}=Jg({id:a,data:C,attributes:{...Nte,...n},disabled:w.draggable}),L=Cz(I,F),Q=!!E,V=Q&&!g&&ac(p)&&ac(v),ce=!y&&B,ve=ce&&V?ee:null,De=V?ve??(l??b)({rects:x,activeNodeRect:T,activeIndex:p,overIndex:v,index:_}):null,me=ac(p)&&ac(v)?r({id:a,items:u,activeIndex:p,overIndex:v}):_,$=E?.id,z=m.useRef({activeId:$,items:u,newIndex:me,containerId:h}),de=u!==z.current.items,X=t({active:E,containerId:h,isDragging:B,isSorting:Q,id:a,index:_,items:u,newIndex:z.current.newIndex,previousItems:z.current.items,previousContainerId:z.current.containerId,transition:c,wasDragging:z.current.activeId!=null}),oe=Tte({disabled:!X,index:_,node:k,rect:S});return m.useEffect(()=>{Q&&z.current.newIndex!==me&&(z.current.newIndex=me),h!==z.current.containerId&&(z.current.containerId=h),u!==z.current.items&&(z.current.items=u)},[Q,me,h,u]),m.useEffect(()=>{if($===z.current.activeId)return;if($!=null&&z.current.activeId==null){z.current.activeId=$;return}const ae=setTimeout(()=>{z.current.activeId=$},50);return()=>clearTimeout(ae)},[$]),{active:E,activeIndex:p,attributes:H,data:C,rect:S,index:_,newIndex:me,items:u,isOver:A,isSorting:Q,isDragging:B,listeners:O,node:k,overIndex:v,over:Y,setNodeRef:L,setActivatorNodeRef:U,setDroppableNodeRef:I,setDraggableNodeRef:F,transform:oe??De,transition:Z()};function Z(){if(oe||de&&z.current.newIndex===_)return _te;if(!(ce&&!lh(D)||!c)&&(Q||X))return zi.Transition.toString({...c,property:dE})}}function Dte(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}}pn.Down,pn.Right,pn.Up,pn.Left;const iC=["idle","running","waiting","error"];function cE(e,t){return e?Nv({...e,hasRunningChild:Rg({...e,status:e.status??"idle"},t)}):"idle"}function Nv(e){const t=Hg({status:e.status??"idle",spawning:e.spawning,pendingAskCount:(e.pendingAsks?.length??0)+(e.pendingApprovals?.length??0)+(e.pendingCapabilityAsks?.length??0),hasRunningChild:e.hasRunningChild});return t==="failed"?"error":t==="unread"?"idle":t}function Ite(e){let t=0;for(const n of Object.values(e))!n||n.parentId||n.btwParentId||(t=Math.max(t,iC.indexOf(cE(n,e))));return iC[t]}const Ete=e=>e==="/"?null:e.replace(/\/[^/]+$/,"")||"/";function Pte(e,t){const n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}function Qm({list:e,create:t,initialPath:n,reloadKey:s=0,onSelect:o,onClose:r}){const{t:a}=J(),[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),b=m.useRef(null),w=m.useRef(e);w.current=e;const _=m.useCallback((I,E=!1)=>{const D=++y.current;u(!0),p(""),w.current(I,E).then(T=>{if(!(D!==y.current||!T)){if("error"in T){p(T.error);return}d(T),b.current=T.path}}).catch(()=>{D===y.current&&p(a("Failed to list remote directory."))}).finally(()=>{D===y.current&&u(!1)})},[a]),C=m.useRef(n);m.useEffect(()=>{_(C.current)},[_]),m.useEffect(()=>{s&&_(b.current??C.current,!0)},[s,_]);const N=l?.path??null,S=l?.dirs??[],k=l?.parent??null,A=()=>{if(!t||!N||f===null||!f.trim())return;const I=++y.current;u(!0),v(""),t(N,f).then(E=>{if(I===y.current){if("error"in E){v(a(E.error));return}g(null),p(""),d(E),b.current=E.path}}).catch(()=>{I===y.current&&v(a("Failed to list remote directory."))}).finally(()=>{I===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(fe,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!k||c,onClick:()=>k&&_(k),children:a("Up")}),t&&i.jsx(fe,{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(fe,{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(Jt,{autoFocus:!0,size:"sm",className:"min-w-0 flex-1 font-mono text-xs",placeholder:a("Folder name"),value:f,disabled:c,onChange:I=>g(I.target.value),onKeyDown:I=>{I.key==="Enter"?(I.preventDefault(),A()):I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),g(null))}}),i.jsx(fe,{type:"button",size:"sm",className:"h-7 px-2 text-xs",disabled:c||!f.trim(),onClick:A,children:a("Create")}),i.jsx(fe,{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}):S.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:S.map(I=>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&&_(Pte(N,I)),children:[I,"/"]},I))}),c&&i.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60",children:[i.jsx(Zt,{className:"h-4 w-4 animate-spin text-muted-foreground"}),i.jsx("span",{className:"sr-only",children:a("Loading...")})]})]}),i.jsx(fe,{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 Ate({open:e,onOpenChange:t,onAdd:n,groups:s=[],defaultGroupId:o}){const{t:r}=J(),a=Se(z=>z.projects),[l,d]=m.useState("local"),[c,u]=m.useState(""),[h,p]=m.useState(""),[f,g]=m.useState(""),[x,v]=m.useState([]),[y,b]=m.useState(o),[w,_]=m.useState(!1),[C,N]=m.useState([]),[S,k]=m.useState(""),[A,I]=m.useState(null),[E,D]=m.useState(null),[T,H]=m.useState(0),[F,O]=m.useState(!1),B=m.useMemo(()=>[{value:"",label:r("Ungrouped")},...s.map(z=>({value:z.id,label:z.name}))],[s,r]);m.useEffect(()=>{e&&(d("local"),u(""),p(""),g(""),b(o),_(!1),k(""),I(null),D(null),H(0),window.electronAPI.sshConnections.list().then(v).catch(()=>v([])),window.electronAPI.projects.getRecent().then(N).catch(()=>N([])))},[e,o]);const Y=m.useMemo(()=>new Set(a.map(z=>z.path)),[a]),U=m.useMemo(()=>C.filter(z=>!Y.has(z.path)),[C,Y]),ee=m.useCallback((z,de)=>{if(!de)return!0;const X=de.toLowerCase();return z.path.toLowerCase().includes(X)||z.displayPath.toLowerCase().includes(X)||z.sourceName.toLowerCase().includes(X)},[]),L=!!window.electronAPI.remote,Q=async()=>{if(L){_(de=>!de);return}const z=await window.electronAPI.dialog.selectDirectory();z&&u(z)},V=m.useCallback(z=>window.electronAPI.projects.listHostDirs(z).then(de=>de.ok?de:{error:de.error}),[]),ce=m.useCallback((z,de)=>window.electronAPI.projects.createHostDir(z,de).then(X=>X.ok?X:{error:X.error}),[]),ve=m.useCallback(async(z,de)=>{const X=await window.electronAPI.sshConnections.listDirs(h,z);if(X.ok)return{path:X.path,parent:Ete(X.path),dirs:X.dirs};const oe=k0(X,x.find(Z=>Z.id===h));return!oe||de?{error:X.error}:(D("browse"),I(oe),null)},[h,x]),_e=l==="local"?c.trim().length>0:h.length>0&&f.trim().startsWith("/"),De=()=>{const z=x.find(de=>de.id===h);n({path:f.trim(),sshConnectionId:h,sshHost:z?.name,...y?{groupId:y}:{}}),t(!1)},me=z=>{if(z.preventDefault(),!_e)return;if(l!=="ssh"){n({path:c.trim(),...y?{groupId:y}:{}}),t(!1);return}k("");const de=x.find(X=>X.id===h);window.electronAPI.sshConnections.test(h).then(X=>{if(!X.ok){const oe=k0(X,de);if(oe){D("submit"),I(oe);return}k(X.error);return}De()})},$=async()=>{if(!A)return;O(!0);const z=await window.electronAPI.sshConnections.trustHost(h);if(O(!1),!z.ok){k(z.error||r("Could not save host key.")),I(null),D(null);return}const de=E;if(I(null),D(null),de==="browse"){H(X=>X+1);return}de==="submit"&&De()};return i.jsxs(vn,{open:e,onOpenChange:t,children:[i.jsx(bn,{className:"max-w-lg",children:i.jsxs("form",{onSubmit:me,className:"flex flex-col",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:r("Add project")}),i.jsx(As,{children:r("Add a local directory as the conversation working folder.")})]}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsx(Xu,{value:l,onValueChange:z=>{d(z),_(!1)},children:i.jsxs(Zu,{children:[i.jsx(Is,{value:"local",children:r("Local directory")}),i.jsx(Is,{value:"ssh",children:r("Remote (SSH)")})]})}),l==="ssh"?i.jsxs(i.Fragment,{children:[i.jsxs(Os,{className:"w-full",children:[i.jsx(zs,{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(vs,{items:[{value:"",label:r("Select an SSH connection")},...x.map(z=>({value:z.id,label:`${z.name} (${z.user?`${z.user}@`:""}${z.host})`}))],value:h,onValueChange:z=>p(z??""),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsxs(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:[i.jsx(os,{value:"",children:r("Select an SSH connection")}),x.map(z=>i.jsxs(os,{value:z.id,children:[z.name," (",z.user?`${z.user}@`:"",z.host,")"]},z.id))]})]})]}),i.jsxs(Os,{className:"w-full",children:[i.jsx(zs,{children:r("Remote directory")}),i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx(Jt,{value:f,onChange:z=>g(z.target.value),placeholder:"/home/user/project",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,className:"min-w-0 flex-1"}),i.jsx(fe,{type:"button",variant:"outline",disabled:!h,onClick:()=>_(z=>!z),children:r("Browse")})]})]}),w&&h&&i.jsx(Qm,{list:ve,initialPath:f.trim().startsWith("/")?f.trim():void 0,reloadKey:T,onSelect:z=>{g(z),_(!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.")}),S&&i.jsx("p",{className:"text-destructive text-xs",children:S})]}):i.jsxs(Os,{className:"w-full",children:[i.jsx(zs,{children:r("Working directory")}),i.jsxs(fv,{value:c,onValueChange:z=>u(z??""),items:U,filter:ee,itemToStringValue:z=>z.path,children:[i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(mv,{placeholder:r("Type a path or select from recent projects..."),showClear:!!c,showTrigger:!0})}),i.jsx(fe,{type:"button",variant:"outline",onClick:()=>{Q()},children:r("Browse")})]}),i.jsxs(SI,{zIndex:kn.DROPDOWN_IN_MODAL,children:[i.jsx(xv,{children:r("No matching projects found")}),i.jsx(vv,{children:z=>i.jsxs(gv,{value:z,className:"gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",title:z.path,children:z.displayPath}),i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:z.sourceName})]},z.path)})]})]}),w&&L&&i.jsx(Qm,{list:V,create:ce,initialPath:c.trim()||void 0,onSelect:z=>{u(z),_(!1)},onClose:()=>_(!1)})]}),s.length>0&&i.jsxs(Os,{children:[i.jsx(zs,{children:r("Project group")}),i.jsxs(vs,{items:B,value:y??"",onValueChange:z=>b(z||void 0),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:B.map(z=>i.jsx(os,{value:z.value,children:z.label},z.value||"ungrouped"))})]})]})]}),i.jsxs(rs,{children:[i.jsx(fe,{type:"button",variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(fe,{type:"submit",size:"sm",disabled:!_e,children:r("Add")})]})]})}),i.jsx(C5,{challenge:A,nested:!0,busy:F,onTrust:()=>{$()},onDismiss:()=>{F||(I(null),D(null))}})]})}function Mte(e,t){return{x:e.left-t,width:Math.max(0,e.width)}}const uE="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",hE="flex size-4.5 shrink-0 items-center justify-center rounded-[5px] text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",Rte=24,$a=20;function Lte({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}=J(),g=e.slice().sort((Y,U)=>Y.order-U.order),x=g.length>0,v=d||a.length>0,y=m.useRef(null),b=m.useRef(null),w=m.useRef(null),_=m.useRef(null),C=m.useRef(null),[N,S]=m.useState({left:!1,right:!1,overflow:!1}),{active:k}=xd(),A=g.find(Y=>Y.id===t),I=t===hs?f("Ungrouped"):A?.name??null,E=I?f("Search in {{group}}...",{group:I}):f("Search conversations..."),D=m.useCallback(()=>{const Y=w.current,U=b.current,ee=_.current,L=C.current,Q=U?.querySelector("[data-selected]");if(!Y||!U||!ee||!L||!Q||Y.offsetParent===null){L&&(L.style.width="0px");return}const V=U.getBoundingClientRect(),ce=Y.getBoundingClientRect(),ve=Q.getBoundingClientRect(),_e=Mte(ve,V.left);ee.style.left=`${V.left-ce.left}px`,ee.style.width=`${V.width}px`,L.style.transform=`translateX(${_e.x}px)`,L.style.width=`${_e.width}px`},[]),T=m.useCallback(()=>{const Y=b.current;D(),!(!Y||Y.clientWidth===0)&&S(U=>{const ee=U.overflow?Rte:0,L={left:Y.scrollLeft>1,right:Y.scrollLeft+Y.clientWidth<Y.scrollWidth-1,overflow:Y.scrollWidth>Y.clientWidth+ee+1};return U.left===L.left&&U.right===L.right&&U.overflow===L.overflow?U:L})},[D]);m.useLayoutEffect(()=>{const Y=b.current;if(!Y)return;T();const U=new ResizeObserver(T);return U.observe(Y),Y.firstElementChild&&U.observe(Y.firstElementChild),()=>U.disconnect()},[T]),m.useLayoutEffect(()=>{D()},[D,k,t,v,g.length]),m.useEffect(()=>{const Y=b.current;if(!Y)return;const U=ee=>{Math.abs(ee.deltaY)<=Math.abs(ee.deltaX)||Y.scrollWidth<=Y.clientWidth||(Y.scrollLeft+=ee.deltaY,ee.preventDefault())};return Y.addEventListener("wheel",U,{passive:!1}),()=>Y.removeEventListener("wheel",U)},[]);const H=m.useRef(!1);m.useLayoutEffect(()=>{const Y=b.current,U=Y?.querySelector("[data-selected]");if(!Y||!U||Y.clientWidth===0)return;const ee=H.current?"smooth":"auto";H.current=!0;const L=U.offsetLeft,Q=L+U.offsetWidth;L<Y.scrollLeft+$a?Y.scrollTo({left:L-$a,behavior:ee}):Q>Y.scrollLeft+Y.clientWidth-$a&&Y.scrollTo({left:Q-Y.clientWidth+$a,behavior:ee})},[t,x,d]),m.useEffect(()=>{d&&y.current?.focus()},[d]);const F=()=>{l(""),c(!1)},O=Y=>Y?`${$a}px`:"0px",B=N.left||N.right?`linear-gradient(to right, transparent, #000 ${O(N.left)}, #000 calc(100% - ${O(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(AN,{className:"size-3.5 shrink-0"}),i.jsx("input",{ref:y,value:a,onChange:Y=>l(Y.target.value),onKeyDown:Y=>{Y.key==="Escape"&&(Y.stopPropagation(),F())},onBlur:()=>{!a&&document.hasFocus()&&c(!1)},placeholder:E,className:"h-full min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground"}),i.jsx("button",{type:"button",onClick:F,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(ln,{className:"size-3"})})]}),i.jsxs("div",{ref:w,className:W("relative flex min-w-0 flex-1 items-center gap-1.5",v&&"hidden"),children:[i.jsx("div",{ref:b,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-enso":"group-chip","data-selected":t===In||void 0,"data-active":t===In||void 0,onClick:()=>u(In),className:Lu(t===In,!1),children:i.jsx(Ou,{label:f("All"),count:s})}),i.jsx("button",{type:"button","data-enso":"group-chip","data-selected":t===Eo||void 0,"data-active":t===Eo||void 0,onClick:()=>u(Eo),className:Lu(t===Eo,!1),children:i.jsx(Ou,{label:f("Recent"),count:o})}),i.jsx(Jm,{items:g.map(Y=>yv(Y.id)),strategy:wte,children:g.map(Y=>i.jsx(Ote,{group:Y,count:n[Y.id]??0,selected:t===Y.id,onSelect:()=>u(Y.id)},Y.id))}),x&&i.jsx(zte,{label:f("Ungrouped"),count:r,selected:t===hs,onSelect:()=>u(hs)})]})}),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:C,className:"absolute top-0 left-0 h-full rounded-full bg-foreground"})}),i.jsx("button",{type:"button",onClick:h,className:W(hE,"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(us,{className:"size-3"})}),N.overflow&&i.jsx(Gte,{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 Lu(e,t){return W("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 Ou({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 pE=e=>e?.type==="project";function Ote({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}=Oh({id:yv(e.id),data:{type:"project-group",groupId:e.id}});return i.jsx("button",{ref:a,type:"button","data-enso":"group-chip","data-selected":n||void 0,"data-active":n||void 0,onClick:s,style:{transform:l?`translate3d(${Math.round(l.x)}px, 0, 0)`:void 0,transition:d},className:W(Lu(n,u&&pE(h?.data.current)),c&&"z-10 cursor-grabbing text-foreground"),...o,...r,children:i.jsx(Ou,{label:e.name,count:t,emoji:e.emoji,color:e.color})})}function zte({label:e,count:t,selected:n,onSelect:s}){const{active:o}=xd(),{setNodeRef:r,isOver:a}=vd({id:yv(hs),disabled:o?.data.current?.type==="project-group"});return i.jsx("button",{ref:r,type:"button","data-enso":"group-chip","data-selected":n||void 0,"data-active":n||void 0,onClick:s,className:Lu(n,a&&pE(o?.data.current)),children:i.jsx(Ou,{label:e,count:t})})}function Gte({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,onSelect:a,onAddGroup:l,onEditGroup:d}){const{t:c}=J(),[u,h]=m.useState(!1),p=f=>()=>{h(!1),f()};return i.jsxs(gi,{open:u,onOpenChange:h,children:[i.jsx(xi,{className:W(hE,"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($n,{className:"size-3"})}),i.jsxs(vi,{side:"bottom",align:"end",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsx(cc,{label:c("All"),count:s,selected:t===In,onSelect:p(()=>a(In))}),i.jsx(cc,{label:c("Recent"),count:o,selected:t===Eo,onSelect:p(()=>a(Eo))}),e.map(f=>i.jsx(cc,{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(cc,{label:c("Ungrouped"),count:r,selected:t===hs,onSelect:p(()=>a(hs))}),i.jsx("div",{className:"my-1 border-t"}),i.jsxs("button",{type:"button",onClick:p(l),className:W(uE,"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx(us,{className:"size-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:c("New group")})]})]})]})}function cc({label:e,count:t,emoji:n,color:s,selected:o,onSelect:r,onEdit:a}){const{t:l}=J();return i.jsxs("div",{className:"group/row relative",children:[i.jsxs("button",{type:"button",onClick:r,className:W(uE,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(Kn,{className:W("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($s,{className:"size-3.5"})})]})}function fE({value:e,reasoningEnabled:t,thinkingLevel:n,onChange:s,onReasoningChange:o,onThinkingChange:r,description:a,inheritLabel:l}){const{t:d}=J(),c=Se(g=>g.virtualModels),u=Fg(),h=e?u.find(g=>g.id===e.providerId):void 0,p=h?.models.find(g=>g.id===e?.modelId),f=Gj(c,e);return i.jsxs(Os,{className:"w-full items-stretch",children:[i.jsx(zs,{children:d("Default model")}),i.jsx(c_,{children:a}),u.length>0&&i.jsx("div",{className:"w-full min-w-0",children:i.jsx(ih,{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:k5,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(fe,{type:"button",variant:"ghost",size:"sm",className:"self-start",onClick:()=>s(null),children:d("Follow default model")})]})}const Fte=["#3b82f6","#22c55e","#eab308","#f97316","#ef4444","#a855f7","#06b6d4","#64748b"];function Hte({open:e,group:t,projects:n,onOpenChange:s,onSave:o,onDelete:r}){const{t:a}=J(),l=Se(D=>D.defaultReasoningEnabled),d=Se(D=>D.defaultThinkingLevel),[c,u]=m.useState(""),[h,p]=m.useState(),[f,g]=m.useState(null),[x,v]=m.useState(!0),[y,b]=m.useState("medium"),[w,_]=m.useState(new Set),[C,N]=m.useState(""),S=t===null,k=S?n??[]:[],A=C.trim().toLowerCase(),I=A?k.filter(D=>D.name.toLowerCase().includes(A)):k;m.useEffect(()=>{if(!e)return;u(t?.name??""),p(t?.color),g(t?.defaultModel??null);const D=nu({defaultReasoningEnabled:l,defaultThinkingLevel:d});v(t?.defaultReasoningEnabled??D.reasoningEnabled),b(t?.defaultThinkingLevel??D.thinkingLevel),_(new Set),N("")},[e,t,l,d]);const E=D=>{_(T=>{const H=new Set(T);return H.has(D)?H.delete(D):H.add(D),H})};return i.jsx(vn,{open:e,onOpenChange:s,children:i.jsx(bn,{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,...S&&w.size>0?{projectIds:[...w]}:{}}),s(!1))},children:[i.jsxs(wn,{children:[i.jsx(yn,{children:a(t?"Edit group":"New group")}),i.jsx(As,{children:a("Groups organize projects in the sidebar.")})]}),i.jsxs(Mn,{className:"space-y-3",children:[i.jsxs(Os,{children:[i.jsx(zs,{children:a("Name")}),i.jsx(Jt,{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(ln,{className:"h-3 w-3"})}),Fte.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(fE,{value:f,reasoningEnabled:x,thinkingLevel:y,onChange:D=>{if(g(D),D)return;const T=nu({defaultReasoningEnabled:l,defaultThinkingLevel:d});v(T.reasoningEnabled),b(T.thinkingLevel)},onReasoningChange:v,onThinkingChange:b,description:a("Used for new conversations in this group."),inheritLabel:a("Follows the global default")}),k.length>0&&i.jsxs(Os,{className:"w-full items-stretch",children:[i.jsx(zs,{children:a("Move projects into this group")}),i.jsx(Jt,{value:C,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:[I.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(hd,{checked:w.has(D.id),onCheckedChange:()=>E(D.id)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:D.name})]},D.id)),I.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(rs,{className:t?"sm:justify-between":void 0,children:[t&&r?i.jsx(fe,{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(fe,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),children:a("Cancel")}),i.jsx(fe,{type:"submit",size:"sm",disabled:!c.trim(),children:a("Save")})]})]})]})})})}function Bte({project:e,onClose:t}){const{t:n}=J(),[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&&(se.getState().addImportedConversation(e.id,p),t())}finally{u(!1)}}};return i.jsx(vn,{open:e!==null,onOpenChange:p=>!p&&t(),children:i.jsxs(bn,{className:"max-w-3xl",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:n("Import session")}),i.jsx(As,{children:n("Pick a conversation from a local AI app under {{name}}.",{name:e?.name??""})})]}),i.jsx(Mn,{children:s===null?i.jsx("div",{className:"flex flex-col items-center gap-3 py-12",children:i.jsx(pr,{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:W("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(pr,{className:"size-4"})}):i.jsx("div",{className:"flex flex-col gap-2.5",children:l.map((p,f)=>i.jsx("div",{className:W("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(rs,{children:[i.jsx(fe,{variant:"outline",onClick:t,children:n("Cancel")}),i.jsxs(fe,{onClick:()=>{h()},disabled:!r||c,children:[c?i.jsx(pr,{className:"mr-1.5 size-3.5"}):i.jsx(od,{className:"mr-1.5 h-3.5 w-3.5"}),n("Import")]})]})]})})}function $te({open:e,project:t,onOpenChange:n}){const{t:s}=J(),o=Se(L=>L.projectGroups),r=Se(L=>L.defaultReasoningEnabled),a=Se(L=>L.defaultThinkingLevel),l=Se(L=>L.setProjectDefaultModel),d=Se(L=>L.setProjectGroupId),c=Se(L=>L.setProjectAlias),u=Se(L=>L.setProjectDisabledBuiltinTools),h=Se(L=>L.setProjectSubagentAllowedModes),p=Se(L=>L.setProjectTrustedCode),f=Se(L=>L.disabledBuiltinTools),g=Se(L=>L.subagentAllowedModes),[x,v]=m.useState(""),[y,b]=m.useState(null),[w,_]=m.useState(!0),[C,N]=m.useState("medium"),[S,k]=m.useState(""),[A,I]=m.useState(!0),[E,D]=m.useState([]),[T,H]=m.useState(!0),[F,O]=m.useState([]),[B,Y]=m.useState(!1);m.useEffect(()=>{if(!e)return;Y(!1),b(t?.defaultModel??null),k(t?.groupId??""),v(t?.alias??"");const L=t?.groupId?o.find(ve=>ve.id===t.groupId):void 0,Q=nu({groupReasoningEnabled:L?.defaultReasoningEnabled,groupThinkingLevel:L?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});_(t?.defaultReasoningEnabled??Q.reasoningEnabled),N(t?.defaultThinkingLevel??Q.thinkingLevel);const V=t?.disabledBuiltinTools===void 0;I(V),D(V?[...f]:[...t?.disabledBuiltinTools??[]]);const ce=t?.subagentAllowedModes===void 0;H(ce),O(ce?[...g]:[...t?.subagentAllowedModes??[]])},[e,t,o,r,a,f,g]);const U=m.useMemo(()=>[{value:"",label:s("Ungrouped")},...o.slice().sort((L,Q)=>L.order-Q.order).map(L=>({value:L.id,label:L.name}))],[o,s]),ee=t?.kind==="ssh"?`${t.sshConnectionName??t.sshHost}:${t.path}`:t?.path??"";return i.jsx(vn,{open:e,onOpenChange:n,children:i.jsx(bn,{className:"max-w-lg",children:i.jsxs("form",{className:"contents",onSubmit:L=>{L.preventDefault(),t&&(l(t.id,y,y?{reasoningEnabled:w,thinkingLevel:C}:null),d(t.id,S||null),c(t.id,x),u(t.id,A?null:E),h(t.id,T?null:F),B&&p(t.id,null),n(!1))},children:[i.jsxs(wn,{children:[i.jsx(yn,{children:s("Project settings")}),i.jsx(As,{children:t?Ao(t):s("Project")})]}),i.jsxs(Mn,{className:"max-h-[60vh] space-y-4",children:[i.jsxs(Os,{className:"w-full items-stretch",children:[i.jsx(zs,{children:s("Alias")}),i.jsx(Jt,{value:x,onChange:L=>v(L.target.value),placeholder:t?Ao({...t,alias:void 0}):""}),i.jsx(c_,{children:s("Shown in the sidebar instead of the folder name. Leave blank to reset.")})]}),i.jsxs(Os,{className:"w-full items-stretch",children:[i.jsx(zs,{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:ee,children:ee}),i.jsx(Lk,{text:ee,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(Os,{className:"w-full items-stretch",children:[i.jsx(zs,{children:s("Project group")}),i.jsxs(vs,{items:U,value:S,onValueChange:L=>k(L??""),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:U.map(L=>i.jsx(os,{value:L.value,children:L.label},L.value||"ungrouped"))})]})]}),i.jsx(fE,{value:y,reasoningEnabled:w,thinkingLevel:C,onChange:L=>{if(b(L),L)return;const Q=S?o.find(ce=>ce.id===S):void 0,V=nu({groupReasoningEnabled:Q?.defaultReasoningEnabled,groupThinkingLevel:Q?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});_(V.reasoningEnabled),N(V.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(ci,{checked:A,onCheckedChange:I})]}),!A&&i.jsx("div",{className:"space-y-2",children:j5.map(L=>i.jsxs("div",{className:"flex items-center gap-3 rounded-md border px-3 py-2.5",children:[i.jsx(Tg,{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(L.name)}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s(L.description)})]}),i.jsx(ci,{checked:!E.includes(L.id),onCheckedChange:Q=>D(V=>Q?V.filter(ce=>ce!==L.id):[...new Set([...V,L.id])])})]},L.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(ci,{checked:T,onCheckedChange:L=>{H(L),L||O([...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(([L,Q])=>i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsx("span",{className:"text-sm",children:s(Q)}),i.jsx(ci,{checked:F.includes(L),disabled:(A?f:E).includes("subagent"),onCheckedChange:V=>O(ce=>V?[...new Set([...ce,L])]:ce.filter(ve=>ve!==L))})]},L)),(A?f:E).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(sa,{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(fe,{type:"button",size:"xs",variant:"outline",disabled:B,onClick:()=>Y(!0),children:s("Revoke trust")})]}):null]}),i.jsxs(rs,{children:[i.jsx(fe,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsx(fe,{type:"submit",size:"sm",disabled:!t,children:s("Save")})]})]})})})}const Vte={connecting:"Connecting…","host-offline":"Desktop is offline",unauthorized:"Pairing expired",offline:"Reconnecting…"};function Wte(e,t){if(e.state!=="online")return t(Vte[e.state]);const n=e.transport==="direct"?t("Direct link"):t("Via relay"),s=_5(e.rttMs);return s?`${t("Connected")} · ${n} · ${s}`:`${t("Connected")} · ${n}`}function Ute(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}function Kte(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(n,s=>s.charCodeAt(0))}function qte(e){return e==="AbortError"?"service-unreachable":e==="NotAllowedError"?"permission-denied":"subscribe-failed"}async function Yte(e){if(!Ute())return{ok:!1,reason:"unsupported"};if(await Notification.requestPermission()!=="granted")return{ok:!1,reason:"permission-denied"};const n=await navigator.serviceWorker.ready;try{const o=(await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Kte(e)})).toJSON();return!o.endpoint||!o.keys?.p256dh||!o.keys?.auth?{ok:!1,reason:"subscribe-failed"}:{ok:!0,subscription:{endpoint:o.endpoint,keys:{p256dh:o.keys.p256dh,auth:o.keys.auth}}}}catch(s){const o=s instanceof Error?s.name:"";return{ok:!1,reason:qte(o)}}}const Xte="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground disabled:opacity-40";function Zte(){const e=window.electronAPI.remote,[t,n]=m.useState(null);return m.useEffect(()=>{if(!(!e?.linkStatus||!e.onLinkStatus))return n(e.linkStatus()),e.onLinkStatus(n)},[e]),t}function Jte(e,t){return e.pushError?t(mE[e.pushError]):e.pushAvailability==="needs-install"?t("Add this app to the Home Screen before notifications can be turned on."):e.pushAvailability==="unsupported"?t("This browser cannot show notifications."):e.pushReady?e.pushBusy?t("Turning on notifications…"):e.pushEnabled?t("Turn off notifications"):t("Turn on notifications"):t("Notifications need a newer desktop app.")}const mE={unsupported:"This browser cannot show notifications.","permission-denied":"Notification permission was denied. Allow notifications for this site and try again.","service-unreachable":"Cannot reach the push service. Check the network or proxy and try again.","subscribe-failed":"Could not turn on notifications."};function oC(){const{t:e}=J(),t=Zte();if(!t)return null;const n=Wte(t,e),s=Jte(t,e),o=t.pushBusy||t.pushAvailability!=="ok"||!t.pushReady||t.state!=="online"&&!t.pushEnabled;return i.jsxs(gi,{children:[i.jsx(xi,{className:Xte,title:n,"aria-label":n,children:i.jsx(nh,{className:"h-4 w-4"})}),i.jsxs(vi,{side:"top",align:"end",className:"w-64 [&_[data-slot=popover-viewport]]:px-3 [&_[data-slot=popover-viewport]]:py-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-md bg-background text-muted-foreground shadow-xs ring-1 ring-border",children:i.jsx(N5,{className:"size-3.5"})}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate font-medium text-sm leading-4",children:t.deviceLabel}),i.jsx("span",{className:"truncate text-subtle-foreground text-xs leading-4",children:n})]})]}),i.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 border-t pt-3",children:[i.jsx("span",{className:"text-sm",children:e("Push notifications")}),i.jsx(ci,{checked:t.pushEnabled,disabled:o,title:s,"aria-label":s,onCheckedChange:()=>{Qte(t)}})]}),t.pushError&&i.jsx("p",{className:"mt-2 text-destructive text-xs",children:e(mE[t.pushError])})]})]})}async function Qte(e){const t=window.electronAPI.remote;if(!t?.setPushSubscription||!t.setPushPending)return;if(e.pushEnabled){t.setPushSubscription(null);return}const n=t.vapidPublicKey?.();if(!n)return;t.setPushPending({busy:!0,enabled:!0,error:null});const s=await Yte(n);if(!s.ok){t.setPushPending({busy:!1,enabled:!1,error:s.reason});return}t.setPushSubscription(s.subscription)}const zh=5,gE=15,rC=9;function Gh(e,t){return e<=0?0:Math.min(e,zh+Math.max(0,t))}function ene(e,t){return Gh(e,t)>=e?0:Math.min(Math.max(0,e-zh),t+gE)}function tne(e){return Math.max(0,e-gE)}function nne(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>=rC||(f.add(v),p.push(v))};for(const v of h)g(v);const x=u_(t,n,s,r);for(const v of d?x.filter(c):x)g(v);for(const v of o){if(p.length>=rC)break;if(d?!1:a[v]===!0)continue;const b=al(t,n,v),w=!d||u(v)?b:b.filter(c),_=d?w:w.slice(0,Gh(w.length,l[v]??0));for(const C of _)g(C)}return p}function Tv(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 uc(e,t,n,s){const o=Tv(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 sne(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 ine(e,t){return e.includes(t)?e.filter(n=>n!==t):[t,...e]}function one(e,t,n){const s=n.includes(e),o=n.includes(t);return s&&o?"pinned":!s&&!o?"order":null}const Yc="enso-project-order",eg="enso-pinned-order",nl="enso-archived-projects",aC="enso-pinned-projects",tg=new Set;function hr(e){try{const t=JSON.parse(localStorage.getItem(e)??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Qo(e,t){localStorage.setItem(e,JSON.stringify(t));for(const n of tg)n()}function rne(e){return tg.add(e),()=>tg.delete(e)}function sf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function lC(e){return e==="browser"||typeof e=="string"&&e.startsWith("browser:")}function ane(e){if(typeof e.contentComponent=="string")return e.contentComponent;if(typeof e.component=="string")return e.component}function dC(e){if(!sf(e)||!sf(e.panels))return{browsers:0,terminals:0};let t=0,n=0;for(const[s,o]of Object.entries(e.panels)){if(!sf(o))continue;const r=ane(o);r==="browser"||lC(o.id)||lC(s)?t+=1:r==="terminal"&&(n+=1)}return{browsers:t,terminals:n}}function lne({conversationId:e}){const{t}=J(),n=xn(o=>dC(o.layouts[e]).browsers),s=xn(o=>dC(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(mo,{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(Fo,{className:"h-3 w-3","aria-hidden":!0}),s]})]})}const dne=[7,15,30],cC="h-6.5 rounded-lg px-2 text-xs text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",uC="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",of="-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 hC({width:e,collapsed:t,onToggleCollapse:n,onOpenSearch:s,onNavigate:o}){const{t:r,locale:a}=J(),l=Se(q=>q.projects),c=sh()==="mobile",u=Se(q=>q.scratchSessionsEnabled),h=Se(q=>q.projectGroups),p=Se(q=>q.createProjectGroup),f=Se(q=>q.updateProjectGroup),g=Se(q=>q.removeProjectGroup),x=Se(q=>q.reorderProjectGroups),v=Se(q=>q.setProjectGroupId),y=Se(q=>q.keybindings),b=Se(q=>q.activeRetentionMinutes),w=Li(y)["search-workspace"],_=w?mi(w):"",C=Se(q=>q.addProject),N=Se(q=>q.removeProject),S=se(q=>bv(q.conversations)),k=se(q=>q.order),A=se(q=>q.activeId),I=se(q=>q.newConversation),E=se(q=>q.selectConversation),D=m.useRef(o);D.current=o;const T=m.useCallback(q=>{D.current?.(),E(q)},[E]),H=se(q=>q.removeConversation),F=se(q=>q.togglePinConversation),O=se(q=>q.toggleArchiveConversation),B=se(q=>q.moveConversationToWorktree),Y=se(q=>q.cleanupWorktree),U=se(q=>q.refreshWorktreeStatuses),ee=se(q=>q.worktreeStatuses),[L,Q]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-projects")??"{}")}catch{return{}}}),V=q=>{Q(Ce=>{const ct={...Ce,[q]:!Ce[q]};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(ct)),ct})},[ce,ve]=m.useState(()=>{try{return localStorage.getItem(uC)==="1"}catch{return!1}}),_e=q=>{try{localStorage.setItem(uC,q?"1":"0")}catch{}},De=()=>{ve(q=>{const Ce=!q;return _e(Ce),Ce})},me=()=>{ve(q=>q&&(_e(!1),!1))},[$,z]=m.useState(()=>hr(Yc)),de=Tv(l.filter(q=>q.kind!=="scratch"),$),X=l.find(q=>q.kind==="scratch"),[oe,Z]=m.useState(()=>hr(nl)),[ae,be]=m.useState(()=>hr(aC)),ze=q=>{be(q),Qo(aC,q)},Ye=q=>{if(ze(ine(ae,q)),!ae.includes(q)&&oe.includes(q)){const Ce=oe.filter(ct=>ct!==q);Z(Ce),Qo(nl,Ce)}},Ve=q=>{const Ce=oe.includes(q)?oe.filter(ct=>ct!==q):[...oe,q];Z(Ce),Qo(nl,Ce),!oe.includes(q)&&ae.includes(q)&&ze(ae.filter(ct=>ct!==q))},[at,Ze]=m.useState(()=>{try{return localStorage.getItem("enso-selected-project-group")??In}catch{return In}}),[Et,Gt]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-project-groups")??"{}")}catch{return{}}}),Pt=q=>{Ze(q),localStorage.setItem("enso-selected-project-group",q)},ne=q=>{Gt(Ce=>{const ct={...Ce,[q]:!Ce[q]};return localStorage.setItem("enso-collapsed-project-groups",JSON.stringify(ct)),ct})},ie=at===In||at===Eo||at===hs||h.some(q=>q.id===at)?at:In,He=ie===Eo,St=h.find(q=>q.id===ie)?.id,it=zr(de,h,oe,ie),je=T5(zr(de,h,oe,In),k,S,Date.now()),{pinned:ht,rest:$t}=He?{pinned:[],rest:je}:sne(it,ae),Oe=h_($t,h,[]),yt=[...ht,...$t],Ht=yt.map(q=>q.id),re=new Set(Ht),[$e,st]=m.useState(()=>hr(eg)),{active:Nt}=xd(),mt=Nt?.data.current;C_({onDragEnd:q=>{const Ce=q.active.data.current;if(!Ce)return;const ct=q.over?String(q.over.id):null,bt=OQ(Ce,ct,A??void 0,{projectGroupId:Mt=>l.find(ts=>ts.id===Mt)?.groupId});if(bt)switch(bt.kind){case"move-project-to-group":{if(He&&bt.beforeProjectId)break;if(v(bt.projectId,bt.groupId),bt.beforeProjectId){const Mt=uc(l,$,bt.projectId,bt.beforeProjectId);z(Mt),Qo(Yc,Mt)}break}case"reorder-groups":x(bt.activeId,bt.overId);break;case"reorder-projects":{if(He)break;const Mt=one(bt.activeId,bt.overId,ae);if(Mt==="pinned"){const Ko=uc(ae.map(Co=>({id:Co})),ae,bt.activeId,bt.overId);ze(Ko);break}if(Mt!=="order")break;const ts=uc(l,$,bt.activeId,bt.overId);z(ts),Qo(Yc,ts);break}case"insert-file-mention":Jl({kind:"file",id:bt.path,label:bt.label,relativePath:bt.path});break;case"insert-chat-mention":Jl({kind:"chat",id:bt.conversationId,label:bt.label,sessionFile:bt.sessionFile});break;case"pin-conversation":F(bt.conversationId);break;case"reorder-pinned":{const Mt=uc(At.map(ts=>({id:ts})),$e,bt.activeId,bt.overId);st(Mt),Qo(eg,Mt);break}}}});const[K,he]=m.useState(null),[Ie,Ee]=m.useState(null),[Be,Je]=m.useState(!1),[ge,qe]=m.useState(!1),[lt,Tt]=m.useState(null),zt=q=>{const Ce=new Set(l.map(ct=>ct.id));q.sshConnectionId&&Tt({name:Uj(q.path),path:q.path,sshHost:q.sshHost}),C(q.path,q.sshConnectionId?{sshConnectionId:q.sshConnectionId}:void 0,q.groupId??St).then(ct=>{if(ct){if(oe.includes(ct.id)){const bt=oe.filter(Mt=>Mt!==ct.id);Z(bt),Qo(nl,bt)}if(Ce.has(ct.id)){Q(Mt=>{if(Mt[ct.id]!==!0)return Mt;const ts={...Mt,[ct.id]:!1};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(ts)),ts});const bt=al(k,S,ct.id)[0];if(bt){T(bt);return}}I(ct.id)}}).catch(ct=>{Fe({type:"error",title:r("Failed to add project"),description:ct instanceof Error?ct.message:String(ct)})}).finally(()=>Tt(null))},[cn,P]=m.useState(null),[M,R]=m.useState(null),j=async q=>{const Ce=S[q];let ct;if(Ce?.worktree){const bt=await dn(q);Tc(bt)&&(ct=qn(bt))}R({kind:"conversation",id:q,worktreeWarning:ct})},[G,pe]=m.useState({}),[xe,Pe]=m.useState(""),[Ke,ut]=m.useState(!1),[nt,Kt]=m.useState(()=>Date.now());m.useEffect(()=>{const q=setInterval(()=>Kt(Date.now()),D5);return()=>clearInterval(q)},[]);const dt={now:nt,ms:b*6e4},_t=I5(k,S,oe,dt),Dt=q=>{const Ce=gC(l,S[q].projectId),ct=A5(q,S,dt);if(ct===void 0)return Ce;const bt=r("Stays in Active for about {{count}} more min",{count:Math.ceil(ct/6e4)});return Ce?`${Ce}
|
|
97
|
-
${bt}`:bt},At=u_(k,S,$e,oe),Ct=E5(k,S,de.map(q=>q.id),oe).filter(q=>u||q.projectId!==X?.id),xt=xe.trim().length>0,kt=q=>Ha(xe,[S[q]?.title||r("New conversation")]),It=X?al(k,S,X.id).filter(q=>!xt||kt(q)):[],le=xt?!1:ce,Te=q=>{const Ce=S[q]?.projectId;return!Ce||re.has(Ce)},Ae=(xt?_t.filter(kt):_t).filter(Te),Ge=nne({order:k,conversations:S,pinnedOrderIds:$e,projectIds:Ht,archivedProjectIds:oe,collapsedProjects:L,revealedExtras:G,searching:xt,matches:kt,projectMatches:q=>{const Ce=de.find(ct=>ct.id===q);return!!(Ce&&Ha(xe,[Ce.alias??"",Ce.name,Ce.path]))},leadingIds:Ae}),Qe=m.useRef(Ge);Qe.current=Ge;const et=(xt?At.filter(kt):At).filter(Te),ye=new Set(et),ke=new Set(Ae),Me=(q,Ce)=>{if(t||!Ke)return;const ct=Ge.indexOf(q);if(!(ct<0||(ke.has(q)?"active":ye.has(q)?"pinned":"project")!==Ce))return mi(`mod+${ct+1}`)},[Le,Re]=m.useState(!1),[We,jt]=m.useState(""),[Bt,Vt]=m.useState(null),Wt=We.trim()?Ct.map(q=>{const Ce=l.find(bt=>bt.id===q.projectId);return q.projectArchived===!0&&!!(Ce&&Ha(We,[Ce.alias??"",Ce.name,Ce.path]))?q:{...q,ids:q.ids.filter(bt=>Ha(We,[S[bt]?.title||r("New conversation")]))}}).filter(q=>q.ids.length>0):Ct,te=q=>{if(ie===In)return!0;const Ce=l.find(ct=>ct.id===q.projectId);return Ce?ie===hs?!Ce.groupId||!h.some(ct=>ct.id===Ce.groupId):Ce.groupId===ie:ie===hs},qt=Wt.filter(te),en=Ct.filter(te).reduce((q,Ce)=>q+Ce.ids.length,0),on=()=>{jt(""),Re(!0)};m.useEffect(()=>{ie!==at&&(Ze(In),localStorage.setItem("enso-selected-project-group",In))},[ie,at]),m.useEffect(()=>{const q=Mt=>{const Ko=(N0?Mt.metaKey:Mt.ctrlKey)&&!Mt.shiftKey&&!Mt.altKey;if(ut(Ko),!Ko||Mt.repeat||is.getState().activeNodeId!=="local")return;const Co=Number(Mt.key);if(Co<1||Co>9)return;const qo=Qe.current[Co-1];qo&&(Mt.preventDefault(),T(qo))},Ce=Mt=>{const ts=N0?Mt.metaKey:Mt.ctrlKey;ut(ts&&!Mt.shiftKey&&!Mt.altKey)},ct=()=>ut(!1),bt=()=>{document.hidden&&ct()};return window.addEventListener("keydown",q),window.addEventListener("keyup",Ce),window.addEventListener("blur",ct),document.addEventListener("visibilitychange",bt),()=>{window.removeEventListener("keydown",q),window.removeEventListener("keyup",Ce),window.removeEventListener("blur",ct),document.removeEventListener("visibilitychange",bt)}},[T]),m.useEffect(()=>{U();const q=setInterval(()=>{U()},3e4),Ce=()=>{U()};return window.addEventListener("focus",Ce),()=>{clearInterval(q),window.removeEventListener("focus",Ce)}},[U]);const[Ot,tn]=m.useState(null),[nn,Dn]=m.useState(null),dn=async q=>{const Ce=await window.electronAPI.worktree.status(q);return Ce.ok?Ce.value:void 0},Nn=async(q,Ce)=>{const ct=await Y(q);if(ct){Fe({type:"error",title:r("Failed to clean up worktree"),description:ct});return}Ce&&O(q),U()},Sn=async q=>{const Ce=await dn(q);if(Tc(Ce)){tn({kind:"cleanup",id:q,status:Ce});return}await Nn(q,!1)},gn=async q=>{const Ce=S[q];if(!Ce)return;if(Ce.archived||!Ce.worktree){O(q);return}const ct=await dn(q);if(Tc(ct)){tn({kind:"archive",id:q,status:ct});return}await Nn(q,!0)},Hn=async q=>{for(const Ce of q)!S[Ce]||S[Ce].archived||await gn(Ce)},zn=async(q,Ce=!1)=>{const ct=await B(q,{allowDirtyMainTree:Ce});if(ct===d_){Dn(q);return}if(ct){Fe({type:"error",title:r("Failed to move to worktree"),description:ct});return}U()},qn=q=>{const Ce=[];return q?.dirty&&Ce.push(r("Uncommitted changes")),q&&q.ahead>0&&Ce.push(r("{{n}} unmerged commits (branch is kept)",{n:q.ahead})),Ce.join("; ")};return i.jsxs(Rs.aside,{initial:!1,animate:{width:t?48:e},transition:ea,"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:()=>Je(!0),className:Zi,title:r("Add project"),children:i.jsx(hm,{className:"h-4 w-4"})}),i.jsx("div",{className:"flex-1"}),window.electronAPI.remote?.linkStatus&&i.jsx(oC,{}),en>0&&i.jsx("button",{type:"button",onClick:on,className:Zi,title:`${r("Archived")} (${en})`,children:i.jsx(Ai,{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(j0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"settings-button",onClick:()=>window.electronAPI.window.openSettings(),className:Zi,title:r("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})})]}),i.jsxs("div",{className:W("flex h-full min-h-0 flex-col",c&&"pt-3",t&&"hidden"),style:{width:e},children:[i.jsx(Lte,{groups:h,selectedId:ie,counts:Object.fromEntries(h.map(q=>[q.id,zr(de,h,oe,q.id).length])),totalCount:zr(de,h,oe,In).length,recentCount:je.length,ungroupedCount:zr(de,h,oe,hs).length,query:xe,onQueryChange:Pe,searchOpen:ge,onSearchOpenChange:qe,onSelect:Pt,onAddGroup:()=>he({mode:"create"}),onEditGroup:q=>he({mode:"edit",id:q})}),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:()=>Je(!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(),I(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(Wa,{section:"active",children:r("Active")}),i.jsx("div",{className:"flex flex-col",children:Ae.map(q=>i.jsx(fC,{id:q,dragId:RQ(q),conversation:S[q],children:i.jsx(Va,{id:q,conversation:S[q],active:A===q,switchHint:Me(q,"active"),locale:a,nowTick:nt,hoverTitle:Dt(q),worktreeStatus:S[q].worktree?ee[q]:void 0,isolated:!!S[q].worktree,onSelect:T,onTogglePin:F,onToggleArchive:Ce=>{gn(Ce)},onCleanupWorktree:Ce=>{Sn(Ce)},onMoveToWorktree:Ce=>{zn(Ce)},onRemove:Ce=>{j(Ce)}})},q))})]}),At.length===0&&mt?.type==="chat"&&!mt.pinned&&i.jsx(mC,{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")]})}),et.length>0&&i.jsxs(mC,{"data-slot":"pinned-section",children:[i.jsx(Wa,{section:"pinned",children:r("Pinned")}),i.jsx("div",{className:"flex flex-col",children:i.jsx(Jm,{items:et.map(q=>$I(q)),strategy:sC,children:et.map(q=>i.jsx(fne,{id:q,conversation:S[q],children:i.jsx(Va,{id:q,conversation:S[q],active:A===q,switchHint:Me(q,"pinned"),locale:a,nowTick:nt,hoverTitle:gC(l,S[q].projectId),worktreeStatus:S[q].worktree?ee[q]:void 0,isolated:!!S[q].worktree,onSelect:T,onTogglePin:F,onToggleArchive:Ce=>{gn(Ce)},onCleanupWorktree:Ce=>{Sn(Ce)},onMoveToWorktree:Ce=>{zn(Ce)},onRemove:Ce=>{j(Ce)}})},q))})})]}),u&&X&&i.jsxs("div",{"data-slot":"scratch-section",children:[i.jsxs("div",{"data-enso":"section-header","data-section":"scratch",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:De,"aria-expanded":!le,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(un,{"data-enso":"tree-chevron","data-expanded":!le||void 0,className:W("size-3 shrink-0 transition-[opacity,transform] duration-150",!le&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:"ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",children:It.length})]}),i.jsx("button",{type:"button",className:of,title:r("Start a temporary chat"),"aria-label":r("Start a temporary chat"),onClick:()=>{me(),I(X.id)},children:i.jsx(us,{className:"size-3.25"})})]}),i.jsx(fl,{initial:!1,children:!le&&i.jsx(Rs.div,{initial:"initial",animate:"animate",exit:"exit",variants:zp,className:"overflow-hidden",children:i.jsx("div",{className:"flex flex-col",children:It.map(q=>i.jsx(Va,{id:q,conversation:S[q],active:A===q,switchHint:Me(q,"project"),locale:a,nowTick:nt,onSelect:T,onTogglePin:F,onToggleArchive:Ce=>{gn(Ce)},onCleanupWorktree:Ce=>{Sn(Ce)},onMoveToWorktree:Ce=>{zn(Ce)},onRemove:Ce=>{j(Ce)}},q))})},"scratch-conversations")})]}),de.length>0&&i.jsx(Wa,{section:"projects",actions:i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:()=>qe(!0),className:W(of,(ge||xt)&&"bg-foreground/5 text-foreground opacity-100"),title:r("Search conversations..."),"aria-label":r("Search conversations..."),children:i.jsx(AN,{className:"size-3.25"})}),i.jsx("button",{type:"button",onClick:()=>Je(!0),className:of,title:r("Add project"),"aria-label":r("Add project"),children:i.jsx(us,{className:"size-3.25"})})]}),children:r("Projects")}),lt&&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(Zt,{className:"size-4 animate-spin"})}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium",title:lt.path,children:[lt.name,lt.sshHost&&i.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal",children:lt.sshHost})]}),i.jsx("span",{className:"shrink-0 text-xs",children:r("Adding...")})]}),i.jsx(Jm,{items:[...ie===In?Oe.map(q=>q.groupId===hs?wv:BI(q.groupId)):[],...Ht.map(q=>HI(q))],strategy:sC,children:(()=>{const q=Ce=>{const ct=al(k,S,Ce.id),bt=Ha(xe,[Ce.alias??"",Ce.name,Ce.path]),Mt=!xt||bt?ct:ct.filter(kt);if(xt&&Mt.length===0)return null;const ts=xt?!1:L[Ce.id]===!0,Ko=G[Ce.id]??0,Co=xt?Mt.length:Gh(Mt.length,Ko),qo=Mt.slice(Co),_r=ae.includes(Ce.id),Kv=[{kind:"item",key:"pin",label:r(_r?"Unpin project":"Pin project"),icon:_r?i.jsx(yu,{}):i.jsx(di,{}),onSelect:()=>Ye(Ce.id)},{kind:"item",key:"settings",label:r("Project settings"),icon:i.jsx(hi,{}),onSelect:()=>Ee(Ce.id)},...Ce.kind!=="ssh"?[{kind:"item",key:"reveal",label:r(jv(window.electronAPI.env.platform)),icon:i.jsx(ni,{}),onSelect:()=>_v({projectId:Ce.id},r)}]:[],{kind:"item",key:"import",label:r("Import session"),icon:i.jsx(M5,{}),onSelect:()=>P(Ce)},{kind:"separator",key:"sep-group"},{kind:"submenu",key:"move-to-group",label:r("Move to group"),icon:i.jsx(rf,{}),items:[{kind:"item",key:"ungrouped",label:r("Ungrouped"),icon:i.jsx(rf,{}),onSelect:()=>v(Ce.id,null)},...h.map(Ki=>({kind:"item",key:`group-${Ki.id}`,label:Ki.name,icon:i.jsx(rf,{emoji:Ki.emoji,color:Ki.color}),onSelect:()=>v(Ce.id,Ki.id)}))]},{kind:"item",key:"new-group",label:r("New group"),icon:i.jsx(hm,{}),onSelect:()=>he({mode:"create"})},{kind:"separator",key:"sep-danger"},{kind:"item",key:"archive",label:r("Archive project"),icon:i.jsx(Ai,{}),onSelect:()=>Ve(Ce.id)},{kind:"item",key:"remove",label:r("Remove project"),icon:i.jsx(Bs,{}),destructive:!0,onSelect:()=>R({kind:"project",project:Ce,conversationIds:ct})}];return i.jsx(pne,{project:Ce,activitySorted:He,children:Ki=>i.jsxs(ho,{children:[i.jsx(po,{render:i.jsxs("div",{ref:Ki.setNodeRef,style:Ki.style,children:[i.jsxs("div",{"data-enso":"project-row","data-expanded":!ts||void 0,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:()=>V(Ce.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",title:Ce.path,children:[i.jsx(xE,{folded:ts}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium text-foreground",title:Ce.kind==="ssh"?`${Ce.sshHost}:${Ce.path}`:Ce.path,children:[Ao(Ce),Ce.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:Ce.sshConnectionName??Ce.sshHost}),He&&i.jsx("span",{className:"ml-1.5 font-normal text-[0.7857rem] text-subtle-foreground",children:h.find(ns=>ns.id===Ce.groupId)?.name??r("Ungrouped")})]})]}),i.jsx("button",{type:"button",onClick:()=>Ye(Ce.id),className:"hidden shrink-0 rounded-md p-1 text-muted-foreground group-hover:block hover:bg-muted hover:text-foreground",title:r(_r?"Unpin project":"Pin project"),children:_r?i.jsx(yu,{className:"h-3.5 w-3.5"}):i.jsx(di,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",onClick:()=>{I(Ce.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(Lo,{className:"h-3.5 w-3.5"})}),i.jsx(gne,{actions:Kv}),(_r||ts)&&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:[_r&&i.jsx(di,{className:"h-3.5 w-3.5"}),ts&&ct.length]})]}),i.jsx(fl,{initial:!1,children:!ts&&i.jsx(Rs.div,{initial:"initial",animate:"animate",exit:"exit",variants:zp,className:"overflow-hidden",children:i.jsxs("div",{className:"flex flex-col",children:[Mt.slice(0,Co).map(ns=>i.jsx(Rs.div,{layout:mt?.type==="project"?!1:"position",transition:ea,children:i.jsx(fC,{id:ns,conversation:S[ns],children:i.jsx(Va,{id:ns,conversation:S[ns],active:A===ns,switchHint:Me(ns,"project"),locale:a,nowTick:nt,worktreeStatus:S[ns].worktree?ee[ns]:void 0,isolated:!!S[ns].worktree,onSelect:T,onTogglePin:F,onToggleArchive:Yo=>{gn(Yo)},onCleanupWorktree:Yo=>{Sn(Yo)},onMoveToWorktree:Yo=>{zn(Yo)},onRemove:Yo=>{j(Yo)}})})},ns)),!xt&&ct.length>zh&&i.jsxs("div",{className:"flex items-center gap-1 pl-6",children:[qo.length>0&&i.jsxs(ho,{children:[i.jsx(po,{render:i.jsx("button",{type:"button",onClick:()=>pe(ns=>({...ns,[Ce.id]:ene(Mt.length,ns[Ce.id]??0)})),className:cC,children:r("Show {{n}} more",{n:qo.length})})}),i.jsx(fo,{className:"min-w-36",children:i.jsxs(Yt,{onClick:()=>{Hn(qo)},children:[i.jsx(Ai,{}),r("Archive {{n}} conversations",{n:qo.length})]})})]}),Ko>0&&i.jsx("button",{type:"button",onClick:()=>pe(ns=>({...ns,[Ce.id]:tne(ns[Ce.id]??0)})),className:cC,children:r("Collapse")})]}),Mt.length===0&&i.jsx("p",{className:"py-1.5 pl-8 text-xs text-subtle-foreground",children:r("No conversations yet")})]})})})]})}),i.jsx(fo,{className:"min-w-40",children:zu(Kv)})]})},Ce.id)};return He&&!xt&&yt.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:P5})}):!xt&&de.length>0&&yt.length===0?i.jsx("p",{className:"px-2 py-1.5 text-xs text-subtle-foreground",children:r("No projects in this group yet")}):ie===In&&h.length>0?i.jsxs("div",{children:[ht.length>0&&i.jsxs("div",{children:[i.jsx(Wa,{section:"pinned-projects",children:r("Pinned projects")}),i.jsx("div",{children:ht.map(q)})]}),Oe.map(Ce=>{const ct=xt?!1:Et[Ce.groupId]===!0;return i.jsxs("div",{children:[i.jsx(cne,{groupId:Ce.groupId,name:Ce.group?.name??r("Ungrouped"),emoji:Ce.group?.emoji,color:Ce.group?.color,count:Ce.projects.length,folded:ct,sortable:Ce.groupId!==hs,onToggle:()=>ne(Ce.groupId),onEdit:Ce.group?()=>he({mode:"edit",id:Ce.groupId}):void 0}),i.jsx(fl,{initial:!1,children:!ct&&i.jsx(Rs.div,{initial:"initial",animate:"animate",exit:"exit",variants:zp,className:"overflow-hidden",children:i.jsx("div",{children:Ce.projects.map(q)})},`content-${Ce.groupId}`)})]},Ce.groupId)})]}):ht.length>0&&$t.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{children:[i.jsx(Wa,{section:"pinned-projects",children:r("Pinned projects")}),i.jsx("div",{children:ht.map(q)})]}),i.jsx("div",{children:$t.map(q)})]}):yt.map(q)})()})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[window.electronAPI.remote?.linkStatus?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"min-w-0 flex-1"}),i.jsx(oC,{})]}):i.jsx(p_,{}),en>0&&i.jsx("button",{type:"button","data-slot":"archived-button",onClick:on,className:Zi,title:`${r("Archived")} (${en})`,children:i.jsx(Ai,{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(j0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"settings-button",onClick:()=>window.electronAPI.window.openSettings(),className:Zi,title:r("Settings"),"aria-label":r("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})}),c&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-enso":"search-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","data-enso":"sidebar-toggle",onClick:n,className:Zi,title:r("Collapse sidebar"),children:i.jsx(Px,{className:"h-4 w-4"})})]})]})]}),i.jsx(vn,{open:Le,onOpenChange:Re,children:i.jsxs(bn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(wn,{children:[i.jsxs(yn,{className:"flex items-baseline gap-2",children:[r("Archived"),i.jsx("span",{className:"font-sans text-sm text-muted-foreground tabular-nums",children:en})]}),i.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[i.jsxs(Qu,{"data-size":"sm",children:[i.jsx(eh,{children:i.jsx(ti,{})}),i.jsx(th,{value:We,placeholder:r("Search conversations..."),onChange:q=>jt(q.target.value)})]}),i.jsx(pC,{open:Bt==="*",onOpenChange:q=>Vt(q?"*":null),idsForDays:q=>_0(k,S,q,Date.now()),onPick:(q,Ce)=>R({kind:"archived",days:q,conversationIds:Ce}),className:"h-8 w-8 rounded-md opacity-100 hover:bg-muted"})]})]}),i.jsxs(Mn,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[qt.length===0&&i.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:We.trim()?r("No matching conversations"):r("No conversations")}),qt.map(q=>{const Ce=l.find(bt=>bt.id===q.projectId),ct=Ce?Ao(Ce):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:[q.projectArchived&&i.jsx(QV,{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:ct}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:q.ids.length}),q.projectArchived?i.jsx("button",{type:"button",onClick:()=>Ve(q.projectId),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",title:r("Unarchive project"),children:i.jsx(Bl,{className:"h-3.5 w-3.5"})}):i.jsx(pC,{open:Bt===q.projectId,onOpenChange:bt=>Vt(bt?q.projectId:null),idsForDays:bt=>_0(k,S,bt,Date.now(),q.projectId),onPick:(bt,Mt)=>R({kind:"archived",days:bt,conversationIds:Mt,projectName:ct})})]}),i.jsx("div",{className:"flex flex-col",children:q.ids.map(bt=>i.jsx(Rs.div,{layout:"position",transition:ea,children:i.jsx(Va,{id:bt,conversation:S[bt],active:A===bt,locale:a,nowTick:nt,worktreeStatus:S[bt].worktree?ee[bt]:void 0,isolated:!!S[bt].worktree,menuZIndex:kn.DROPDOWN_IN_MODAL,onSelect:Mt=>{T(Mt),Re(!1)},onTogglePin:F,onToggleArchive:Mt=>{gn(Mt)},onCleanupWorktree:Mt=>{Sn(Mt)},onMoveToWorktree:Mt=>{zn(Mt)},onRemove:Mt=>{j(Mt)}})},bt))})]},q.projectId)})]})]})}),i.jsx(Ate,{open:Be,onOpenChange:Je,onAdd:zt,groups:h,defaultGroupId:St}),i.jsx(Hte,{open:K!==null,group:K?.mode==="edit"?h.find(q=>q.id===K.id)??null:null,projects:de.filter(q=>!oe.includes(q.id)),onOpenChange:q=>{q||he(null)},onSave:q=>{if(K?.mode==="edit"){f(K.id,q);return}const Ce=p(q);for(const ct of q.projectIds??[])v(ct,Ce.id)},onDelete:K?.mode==="edit"?()=>{const q=K.id;g(q),at===q&&Pt(In)}:void 0}),i.jsx($te,{open:Ie!==null,project:l.find(q=>q.id===Ie)??null,onOpenChange:q=>{q||Ee(null)}}),i.jsx(Bte,{project:cn,onClose:()=>P(null)}),i.jsx(ms,{open:Ot!==null,onOpenChange:q=>{q||tn(null)},title:Ot?.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:qn(Ot?.status)}),confirmLabel:Ot?.kind==="archive"?r("Archive"):r("Clean up"),onConfirm:()=>{Ot&&Nn(Ot.id,Ot.kind==="archive")}}),i.jsx(ms,{open:nn!==null,onOpenChange:q=>{q||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(!nn)return;const q=nn;Dn(null),zn(q,!0)}}),i.jsx(ms,{open:M!==null,onOpenChange:q=>{q||R(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 q of M.conversationIds)H(q);N(M.project.id)}else if(M.kind==="archived")for(const q of M.conversationIds)H(q);else H(M.id)}}),Ks.createPortal(i.jsx(tG,{dropAnimation:null,children:mt?.type==="project"?i.jsx(hne,{projectId:mt.projectId,name:une(l,mt.projectId,mt.name),folded:L[mt.projectId]===!0,revealedExtra:G[mt.projectId]??0,width:e}):(mt?.type==="chat"||mt?.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:[mt.type==="workspace-file"?i.jsx(wo,{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:mt.type==="workspace-file"?mt.name:mt.title.split(`
|
|
98
|
-
`)[0].trim()||r("New conversation")})]})}),document.body)]})}function cne({groupId:e,name:t,emoji:n,color:s,count:o,folded:r,sortable:a,onToggle:l,onEdit:d}){const c=e===hs?wv:BI(e),u=vd({id:c}),h=Oh({id:c,data:{type:"project-group",groupId:e},disabled:!a}),p=f=>{u.setNodeRef(f),h.setNodeRef(f)};return i.jsxs("div",{ref:p,"data-enso":"section-header","data-section":"group",style:{transform:zi.Transform.toString(h.transform),transition:h.transition,opacity:h.isDragging?.4:void 0},className:W("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(un,{"data-enso":"tree-chevron","data-expanded":!r||void 0,className:W("size-3 shrink-0 transition-[opacity,transform] duration-150",!r&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:W("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($s,{className:"size-3.25"})})]})}function une(e,t,n){const s=e.find(o=>o.id===t);return s?Ao(s):n}function hne({projectId:e,name:t,folded:n,revealedExtra:s,width:o}){const{t:r}=J(),a=se(h=>bv(h.conversations)),l=se(h=>h.order),d=al(l,a,e),c=n?[]:d.slice(0,Gh(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(xE,{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(vE,{conversation:p}),i.jsx("span",{className:"min-w-0 truncate",children:p.title||r("New conversation")})]},h):null}),d.length>zh&&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 pne({project:e,activitySorted:t=!1,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Oh({id:HI(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 pC({open:e,onOpenChange:t,idsForDays:n,onPick:s,className:o}){const{t:r}=J();return i.jsxs(Hi,{open:e,onOpenChange:t,children:[i.jsx(Bi,{className:W("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(Bg,{className:"h-3.5 w-3.5"})}),i.jsxs($i,{align:"end",className:"min-w-40",zIndex:kn.DROPDOWN_IN_MODAL,children:[dne.map(a=>{const l=n(a);return i.jsx(fn,{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(fn,{variant:"destructive",disabled:a.length===0,onClick:()=>s(0,a),children:r("Delete all archived")})})()]})]})}function fne({id:e,conversation:t,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Oh({id:$I(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 fC({id:e,conversation:t,children:n,dragId:s}){const{setNodeRef:o,listeners:r,isDragging:a}=Jg({id:s??MQ(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 mC({children:e,...t}){const{setNodeRef:n,isOver:s,active:o}=vd({id:FI}),r=o?.data.current?.type==="chat";return i.jsx("div",{ref:n,className:W("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}=J(),b=Se(L=>L.projects.some(Q=>Q.id===t.projectId&&Q.kind!=="ssh")),w=Se(L=>L.projects.some(Q=>Q.id===t.projectId&&Q.kind==="scratch")),[_,C]=m.useState(!1),N=se(L=>L.conversations[e]?.worktree),S=se(L=>!!L.conversations[e]?.workspaceMigrating),k=se(L=>L.conversations[e]?.worktreeMissing),[A,I]=m.useState(!1),[E,D]=m.useState(null),T=A||S||t.spawning||t.status==="running"||t.reloading===!0,H=async()=>{if(!T){I(!0);try{await se.getState().newConversation(t.projectId,{worktreeFromConversationId:e})||Fe({type:"error",title:y("Failed to create conversation")})}catch(L){Fe({type:"error",title:y("Failed to create conversation"),description:String(L)})}finally{I(!1)}}},F=t.pinned===!0,O=t.archived===!0,B=F?yu:di,Y=t.title||y("New conversation"),U=t.forkedFromConversationId?se.getState().conversations[t.forkedFromConversationId]?.title:void 0,ee=i.jsxs("div",{"data-slot":"conversation-row","data-pinned":F?"true":"false","data-enso":"session-row","data-active":n||void 0,"data-status":Nv(t),"data-unread":t.unread||void 0,className:W("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:L=>{L.preventDefault(),L.stopPropagation(),C(!0)},onKeyDown:L=>{L.key==="Enter"&&!_&&h(e)},role:"button",tabIndex:0,title:r,children:[i.jsx(vE,{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:[U&&i.jsx("span",{className:"max-w-1/3 truncate text-[0.7857rem] text-subtle-foreground",children:y("Branched from {{title}}",{title:U})}),_?i.jsx(UI,{title:Y,onCommit:L=>{se.getState().renameConversation(e,L),C(!1)},onCancel:()=>C(!1)}):i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[Y,a&&i.jsx("span",{className:"ml-1.5 text-[0.7857rem] text-subtle-foreground",children:a})]})]}),l&&N&&i.jsx(cte,{worktree:N,status:d}),i.jsx(lne,{conversationId:e}),!_&&i.jsx(mne,{pending:t.titleSummaryPending,error:t.titleSummaryError,onRetry:()=>se.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:[F&&!O&&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:zo(t.lastActiveAt??t.createdAt,s,o)}),!O&&i.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),p(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:y(F?"Unpin":"Pin"),children:i.jsx(B,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),f(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:y(O?"Unarchive":"Archive"),children:O?i.jsx(Bl,{className:"h-3.5 w-3.5"}):i.jsx(Ai,{className:"h-3.5 w-3.5"})}),O&&i.jsx("button",{type:"button",onClick:L=>{L.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(Bs,{className:"h-3.5 w-3.5"})})]}))]})]});return i.jsxs(i.Fragment,{children:[i.jsxs(ho,{children:[i.jsx(po,{render:ee}),i.jsxs(fo,{className:"min-w-36",zIndex:u,children:[i.jsxs(Yt,{onClick:()=>C(!0),children:[i.jsx($s,{}),y("Rename")]}),i.jsxs(Yt,{disabled:t.reloading===!0||t.spawning,onClick:()=>{KI(e,y)},children:[i.jsx(Ho,{className:t.reloading?"animate-spin":void 0}),y("Reload conversation")]}),i.jsxs(Yt,{disabled:T,onClick:()=>{iee(e,y)},children:[i.jsx(ia,{}),y("Restart conversation (reload settings)")]}),b&&i.jsxs(Yt,{disabled:S||k||d?.exists===!1,onClick:()=>{_v({projectId:t.projectId,conversationId:e},y)},children:[i.jsx(ni,{}),y(jv(window.electronAPI.env.platform))]}),!O&&i.jsxs(Yt,{onClick:()=>p(e),children:[i.jsx(B,{}),y(F?"Unpin":"Pin")]}),i.jsxs(Yt,{onClick:()=>f(e),children:[O?i.jsx(Bl,{}):i.jsx(Ai,{}),y(O?"Unarchive":"Archive")]}),N&&i.jsxs(i.Fragment,{children:[i.jsxs(Yt,{disabled:T||k||d?.exists===!1,onClick:()=>{H()},children:[A?i.jsx(Zt,{className:"animate-spin"}):i.jsx(Lo,{}),y("New conversation in this worktree")]}),i.jsxs(Yt,{disabled:T||k||d?.exists===!1,onClick:()=>D({conversationId:e,worktree:N}),children:[i.jsx($s,{}),y("Rename worktree")]})]}),!O&&(l?g&&i.jsxs(Yt,{disabled:T,onClick:()=>g(e),children:[i.jsx(Bg,{}),y("Clean up worktree")]}):x&&b&&!w&&i.jsxs(Yt,{disabled:T,onClick:()=>x(e),children:[i.jsx(o6,{}),y("Move to worktree")]})),i.jsx(Mg,{}),i.jsxs(Yt,{variant:"destructive",onClick:()=>v(e),children:[i.jsx(Bs,{}),y("Delete")]})]})]}),i.jsx(iE,{entity:E,onClose:()=>D(null)})]})}function mne({pending:e,error:t,onRetry:n}){const{t:s}=J();return e?i.jsxs(Df,{children:[i.jsx(If,{render:i.jsx("span",{role:"status",className:"shrink-0 text-muted-foreground/60","aria-label":s("Summarizing title")}),children:i.jsx(Zt,{className:"h-3 w-3 animate-spin"})}),i.jsx(Ef,{side:"right",children:s("Summarizing title")})]}):t?i.jsxs(Df,{children:[i.jsx(If,{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(Ef,{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 gC(e,t){const n=e.find(s=>s.id===t);return n?Ao(n):void 0}function rf({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(s6,{style:t?{color:t}:void 0})}function zu(e,t="context"){return e.map(n=>n.kind==="separator"?t==="menu"?i.jsx(ba,{},n.key):i.jsx(Mg,{},n.key):n.kind==="submenu"?t==="menu"?i.jsxs(Nj,{children:[i.jsxs(Tj,{children:[n.icon,n.label]}),i.jsx(Dj,{className:"min-w-40",children:zu(n.items,"menu")})]},n.key):i.jsxs(Bj,{children:[i.jsxs($j,{children:[n.icon,n.label]}),i.jsx(Vj,{className:"min-w-40",children:zu(n.items)})]},n.key):t==="menu"?i.jsxs(fn,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key):i.jsxs(Yt,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key))}function gne({actions:e}){const{t}=J();return i.jsxs(Hi,{children:[i.jsx(Bi,{"data-enso":"row-menu","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(xh,{className:"h-3.5 w-3.5"})}),i.jsx($i,{align:"end",className:"min-w-40",children:zu(e,"menu")})]})}function Wa({section:e,children:t,actions:n}){return i.jsxs("div",{"data-enso":"section-header","data-section":e,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:t}),n]})}function xE({folded:e}){return i.jsx("span",{"data-enso":"tree-chevron","data-expanded":!e||void 0,className:"flex size-4 shrink-0 items-center justify-center text-subtle-foreground",children:i.jsx(un,{className:W("size-3.5 transition-transform duration-150",!e&&"rotate-90")})})}function vE({conversation:e}){const t=(e.pendingApprovals?.length??0)>0||(e.pendingCapabilityAsks?.length??0)>0?"attention":Hg({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(Lh,{tone:t,size:"sm","data-enso":"session-status","data-status":Nv(e)})})}const xne=15e3,xC={"host-dirs":"host-dirs-result","project-add":"project-add-result"};function af(e,t){const n=t.type,s=crypto.randomUUID();return new Promise(o=>{const r=(d,c)=>{clearTimeout(l),a(),o(c??{type:xC[n],requestId:s,error:d})},a=window.electronAPI.nodes.onMessage(d=>{if(d.nodeId!==e)return;const c=d.payload;c.type==="command-rejected"&&c.command===n?r(c.error):c.type===xC[n]&&c.requestId===s&&r(void 0,c)}),l=setTimeout(()=>r("timeout"),xne);window.electronAPI.nodes.send(e,{...t,requestId:s}).then(d=>{d.ok||r(d.error??"offline")})})}function vne({nodeId:e,open:t,onOpenChange:n}){const{t:s}=J(),[o,r]=m.useState(""),[a,l]=m.useState(!0),[d,c]=m.useState(!1),[u,h]=m.useState("");m.useEffect(()=>{t&&(r(""),l(!0),c(!1),h(""))},[t]);const p=m.useCallback(b=>s(b==="timeout"?"The remote desktop did not respond. It may need to be updated.":b),[s]),f=m.useCallback(b=>b.error!==void 0||b.path===void 0?{error:p(b.error??"Failed to list remote directory.")}:{path:b.path,parent:b.parent??null,dirs:b.dirs??[]},[p]),g=m.useCallback(b=>af(e,{type:"host-dirs",...b?{path:b}:{}}).then(f),[e,f]),x=m.useCallback((b,w)=>af(e,{type:"host-dirs",path:b,create:w}).then(f),[e,f]),v=o.trim(),y=async b=>{if(b.preventDefault(),!v||d)return;c(!0),h("");const w=await af(e,{type:"project-add",path:v});if(c(!1),w.error!==void 0){h(p(w.error));return}n(!1)};return i.jsx(vn,{open:t,onOpenChange:n,children:i.jsx(bn,{className:"max-w-lg",children:i.jsxs("form",{onSubmit:b=>{y(b)},className:"flex flex-col",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:s("Add project")}),i.jsx(As,{children:s("Add a directory on the remote computer as a project.")})]}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsxs(Os,{className:"w-full",children:[i.jsx(zs,{children:s("Working directory")}),i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx(Jt,{value:o,onChange:b=>r(b.target.value),placeholder:"/home/user/project",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,className:"min-w-0 flex-1"}),i.jsx(fe,{type:"button",variant:"outline",onClick:()=>l(b=>!b),children:s("Browse")})]}),a&&i.jsx(Qm,{list:g,create:x,initialPath:v||void 0,onSelect:b=>{r(b),l(!1)},onClose:()=>l(!1)})]}),u&&i.jsx("p",{className:"text-destructive text-xs",children:u})]}),i.jsxs(rs,{children:[i.jsx(fe,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsx(fe,{type:"submit",size:"sm",disabled:!v||d,children:s("Add")})]})]})})})}function bne(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 lf={exports:{}};const wne={},yne=Object.freeze(Object.defineProperty({__proto__:null,default:wne},Symbol.toStringTag,{value:"Module"})),Sne=R5(yne);var vC;function Cne(){return vC||(vC=1,(function(e){(function(t){var n=function(P){var M,R=new Float64Array(16);if(P)for(M=0;M<P.length;M++)R[M]=P[M];return R},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,R,j){P[M]=R>>24&255,P[M+1]=R>>16&255,P[M+2]=R>>8&255,P[M+3]=R&255,P[M+4]=j>>24&255,P[M+5]=j>>16&255,P[M+6]=j>>8&255,P[M+7]=j&255}function x(P,M,R,j,G){var pe,xe=0;for(pe=0;pe<G;pe++)xe|=P[M+pe]^R[j+pe];return(1&xe-1>>>8)-1}function v(P,M,R,j){return x(P,M,R,j,16)}function y(P,M,R,j){return x(P,M,R,j,32)}function b(P,M,R,j){for(var G=j[0]&255|(j[1]&255)<<8|(j[2]&255)<<16|(j[3]&255)<<24,pe=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,xe=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,Pe=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,Ke=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,ut=j[4]&255|(j[5]&255)<<8|(j[6]&255)<<16|(j[7]&255)<<24,nt=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,Kt=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,dt=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,Dt=j[8]&255|(j[9]&255)<<8|(j[10]&255)<<16|(j[11]&255)<<24,At=R[16]&255|(R[17]&255)<<8|(R[18]&255)<<16|(R[19]&255)<<24,Ct=R[20]&255|(R[21]&255)<<8|(R[22]&255)<<16|(R[23]&255)<<24,xt=R[24]&255|(R[25]&255)<<8|(R[26]&255)<<16|(R[27]&255)<<24,kt=R[28]&255|(R[29]&255)<<8|(R[30]&255)<<16|(R[31]&255)<<24,It=j[12]&255|(j[13]&255)<<8|(j[14]&255)<<16|(j[15]&255)<<24,le=G,Te=pe,Ae=xe,Ge=Pe,Qe=Ke,et=ut,ye=nt,ke=Kt,Me=dt,Le=_t,Re=Dt,We=At,jt=Ct,Bt=xt,Vt=kt,Wt=It,te,qt=0;qt<20;qt+=2)te=le+jt|0,Qe^=te<<7|te>>>25,te=Qe+le|0,Me^=te<<9|te>>>23,te=Me+Qe|0,jt^=te<<13|te>>>19,te=jt+Me|0,le^=te<<18|te>>>14,te=et+Te|0,Le^=te<<7|te>>>25,te=Le+et|0,Bt^=te<<9|te>>>23,te=Bt+Le|0,Te^=te<<13|te>>>19,te=Te+Bt|0,et^=te<<18|te>>>14,te=Re+ye|0,Vt^=te<<7|te>>>25,te=Vt+Re|0,Ae^=te<<9|te>>>23,te=Ae+Vt|0,ye^=te<<13|te>>>19,te=ye+Ae|0,Re^=te<<18|te>>>14,te=Wt+We|0,Ge^=te<<7|te>>>25,te=Ge+Wt|0,ke^=te<<9|te>>>23,te=ke+Ge|0,We^=te<<13|te>>>19,te=We+ke|0,Wt^=te<<18|te>>>14,te=le+Ge|0,Te^=te<<7|te>>>25,te=Te+le|0,Ae^=te<<9|te>>>23,te=Ae+Te|0,Ge^=te<<13|te>>>19,te=Ge+Ae|0,le^=te<<18|te>>>14,te=et+Qe|0,ye^=te<<7|te>>>25,te=ye+et|0,ke^=te<<9|te>>>23,te=ke+ye|0,Qe^=te<<13|te>>>19,te=Qe+ke|0,et^=te<<18|te>>>14,te=Re+Le|0,We^=te<<7|te>>>25,te=We+Re|0,Me^=te<<9|te>>>23,te=Me+We|0,Le^=te<<13|te>>>19,te=Le+Me|0,Re^=te<<18|te>>>14,te=Wt+Vt|0,jt^=te<<7|te>>>25,te=jt+Wt|0,Bt^=te<<9|te>>>23,te=Bt+jt|0,Vt^=te<<13|te>>>19,te=Vt+Bt|0,Wt^=te<<18|te>>>14;le=le+G|0,Te=Te+pe|0,Ae=Ae+xe|0,Ge=Ge+Pe|0,Qe=Qe+Ke|0,et=et+ut|0,ye=ye+nt|0,ke=ke+Kt|0,Me=Me+dt|0,Le=Le+_t|0,Re=Re+Dt|0,We=We+At|0,jt=jt+Ct|0,Bt=Bt+xt|0,Vt=Vt+kt|0,Wt=Wt+It|0,P[0]=le>>>0&255,P[1]=le>>>8&255,P[2]=le>>>16&255,P[3]=le>>>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]=Qe>>>0&255,P[17]=Qe>>>8&255,P[18]=Qe>>>16&255,P[19]=Qe>>>24&255,P[20]=et>>>0&255,P[21]=et>>>8&255,P[22]=et>>>16&255,P[23]=et>>>24&255,P[24]=ye>>>0&255,P[25]=ye>>>8&255,P[26]=ye>>>16&255,P[27]=ye>>>24&255,P[28]=ke>>>0&255,P[29]=ke>>>8&255,P[30]=ke>>>16&255,P[31]=ke>>>24&255,P[32]=Me>>>0&255,P[33]=Me>>>8&255,P[34]=Me>>>16&255,P[35]=Me>>>24&255,P[36]=Le>>>0&255,P[37]=Le>>>8&255,P[38]=Le>>>16&255,P[39]=Le>>>24&255,P[40]=Re>>>0&255,P[41]=Re>>>8&255,P[42]=Re>>>16&255,P[43]=Re>>>24&255,P[44]=We>>>0&255,P[45]=We>>>8&255,P[46]=We>>>16&255,P[47]=We>>>24&255,P[48]=jt>>>0&255,P[49]=jt>>>8&255,P[50]=jt>>>16&255,P[51]=jt>>>24&255,P[52]=Bt>>>0&255,P[53]=Bt>>>8&255,P[54]=Bt>>>16&255,P[55]=Bt>>>24&255,P[56]=Vt>>>0&255,P[57]=Vt>>>8&255,P[58]=Vt>>>16&255,P[59]=Vt>>>24&255,P[60]=Wt>>>0&255,P[61]=Wt>>>8&255,P[62]=Wt>>>16&255,P[63]=Wt>>>24&255}function w(P,M,R,j){for(var G=j[0]&255|(j[1]&255)<<8|(j[2]&255)<<16|(j[3]&255)<<24,pe=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,xe=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,Pe=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,Ke=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,ut=j[4]&255|(j[5]&255)<<8|(j[6]&255)<<16|(j[7]&255)<<24,nt=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,Kt=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,dt=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,Dt=j[8]&255|(j[9]&255)<<8|(j[10]&255)<<16|(j[11]&255)<<24,At=R[16]&255|(R[17]&255)<<8|(R[18]&255)<<16|(R[19]&255)<<24,Ct=R[20]&255|(R[21]&255)<<8|(R[22]&255)<<16|(R[23]&255)<<24,xt=R[24]&255|(R[25]&255)<<8|(R[26]&255)<<16|(R[27]&255)<<24,kt=R[28]&255|(R[29]&255)<<8|(R[30]&255)<<16|(R[31]&255)<<24,It=j[12]&255|(j[13]&255)<<8|(j[14]&255)<<16|(j[15]&255)<<24,le=G,Te=pe,Ae=xe,Ge=Pe,Qe=Ke,et=ut,ye=nt,ke=Kt,Me=dt,Le=_t,Re=Dt,We=At,jt=Ct,Bt=xt,Vt=kt,Wt=It,te,qt=0;qt<20;qt+=2)te=le+jt|0,Qe^=te<<7|te>>>25,te=Qe+le|0,Me^=te<<9|te>>>23,te=Me+Qe|0,jt^=te<<13|te>>>19,te=jt+Me|0,le^=te<<18|te>>>14,te=et+Te|0,Le^=te<<7|te>>>25,te=Le+et|0,Bt^=te<<9|te>>>23,te=Bt+Le|0,Te^=te<<13|te>>>19,te=Te+Bt|0,et^=te<<18|te>>>14,te=Re+ye|0,Vt^=te<<7|te>>>25,te=Vt+Re|0,Ae^=te<<9|te>>>23,te=Ae+Vt|0,ye^=te<<13|te>>>19,te=ye+Ae|0,Re^=te<<18|te>>>14,te=Wt+We|0,Ge^=te<<7|te>>>25,te=Ge+Wt|0,ke^=te<<9|te>>>23,te=ke+Ge|0,We^=te<<13|te>>>19,te=We+ke|0,Wt^=te<<18|te>>>14,te=le+Ge|0,Te^=te<<7|te>>>25,te=Te+le|0,Ae^=te<<9|te>>>23,te=Ae+Te|0,Ge^=te<<13|te>>>19,te=Ge+Ae|0,le^=te<<18|te>>>14,te=et+Qe|0,ye^=te<<7|te>>>25,te=ye+et|0,ke^=te<<9|te>>>23,te=ke+ye|0,Qe^=te<<13|te>>>19,te=Qe+ke|0,et^=te<<18|te>>>14,te=Re+Le|0,We^=te<<7|te>>>25,te=We+Re|0,Me^=te<<9|te>>>23,te=Me+We|0,Le^=te<<13|te>>>19,te=Le+Me|0,Re^=te<<18|te>>>14,te=Wt+Vt|0,jt^=te<<7|te>>>25,te=jt+Wt|0,Bt^=te<<9|te>>>23,te=Bt+jt|0,Vt^=te<<13|te>>>19,te=Vt+Bt|0,Wt^=te<<18|te>>>14;P[0]=le>>>0&255,P[1]=le>>>8&255,P[2]=le>>>16&255,P[3]=le>>>24&255,P[4]=et>>>0&255,P[5]=et>>>8&255,P[6]=et>>>16&255,P[7]=et>>>24&255,P[8]=Re>>>0&255,P[9]=Re>>>8&255,P[10]=Re>>>16&255,P[11]=Re>>>24&255,P[12]=Wt>>>0&255,P[13]=Wt>>>8&255,P[14]=Wt>>>16&255,P[15]=Wt>>>24&255,P[16]=ye>>>0&255,P[17]=ye>>>8&255,P[18]=ye>>>16&255,P[19]=ye>>>24&255,P[20]=ke>>>0&255,P[21]=ke>>>8&255,P[22]=ke>>>16&255,P[23]=ke>>>24&255,P[24]=Me>>>0&255,P[25]=Me>>>8&255,P[26]=Me>>>16&255,P[27]=Me>>>24&255,P[28]=Le>>>0&255,P[29]=Le>>>8&255,P[30]=Le>>>16&255,P[31]=Le>>>24&255}function _(P,M,R,j){b(P,M,R,j)}function C(P,M,R,j){w(P,M,R,j)}var N=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(P,M,R,j,G,pe,xe){var Pe=new Uint8Array(16),Ke=new Uint8Array(64),ut,nt;for(nt=0;nt<16;nt++)Pe[nt]=0;for(nt=0;nt<8;nt++)Pe[nt]=pe[nt];for(;G>=64;){for(_(Ke,Pe,xe,N),nt=0;nt<64;nt++)P[M+nt]=R[j+nt]^Ke[nt];for(ut=1,nt=8;nt<16;nt++)ut=ut+(Pe[nt]&255)|0,Pe[nt]=ut&255,ut>>>=8;G-=64,M+=64,j+=64}if(G>0)for(_(Ke,Pe,xe,N),nt=0;nt<G;nt++)P[M+nt]=R[j+nt]^Ke[nt];return 0}function k(P,M,R,j,G){var pe=new Uint8Array(16),xe=new Uint8Array(64),Pe,Ke;for(Ke=0;Ke<16;Ke++)pe[Ke]=0;for(Ke=0;Ke<8;Ke++)pe[Ke]=j[Ke];for(;R>=64;){for(_(xe,pe,G,N),Ke=0;Ke<64;Ke++)P[M+Ke]=xe[Ke];for(Pe=1,Ke=8;Ke<16;Ke++)Pe=Pe+(pe[Ke]&255)|0,pe[Ke]=Pe&255,Pe>>>=8;R-=64,M+=64}if(R>0)for(_(xe,pe,G,N),Ke=0;Ke<R;Ke++)P[M+Ke]=xe[Ke];return 0}function A(P,M,R,j,G){var pe=new Uint8Array(32);C(pe,j,G,N);for(var xe=new Uint8Array(8),Pe=0;Pe<8;Pe++)xe[Pe]=j[Pe+16];return k(P,M,R,xe,pe)}function I(P,M,R,j,G,pe,xe){var Pe=new Uint8Array(32);C(Pe,pe,xe,N);for(var Ke=new Uint8Array(8),ut=0;ut<8;ut++)Ke[ut]=pe[ut+16];return S(P,M,R,j,G,Ke,Pe)}var E=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,R,j,G,pe,xe,Pe,Ke;M=P[0]&255|(P[1]&255)<<8,this.r[0]=M&8191,R=P[2]&255|(P[3]&255)<<8,this.r[1]=(M>>>13|R<<3)&8191,j=P[4]&255|(P[5]&255)<<8,this.r[2]=(R>>>10|j<<6)&7939,G=P[6]&255|(P[7]&255)<<8,this.r[3]=(j>>>7|G<<9)&8191,pe=P[8]&255|(P[9]&255)<<8,this.r[4]=(G>>>4|pe<<12)&255,this.r[5]=pe>>>1&8190,xe=P[10]&255|(P[11]&255)<<8,this.r[6]=(pe>>>14|xe<<2)&8191,Pe=P[12]&255|(P[13]&255)<<8,this.r[7]=(xe>>>11|Pe<<5)&8065,Ke=P[14]&255|(P[15]&255)<<8,this.r[8]=(Pe>>>8|Ke<<8)&8191,this.r[9]=Ke>>>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};E.prototype.blocks=function(P,M,R){for(var j=this.fin?0:2048,G,pe,xe,Pe,Ke,ut,nt,Kt,dt,_t,Dt,At,Ct,xt,kt,It,le,Te,Ae,Ge=this.h[0],Qe=this.h[1],et=this.h[2],ye=this.h[3],ke=this.h[4],Me=this.h[5],Le=this.h[6],Re=this.h[7],We=this.h[8],jt=this.h[9],Bt=this.r[0],Vt=this.r[1],Wt=this.r[2],te=this.r[3],qt=this.r[4],en=this.r[5],on=this.r[6],Ot=this.r[7],tn=this.r[8],nn=this.r[9];R>=16;)G=P[M+0]&255|(P[M+1]&255)<<8,Ge+=G&8191,pe=P[M+2]&255|(P[M+3]&255)<<8,Qe+=(G>>>13|pe<<3)&8191,xe=P[M+4]&255|(P[M+5]&255)<<8,et+=(pe>>>10|xe<<6)&8191,Pe=P[M+6]&255|(P[M+7]&255)<<8,ye+=(xe>>>7|Pe<<9)&8191,Ke=P[M+8]&255|(P[M+9]&255)<<8,ke+=(Pe>>>4|Ke<<12)&8191,Me+=Ke>>>1&8191,ut=P[M+10]&255|(P[M+11]&255)<<8,Le+=(Ke>>>14|ut<<2)&8191,nt=P[M+12]&255|(P[M+13]&255)<<8,Re+=(ut>>>11|nt<<5)&8191,Kt=P[M+14]&255|(P[M+15]&255)<<8,We+=(nt>>>8|Kt<<8)&8191,jt+=Kt>>>5|j,dt=0,_t=dt,_t+=Ge*Bt,_t+=Qe*(5*nn),_t+=et*(5*tn),_t+=ye*(5*Ot),_t+=ke*(5*on),dt=_t>>>13,_t&=8191,_t+=Me*(5*en),_t+=Le*(5*qt),_t+=Re*(5*te),_t+=We*(5*Wt),_t+=jt*(5*Vt),dt+=_t>>>13,_t&=8191,Dt=dt,Dt+=Ge*Vt,Dt+=Qe*Bt,Dt+=et*(5*nn),Dt+=ye*(5*tn),Dt+=ke*(5*Ot),dt=Dt>>>13,Dt&=8191,Dt+=Me*(5*on),Dt+=Le*(5*en),Dt+=Re*(5*qt),Dt+=We*(5*te),Dt+=jt*(5*Wt),dt+=Dt>>>13,Dt&=8191,At=dt,At+=Ge*Wt,At+=Qe*Vt,At+=et*Bt,At+=ye*(5*nn),At+=ke*(5*tn),dt=At>>>13,At&=8191,At+=Me*(5*Ot),At+=Le*(5*on),At+=Re*(5*en),At+=We*(5*qt),At+=jt*(5*te),dt+=At>>>13,At&=8191,Ct=dt,Ct+=Ge*te,Ct+=Qe*Wt,Ct+=et*Vt,Ct+=ye*Bt,Ct+=ke*(5*nn),dt=Ct>>>13,Ct&=8191,Ct+=Me*(5*tn),Ct+=Le*(5*Ot),Ct+=Re*(5*on),Ct+=We*(5*en),Ct+=jt*(5*qt),dt+=Ct>>>13,Ct&=8191,xt=dt,xt+=Ge*qt,xt+=Qe*te,xt+=et*Wt,xt+=ye*Vt,xt+=ke*Bt,dt=xt>>>13,xt&=8191,xt+=Me*(5*nn),xt+=Le*(5*tn),xt+=Re*(5*Ot),xt+=We*(5*on),xt+=jt*(5*en),dt+=xt>>>13,xt&=8191,kt=dt,kt+=Ge*en,kt+=Qe*qt,kt+=et*te,kt+=ye*Wt,kt+=ke*Vt,dt=kt>>>13,kt&=8191,kt+=Me*Bt,kt+=Le*(5*nn),kt+=Re*(5*tn),kt+=We*(5*Ot),kt+=jt*(5*on),dt+=kt>>>13,kt&=8191,It=dt,It+=Ge*on,It+=Qe*en,It+=et*qt,It+=ye*te,It+=ke*Wt,dt=It>>>13,It&=8191,It+=Me*Vt,It+=Le*Bt,It+=Re*(5*nn),It+=We*(5*tn),It+=jt*(5*Ot),dt+=It>>>13,It&=8191,le=dt,le+=Ge*Ot,le+=Qe*on,le+=et*en,le+=ye*qt,le+=ke*te,dt=le>>>13,le&=8191,le+=Me*Wt,le+=Le*Vt,le+=Re*Bt,le+=We*(5*nn),le+=jt*(5*tn),dt+=le>>>13,le&=8191,Te=dt,Te+=Ge*tn,Te+=Qe*Ot,Te+=et*on,Te+=ye*en,Te+=ke*qt,dt=Te>>>13,Te&=8191,Te+=Me*te,Te+=Le*Wt,Te+=Re*Vt,Te+=We*Bt,Te+=jt*(5*nn),dt+=Te>>>13,Te&=8191,Ae=dt,Ae+=Ge*nn,Ae+=Qe*tn,Ae+=et*Ot,Ae+=ye*on,Ae+=ke*en,dt=Ae>>>13,Ae&=8191,Ae+=Me*qt,Ae+=Le*te,Ae+=Re*Wt,Ae+=We*Vt,Ae+=jt*Bt,dt+=Ae>>>13,Ae&=8191,dt=(dt<<2)+dt|0,dt=dt+_t|0,_t=dt&8191,dt=dt>>>13,Dt+=dt,Ge=_t,Qe=Dt,et=At,ye=Ct,ke=xt,Me=kt,Le=It,Re=le,We=Te,jt=Ae,M+=16,R-=16;this.h[0]=Ge,this.h[1]=Qe,this.h[2]=et,this.h[3]=ye,this.h[4]=ke,this.h[5]=Me,this.h[6]=Le,this.h[7]=Re,this.h[8]=We,this.h[9]=jt},E.prototype.finish=function(P,M){var R=new Uint16Array(10),j,G,pe,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(j=this.h[1]>>>13,this.h[1]&=8191,xe=2;xe<10;xe++)this.h[xe]+=j,j=this.h[xe]>>>13,this.h[xe]&=8191;for(this.h[0]+=j*5,j=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=j,j=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=j,R[0]=this.h[0]+5,j=R[0]>>>13,R[0]&=8191,xe=1;xe<10;xe++)R[xe]=this.h[xe]+j,j=R[xe]>>>13,R[xe]&=8191;for(R[9]-=8192,G=(j^1)-1,xe=0;xe<10;xe++)R[xe]&=G;for(G=~G,xe=0;xe<10;xe++)this.h[xe]=this.h[xe]&G|R[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,pe=this.h[0]+this.pad[0],this.h[0]=pe&65535,xe=1;xe<8;xe++)pe=(this.h[xe]+this.pad[xe]|0)+(pe>>>16)|0,this.h[xe]=pe&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},E.prototype.update=function(P,M,R){var j,G;if(this.leftover){for(G=16-this.leftover,G>R&&(G=R),j=0;j<G;j++)this.buffer[this.leftover+j]=P[M+j];if(R-=G,M+=G,this.leftover+=G,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(R>=16&&(G=R-R%16,this.blocks(P,M,G),M+=G,R-=G),R){for(j=0;j<R;j++)this.buffer[this.leftover+j]=P[M+j];this.leftover+=R}};function D(P,M,R,j,G,pe){var xe=new E(pe);return xe.update(R,j,G),xe.finish(P,M),0}function T(P,M,R,j,G,pe){var xe=new Uint8Array(16);return D(xe,0,R,j,G,pe),v(P,M,xe,0)}function H(P,M,R,j,G){var pe;if(R<32)return-1;for(I(P,0,M,0,R,j,G),D(P,16,P,32,R-32,P),pe=0;pe<16;pe++)P[pe]=0;return 0}function F(P,M,R,j,G){var pe,xe=new Uint8Array(32);if(R<32||(A(xe,0,32,j,G),T(M,16,M,32,R-32,xe)!==0))return-1;for(I(P,0,M,0,R,j,G),pe=0;pe<32;pe++)P[pe]=0;return 0}function O(P,M){var R;for(R=0;R<16;R++)P[R]=M[R]|0}function B(P){var M,R,j=1;for(M=0;M<16;M++)R=P[M]+j+65535,j=Math.floor(R/65536),P[M]=R-j*65536;P[0]+=j-1+37*(j-1)}function Y(P,M,R){for(var j,G=~(R-1),pe=0;pe<16;pe++)j=G&(P[pe]^M[pe]),P[pe]^=j,M[pe]^=j}function U(P,M){var R,j,G,pe=n(),xe=n();for(R=0;R<16;R++)xe[R]=M[R];for(B(xe),B(xe),B(xe),j=0;j<2;j++){for(pe[0]=xe[0]-65517,R=1;R<15;R++)pe[R]=xe[R]-65535-(pe[R-1]>>16&1),pe[R-1]&=65535;pe[15]=xe[15]-32767-(pe[14]>>16&1),G=pe[15]>>16&1,pe[14]&=65535,Y(xe,pe,1-G)}for(R=0;R<16;R++)P[2*R]=xe[R]&255,P[2*R+1]=xe[R]>>8}function ee(P,M){var R=new Uint8Array(32),j=new Uint8Array(32);return U(R,P),U(j,M),y(R,0,j,0)}function L(P){var M=new Uint8Array(32);return U(M,P),M[0]&1}function Q(P,M){var R;for(R=0;R<16;R++)P[R]=M[2*R]+(M[2*R+1]<<8);P[15]&=32767}function V(P,M,R){for(var j=0;j<16;j++)P[j]=M[j]+R[j]}function ce(P,M,R){for(var j=0;j<16;j++)P[j]=M[j]-R[j]}function ve(P,M,R){var j,G,pe=0,xe=0,Pe=0,Ke=0,ut=0,nt=0,Kt=0,dt=0,_t=0,Dt=0,At=0,Ct=0,xt=0,kt=0,It=0,le=0,Te=0,Ae=0,Ge=0,Qe=0,et=0,ye=0,ke=0,Me=0,Le=0,Re=0,We=0,jt=0,Bt=0,Vt=0,Wt=0,te=R[0],qt=R[1],en=R[2],on=R[3],Ot=R[4],tn=R[5],nn=R[6],Dn=R[7],dn=R[8],Nn=R[9],Sn=R[10],gn=R[11],Hn=R[12],zn=R[13],qn=R[14],q=R[15];j=M[0],pe+=j*te,xe+=j*qt,Pe+=j*en,Ke+=j*on,ut+=j*Ot,nt+=j*tn,Kt+=j*nn,dt+=j*Dn,_t+=j*dn,Dt+=j*Nn,At+=j*Sn,Ct+=j*gn,xt+=j*Hn,kt+=j*zn,It+=j*qn,le+=j*q,j=M[1],xe+=j*te,Pe+=j*qt,Ke+=j*en,ut+=j*on,nt+=j*Ot,Kt+=j*tn,dt+=j*nn,_t+=j*Dn,Dt+=j*dn,At+=j*Nn,Ct+=j*Sn,xt+=j*gn,kt+=j*Hn,It+=j*zn,le+=j*qn,Te+=j*q,j=M[2],Pe+=j*te,Ke+=j*qt,ut+=j*en,nt+=j*on,Kt+=j*Ot,dt+=j*tn,_t+=j*nn,Dt+=j*Dn,At+=j*dn,Ct+=j*Nn,xt+=j*Sn,kt+=j*gn,It+=j*Hn,le+=j*zn,Te+=j*qn,Ae+=j*q,j=M[3],Ke+=j*te,ut+=j*qt,nt+=j*en,Kt+=j*on,dt+=j*Ot,_t+=j*tn,Dt+=j*nn,At+=j*Dn,Ct+=j*dn,xt+=j*Nn,kt+=j*Sn,It+=j*gn,le+=j*Hn,Te+=j*zn,Ae+=j*qn,Ge+=j*q,j=M[4],ut+=j*te,nt+=j*qt,Kt+=j*en,dt+=j*on,_t+=j*Ot,Dt+=j*tn,At+=j*nn,Ct+=j*Dn,xt+=j*dn,kt+=j*Nn,It+=j*Sn,le+=j*gn,Te+=j*Hn,Ae+=j*zn,Ge+=j*qn,Qe+=j*q,j=M[5],nt+=j*te,Kt+=j*qt,dt+=j*en,_t+=j*on,Dt+=j*Ot,At+=j*tn,Ct+=j*nn,xt+=j*Dn,kt+=j*dn,It+=j*Nn,le+=j*Sn,Te+=j*gn,Ae+=j*Hn,Ge+=j*zn,Qe+=j*qn,et+=j*q,j=M[6],Kt+=j*te,dt+=j*qt,_t+=j*en,Dt+=j*on,At+=j*Ot,Ct+=j*tn,xt+=j*nn,kt+=j*Dn,It+=j*dn,le+=j*Nn,Te+=j*Sn,Ae+=j*gn,Ge+=j*Hn,Qe+=j*zn,et+=j*qn,ye+=j*q,j=M[7],dt+=j*te,_t+=j*qt,Dt+=j*en,At+=j*on,Ct+=j*Ot,xt+=j*tn,kt+=j*nn,It+=j*Dn,le+=j*dn,Te+=j*Nn,Ae+=j*Sn,Ge+=j*gn,Qe+=j*Hn,et+=j*zn,ye+=j*qn,ke+=j*q,j=M[8],_t+=j*te,Dt+=j*qt,At+=j*en,Ct+=j*on,xt+=j*Ot,kt+=j*tn,It+=j*nn,le+=j*Dn,Te+=j*dn,Ae+=j*Nn,Ge+=j*Sn,Qe+=j*gn,et+=j*Hn,ye+=j*zn,ke+=j*qn,Me+=j*q,j=M[9],Dt+=j*te,At+=j*qt,Ct+=j*en,xt+=j*on,kt+=j*Ot,It+=j*tn,le+=j*nn,Te+=j*Dn,Ae+=j*dn,Ge+=j*Nn,Qe+=j*Sn,et+=j*gn,ye+=j*Hn,ke+=j*zn,Me+=j*qn,Le+=j*q,j=M[10],At+=j*te,Ct+=j*qt,xt+=j*en,kt+=j*on,It+=j*Ot,le+=j*tn,Te+=j*nn,Ae+=j*Dn,Ge+=j*dn,Qe+=j*Nn,et+=j*Sn,ye+=j*gn,ke+=j*Hn,Me+=j*zn,Le+=j*qn,Re+=j*q,j=M[11],Ct+=j*te,xt+=j*qt,kt+=j*en,It+=j*on,le+=j*Ot,Te+=j*tn,Ae+=j*nn,Ge+=j*Dn,Qe+=j*dn,et+=j*Nn,ye+=j*Sn,ke+=j*gn,Me+=j*Hn,Le+=j*zn,Re+=j*qn,We+=j*q,j=M[12],xt+=j*te,kt+=j*qt,It+=j*en,le+=j*on,Te+=j*Ot,Ae+=j*tn,Ge+=j*nn,Qe+=j*Dn,et+=j*dn,ye+=j*Nn,ke+=j*Sn,Me+=j*gn,Le+=j*Hn,Re+=j*zn,We+=j*qn,jt+=j*q,j=M[13],kt+=j*te,It+=j*qt,le+=j*en,Te+=j*on,Ae+=j*Ot,Ge+=j*tn,Qe+=j*nn,et+=j*Dn,ye+=j*dn,ke+=j*Nn,Me+=j*Sn,Le+=j*gn,Re+=j*Hn,We+=j*zn,jt+=j*qn,Bt+=j*q,j=M[14],It+=j*te,le+=j*qt,Te+=j*en,Ae+=j*on,Ge+=j*Ot,Qe+=j*tn,et+=j*nn,ye+=j*Dn,ke+=j*dn,Me+=j*Nn,Le+=j*Sn,Re+=j*gn,We+=j*Hn,jt+=j*zn,Bt+=j*qn,Vt+=j*q,j=M[15],le+=j*te,Te+=j*qt,Ae+=j*en,Ge+=j*on,Qe+=j*Ot,et+=j*tn,ye+=j*nn,ke+=j*Dn,Me+=j*dn,Le+=j*Nn,Re+=j*Sn,We+=j*gn,jt+=j*Hn,Bt+=j*zn,Vt+=j*qn,Wt+=j*q,pe+=38*Te,xe+=38*Ae,Pe+=38*Ge,Ke+=38*Qe,ut+=38*et,nt+=38*ye,Kt+=38*ke,dt+=38*Me,_t+=38*Le,Dt+=38*Re,At+=38*We,Ct+=38*jt,xt+=38*Bt,kt+=38*Vt,It+=38*Wt,G=1,j=pe+G+65535,G=Math.floor(j/65536),pe=j-G*65536,j=xe+G+65535,G=Math.floor(j/65536),xe=j-G*65536,j=Pe+G+65535,G=Math.floor(j/65536),Pe=j-G*65536,j=Ke+G+65535,G=Math.floor(j/65536),Ke=j-G*65536,j=ut+G+65535,G=Math.floor(j/65536),ut=j-G*65536,j=nt+G+65535,G=Math.floor(j/65536),nt=j-G*65536,j=Kt+G+65535,G=Math.floor(j/65536),Kt=j-G*65536,j=dt+G+65535,G=Math.floor(j/65536),dt=j-G*65536,j=_t+G+65535,G=Math.floor(j/65536),_t=j-G*65536,j=Dt+G+65535,G=Math.floor(j/65536),Dt=j-G*65536,j=At+G+65535,G=Math.floor(j/65536),At=j-G*65536,j=Ct+G+65535,G=Math.floor(j/65536),Ct=j-G*65536,j=xt+G+65535,G=Math.floor(j/65536),xt=j-G*65536,j=kt+G+65535,G=Math.floor(j/65536),kt=j-G*65536,j=It+G+65535,G=Math.floor(j/65536),It=j-G*65536,j=le+G+65535,G=Math.floor(j/65536),le=j-G*65536,pe+=G-1+37*(G-1),G=1,j=pe+G+65535,G=Math.floor(j/65536),pe=j-G*65536,j=xe+G+65535,G=Math.floor(j/65536),xe=j-G*65536,j=Pe+G+65535,G=Math.floor(j/65536),Pe=j-G*65536,j=Ke+G+65535,G=Math.floor(j/65536),Ke=j-G*65536,j=ut+G+65535,G=Math.floor(j/65536),ut=j-G*65536,j=nt+G+65535,G=Math.floor(j/65536),nt=j-G*65536,j=Kt+G+65535,G=Math.floor(j/65536),Kt=j-G*65536,j=dt+G+65535,G=Math.floor(j/65536),dt=j-G*65536,j=_t+G+65535,G=Math.floor(j/65536),_t=j-G*65536,j=Dt+G+65535,G=Math.floor(j/65536),Dt=j-G*65536,j=At+G+65535,G=Math.floor(j/65536),At=j-G*65536,j=Ct+G+65535,G=Math.floor(j/65536),Ct=j-G*65536,j=xt+G+65535,G=Math.floor(j/65536),xt=j-G*65536,j=kt+G+65535,G=Math.floor(j/65536),kt=j-G*65536,j=It+G+65535,G=Math.floor(j/65536),It=j-G*65536,j=le+G+65535,G=Math.floor(j/65536),le=j-G*65536,pe+=G-1+37*(G-1),P[0]=pe,P[1]=xe,P[2]=Pe,P[3]=Ke,P[4]=ut,P[5]=nt,P[6]=Kt,P[7]=dt,P[8]=_t,P[9]=Dt,P[10]=At,P[11]=Ct,P[12]=xt,P[13]=kt,P[14]=It,P[15]=le}function _e(P,M){ve(P,M,M)}function De(P,M){var R=n(),j;for(j=0;j<16;j++)R[j]=M[j];for(j=253;j>=0;j--)_e(R,R),j!==2&&j!==4&&ve(R,R,M);for(j=0;j<16;j++)P[j]=R[j]}function me(P,M){var R=n(),j;for(j=0;j<16;j++)R[j]=M[j];for(j=250;j>=0;j--)_e(R,R),j!==1&&ve(R,R,M);for(j=0;j<16;j++)P[j]=R[j]}function $(P,M,R){var j=new Uint8Array(32),G=new Float64Array(80),pe,xe,Pe=n(),Ke=n(),ut=n(),nt=n(),Kt=n(),dt=n();for(xe=0;xe<31;xe++)j[xe]=M[xe];for(j[31]=M[31]&127|64,j[0]&=248,Q(G,R),xe=0;xe<16;xe++)Ke[xe]=G[xe],nt[xe]=Pe[xe]=ut[xe]=0;for(Pe[0]=nt[0]=1,xe=254;xe>=0;--xe)pe=j[xe>>>3]>>>(xe&7)&1,Y(Pe,Ke,pe),Y(ut,nt,pe),V(Kt,Pe,ut),ce(Pe,Pe,ut),V(ut,Ke,nt),ce(Ke,Ke,nt),_e(nt,Kt),_e(dt,Pe),ve(Pe,ut,Pe),ve(ut,Ke,Kt),V(Kt,Pe,ut),ce(Pe,Pe,ut),_e(Ke,Pe),ce(ut,nt,dt),ve(Pe,ut,d),V(Pe,Pe,nt),ve(ut,ut,Pe),ve(Pe,nt,dt),ve(nt,Ke,G),_e(Ke,Kt),Y(Pe,Ke,pe),Y(ut,nt,pe);for(xe=0;xe<16;xe++)G[xe+16]=Pe[xe],G[xe+32]=ut[xe],G[xe+48]=Ke[xe],G[xe+64]=nt[xe];var _t=G.subarray(32),Dt=G.subarray(16);return De(_t,_t),ve(Dt,Dt,_t),U(P,Dt),0}function z(P,M){return $(P,M,r)}function de(P,M){return s(M,32),z(P,M)}function X(P,M,R){var j=new Uint8Array(32);return $(j,R,M),C(P,o,j,N)}var oe=H,Z=F;function ae(P,M,R,j,G,pe){var xe=new Uint8Array(32);return X(xe,G,pe),oe(P,M,R,j,xe)}function be(P,M,R,j,G,pe){var xe=new Uint8Array(32);return X(xe,G,pe),Z(P,M,R,j,xe)}var ze=[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 Ye(P,M,R,j){for(var G=new Int32Array(16),pe=new Int32Array(16),xe,Pe,Ke,ut,nt,Kt,dt,_t,Dt,At,Ct,xt,kt,It,le,Te,Ae,Ge,Qe,et,ye,ke,Me,Le,Re,We,jt=P[0],Bt=P[1],Vt=P[2],Wt=P[3],te=P[4],qt=P[5],en=P[6],on=P[7],Ot=M[0],tn=M[1],nn=M[2],Dn=M[3],dn=M[4],Nn=M[5],Sn=M[6],gn=M[7],Hn=0;j>=128;){for(Qe=0;Qe<16;Qe++)et=8*Qe+Hn,G[Qe]=R[et+0]<<24|R[et+1]<<16|R[et+2]<<8|R[et+3],pe[Qe]=R[et+4]<<24|R[et+5]<<16|R[et+6]<<8|R[et+7];for(Qe=0;Qe<80;Qe++)if(xe=jt,Pe=Bt,Ke=Vt,ut=Wt,nt=te,Kt=qt,dt=en,_t=on,Dt=Ot,At=tn,Ct=nn,xt=Dn,kt=dn,It=Nn,le=Sn,Te=gn,ye=on,ke=gn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=(te>>>14|dn<<18)^(te>>>18|dn<<14)^(dn>>>9|te<<23),ke=(dn>>>14|te<<18)^(dn>>>18|te<<14)^(te>>>9|dn<<23),Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,ye=te&qt^~te&en,ke=dn&Nn^~dn&Sn,Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,ye=ze[Qe*2],ke=ze[Qe*2+1],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,ye=G[Qe%16],ke=pe[Qe%16],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,Ae=Re&65535|We<<16,Ge=Me&65535|Le<<16,ye=Ae,ke=Ge,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=(jt>>>28|Ot<<4)^(Ot>>>2|jt<<30)^(Ot>>>7|jt<<25),ke=(Ot>>>28|jt<<4)^(jt>>>2|Ot<<30)^(jt>>>7|Ot<<25),Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,ye=jt&Bt^jt&Vt^Bt&Vt,ke=Ot&tn^Ot&nn^tn&nn,Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,_t=Re&65535|We<<16,Te=Me&65535|Le<<16,ye=ut,ke=xt,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=Ae,ke=Ge,Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,ut=Re&65535|We<<16,xt=Me&65535|Le<<16,Bt=xe,Vt=Pe,Wt=Ke,te=ut,qt=nt,en=Kt,on=dt,jt=_t,tn=Dt,nn=At,Dn=Ct,dn=xt,Nn=kt,Sn=It,gn=le,Ot=Te,Qe%16===15)for(et=0;et<16;et++)ye=G[et],ke=pe[et],Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=G[(et+9)%16],ke=pe[(et+9)%16],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Ae=G[(et+1)%16],Ge=pe[(et+1)%16],ye=(Ae>>>1|Ge<<31)^(Ae>>>8|Ge<<24)^Ae>>>7,ke=(Ge>>>1|Ae<<31)^(Ge>>>8|Ae<<24)^(Ge>>>7|Ae<<25),Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Ae=G[(et+14)%16],Ge=pe[(et+14)%16],ye=(Ae>>>19|Ge<<13)^(Ge>>>29|Ae<<3)^Ae>>>6,ke=(Ge>>>19|Ae<<13)^(Ae>>>29|Ge<<3)^(Ge>>>6|Ae<<26),Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,G[et]=Re&65535|We<<16,pe[et]=Me&65535|Le<<16;ye=jt,ke=Ot,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[0],ke=M[0],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[0]=jt=Re&65535|We<<16,M[0]=Ot=Me&65535|Le<<16,ye=Bt,ke=tn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[1],ke=M[1],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[1]=Bt=Re&65535|We<<16,M[1]=tn=Me&65535|Le<<16,ye=Vt,ke=nn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[2],ke=M[2],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[2]=Vt=Re&65535|We<<16,M[2]=nn=Me&65535|Le<<16,ye=Wt,ke=Dn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[3],ke=M[3],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[3]=Wt=Re&65535|We<<16,M[3]=Dn=Me&65535|Le<<16,ye=te,ke=dn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[4],ke=M[4],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[4]=te=Re&65535|We<<16,M[4]=dn=Me&65535|Le<<16,ye=qt,ke=Nn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[5],ke=M[5],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[5]=qt=Re&65535|We<<16,M[5]=Nn=Me&65535|Le<<16,ye=en,ke=Sn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[6],ke=M[6],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[6]=en=Re&65535|We<<16,M[6]=Sn=Me&65535|Le<<16,ye=on,ke=gn,Me=ke&65535,Le=ke>>>16,Re=ye&65535,We=ye>>>16,ye=P[7],ke=M[7],Me+=ke&65535,Le+=ke>>>16,Re+=ye&65535,We+=ye>>>16,Le+=Me>>>16,Re+=Le>>>16,We+=Re>>>16,P[7]=on=Re&65535|We<<16,M[7]=gn=Me&65535|Le<<16,Hn+=128,j-=128}return j}function Ve(P,M,R){var j=new Int32Array(8),G=new Int32Array(8),pe=new Uint8Array(256),xe,Pe=R;for(j[0]=1779033703,j[1]=3144134277,j[2]=1013904242,j[3]=2773480762,j[4]=1359893119,j[5]=2600822924,j[6]=528734635,j[7]=1541459225,G[0]=4089235720,G[1]=2227873595,G[2]=4271175723,G[3]=1595750129,G[4]=2917565137,G[5]=725511199,G[6]=4215389547,G[7]=327033209,Ye(j,G,M,R),R%=128,xe=0;xe<R;xe++)pe[xe]=M[Pe-R+xe];for(pe[R]=128,R=256-128*(R<112?1:0),pe[R-9]=0,g(pe,R-8,Pe/536870912|0,Pe<<3),Ye(j,G,pe,R),xe=0;xe<8;xe++)g(P,8*xe,j[xe],G[xe]);return 0}function at(P,M){var R=n(),j=n(),G=n(),pe=n(),xe=n(),Pe=n(),Ke=n(),ut=n(),nt=n();ce(R,P[1],P[0]),ce(nt,M[1],M[0]),ve(R,R,nt),V(j,P[0],P[1]),V(nt,M[0],M[1]),ve(j,j,nt),ve(G,P[3],M[3]),ve(G,G,u),ve(pe,P[2],M[2]),V(pe,pe,pe),ce(xe,j,R),ce(Pe,pe,G),V(Ke,pe,G),V(ut,j,R),ve(P[0],xe,Pe),ve(P[1],ut,Ke),ve(P[2],Ke,Pe),ve(P[3],xe,ut)}function Ze(P,M,R){var j;for(j=0;j<4;j++)Y(P[j],M[j],R)}function Et(P,M){var R=n(),j=n(),G=n();De(G,M[2]),ve(R,M[0],G),ve(j,M[1],G),U(P,j),P[31]^=L(R)<<7}function Gt(P,M,R){var j,G;for(O(P[0],a),O(P[1],l),O(P[2],l),O(P[3],a),G=255;G>=0;--G)j=R[G/8|0]>>(G&7)&1,Ze(P,M,j),at(M,P),at(P,P),Ze(P,M,j)}function Pt(P,M){var R=[n(),n(),n(),n()];O(R[0],h),O(R[1],p),O(R[2],l),ve(R[3],h,p),Gt(P,R,M)}function ne(P,M,R){var j=new Uint8Array(64),G=[n(),n(),n(),n()],pe;for(R||s(M,32),Ve(j,M,32),j[0]&=248,j[31]&=127,j[31]|=64,Pt(G,j),Et(P,G),pe=0;pe<32;pe++)M[pe+32]=P[pe];return 0}var ie=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 R,j,G,pe;for(j=63;j>=32;--j){for(R=0,G=j-32,pe=j-12;G<pe;++G)M[G]+=R-16*M[j]*ie[G-(j-32)],R=Math.floor((M[G]+128)/256),M[G]-=R*256;M[G]+=R,M[j]=0}for(R=0,G=0;G<32;G++)M[G]+=R-(M[31]>>4)*ie[G],R=M[G]>>8,M[G]&=255;for(G=0;G<32;G++)M[G]-=R*ie[G];for(j=0;j<32;j++)M[j+1]+=M[j]>>8,P[j]=M[j]&255}function St(P){var M=new Float64Array(64),R;for(R=0;R<64;R++)M[R]=P[R];for(R=0;R<64;R++)P[R]=0;He(P,M)}function it(P,M,R,j){var G=new Uint8Array(64),pe=new Uint8Array(64),xe=new Uint8Array(64),Pe,Ke,ut=new Float64Array(64),nt=[n(),n(),n(),n()];Ve(G,j,32),G[0]&=248,G[31]&=127,G[31]|=64;var Kt=R+64;for(Pe=0;Pe<R;Pe++)P[64+Pe]=M[Pe];for(Pe=0;Pe<32;Pe++)P[32+Pe]=G[32+Pe];for(Ve(xe,P.subarray(32),R+32),St(xe),Pt(nt,xe),Et(P,nt),Pe=32;Pe<64;Pe++)P[Pe]=j[Pe];for(Ve(pe,P,R+64),St(pe),Pe=0;Pe<64;Pe++)ut[Pe]=0;for(Pe=0;Pe<32;Pe++)ut[Pe]=xe[Pe];for(Pe=0;Pe<32;Pe++)for(Ke=0;Ke<32;Ke++)ut[Pe+Ke]+=pe[Pe]*G[Ke];return He(P.subarray(32),ut),Kt}function je(P,M){var R=n(),j=n(),G=n(),pe=n(),xe=n(),Pe=n(),Ke=n();return O(P[2],l),Q(P[1],M),_e(G,P[1]),ve(pe,G,c),ce(G,G,P[2]),V(pe,P[2],pe),_e(xe,pe),_e(Pe,xe),ve(Ke,Pe,xe),ve(R,Ke,G),ve(R,R,pe),me(R,R),ve(R,R,G),ve(R,R,pe),ve(R,R,pe),ve(P[0],R,pe),_e(j,P[0]),ve(j,j,pe),ee(j,G)&&ve(P[0],P[0],f),_e(j,P[0]),ve(j,j,pe),ee(j,G)?-1:(L(P[0])===M[31]>>7&&ce(P[0],a,P[0]),ve(P[3],P[0],P[1]),0)}function ht(P,M,R,j){var G,pe=new Uint8Array(32),xe=new Uint8Array(64),Pe=[n(),n(),n(),n()],Ke=[n(),n(),n(),n()];if(R<64||je(Ke,j))return-1;for(G=0;G<R;G++)P[G]=M[G];for(G=0;G<32;G++)P[G+32]=j[G];if(Ve(xe,P,R),St(xe),Gt(Pe,Ke,xe),Pt(Ke,M.subarray(32)),at(Pe,Ke),Et(pe,Pe),R-=64,y(M,0,pe,0)){for(G=0;G<R;G++)P[G]=0;return-1}for(G=0;G<R;G++)P[G]=M[G+64];return R}var $t=32,Oe=24,yt=32,Ht=16,re=32,$e=32,st=32,Nt=32,mt=32,K=Oe,he=yt,Ie=Ht,Ee=64,Be=32,Je=64,ge=32,qe=64;t.lowlevel={crypto_core_hsalsa20:C,crypto_stream_xor:I,crypto_stream:A,crypto_stream_salsa20_xor:S,crypto_stream_salsa20:k,crypto_onetimeauth:D,crypto_onetimeauth_verify:T,crypto_verify_16:v,crypto_verify_32:y,crypto_secretbox:H,crypto_secretbox_open:F,crypto_scalarmult:$,crypto_scalarmult_base:z,crypto_box_beforenm:X,crypto_box_afternm:oe,crypto_box:ae,crypto_box_open:be,crypto_box_keypair:de,crypto_hash:Ve,crypto_sign:it,crypto_sign_keypair:ne,crypto_sign_open:ht,crypto_secretbox_KEYBYTES:$t,crypto_secretbox_NONCEBYTES:Oe,crypto_secretbox_ZEROBYTES:yt,crypto_secretbox_BOXZEROBYTES:Ht,crypto_scalarmult_BYTES:re,crypto_scalarmult_SCALARBYTES:$e,crypto_box_PUBLICKEYBYTES:st,crypto_box_SECRETKEYBYTES:Nt,crypto_box_BEFORENMBYTES:mt,crypto_box_NONCEBYTES:K,crypto_box_ZEROBYTES:he,crypto_box_BOXZEROBYTES:Ie,crypto_sign_BYTES:Ee,crypto_sign_PUBLICKEYBYTES:Be,crypto_sign_SECRETKEYBYTES:Je,crypto_sign_SEEDBYTES:ge,crypto_hash_BYTES:qe,gf:n,D:c,L:ie,pack25519:U,unpack25519:Q,M:ve,A:V,S:_e,Z:ce,pow2523:me,add:at,set25519:O,modL:He,scalarmult:Gt,scalarbase:Pt};function lt(P,M){if(P.length!==$t)throw new Error("bad key size");if(M.length!==Oe)throw new Error("bad nonce size")}function Tt(P,M){if(P.length!==st)throw new Error("bad public key size");if(M.length!==Nt)throw new Error("bad secret key size")}function zt(){for(var P=0;P<arguments.length;P++)if(!(arguments[P]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function cn(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,R){zt(P,M,R),lt(R,M);for(var j=new Uint8Array(yt+P.length),G=new Uint8Array(j.length),pe=0;pe<P.length;pe++)j[pe+yt]=P[pe];return H(G,j,j.length,M,R),G.subarray(Ht)},t.secretbox.open=function(P,M,R){zt(P,M,R),lt(R,M);for(var j=new Uint8Array(Ht+P.length),G=new Uint8Array(j.length),pe=0;pe<P.length;pe++)j[pe+Ht]=P[pe];return j.length<32||F(G,j,j.length,M,R)!==0?null:G.subarray(yt)},t.secretbox.keyLength=$t,t.secretbox.nonceLength=Oe,t.secretbox.overheadLength=Ht,t.scalarMult=function(P,M){if(zt(P,M),P.length!==$e)throw new Error("bad n size");if(M.length!==re)throw new Error("bad p size");var R=new Uint8Array(re);return $(R,P,M),R},t.scalarMult.base=function(P){if(zt(P),P.length!==$e)throw new Error("bad n size");var M=new Uint8Array(re);return z(M,P),M},t.scalarMult.scalarLength=$e,t.scalarMult.groupElementLength=re,t.box=function(P,M,R,j){var G=t.box.before(R,j);return t.secretbox(P,M,G)},t.box.before=function(P,M){zt(P,M),Tt(P,M);var R=new Uint8Array(mt);return X(R,P,M),R},t.box.after=t.secretbox,t.box.open=function(P,M,R,j){var G=t.box.before(R,j);return t.secretbox.open(P,M,G)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var P=new Uint8Array(st),M=new Uint8Array(Nt);return de(P,M),{publicKey:P,secretKey:M}},t.box.keyPair.fromSecretKey=function(P){if(zt(P),P.length!==Nt)throw new Error("bad secret key size");var M=new Uint8Array(st);return z(M,P),{publicKey:M,secretKey:new Uint8Array(P)}},t.box.publicKeyLength=st,t.box.secretKeyLength=Nt,t.box.sharedKeyLength=mt,t.box.nonceLength=K,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(P,M){if(zt(P,M),M.length!==Je)throw new Error("bad secret key size");var R=new Uint8Array(Ee+P.length);return it(R,P,P.length,M),R},t.sign.open=function(P,M){if(zt(P,M),M.length!==Be)throw new Error("bad public key size");var R=new Uint8Array(P.length),j=ht(R,P,P.length,M);if(j<0)return null;for(var G=new Uint8Array(j),pe=0;pe<G.length;pe++)G[pe]=R[pe];return G},t.sign.detached=function(P,M){for(var R=t.sign(P,M),j=new Uint8Array(Ee),G=0;G<j.length;G++)j[G]=R[G];return j},t.sign.detached.verify=function(P,M,R){if(zt(P,M,R),M.length!==Ee)throw new Error("bad signature size");if(R.length!==Be)throw new Error("bad public key size");var j=new Uint8Array(Ee+P.length),G=new Uint8Array(Ee+P.length),pe;for(pe=0;pe<Ee;pe++)j[pe]=M[pe];for(pe=0;pe<P.length;pe++)j[pe+Ee]=P[pe];return ht(G,j,j.length,R)>=0},t.sign.keyPair=function(){var P=new Uint8Array(Be),M=new Uint8Array(Je);return ne(P,M),{publicKey:P,secretKey:M}},t.sign.keyPair.fromSecretKey=function(P){if(zt(P),P.length!==Je)throw new Error("bad secret key size");for(var M=new Uint8Array(Be),R=0;R<M.length;R++)M[R]=P[32+R];return{publicKey:M,secretKey:new Uint8Array(P)}},t.sign.keyPair.fromSeed=function(P){if(zt(P),P.length!==ge)throw new Error("bad seed size");for(var M=new Uint8Array(Be),R=new Uint8Array(Je),j=0;j<32;j++)R[j]=P[j];return ne(M,R,!0),{publicKey:M,secretKey:R}},t.sign.publicKeyLength=Be,t.sign.secretKeyLength=Je,t.sign.seedLength=ge,t.sign.signatureLength=Ee,t.hash=function(P){zt(P);var M=new Uint8Array(qe);return Ve(M,P,P.length),M},t.hash.hashLength=qe,t.verify=function(P,M){return zt(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(R,j){var G,pe=new Uint8Array(j);for(G=0;G<j;G+=M)P.getRandomValues(pe.subarray(G,G+Math.min(j-G,M)));for(G=0;G<j;G++)R[G]=pe[G];cn(pe)})}else typeof bne<"u"&&(P=Sne,P&&P.randomBytes&&t.setPRNG(function(R,j){var G,pe=P.randomBytes(j);for(G=0;G<j;G++)R[G]=pe[G];cn(pe)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})(lf)),lf.exports}Cne();new TextEncoder;new TextDecoder;function kne(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 jne(e){return e.kind!=="ssh"?void 0:e.sshConnectionName?.trim()||e.sshHost}function bE(e){return e.alias?.trim()||e.name}function bC(e){const t=bE(e),n=jne(e);return n?`${t} (${n})`:t}const hc={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},wC={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"};function _ne({open:e,onOpenChange:t,projects:n,providers:s,onCreate:o}){const{t:r}=J(),a=Se(D=>D.approvalReviewer),l=Se(D=>D.lastApprovalMode),d=ya(),c=Fi(D=>D.snapshot),u=m.useMemo(()=>L5(a,d,da(c),l),[a,l,d,c]),[h,p]=m.useState(null),[f,g]=m.useState(null),[x,v]=m.useState(null),[y,b]=m.useState(u),[w,_]=m.useState(!1),[C,N]=m.useState("medium");m.useEffect(()=>{e&&(p(null),g(null),v(null),b(u))},[e,u]);const S=n.find(D=>D.id===h)?.id??n[0]?.id??"",k=s.find(D=>D.id===f)??s[0]??{id:"",models:[]},A=k.models.find(D=>D.id===x)?.id??k.models[0]?.id??"",I=!!(S&&k.id&&A),E=()=>{I&&(Se.getState().setLastApprovalMode(y),o({projectId:S,providerId:k.id,modelId:A,approvalMode:y,...w?{reasoningEnabled:!0,thinkingLevel:C}:{}}),t(!1))};return i.jsx(vn,{open:e,onOpenChange:t,children:i.jsxs(bn,{className:"max-w-md",children:[i.jsxs(wn,{children:[i.jsx(yn,{children:r("New remote conversation")}),i.jsx(As,{children:r("The conversation runs on the remote computer with its projects, models and keys.")})]}),i.jsxs(Mn,{className:"space-y-4",children:[i.jsx(Ua,{label:r("Project"),children:i.jsxs(vs,{items:n.map(D=>({value:D.id,label:bC(D)})),value:S,onValueChange:D=>p(D),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:n.map(D=>i.jsx(os,{value:D.id,children:bC(D)},D.id))})]})}),i.jsx(Ua,{label:r("Provider"),children:i.jsxs(vs,{items:s.map(D=>({value:D.id,label:D.name})),value:k.id,onValueChange:D=>{g(D),v(null)},children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:s.map(D=>i.jsx(os,{value:D.id,children:D.name},D.id))})]})}),i.jsx(Ua,{label:r("Model"),children:i.jsxs(vs,{items:k.models.map(D=>({value:D.id,label:D.label??D.id})),value:A,onValueChange:D=>v(D),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:k.models.map(D=>i.jsx(os,{value:D.id,children:D.label??D.id},D.id))})]})}),i.jsx(Ua,{label:r("Approval mode"),children:i.jsxs(vs,{items:Object.keys(hc).map(D=>({value:D,label:r(hc[D])})),value:y,onValueChange:D=>b(D),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:Object.keys(hc).map(D=>i.jsx(os,{value:D,children:r(hc[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(ci,{checked:w,onCheckedChange:_})]}),w&&i.jsx(Ua,{label:r("Thinking level"),children:i.jsxs(vs,{items:Lf.map(D=>({value:D,label:r(wC[D])})),value:C,onValueChange:D=>N(D),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:kn.DROPDOWN_IN_MODAL,children:Lf.map(D=>i.jsx(os,{value:D,children:r(wC[D])},D))})]})})]}),i.jsxs(rs,{children:[i.jsx(fe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(fe,{size:"sm",disabled:!I,onClick:E,children:r("Create")})]})]})})}function Ua({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 Nne(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 Tne(e){return Lf.includes(e??"")?e:"medium"}function Dne(e){const{t}=J(),{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:O5(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(()=>Nne(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(kh.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(z5,{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(G5,{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(yC,{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(yC,{active:s===v.id,icon:i.jsx(Vs,{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(Nh,{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:ji,children:[r?.retry&&i.jsx(Mh,{retry:r.retry}),i.jsx(kv,{sessionId:s,tasks:r?.tasks??[],subagents:r?.subagents??[]},s),i.jsx(Vl,{approvals:r?.approvals??[],onRespond:e.onApproval}),i.jsx(wh,{asks:r?.asks??[],onAnswer:e.onAsk}),i.jsx(Sv,{commands:[],running:d,busy:d,locked:(r?.approvals??[]).length>0,focusKey:`${n.nodeId}:${s}`,toolbar:g&&o?i.jsx(ih,{providers:f,providerId:o.providerId??"",modelId:o.modelId??"",reasoningEnabled:o.reasoningEnabled??!1,thinkingLevel:Tne(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 yC({active:e,icon:t,label:n,status:s,onClick:o}){return i.jsxs("button",{type:"button",onClick:o,className:W("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:W("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 Gu(e){return[...e].sort((t,n)=>(n.updatedAt??0)-(t.updatedAt??0))}function wE(e){const t=n=>(n.pendingAskCount??0)>0||(n.pendingApprovalCount??0)>0;return[...e.filter(t),...e.filter(n=>!t(n))]}function Ine(e,t){const n=Gu(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,...wE([...s.values()])]}function SC(e){return wE([...Gu(e.filter(t=>t.pinned)),...Gu(e.filter(t=>!t.pinned))])}const df="flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function Ene({width:e,node:t,catalog:n,pinnedOrder:s,projects:o,groups:r=[],activeId:a,canCreate:l,onSelect:d,onNewConversation:c,onAddProject:u}){const{t:h,locale:p}=J(),[f,g]=m.useState(In),[x,v]=m.useState(""),[y,b]=m.useState({}),[w,_]=m.useState(!1),[C,N]=m.useState(()=>Date.now());m.useEffect(()=>{const U=setInterval(()=>N(Date.now()),6e4);return()=>clearInterval(U)},[]);const S=f===In||f===hs||r.some(U=>U.id===f)?f:In,k=o.filter(U=>U.archived).map(U=>U.id),A=zr(o,r,k,S),I=new Set(A.map(U=>U.id)),E=x.trim().toLowerCase(),D=m.useMemo(()=>n.filter(U=>!U.parentId&&(!E||U.title.toLowerCase().includes(E))),[n,E]),T=Ine(D.filter(U=>U.pinned&&!U.archived&&(!U.projectId||I.has(U.projectId))),s),H=Gu(D.filter(U=>U.archived?S===In?!0:!!(U.projectId&&I.has(U.projectId)):!1)),F=D.filter(U=>!U.archived),O=new Set(o.map(U=>U.id)),B=SC(F.filter(U=>!O.has(U.projectId))),Y=(U,ee)=>i.jsxs("button",{type:"button",onClick:()=>d(U.id),className:W("group flex w-full items-center gap-2 rounded-lg py-1.5 pr-2 pl-4 text-left text-sm transition-colors",a===U.id?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted/60"),children:[i.jsx("span",{className:W("h-2 w-2 shrink-0 rounded-full",U.status==="running"&&"animate-pulse bg-brand",U.status==="failed"&&"bg-destructive",U.status==="idle"&&(U.unread?"bg-emerald-500":"bg-muted-foreground/30"))}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[U.title||h("New conversation"),ee&&i.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:ee})]}),U.updatedAt!==void 0&&i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/80 tabular-nums",children:zo(U.updatedAt,p,C)})]},U.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:W("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(Jt,{value:x,onChange:U=>v(U.target.value),placeholder:h("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(vs,{items:[{value:In,label:h("All")},...r.slice().sort((U,ee)=>U.order-ee.order).map(U=>({value:U.id,label:U.name})),{value:hs,label:h("Ungrouped")}],value:S,onValueChange:U=>{U&&g(U)},children:[i.jsx(bs,{className:"w-full",size:"sm",children:i.jsx(ws,{})}),i.jsxs(ys,{children:[i.jsx(os,{value:In,children:h("All")}),r.slice().sort((U,ee)=>U.order-ee.order).map(U=>i.jsx(os,{value:U.id,children:U.name},U.id)),i.jsx(os,{value:hs,children:h("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?h("Remote desktop is offline"):h("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:h("The remote desktop has no projects yet")}),T.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:h("Pinned")})]}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:T.map(U=>Y(U,U.projectName))})]}),(S===In&&r.length>0?h_(o,r,k).flatMap(U=>{const ee=y[`g:${U.groupId}`]===!0;return[{kind:"header",section:U,foldedSection:ee},...ee?[]:U.projects.map(L=>({kind:"project",project:L}))]}):A.map(U=>({kind:"project",project:U}))).map(U=>{if(U.kind==="header")return i.jsxs("button",{type:"button",onClick:()=>b(V=>({...V,[`g:${U.section.groupId}`]:!V[`g:${U.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(un,{className:W("h-3.5 w-3.5 shrink-0 transition-transform duration-150",!U.foldedSection&&"rotate-90")}),U.section.group?.emoji&&i.jsx("span",{className:"shrink-0 text-sm",children:U.section.group.emoji}),U.section.group?.color&&i.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:U.section.group.color}}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:U.section.group?.name??h("Ungrouped")}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/70",children:U.section.projects.length})]},`hdr-${U.section.groupId}`);const{project:ee}=U,L=SC(F.filter(V=>V.projectId===ee.id&&!V.pinned));if(E&&L.length===0)return null;const Q=y[ee.id]===!0;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>b(V=>({...V,[ee.id]:!Q})),className:"flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60",children:[Q?i.jsx(un,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx($n,{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:bE(ee)}),ee.sshHost&&i.jsx("span",{className:"shrink-0 rounded bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"ssh"})]}),!Q&&i.jsxs("div",{className:"flex flex-col gap-y-0.5",children:[L.length===0&&i.jsx("p",{className:"px-4 py-1.5 text-muted-foreground text-xs",children:h("No conversations")}),L.map(V=>Y(V))]})]},ee.id)}),B.length>0&&i.jsxs("div",{children:[i.jsx("div",{className:"px-2 py-2 font-medium text-sm",children:h("Other")}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:B.map(U=>Y(U))})]}),H.length>0&&i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>_(U=>!U),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(Ai,{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:h("Archived")}),i.jsx("span",{className:"text-[10px] text-muted-foreground",children:H.length})]}),w&&i.jsx("div",{className:"flex flex-col gap-y-0.5",children:H.map(U=>Y(U,U.projectName))})]})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[i.jsx(p_,{}),i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.nodes.openSettings(t.nodeId)},disabled:!t.hostOnline,className:W(df,!t.hostOnline&&"opacity-40"),title:h("Node settings"),children:i.jsx(hi,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:u,disabled:!t.hostOnline,className:W(df,!t.hostOnline&&"opacity-40"),title:h("Add project"),children:i.jsx(hm,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:c,disabled:!l,className:W(df,!l&&"opacity-40"),title:h("New remote conversation"),children:i.jsx(EN,{className:"h-4 w-4"})})]})]})}function Pne({nodeId:e,sidebarWidth:t}){const n=is(b=>b.nodes.find(w=>w.nodeId===e)),s=is(b=>b.byNode[e])??Ane,o=is(b=>b.selectSession),r=is(b=>b.send),a=is(b=>b.requestHistory),l=is(b=>b.spawn),[d,c]=m.useState(!1),[u,h]=m.useState(!1),p=s.activeSessionId,f=m.useMemo(()=>s.catalog.find(b=>b.id===p),[s.catalog,p]),g=m.useMemo(()=>{if(!f)return;const b=f.parentId?s.catalog.find(_=>_.id===f.parentId):f;if(!b)return;const w=s.catalog.filter(_=>_.parentId===b.id);return w.length>0?{parent:b,children:w}:void 0},[s.catalog,f]),x=p?s.sessions[p]??null:null,v=!!(x&&x.messages.size>0&&Math.min(...x.messages.keys())>0);if(!n)return null;const y=b=>r(e,b);return i.jsxs(i.Fragment,{children:[i.jsx(Ene,{width:t,node:n,catalog:s.catalog,pinnedOrder:s.pinnedOrder,projects:s.projects,groups:s.groups,activeId:p,canCreate:n.hostOnline&&s.projects.length>0,onSelect:b=>o(e,b),onNewConversation:()=>c(!0),onAddProject:()=>h(!0)}),i.jsx(Dne,{node:n,sessionId:p,entry:f,tabGroup:g,view:x,syncing:s.sync.state==="syncing",providers:s.providers,hasOlder:v,historyLoading:!!(p&&s.historyPending.has(p)),onLoadOlder:()=>p&&a(e,p),onSelectTab:b=>o(e,b),onSend:(b,w)=>{p&&y({type:x?.status==="running"?"steer":"prompt",sessionId:p,text:b,...w.length?{images:w}:{}})},onAbort:()=>p&&y({type:"abort",sessionId:p}),onApproval:(b,w)=>p&&y({type:"approval-respond",sessionId:p,requestId:b,decision:w}),onAsk:(b,w)=>p&&y({type:"ask-respond",sessionId:p,requestId:b,answer:w}),onSetModel:(b,w)=>p&&y({type:"set-model",sessionId:p,providerId:b,modelId:w}),onSetReasoning:b=>p&&y({type:"set-reasoning",sessionId:p,enabled:b}),onSetThinking:b=>p&&y({type:"set-thinking",sessionId:p,level:b})}),i.jsx(_ne,{open:d,onOpenChange:c,projects:s.projects,providers:s.providers,onCreate:b=>l(e,b)}),i.jsx(vne,{nodeId:e,open:u,onOpenChange:h})]})}const Ane=F5(),cf=["welcome","provider","skill","mcp","instruction","preset","agentType","done"];function Mne(){const{t:e}=J();Qk();const t=Se(E=>E.setOnboarded),n=ya(),s=Se(E=>E.virtualModels),o=Se(E=>E.skills),r=Se(E=>E.mcpServers),a=Se(E=>E.instructions),l=Se(E=>E.presets),d=Se(E=>E.defaultModel),c=Fi(E=>E.snapshot),u=Rl({defaultModel:d,providers:n,credentials:da(c),virtualModels:s}).source!=="none",[h,p]=m.useState(0),[f,g]=m.useState(null),[x,v]=m.useState(!1),[y,b]=m.useState(!1),[w,_]=m.useState(!1),C=cf[h],N=()=>t(!0),S=()=>{N(),window.electronAPI.window.summonAgent({typeKey:tu})},k=()=>p(E=>Math.min(cf.length-1,E+1)),A=()=>p(E=>Math.max(0,E-1)),I={provider:{icon:B5,title:e("Model Providers"),desc:e("Add a provider subscription or API Key, or import providers from local AI apps"),count:n.length,onImport:()=>b(!0),importLabel:e("Add model or provider"),secondary:{label:e("Import from local apps"),onClick:()=>v(!0)}},skill:{icon:Hs,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:Rk,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:Qc,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(ln,{className:"h-4 w-4"})}),i.jsx("div",{className:"mb-5 flex items-center gap-1.5",children:cf.map((E,D)=>i.jsx("span",{className:W("h-1 flex-1 rounded-full transition-colors",D<=h?"bg-primary":"bg-muted")},E))}),C==="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(H5,{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.")})]}),C!=="welcome"&&C!=="done"&&C!=="preset"&&C!=="agentType"&&i.jsx(CC,{...I[C],importedLabel:e("{{count}} imported",{count:I[C].count})}),C==="preset"&&i.jsx(CC,{icon:Qc,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")}),C==="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(Vs,{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($5,{})})]}),C==="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(Kn,{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(fe,{variant:"ghost",size:"sm",onClick:S,children:[i.jsx(Hs,{className:"h-3.5 w-3.5"}),e("Ask Enso")]})]}),i.jsxs("div",{className:"mt-6 flex items-center justify-between",children:[i.jsx(fe,{variant:"ghost",size:"sm",onClick:A,disabled:h===0,children:e("Back")}),i.jsxs("div",{className:"flex items-center gap-2",children:[C!=="done"&&C!=="welcome"&&i.jsx(fe,{variant:"ghost",size:"sm",onClick:k,children:e("Skip")}),C==="done"?i.jsx(fe,{size:"sm",onClick:N,children:e("Done")}):i.jsx(fe,{size:"sm",onClick:k,children:e(C==="welcome"?"Get started":"Next")})]})]})]}),i.jsx(V5,{open:x,onOpenChange:v}),i.jsx(W5,{open:y,onOpenChange:b}),f&&i.jsx(U5,{kind:f,open:!0,onOpenChange:E=>!E&&g(null)}),w&&i.jsx(K5,{preset:null,onClose:()=>_(!1)})]})}function CC({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(fe,{variant:"outline",size:"sm",onClick:o,children:a}),l&&i.jsx(fe,{variant:"ghost",size:"sm",onClick:l.onClick,children:l.label})]}),s>0&&i.jsx("p",{className:"text-xs text-primary",children:r})]})}const uf=["project","all","all-including-archived"];function kC(e,t=!1){const n=uf.length,s=uf.indexOf(e);return uf[(s+(t?n-1:1))%n]??"all"}const Rne=50,hf=160,Lne=["title","project","id","body","tool"],Dv=/[\p{Letter}\p{Number}]+/gu,One=/[\u3400-\u9fff]/u,zne=/[^.!?。?!]+[.!?。?!]?/g;function yE(e){return e.toLowerCase().match(Dv)??[]}function Iv(e){return One.test(e)}function SE(e){return yE(e)}function CE(e,t){if(t.length===0)return!1;const n=e.toLowerCase(),s=yE(e);return t.every(o=>Iv(o)?n.includes(o):s.some(r=>r.startsWith(o)))}function kE(e,t){return e.isDraftEmpty?!1:t.scope==="project"?e.projectId===t.currentProjectId&&!e.archived:t.scope==="all"?!e.archived:!0}function Gne(e,t){const n=e.toLowerCase(),s=SE(t);if(s.length===0||n.length!==e.length)return[{text:e,match:!1}];const o=[];for(const l of s){if(Iv(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(Dv))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 Fne(e,t){const n=e.toLowerCase();let s=-1;for(const o of t){if(Iv(o)){const r=n.indexOf(o);r>=0&&(s<0||r<s)&&(s=r);continue}for(const r of e.matchAll(Dv))if(r[0].toLowerCase().startsWith(o)&&r.index!==void 0){(s<0||r.index<s)&&(s=r.index);break}}return s}function Hne(e,t){if(e.length<=hf)return e;const n=Math.max(0,Fne(e,t)),s=Math.min(n,Math.max(0,e.length-hf));return e.slice(s,s+hf)}function Bne(e){return(e.match(zne)??[]).map(t=>t.trim()).filter(Boolean)}function $ne(e,t){const n=Bne(e);if(n.length<=1)return;const s=n.findIndex(r=>CE(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 Vne(e,t,n,s){return e.title.trim().toLowerCase()===n.trim().toLowerCase()?0:t==="title"?1:e.projectId===s?2:3}function Wne(e,t,n){const s=n.trim().toLowerCase(),o=e.fields.filter(r=>r.field==="id"?r.text.toLowerCase().startsWith(s):CE(r.text,t));if(o.length!==0)return Lne.map(r=>o.find(a=>a.field===r)).find(r=>!!r)}function jE(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:Vne(e,t.field,n,s),lastActiveAt:e.lastActiveAt}}function _E(e,t=Rne){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 Une(e,t,n){const s=SE(t);if(s.length===0)return[];const o=[];for(const r of e){if(!kE(r,n))continue;const a=Wne(r,s,t);if(!a)continue;const l=$ne(a.text,s);o.push(jE(r,{field:a.field,snippet:Hne(a.text,s),nearby:l},t,n.currentProjectId))}return _E(o,n.limit)}function Kne(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)||!kE(d,o)||a.set(l.conversationId,jE(d,l,s,o.currentProjectId))}return _E([...a.values()],o.limit)}const qne=120,Yne=8;function NE(e){return!e.started&&!e.sessionFile&&e.messages.length===0}function Nl(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt??e.createdAt}function Xne(e,t){return e.filter(n=>n.parentId||NE(n)||n.archived&&t.scope!=="all-including-archived"?!1:t.scope!=="project"||n.projectId===t.currentProjectId).sort((n,s)=>Nl(s)-Nl(n)).slice(0,t.limit??Yne)}function Zne(e){return e.content.map(t=>t.type==="text"?t.text:"").join(`
|
|
99
|
-
`).trim()}function Jne(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,qne);return`${t.join(" ")} ${n}`.trim()}function Qne(e){const t=[{field:"title",text:e.title},{field:"project",text:e.projectName},{field:"id",text:e.conversationId},{field:"body",text:e.messages.map(Zne).filter(Boolean).join(`
|
|
100
|
-
`)}],n=e.messages.map(Jne).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 jC=[],ese={project:"This project",all:"All projects","all-including-archived":"Include archived"},tse={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 Ka({text:e,query:t}){let n=0;return Gne(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 Mr({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 nse(e){try{return new URL(e).host||e}catch{return e}}function sse({open:e,onOpenChange:t}){const{t:n,locale:s}=J(),[o,r]=m.useState(""),[a,l]=m.useState("all"),[d,c]=m.useState(),[u,h]=m.useState([]),[p,f]=m.useState([]),g=se($=>$.conversations),x=se($=>$.activeId),v=Se($=>$.projects),y=Se($=>$.scratchSessionsEnabled),b=Se($=>$.keybindings),w=(x?g[x]?.projectId:void 0)??v[0]?.id??"",_=o.trim(),C=`${a}
|
|
102
|
-
${w}
|
|
103
|
-
${_}`,N=d?.key===C?d.hits:jC,S=m.useMemo(()=>{if(!e)return[];const z=(x?g[x]:void 0)?.activeTabId,de=z&&g[z]?z:x;return Object.values(g).map(X=>{const oe=v.find(Z=>Z.id===X.projectId);return!y&&oe?.kind==="scratch"?null:Qne({conversationId:X.id,projectId:X.projectId,projectName:oe?.name??X.projectId,title:X.title,lastActiveAt:Nl(X),archived:X.archived,isDraftEmpty:NE(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]),k=m.useMemo(()=>_?Une(S,o,{currentProjectId:w,scope:a}):jC,[w,S,o,a,_]),A=m.useMemo(()=>e?Xne(Object.values(g),{scope:a,currentProjectId:w}):[],[g,w,e,a]),I=q5(p),E=m.useMemo(()=>_?Y5(I,o,{translate:$=>n($)}):[],[o,I,n,_]),D=m.useMemo(()=>o.trim()?X5(u,o):[],[u,o]),T=m.useMemo(()=>Z5(u),[u]);m.useEffect(()=>{if(!e)return;const $=z=>{z.key==="Escape"&&(z.preventDefault(),z.stopPropagation(),t(!1))};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[t,e]),m.useEffect(()=>{if(!e){r(""),l("all"),c(void 0);return}window.electronAPI.browser.listSearchableTabs().then($=>h($.filter(z=>!f_(z.conversationId)))).catch(()=>{h([])}),window.electronAPI.sshConnections.list().then($=>{f($.map(z=>({id:z.id,name:z.name})))}).catch(()=>{f([])})},[e]),m.useEffect(()=>{if(!e||!_||!w)return;let $=!1;const z=window.setTimeout(()=>{window.electronAPI.workspaceSearch.query({query:_,currentProjectId:w,scope:a}).then(de=>{$||c({key:C,hits:de.hits})}).catch(()=>{$||c({key:C,hits:[]})})},80);return()=>{$=!0,window.clearTimeout(z)}},[C,w,e,a,_]);const H=m.useMemo(()=>Kne(S,k,N,o,{currentProjectId:w,scope:a}),[N,w,S,k,o,a]),F=$=>{const z=se.getState(),de=z.conversations[$.conversationId],X=$.parentConversationId??de?.parentId;if(X&&z.conversations[X]?(z.selectConversation(X),z.selectTab(X,$.coworkerId??$.conversationId)):z.selectConversation($.conversationId),t(!1),$.field==="body"||$.field==="tool"){const oe=o.trim().split(/\s+/).find(Boolean);oe&&window.setTimeout(()=>RI(oe),0)}},O=$=>{const z=se.getState(),X=z.conversations[$.conversationId]?.parentId;X&&z.conversations[X]?(z.selectConversation(X),z.selectTab(X,$.conversationId)):z.selectConversation($.conversationId),$g({conversationId:$.conversationId,tabId:$.tabId,title:$.title||n("Browser")}),t(!1)},B=$=>{window.electronAPI.window.openSettings({category:$.category,rowId:$.id}),t(!1)},Y=_.length>0&&H.length===0&&D.length===0&&E.length===0,U=$=>{$.key==="Escape"&&($.preventDefault(),$.stopPropagation(),t(!1))},ee=$=>{if($.key!=="Tab"||$.nativeEvent.isComposing){U($);return}$.altKey||$.ctrlKey||$.metaKey||($.preventDefault(),l(z=>kC(z,$.shiftKey)))},L=Li(b),Q=Date.now(),V=$=>{const z=v.find(de=>de.id===$);return z?Ao(z):""},ce=($,z)=>[V($),z?zo(z,s,Q):""].filter(Boolean).join(" · "),ve=($,z)=>i.jsxs(i.Fragment,{children:[$&&i.jsx(aa,{size:"sm",className:"bg-brand/10 text-brand",children:n("Current")}),z&&i.jsx(aa,{variant:"outline",size:"sm",children:n("Archived")})]}),_e=$=>{const z=g[$.conversationId],de=$.parentConversationId??z?.parentId;let X=vr;de&&(X=z?.child?.mode==="task"?zg:Vs);const oe=$.title||z?.child?.agentInstanceName||z?.coworkerName||n("New conversation"),Z=de?g[de]?.title||n("New conversation"):void 0,ae=$.field==="body"||$.field==="tool"||$.field==="id"?$.snippet.replace(/\s+/g," ").trim():"";return i.jsx(Mr,{icon:X,title:i.jsxs(i.Fragment,{children:[Z&&i.jsxs("span",{className:"text-muted-foreground",children:[Z," › "]}),i.jsx(Ka,{text:oe,query:o})]}),badges:ve($.isCurrent,$.archived),detail:ae&&i.jsx(Ka,{text:ae,query:o}),meta:ce($.projectId,z?Nl(z):void 0)})},De=($,z)=>i.jsx(ir,{value:z,className:"gap-2.5",onClick:()=>O($),children:i.jsx(Mr,{icon:mo,title:i.jsx(Ka,{text:$.title||$.url,query:o}),meta:nse($.url)})},z),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:$=>{$.preventDefault(),$.stopPropagation(),l(z=>kC(z,$.shiftKey))},children:[n(ese[a]),i.jsx(ai,{className:"h-4 min-w-4 text-[10px]",children:"⇥"})]});return i.jsx(kI,{open:e,onOpenChange:t,children:i.jsx(jI,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:U,children:i.jsxs(_I,{children:[i.jsx(NI,{placeholder:n("Search conversations, browser tabs, settings…"),value:o,onChange:$=>r($.currentTarget.value),onKeyDown:ee,endAddon:me}),i.jsxs(II,{children:[Y&&i.jsxs(DI,{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(TI,{children:[!_&&i.jsxs(i.Fragment,{children:[A.length>0&&i.jsxs(Pr,{children:[i.jsx(Ar,{children:n("Recent")}),A.map($=>i.jsx(ir,{value:`recent-${$.id}`,className:"gap-2.5",onClick:()=>F({conversationId:$.id,field:"title",snippet:$.title}),children:i.jsx(Mr,{icon:vr,title:$.title||n("New conversation"),badges:ve($.id===x,$.archived),meta:ce($.projectId,Nl($))})},$.id))]}),T.length>0&&i.jsxs(Pr,{children:[i.jsx(Ar,{children:n("Browser")}),T.map($=>De($,`recent-browser-${$.tabId}`))]}),i.jsxs(Pr,{children:[i.jsx(Ar,{children:n("Actions")}),i.jsxs(ir,{value:"new-conversation",className:"gap-2.5",onClick:()=>{w&&se.getState().newConversation(w),t(!1)},children:[i.jsx(Mr,{icon:us,title:i.jsxs(i.Fragment,{children:[n("New conversation"),V(w)&&i.jsxs("span",{className:"text-muted-foreground",children:[" · ",V(w)]})]})}),i.jsx(NS,{children:mi(L["new-conversation"])})]}),i.jsxs(ir,{value:"open-settings",className:"gap-2.5",onClick:()=>{window.electronAPI.window.openSettings(),t(!1)},children:[i.jsx(Mr,{icon:hi,title:n("Open settings")}),i.jsx(NS,{children:mi(L["open-settings"])})]})]})]}),_.length>0&&H.length>0&&i.jsxs(Pr,{children:[i.jsx(Ar,{children:n("Conversations")}),H.map($=>i.jsx(ir,{value:`conv-${$.conversationId}-${$.field}`,className:"gap-2.5",onClick:()=>F($),children:_e($)},`${$.conversationId}-${$.field}`))]}),_.length>0&&D.length>0&&i.jsxs(Pr,{children:[i.jsx(Ar,{children:n("Browser")}),D.map($=>De($,`browser-${$.tabId}`))]}),_.length>0&&E.length>0&&i.jsxs(Pr,{children:[i.jsx(Ar,{children:n("Settings")}),E.map($=>i.jsx(ir,{value:`settings-${$.id}`,className:"gap-2.5",onClick:()=>B($),children:i.jsx(Mr,{icon:hi,title:i.jsx(Ka,{text:n($.title),query:o}),detail:$.description&&i.jsx(Ka,{text:n($.description),query:o}),meta:n(tse[$.category]??$.category)})},$.id))]})]})]}),i.jsxs(EI,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(Hj,{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 TE,DE=class{constructor(){}},Zs=class extends DE{constructor(e,t,n,s){super(),this.viewId=e,this.groupId=t,this.panelId=n,this.tabGroupId=s}},Tl=class extends DE{constructor(e,t){super(),this.viewId=e,this.paneId=t}},vo=class IE{constructor(){}static getInstance(){return IE.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)}};TE=vo;vo.INSTANCE=new TE;function On(){const e=vo.getInstance();if(e.hasData(Zs.prototype))return e.getData(Zs.prototype)[0]}function qa(){const e=vo.getInstance();if(e.hasData(Tl.prototype))return e.getData(Tl.prototype)[0]}let an;(function(e){e.NONE={dispose:()=>{}};function t(n){return{dispose:()=>{n()}}}e.from=t})(an||(an={}));var pt=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=an.NONE}get value(){return this._disposable===an.NONE?void 0:this._disposable}set value(e){this._disposable&&this._disposable.dispose(),this._disposable=e}dispose(){this._disposable&&(this._disposable.dispose(),this._disposable=an.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 Ev=class{constructor(){this._defaultPrevented=!1}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}},EE=class{constructor(){this._isAccepted=!1}get isAccepted(){return this._isAccepted}accept(){this._isAccepted=!0}},ise=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()}},_C=class PE{static create(){var t;return new PE((t=new Error("listener stacktrace").stack)!==null&&t!==void 0?t:"")}constructor(t){this.value=t}print(){console.warn("dockview: stacktrace",this.value)}},ose=class{constructor(e,t){this.callback=e,this.stacktrace=t}},we=class Ni{static setLeakageMonitorEnabled(t){t!==Ni.ENABLE_TRACKING&&Ni.MEMORY_LEAK_WATCHER.clear(),Ni.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 ose(t,Ni.ENABLE_TRACKING?_C.create():void 0);return this._listeners.push(s),{dispose:()=>{const o=this._listeners.indexOf(s);o>-1&&this._listeners.splice(o,1)}}},Ni.ENABLE_TRACKING&&Ni.MEMORY_LEAK_WATCHER.add(this._event,_C.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),an.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&&(Ni.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=[]),Ni.ENABLE_TRACKING&&this._event&&Ni.MEMORY_LEAK_WATCHER.delete(this._event))}};we.ENABLE_TRACKING=!1;we.MEMORY_LEAK_WATCHER=new ise;function rt(e,t,n,s){return e.addEventListener(t,n,s),{dispose:()=>{e.removeEventListener(t,n,s)}}}var NC=class{constructor(){this._onFired=new we,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()}},rse=class extends pt{constructor(e){super(),this._onDidChange=new we,this.onDidChange=this._onDidChange.event,this._value=null,this.addDisposables(this._onDidChange,jr(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 jr(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 Ci=(e,...t)=>{for(const n of t)e.classList.contains(n)&&e.classList.remove(n)},ki=(e,...t)=>{for(const n of t)e.classList.contains(n)||e.classList.add(n)},tt=(e,t,n)=>{const s=e.classList.contains(t);n&&!s&&e.classList.add(t),!n&&s&&e.classList.remove(t)};function ng(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}function AE(e){return new ase(e)}var ase=class extends pt{constructor(e){super(),this._onDidFocus=new we,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new we,this.onDidBlur=this._onDidBlur.event,this.addDisposables(this._onDidFocus,this._onDidBlur);let t=ng(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=()=>{ng(document.activeElement,e)!==t&&(t?o():s())},this.addDisposables(rt(e,"focus",s,!0)),this.addDisposables(rt(e,"blur",o,!0))}refreshState(){this._refreshStateHandler()}};const ME="dv-quasiPreventDefault";function RE(e){e[ME]=!0}function TC(e){return e[ME]}function lse(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 sg(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 LE(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 dse(e,t){e.dataset.testid=t}function cse(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 ed(e=document){const t=cse(["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 use(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 Fh=class{constructor(e){this.element=e,this._classNames=[]}setClassNames(e){for(const t of this._classNames)tt(this.element,t,!1);this._classNames=e.split(" ").filter(t=>t.trim().length>0);for(const t of this._classNames)tt(this.element,t,!0)}};const OE=100;function pf(e,t){const n=sg(e),s=sg(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 hse(e){const t=new we;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 pse(e,t){let n;return new pt(rt(e,"resize",()=>{clearTimeout(n),n=setTimeout(()=>{t()},OE)}))}function fse(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 mse(e){let t=e;for(;t&&(t.style.zIndex==="auto"||t.style.zIndex==="");)t=t.parentElement;return t}function lo(e){if(e.length===0)throw new Error("Invalid tail call");return[e.slice(0,e.length-1),e[e.length-1]]}function zE(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 ff(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))}function pc(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))}function gse(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(t(s))return n}return-1}function GE(e,t){const n=e.indexOf(t);return n>-1?(e.splice(n,1),!0):!1}const Pn=(e,t,n)=>t>n?t:Math.min(n,Math.max(e,t)),Pv=()=>{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 xse=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=Pn((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 DC(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 js;(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})(js||(js={}));var Sr=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,Ci(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,tt(this.element,"dv-splitview-disabled",e)}get margin(){return this._margin}set margin(e){this._margin=e,tt(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 we,this.onDidSashEnd=this._onDidSashEnd.event,this._onDidAddView=new we,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new we,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 I of d)ff(f,I),ff(g,I);if(l)for(const I of l)pc(f,I),pc(g,I);const x=f.reduce((I,E)=>I+this.viewItems[E].minimumSize-a[E],0),v=f.reduce((I,E)=>I+this.viewItems[E].maximumSize-a[E],0),y=g.length===0?Number.POSITIVE_INFINITY:g.reduce((I,E)=>I+a[E]-this.viewItems[E].minimumSize,0),b=g.length===0?Number.NEGATIVE_INFINITY:g.reduce((I,E)=>I+a[E]-this.viewItems[E].maximumSize,0),w=Math.max(x,b),_=Math.min(y,v);let C=!1;if(h){const I=this.viewItems[h.index],E=r>=h.limitDelta;C=E!==I.visible,I.setVisible(E,h.size)}if(!C&&p){const I=this.viewItems[p.index],E=r<p.limitDelta;C=E!==I.visible,I.setVisible(E,p.size)}if(C)return this.resize(o,r,a,l,d,c,u);const N=Pn(r,w,_);let S=0,k=N;for(const I of f){const E=this.viewItems[I],D=a[I],T=Pn(D+k,E.minimumSize,E.maximumSize),H=T-D;S+=H,k-=H,E.size=T}let A=S;for(const I of g){const E=this.viewItems[I],D=a[I],T=Pn(D-A,E.minimumSize,E.maximumSize),H=T-D;A+=H,E.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"?(Ci(this.element,"dv-separator-border"),this.element.style.removeProperty("--dv-separator-border")):(ki(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=Pn(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=Pn(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=js.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 xse(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 O of this.viewItems)O.enabled=!1;const f=(p=d.ownerDocument)!==null&&p!==void 0?p:document,g=ed(f),x=this._orientation==="HORIZONTAL"?h.clientX:h.clientY,v=gse(this.sashes,O=>O.container===d),y=this.viewItems.map(O=>O.size);let b,w;const _=ii(v,-1),C=ii(v+1,this.viewItems.length),N=_.reduce((O,B)=>O+(this.viewItems[B].minimumSize-y[B]),0),S=_.reduce((O,B)=>O+(this.viewItems[B].viewMaximumSize-y[B]),0),k=C.length===0?Number.POSITIVE_INFINITY:C.reduce((O,B)=>O+(y[B]-this.viewItems[B].minimumSize),0),A=C.length===0?Number.NEGATIVE_INFINITY:C.reduce((O,B)=>O+(y[B]-this.viewItems[B].viewMaximumSize),0),I=Math.max(N,A),E=Math.min(k,S),D=this.findFirstSnapIndex(_),T=this.findFirstSnapIndex(C);if(typeof D=="number"){const O=this.viewItems[D],B=Math.floor(O.viewMinimumSize/2);b={index:D,limitDelta:O.visible?I-B:I+B,size:O.size}}if(typeof T=="number"){const O=this.viewItems[T],B=Math.floor(O.viewMinimumSize/2);w={index:T,limitDelta:O.visible?E+B:E-B,size:O.size}}const H=O=>{const B=(this._orientation==="HORIZONTAL"?O.clientX:O.clientY)-x;this.resize(v,B,y,void 0,void 0,I,E,b,w),this.distributeEmptySpace(),this.layoutViews()},F=()=>{for(const O of this.viewItems)O.enabled=!0;g.release(),this.saveProportions(),f.removeEventListener("pointermove",H),f.removeEventListener("pointerup",F),f.removeEventListener("pointercancel",F),f.removeEventListener("contextmenu",F),this._onDidSashEnd.fire(void 0)};f.addEventListener("pointermove",H),f.addEventListener("pointerup",F),f.addEventListener("pointercancel",F),f.addEventListener("contextmenu",F)};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=Pn(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):js.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=Pn(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)ff(s,l);for(const l of r)pc(s,l)}typeof e=="number"&&pc(s,e);for(let r=0;n!==0&&r<s.length;r++){const a=this.viewItems[s[r]],l=Pn(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"&&DC(g,`${f}px`,"0px"),this._orientation==="VERTICAL"&&DC(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){tt(e.container,"dv-disabled",t===2),tt(e.container,"dv-enabled",t===3),tt(e.container,"dv-maximum",t===0),tt(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 ig=Object.keys({orientation:void 0,descriptor:void 0,proportionalLayout:void 0,styles:void 0,margin:void 0,disableAutoResizing:void 0,className:void 0});var IC=class extends pt{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 we,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 Sr(this.element,{orientation:this._orientation,proportionalLayout:!1,descriptor:t.descriptor}),this.getPanes().forEach(s=>{const o=new pt(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),ki(this.element,"dv-animated"),this.animationTimer=setTimeout(()=>{this.animationTimer=void 0,Ci(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()}},ls=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 we,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()}},Xn=class og extends pt{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 og&&(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=an.NONE,this.children=[],this._onDidChange=new we,this.onDidChange=this._onDidChange.event,this._onDidVisibilityChange=new we,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 Sr(this.element,{orientation:this.orientation,descriptor:c,proportionalLayout:n,styles:s,margin:l})}else this.splitview=new Sr(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 pt(Qs.any(...this.children.map(t=>t.onDidChange))(t=>{this.invalidateCachedSizes(),this._onDidChange.fire({size:t.orthogonalSize})}),...this.children.map((t,n)=>t instanceof og?t.onDidVisibilityChange(({visible:s})=>{this.setChildVisible(n,s)}):an.NONE))}dispose(){this._childrenDisposable.dispose(),this.splitview.dispose(),this.children.forEach(t=>t.dispose()),super.dispose()}};function rg(e,t){if(e instanceof ls)return e;if(e instanceof Xn)return rg(e.children[t?e.children.length-1:0],t);throw new Error("invalid node")}function FE(e,t,n){if(e instanceof Xn){const s=new Xn(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(FE(r,r.size,r.orthogonalSize),r.size,0,!0)}return s}else return new ls(e.view,e.orientation,n)}function ag(e,t,n){if(e instanceof Xn){const s=new Xn(Ei(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 Xn?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(ag(a,n,d),d,0,!0)}return s}else return new ls(e.view,Ei(e.orientation),n)}function vse(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=vse(t),s=t.parentElement.parentElement.parentElement;return[...Tn(s),n]}function Ws(e,t,n){if(wse(e,t)===bse(n)){const[s,o]=lo(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 bse(e){return e==="top"||e==="bottom"?"VERTICAL":"HORIZONTAL"}function wse(e,t){return t.length%2===0?Ei(e):e}const Ei=e=>e==="HORIZONTAL"?"VERTICAL":"HORIZONTAL";function yse(e){return!!e.children}const lg=(e,t)=>{const n=t==="VERTICAL"?e.box.width:e.box.height;if(!yse(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=>lg(o,Ei(t)));return typeof e.cachedVisibleSize=="number"?{type:"branch",data:s,size:e.cachedVisibleSize,visible:!1}:{type:"branch",data:s,size:n}};var HE=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=ag(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 Xn&&(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 ls)||((t=this._maximizedNode)===null||t===void 0?void 0:t.leaf)===o)return;this.hasMaximizedView()&&this.exitMaximizedView(),lg(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 ls?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 ls?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:lg(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 Xn(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 ls))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,Ei(t),n,e.size),visible:l.visible}));o=new Xn(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 ls(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 ls)return;e.element.remove();const n=e.removeChild(0);e.dispose(),n.dispose(),this._root=FE(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 Xn(Ei(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(ag(t,t.orthogonalSize,t.size),js.Distribute,0)}else this._root.addChild(e,js.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 ls)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,Ei(t),l))}return{box:s,children:o,cachedVisibleSize:n}}progmaticSelect(e,t=!1){const[n,s]=this.getNode(e);if(!(s instanceof ls))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 rg(r.children[t?a-1:a+1],t)}return rg(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 we,this.onDidChange=this._onDidChange.event,this._onDidViewVisibilityChange=new we,this.onDidViewVisibilityChange=this._onDidViewVisibilityChange.event,this._onDidMaximizedNodeChange=new we,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 Xn(n,e,t,0,0,this.locked,this.margin)}isViewVisible(e){const[t,n]=lo(e),[,s]=this.getNode(t);if(!(s instanceof Xn))throw new TypeError("Invalid from location");return s.isChildVisible(n)}setViewVisible(e,t){this.hasMaximizedView()&&this.exitMaximizedView();const[n,s]=lo(e),[,o]=this.getNode(n);if(!(o instanceof Xn))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 Xn))throw new TypeError("Invalid location");s.moveChild(t,n)}addView(e,t,n){this.hasMaximizedView()&&this.exitMaximizedView();const[s,o]=lo(n),[r,a]=this.getNode(s);if(a instanceof Xn){const l=new ls(e,Ei(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=js.Invisible(p)),l.removeChild(c).dispose();const f=new Xn(a.orientation,this.proportionalLayout,this.styles,a.size,a.orthogonalSize,this.locked,this.margin);l.addChild(f,a.size,c);const g=new ls(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 ls(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]=lo(e),[o,r]=this.getNode(n);if(!(r instanceof Xn))throw new TypeError("Invalid location");const a=r.children[s];if(!(a instanceof ls))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 ls||(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 Xn){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 ls(l.view,Ei(l.orientation),l.size),x=p?l.orthogonalSize:js.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 Xn))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 dg=Object.keys({disableAutoResizing:void 0,proportionalLayout:void 0,orientation:void 0,hideBorders:void 0,className:void 0});var Av=class extends pt{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(jr(this._element,n=>{if(this.isDisposed||this.disableResizing||!this._element.offsetParent||!LE(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 Sse=Pv();function Fu(e){switch(e){case"left":return"left";case"right":return"right";case"above":return"top";case"below":return"bottom";default:return"center"}}var BE=class extends Av{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=Sse.next(),this._groups=new Map,this._onDidRemove=new we,this.onDidRemove=this._onDidRemove.event,this._onDidAdd=new we,this.onDidAdd=this._onDidAdd.event,this._onDidMaximizedChange=new we,this.onDidMaximizedChange=this._onDidMaximizedChange.event,this._onDidActiveChange=new we,this.onDidActiveChange=this._onDidActiveChange.event,this._bufferOnDidLayoutChange=new NC,this.onDidLayoutChange=this._bufferOnDidLayoutChange.onEvent,this._onDidViewVisibilityChangeMicroTaskQueue=new NC,this.onDidViewVisibilityChangeMicroTaskQueue=this._onDidViewVisibilityChangeMicroTaskQueue.onEvent,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new Fh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this.gridview=new HE(!!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()}),an.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??js.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,js.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 td(e){"@babel/helpers - typeof";return td=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},td(e)}function Cse(e,t){if(td(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(td(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function kse(e){var t=Cse(e,"string");return td(t)=="symbol"?t:t+""}function jse(e,t,n){return(t=kse(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function EC(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 gt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?EC(Object(n),!0).forEach(function(s){jse(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):EC(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function _se(e,t){return e==="center"?`Tab into ${t}`:`Split ${e} of ${t}`}function Nse(e,t){return e==="center"?`docked into ${t}`:`split ${e} of ${t}`}const Hu={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)=>`${_se(e,t)}. Arrows to change, Enter to confirm, Escape to go back.`,moveCommitted:(e,t,n)=>`${e} ${Nse(n,t)}.`,moveCancelled:()=>"Move cancelled.",moveNotAllowed:()=>"That move is not allowed.",moveFloated:e=>`${e} floated.`};function $E(e){return e?gt(gt({},Hu),e):Hu}var VE=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()}},nd=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()}},WE=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()}},Mv=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 $E(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()}},UE=class extends pt{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(rt(this.element,"dragenter",e=>{this.onDragEnter(e)},!0)),this.addDisposables(rt(this.element,"dragover",e=>{this.onDragOver(e)},!0)),this.addDisposables(rt(this.element,"dragleave",e=>{this.onDragLeave(e)})),this.addDisposables(rt(this.element,"dragend",e=>{this.onDragEnd(e)})),this.addDisposables(rt(this.element,"drop",e=>{this.onDrop(e)}))}};const Tse={value:50,type:"percentage"},Dse=100,Ise=100;function cg(){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 KE(e,t,n,s){var o,r,a;const l=(o=s?.smallWidthBoundary)!==null&&o!==void 0?o:Dse,d=(r=s?.smallHeightBoundary)!==null&&r!==void 0?r:Ise,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,b=!u&&g;let w=1;const _=(a=s?.size)!==null&&a!==void 0?a:Tse;return _.type==="percentage"?w=Pn(_.value,0,100)/100:((x||v)&&(w=Pn(0,_.value,t)/t),(y||b)&&(w=Pn(0,_.value,n)/n)),{isSmallX:c,isSmallY:u,isLeft:h,isRight:p,isTop:f,isBottom:g,rightClass:x,leftClass:v,topClass:y,bottomClass:b,size:w}}function qE(e,t,n,s,o){const r=KE(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);tt(e,"dv-drop-target-small-vertical",r.isSmallY),tt(e,"dv-drop-target-small-horizontal",r.isSmallX),tt(e,"dv-drop-target-selection-line",p),tt(e,"dv-drop-target-left",r.isLeft),tt(e,"dv-drop-target-right",r.isRight),tt(e,"dv-drop-target-top",r.isTop),tt(e,"dv-drop-target-bottom",r.isBottom),tt(e,"dv-drop-target-center",t==="center")}function Ese(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 Pse(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 YE(e){const t=KE(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),Ese(u,g)?(Pse(u,g),u.className=`dv-drop-target-anchor${e.className?` ${e.className}`:""}`,tt(u,"dv-drop-target-left",t.isLeft),tt(u,"dv-drop-target-right",t.isRight),tt(u,"dv-drop-target-top",t.isTop),tt(u,"dv-drop-target-bottom",t.isBottom),tt(u,"dv-drop-target-anchor-line",t.isSmallX&&(t.isLeft||t.isRight)||t.isSmallY&&(t.isTop||t.isBottom)),tt(u,"dv-drop-target-center",e.quadrant==="center"),d.changed&&(tt(u,"dv-drop-target-anchor-container-changed",!0),setTimeout(()=>{tt(u,"dv-drop-target-anchor-container-changed",!1)},10)),{boundsChanged:!0,targetChanged:d.changed}):{boundsChanged:!1,targetChanged:d.changed}}var XE=class extends Ev{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 PC(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 Ase(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 Mse={value:20,type:"percentage"};var Hh=class sl extends pt{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 we,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new we,this.onWillShowOverlay=this._onWillShowOverlay.event,this._disabled=!1,this._acceptedTargetZonesSet=new Set(this.options.acceptedTargetZones),this.dnd=new UE(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}sl.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,b=this.resolvePosition(v,y,f,g,s);if(this.isAlreadyUsed(s)){this.removeDropTarget();return}if(b===null){this.clearOwnOverlay();return}const w=b.position;if(!this.options.canDisplayOverlay(s,w)){this.clearOwnOverlay();return}const _=new XE({nativeEvent:s,position:w,edge:b.edge,edgeGroup:b.edgeGroup});if(this._onWillShowOverlay.fire(_),_.defaultPrevented){this.clearOwnOverlay();return}if(this.markAsUsed(s),b.edge){this.clearOwnOverlay(),this._state=w,this._edge=!0;return}if(this._edge=!1,!h){if(!this.targetElement){const C=cg();this.targetElement=C.dropzone,this.overlayElement=C.selection,this._state="center",p.classList.add("dv-drop-target"),p.append(this.targetElement)}}this.toggleClasses(w,f,g),this._state=w},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&&sl.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[sl.USED_EVENT_ID]=!0}isAlreadyUsed(t){const n=t[sl.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;YE({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&&qE(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:Mse;return d.type==="percentage"?ZE(t,n,s,o,r,d.value):JE(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=cg();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}};Hh.USED_EVENT_ID="__dockview_droptarget_event_is_used__";function ZE(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 JE(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 Rse(e,t,n){var s,o,r;ki(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(()=>{Ci(t,"dv-dragged"),t.remove()},0)}var Bu=class il extends pt{static getInstance(){var t;return(t=il._instance)!==null&&t!==void 0||(il._instance=new il),il._instance}constructor(){super(),this._targets=new Set,this._targetByElement=new Map,this._onDragStart=new we,this.onDragStart=this._onDragStart.event,this._onDragMove=new we,this.onDragMove=this._onDragMove.event,this._onDragEnd=new we,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=ed((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=rt(c,"pointermove",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleMove(u)}),this._upListener=rt(c,"pointerup",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleEnd(u,!0)}),this._cancelListener=rt(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 Lse={value:20,type:"percentage"};var Ose=class extends pt{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 we,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new we,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,Bu.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 XE({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){YE({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=cg();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&&qE(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:Lse;return a.type==="percentage"?ZE(this._acceptedTargetZonesSet,e,t,n,s,a.value):JE(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 zse=5,Gse=250,Fse=8;var Hse=class extends pt{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(rt(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:Gse;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:zse,u=this.options.pressTolerance,h=(s=typeof u=="function"?u():u)!==null&&s!==void 0?s:Fse,p=(o=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&o!==void 0?o:globalThis.window;this._pendingMoveListener=rt(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=rt(p,"pointerup",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()}),this._pendingCancelListener=rt(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);Bu.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()}},Bse=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())}},$se=class extends pt{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,rt(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=ed((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(Rse(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)}),rt(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(){}},Vse=class{constructor(){this.kind="html5"}createDropTarget(e,t){return new Hh(e,t)}createDragSource(e,t){return new $se(e,t)}},Wse=class{constructor(){this.kind="pointer"}createDropTarget(e,t){return new Ose(e,t)}createDragSource(e,t){const n=t.createGhost?o=>{const r=t.createGhost(o);if(!r)return;const a=new Bse({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 Hse(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 Go=new Vse,bo=new Wse,ug=Object.keys({disableAutoResizing:void 0,disableDnd:void 0,className:void 0});var Use=class extends EE{constructor(e,t,n,s){super(),this.nativeEvent=e,this.position=t,this.getData=n,this.panel=s}},QE=class extends Ev{constructor(){super()}},eP=class extends pt{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 we,this.onDidDimensionsChange=this._onDidDimensionChange.event,this._onDidChangeFocus=new we,this.onDidFocusChange=this._onDidChangeFocus.event,this._onWillFocus=new we,this.onWillFocus=this._onWillFocus.event,this._onDidVisibilityChange=new we,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._onWillVisibilityChange=new we,this.onWillVisibilityChange=this._onWillVisibilityChange.event,this._onDidActiveChange=new we,this.onDidActiveChange=this._onDidActiveChange.event,this._onActiveChange=new we,this.onActiveChange=this._onActiveChange.event,this._onDidParametersChange=new we,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)}},tP=class extends eP{constructor(e,t){super(e,t),this._onDidConstraintsChangeInternal=new we,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new we({replay:!0}),this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new we,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)}},Kse=class extends tP{set pane(e){this._pane=e}constructor(e,t){super(e,t),this._onDidExpansionChange=new we({replay:!0}),this.onDidExpansionChange=this._onDidExpansionChange.event,this._onMouseEnter=new we({}),this.onMouseEnter=this._onMouseEnter.event,this._onMouseLeave=new we({}),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())}},Rv=class extends pt{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=AE(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 QE;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=gt(gt({},this._params),{},{params:gt(gt({},(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()}},qse=class extends Rv{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 Kse(e.id,e.component)),this._onDidChangeExpansionState=new we({replay:!0}),this.onDidChangeExpansionState=this._onDidChangeExpansionState.event,this._onDidChange=new we,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})}),rt(this.element,"mouseenter",t=>{this.api._onMouseEnter.fire(t)}),rt(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?ki(this.header,"focused"):Ci(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(gt(gt({},e),{},{api:this.api})),this.headerPart.init(gt(gt({},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 gt(gt({},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()}}}},Yse=class extends qse{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 we,this.onDidDrop=this._onDidDrop.event,this._onUnhandledDragOver=new we,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:()=>(vo.getInstance().setData([new Tl(t,e)],Tl.prototype),{dispose:()=>{vo.getInstance().clearData(Tl.prototype)}})};this.html5DragSource=Go.createDragSource(this.header,n),this.pointerDragSource=bo.createDragSource(this.header,n);const o={acceptedTargetZones:["top","bottom"],overlayModel:{activationSize:{type:"percentage",value:50}},canDisplayOverlay:(r,a)=>{const l=qa();if(l&&l.paneId!==this.id&&l.viewId===this.accessor.id)return!0;const d=new Use(r,a,qa,this);return this._onUnhandledDragOver.fire(d),d.isAccepted}};this.target=Go.createDropTarget(this.element,o),this.pointerTarget=bo.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=qa();if(t?.viewId!==this.accessor.id){this._onDidDrop.fire(gt(gt({},e),{},{panel:this,api:new nd(this.accessor),getData:qa}));return}const n=this._params.containerApi,s=t.paneId,o=n.getPanel(s);if(!o){this._onDidDrop.fire(gt(gt({},e),{},{panel:this,getData:qa,api:new nd(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 Xse=0;const Zse=()=>`dv-tabpanel-${Xse++}`;var Jse=class extends pt{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 we,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new we,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-content-container",this._element.tabIndex=-1,this._element.id=Zse(),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 Hh(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=bo.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:an.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=AE(l);this.focusTracker=u;const h=new pt;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 Bh=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},Qse=()=>Bh({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"}),nP=()=>Bh({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"}),eie=()=>Bh({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"}),sP=()=>Bh({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"}),tie=500,nie=8;var Lv=class extends pt{constructor(e,t){super(),this.element=e,this.options=t,this._startX=0,this._startY=0,this.addDisposables(rt(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:tie,l=(s=this.options.tolerance)!==null&&s!==void 0?s:nie,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=rt(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=rt(d,"pointerup",c=>{c.pointerId===this._pointerId&&this._cancelPending()}),this._cancelListener=rt(d,"pointercancel",c=>{c.pointerId===this._pointerId&&this._cancelPending()})}_installContextMenuGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=rt(e,"contextmenu",s=>{s.preventDefault(),clearTimeout(n),t?.dispose()},{capture:!0})}_installClickGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=rt(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 ui(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 sie()?{html5:!1,pointer:!0,pointerHandlesMouse:!0}:{html5:!0,pointer:!0,pointerHandlesMouse:!1}}}function sie(){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 iie=0;const oie=()=>`dv-tab-${iie++}`;var rie=class extends pt{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=vo.getInstance(),this._direction="horizontal",this._pinIndicator=void 0,this._onPointDown=new we,this.onPointerDown=this._onPointDown.event,this._onTabClick=new we,this.onTabClick=this._onTabClick.event,this._onDropped=new we,this.onDrop=this._onDropped.event,this._onDragStart=new we,this.onDragStart=this._onDragStart.event,this._onDragEnd=new we,this.onDragEnd=this._onDragEnd.event;const h=ui(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=oie(),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),tt(this.element,"dv-inactive-tab",!0),this._updatePinnedClasses();const f=(x,v)=>{if(this.group.locked)return!1;const y=On();if(this.accessor.id===y?.viewId){var b;return((b=this.accessor.options.theme)===null||b===void 0?void 0:b.tabAnimation)!=="smooth"}return this.group.model.canDisplayOverlay(x,v,"tab")};this.dropTarget=Go.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=bo.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(()=>{tt(this.element,"dv-tab--dragging",!0)})},onDragEnd:x=>{this._onDragEnd.fire(x)}};this.html5DragSource=Go.createDragSource(this._element,gt(gt({},g),{},{disabled:!h.html5})),this.pointerDragSource=bo.createDragSource(this._element,gt(gt({},g),{},{disabled:!h.pointer,touchOnly:!h.pointerHandlesMouse,isCancelled:()=>!ui(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:()=>{}},rt(this._element,"dragend",()=>{tt(this.element,"dv-tab--dragging",!1)}),this.html5DragSource,rt(this._element,"pointerdown",x=>{this._onPointDown.fire(x)}),rt(this._element,"click",x=>{this._onTabClick.fire(x)}),rt(this._element,"contextmenu",x=>{var v;(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,x)}),new Lv(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;tt(this.element,"dv-tab--pinned",o),tt(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(nP()),this._element.insertBefore(l,this._element.firstChild),this._pinIndicator=l}else!a&&this._pinIndicator&&(this._pinIndicator.remove(),this._pinIndicator=void 0)}setActive(e){tt(this.element,"dv-active-tab",e),tt(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=ui(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}},sd=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}},iP=class extends pt{get group(){return this.groupAccessor()}constructor(e){var t,n;super(),this.panelTransfer=vo.getInstance(),this._onDragStart=new we,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=ui(this.accessor.options);this._element.draggable=o.html5,tt(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=Go.createDragSource(this._element,gt(gt({},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=bo.createDragSource(this._element,gt(gt({},l),{},{disabled:!o.pointer,touchOnly:!o.pointerHandlesMouse,touchInitiationDelay:()=>d()?500:250,pressTolerance:()=>d()?1/0:8,isCancelled:()=>!ui(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()}):an.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=ui(this.accessor.options);this._element.draggable=e.html5,tt(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}},aie=class extends pt{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 we,this.onDrop=this._onDrop.event,this._onDragStart=new we,this.onDragStart=this._onDragStart.event,this._element=document.createElement("div"),this._element.className="dv-void-container",this.addDisposables(this._onDrop,this._onDragStart,rt(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this.group)}),rt(this._element,"pointerdown",u=>{u.shiftKey&&RE(u)},!0)),this.dragSource=new iP({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=On();return this.accessor.id===p?.viewId?!0:t.model.canDisplayOverlay(u,h,"header_space")};this.dropTarget=Go.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=bo.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:an.NONE)}updateDragAndDropState(){this.dragSource.updateDragAndDropState()}},oP=class rP extends pt{get element(){return this._element}get orientation(){return this._orientation}set orientation(t){this._orientation!==t&&(this._scrollOffset=0,this._orientation=t,Ci(this._scrollbar,"dv-scrollbar-vertical","dv-scrollbar-horizontal"),t==="vertical"?ki(this._scrollbar,"dv-scrollbar-vertical"):ki(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(rt(this.element,"wheel",n=>{this._scrollOffset+=n.deltaY*rP.MouseWheelSpeed,this.scheduleStyleUpdate()}),rt(this._scrollbar,"pointerdown",n=>{var s;n.preventDefault();const o=(s=this._scrollbar.ownerDocument)!==null&&s!==void 0?s:document;tt(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=()=>{tt(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)}),rt(this.element,"scroll",()=>{this.scheduleStyleUpdate()}),rt(this.scrollableElement,"scroll",()=>{this._scrollOffset=this._orientation==="horizontal"?this.scrollableElement.scrollLeft:this.scrollableElement.scrollTop,this.scheduleStyleUpdate()}),jr(this.element,()=>{tt(this.element,"dv-scrollable-resizing",!0),this._animationTimer&&clearTimeout(this._animationTimer),this._animationTimer=setTimeout(()=>{clearTimeout(this._animationTimer),tt(this.element,"dv-scrollable-resizing",!1)},500),this.scheduleStyleUpdate()}),an.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=Pn(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}};oP.MouseWheelSpeed=1;const aP="dv-tabs-container--wrap";function lie(e,t){return typeof e=="boolean"?e:!!e?.[t]}function hg(e){return typeof e=="boolean"?e:e?Object.values(e).some(Boolean):!1}var lP=class extends EE{constructor(e,t,n,s,o){super(),this.nativeEvent=e,this.target=t,this.position=n,this.getData=s,this.group=o}};const pg=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 die(e){return!!e.referencePanel}function cie(e){return!!e.referenceGroup}function uie(e){return!!e.referencePanel}function hie(e){return!!e.referenceGroup}const Ov=[{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 dP=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 mf;function cP(){var e;return(e=mf)!==null&&e!==void 0||(mf=new dP(Ov,!0)),mf}function zv(e,t,n){const s=(n??cP()).resolveValue(t);s===void 0?e.style.removeProperty("--dv-tab-group-color"):e.style.setProperty("--dv-tab-group-color",s)}function Gv(e,t){return(t??cP()).resolveValue(e)}var AC=class extends pt{get element(){return this._element}constructor(e){super(),this._palette=e,this._onClick=new we,this.onClick=this._onClick.event,this._onContextMenu=new we,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 Lv(this._element,{onLongPress:t=>{this._onContextMenu.fire(t)}}),rt(this._element,"click",t=>{this._onClick.fire(t)}),rt(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;zv(this._element,e,this._palette),tt(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,tt(this._label,"dv-tab-group-chip-label--empty",!e)}updateCollapsed(e){tt(this._element,"dv-tab-group-chip--collapsed",e)}};const pie="dv-tab-group-chip-continuation",MC=8;var uP=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=pie,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(aP);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(),b=getComputedStyle(u),w=n?Number.parseFloat(b.marginTop)||0:Number.parseFloat(b.marginLeft)||0;h=n?y.top-e.top-w:y.left-e.left-w}else{const y=c[0],b=a.get(y);if(b){const w=b.value.element.getBoundingClientRect();h=n?w.top-e.top:w.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 b=a.get(y);return b?.value.element.classList.contains("dv-tab--group-expanding")}))&&u){const y=u.getBoundingClientRect(),b=n?y.top+y.height/2-e.top:y.left+y.width/2-e.left;let w=0,_=0;for(const N of l.panelIds){const S=a.get(N);if(!S)continue;const k=S.value.element;n?(w+=k.getBoundingClientRect().height,_+=k.scrollHeight):(w+=k.getBoundingClientRect().width,_+=k.scrollWidth)}const C=_>0?Math.min(1,w/_):0;h=b+(h-b)*C,x=b+(x-b)*C,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=Gv(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(w=>w.left)),u=Math.max(...l.map(w=>w.right)),h=Math.min(...l.map(w=>w.top)),p=Math.max(...l.map(w=>w.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(),b=o?y==="right":y==="bottom";v.setAttribute("d",this._wrappedPathData(l,o,b,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-MC/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-MC/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}}},fie=class extends uP{_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=Gv(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",b=l&&v==="right";let w,_;if(l?(w=b?c-x:x,_=b?x:c-x):(w=y?x:c-x,_=y?c-x:x),!p){this._applyStraightLine(f,g,e,u,c,w,l);return}const C=p.value.element.getBoundingClientRect();let N,S;if(l?(N=Math.max(0,C.top-a.top-n),S=Math.min(u,C.bottom-a.top-n)):(N=Math.max(0,C.left-a.left-n),S=Math.min(u,C.right-a.left-n)),S<=N){this._applyStraightLine(f,g,e,u,c,w,l);return}const k=6,A=_>w?1:-1;if(l){const I=c,E=u;f.setAttribute("width",String(I)),f.setAttribute("height",String(E)),e.style.width=`${I}px`,e.style.height=`${E}px`;const D=[`M ${w},0`,`L ${w},${N-k}`,`Q ${w},${N} ${w+A*k},${N}`,`L ${_-A*k},${N}`,`Q ${_},${N} ${_},${N+k}`,`L ${_},${S-k}`,`Q ${_},${S} ${_-A*k},${S}`,`L ${w+A*k},${S}`,`Q ${w},${S} ${w},${S+k}`,`L ${w},${E}`].join(" ");g.setAttribute("d",D)}else{const I=u,E=c;f.setAttribute("width",String(I)),f.setAttribute("height",String(E)),e.style.width=`${I}px`,e.style.height=`${E}px`;const D=[`M 0,${w}`,`L ${N-k},${w}`,`Q ${N},${w} ${N},${w+A*k}`,`L ${N},${_-A*k}`,`Q ${N},${_} ${N+k},${_}`,`L ${S-k},${_}`,`Q ${S},${_} ${S},${_-A*k}`,`L ${S},${w+A*k}`,`Q ${S},${w} ${S+k},${w}`,`L ${I},${w}`].join(" ");g.setAttribute("d",D)}}},mie=class extends uP{applyShape(e,t,n,s,o,r,a,l){const c=Gv(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 gie=new Map;var xie=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:gie}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=ui(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"?mie:fie;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=ui(this._ctx.accessor.options);e.element.draggable=n.html5;const s=vo.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=Go.createDragSource(e.element,{getData:o,disabled:!n.html5,isCancelled:()=>!ui(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=bo.createDragSource(e.element,{getData:o,disabled:!n.pointer,touchOnly:!n.pointerHandlesMouse,isCancelled:()=>!ui(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 AC(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 AC?r.push(s.onContextMenu(a)):r.push(new Lv(s.element,{onLongPress:a}),rt(s.element,"contextmenu",a));const l=this._ctx.getDirection()==="vertical",d=new Hh(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=On();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 pt(...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(tt(d.element,"dv-tab--grouped",h),u){const p=u.panelIds,f=p[0]===c,g=p[p.length-1]===c;tt(d.element,"dv-tab--group-first",f),tt(d.element,"dv-tab--group-last",g),zv(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 tt(d.element,"dv-tab--group-first",!1),tt(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())}},vie=class extends pt{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(aP)}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=On();e?.tabGroupId&&e.groupId!==this.group.id&&this._animState.sourceTabGroupId!==e.tabGroupId&&(this._animState=null)}_initAnimStateForExternalDrag(){var e;const t=On();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",tt(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,tt(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"),tt(e,n,!1);else{e.style.marginLeft="0px",tt(e,n,!0);const o=()=>{e.style.removeProperty("margin-left"),tt(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"),tt(e.value.element,"dv-tab--shifting",!1);for(const[,e]of this._tabGroupManager.chipRenderers)e.chip.element.style.removeProperty("margin-left"),tt(e.chip.element,"dv-tab-group-chip--shifting",!1);this._tabGroupManager.positionUnderlines()}commitGroupMove(e,t){const n=On();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)`,tt(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)`,tt(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)tt(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)})}},bie=class extends pt{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 rse(this._tabsList);this._observerDisposable.value=new pt(t,t.onDidChange(n=>{const s=n.hasScrollX||n.hasScrollY;this.toggleDropdown({reset:!s}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}),rt(this._tabsList,"scroll",()=>{this.toggleDropdown({reset:!1}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}))}else this._observerDisposable.value=an.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 pt(rt(e,"dragover",n=>{this._animState&&n.preventDefault()}),rt(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),Ci(this._tabsList,"dv-horizontal","dv-vertical"),e==="vertical"?ki(this._tabsList,"dv-tabs-container-vertical","dv-vertical"):(Ci(this._tabsList,"dv-tabs-container-vertical"),ki(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 we,this.onTabDragStart=this._onTabDragStart.event,this._onDrop=new we,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new we,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onOverflowTabsChange=new we,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 oP(this._tabsList),this._scrollbar.orientation=this.direction,this._element=this._scrollbar.element,this.addDisposables(this._scrollbar)),this._tabGroupManager=new xie({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 vie(this),this.addDisposables(this._onOverflowTabsChange,this._observerDisposable,this._pointerActivation,this._onWillShowOverlay,this._onDrop,this._onTabDragStart,this._reorder,Bu.getInstance().onDragEnd(s=>{this._reorder.handlePointerDragEnd(s)}),Bu.getInstance().onDragMove(s=>{this._reorder.handlePointerDragMove(s.clientX,s.clientY)}),rt(this.element,"pointerdown",s=>{s.defaultPrevented||s.button===0&&this.accessor.doSetGroupActive(this.group)}),rt(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}),rt(this._tabsList,"keydown",s=>{this._onKeyDown(s)}),rt(this._tabsList,"dragover",s=>{this._reorder.processDragOver(s.clientX,s.clientY)&&s.preventDefault()},!0),rt(this._tabsList,"dragleave",s=>{this._reorder.processDragLeave(s.relatedTarget)},!0),rt(this._tabsList,"dragend",()=>{this._reorder.resetDragAnimation()}),rt(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),an.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(!ui(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 rie(e,this.accessor,this.group);n.setContent(e.view.tab),this._direction!=="horizontal"&&n.setDirection(this._direction);const s={value:n,disposable:new pt(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",tt(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=On(),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 sd(o,{kind:"tab",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:On}))}))};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&&!pf(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&&!pf(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&&!pf(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",tt(f.value.element,"dv-tab--dragging",!0));const h=this._tabGroupManager.chipRenderers.get(e.id);h&&(h.chip.element.style.transition="none",tt(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=On(),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 wie(){const e=document.createElement("div");e.className="dv-tabs-overflow-dropdown-default";const t=document.createElement("span");t.textContent="";const n=sP();return e.appendChild(n),e.appendChild(t),{element:e,update:s=>{t.textContent=`${s.tabs}`}}}var yie=class extends pt{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"?(ki(this._element,"dv-groupview-header-vertical"),ki(this.rightActionsContainer,"dv-right-actions-container-vertical"),this.tabs.direction=e):(Ci(this._element,"dv-groupview-header-vertical"),Ci(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 we,this.onDrop=this._onDrop.event,this._onGroupDragStart=new we,this.onGroupDragStart=this._onGroupDragStart.event,this._onWillShowOverlay=new we,this.onWillShowOverlay=this._onWillShowOverlay.event,this._element=document.createElement("div"),this._element.className="dv-tabs-and-actions-container",tt(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 bie(t,e,{showTabsOverflowControl:!e.options.disableTabsOverflowList}),this.voidContainer=new aie(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 sd(n,{kind:"header_space",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:On}))}),rt(this.leftActionsContainer,"dragleave",n=>{const s=n.relatedTarget;!this.leftActionsContainer.contains(s)&&!this._element.contains(s)&&this.tabs.clearExternalAnimState()}),rt(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())}),rt(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)),tt(this._element,"dv-tabs-and-actions-container--pinned-row",!!e))}setDropIndexResolver(e){this._dropIndexResolver=e}resolveDropIndex(e,t){return this._dropIndexResolver(e,t)}updateClassnames(){tt(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=wie();a.update({tabs:o}),this.dropdownPart=a,r.appendChild(a.element),this.rightActionsContainer.prepend(r),this._dropdownDisposable.value=new pt(an.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}),rt(r,"pointerdown",l=>{l.preventDefault()},{capture:!0}),rt(r,"click",l=>{const d=mse(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",zv(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=nP();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");tt(f,"dv-tab",!0),tt(f,"dv-active-tab",c.api.isActive),tt(f,"dv-inactive-tab",!c.api.isActive),h&&tt(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()}},Sie=class extends pt{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 we,this.onDidChange=this._onDidChange.event,this._onDidPanelChange=new we,this.onDidPanelChange=this._onDidPanelChange.event,this._onDidCollapseChange=new we,this.onDidCollapseChange=this._onDidCollapseChange.event,this._onDidDestroy=new we,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()}},Fv=class extends Ev{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()}},hP=class extends Fv{get kind(){return this._kind}constructor(e){super(e),this._kind=e.kind}},Cie=class extends pt{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,tt(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?ng(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(),Ci(this.container,"dv-groupview-header-top","dv-groupview-header-bottom","dv-groupview-header-left","dv-groupview-header-right"),ki(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,tt(this.container,"dv-groupview-floating",!1),tt(this.container,"dv-groupview-popout",!1),tt(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"]),tt(this.container,"dv-groupview-floating",!0);break;case"popout":t(["top","bottom","left","right","center"]),tt(this.container,"dv-groupview-popout",!0);break;case"edge":t(["center"]),tt(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 we,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 we,this.onMove=this._onMove.event,this._onDidDrop=new we,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new we,this.onWillDrop=this._onWillDrop.event,this._onWillShowOverlay=new we,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onTabDragStart=new we,this.onTabDragStart=this._onTabDragStart.event,this._onGroupDragStart=new we,this.onGroupDragStart=this._onGroupDragStart.event,this._onDidAddPanel=new we,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPanelTitleChange=new we,this.onDidPanelTitleChange=this._onDidPanelTitleChange.event,this._onDidPanelParametersChange=new we,this.onDidPanelParametersChange=this._onDidPanelParametersChange.event,this._onDidRemovePanel=new we,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidActivePanelChange=new we,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onUnhandledDragOver=new we,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._tabGroups=[],this._tabGroupMap=new Map,this._panelToTabGroup=new Map,this._tabGroupIdCounter=0,this._pendingTabGroupUpdate=!1,this._onDidCreateTabGroup=new we,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new we,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new we,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new we,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new we,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new we,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,tt(this.container,"dv-groupview",!0),this.container.setAttribute("role","region"),this._api=new Mv(this.accessor),this.tabsContainer=new yie(this.accessor,this.groupPanel),this.contentContainer=new Jse(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(jr(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=On(),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 sd(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:On}))}),this.contentContainer.pointerDropTarget.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(new sd(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:On}))}),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 Sie(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 pt(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,tt(this.container,"dv-active-group",e),tt(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 pt(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,rt(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 lP(e,n,t,On,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=On();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 hP({nativeEvent:t,position:n,panel:a,getData:()=>On(),kind:r(),group:this.groupPanel,api:this._api});if(this._onWillDrop.fire(l),l.defaultPrevented)return;const d=On();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 Fv({nativeEvent:t,position:n,panel:a,getData:()=>On(),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()}},Hv=class extends eP{constructor(e,t,n){super(e,t),this._onDidConstraintsChangeInternal=new we,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new we,this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new we,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)}},pP=class extends Rv{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 Hv(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 we,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 gt(gt({},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 kie=class extends Hv{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 we,this.onDidLocationChange=this._onDidLocationChange.event,this._onDidActivePanelChange=new we,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidCollapsedChange=new we,this.onDidCollapsedChange=this._onDidCollapsedChange.event,this._onDidPeekChange=new we,this.onDidPeekChange=this._onDidPeekChange.event,this._onDidHeaderDirectionChange=new we,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=gt({},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:Ase((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 jie=100,_ie=100;var fc=class extends pP{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:_ie,minimumWidth:(r=(a=n.constraints)===null||a===void 0?void 0:a.minimumWidth)!==null&&r!==void 0?r:jie,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 kie(t,e)),this._explicitConstraints={},this.api.initialize(this),this._model=new Cie(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 Nie={name:"dark",className:"dockview-theme-dark",colorScheme:"dark"},Tie={name:"light",className:"dockview-theme-light",colorScheme:"light"},Die={className:"dockview-theme-abyss",tabGroupIndicator:"none"};var Iie=class extends Hv{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 we,this.onDidTitleChange=this._onDidTitleChange.event,this._onDidChangePinned=new we,this.onDidChangePinned=this._onDidChangePinned.event,this._onDidActiveGroupChange=new we,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._onDidGroupChange=new we,this.onDidGroupChange=this._onDidGroupChange.event,this._onDidRendererChange=new we,this.onDidRendererChange=this._onDidRendererChange.event,this._onDidLocationChange=new we,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 pt(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}))}))}},Fr=class extends pt{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 Iie(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(gt(gt({},e),{},{api:this.api,containerApi:this.containerApi})),this.setTitle(e.title)}focus(){const e=new QE;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=gt(gt({},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()}},RC=class extends pt{get element(){return this._element}constructor(){super(),this._messages=Hu,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=Qse();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:Hu,this.addDisposables(e.api.onDidTitleChange(n=>{this._title=n.title,this.render()}),rt(this.action,"pointerdown",n=>{n.preventDefault()}),rt(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())}},fP=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(gt(gt({},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(gt(gt({},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 RC}console.warn(`dockview: tabComponent '${t}' was not found. falling back to the default tab.`)}return new RC}},Eie=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 fP(this.accessor,r,c,u),p=new Fr(r,c,u,this.accessor,new Mv(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}},Pie=class extends pt{get element(){return this._element}constructor(){super(),this._element=document.createElement("div"),this._element.className="dv-watermark"}init(t){}},Aie=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 mc=new Aie;var Bv=class or extends pt{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 we,this.onDidChange=this._onDidChange.event,this._onDidChangeEnd=new we,this.onDidChangeEnd=this._onDidChangeEnd.event,this._onDidStartMoving=new we,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&&(tt(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(gt(gt(gt(gt({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})),mc.push(this._element)}setVisible(t){t!==this.isVisible&&(this._isVisible=t,tt(this.element,"dv-hidden",!this.isVisible))}bringToFront(){mc.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=Pn(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=Pn(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=Pn(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=Pn(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,tt(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=an.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=ed();if(o&&typeof r=="number"&&typeof o.setPointerCapture=="function")try{o.setPointerCapture(r)}catch{}const f=()=>{tt(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=an.NONE,this._onDidChangeEnd.fire()};this._dragMove.value=new pt({dispose:()=>{if(p.release(),o&&typeof r=="number"&&typeof o.releasePointerCapture=="function")try{o.releasePointerCapture(r)}catch{}}},rt(globalThis.window,"pointermove",g=>{var x;if(this._dragCancelled)return;const v=this.options.container.getBoundingClientRect(),y=g.clientX-v.left,b=g.clientY-v.top;tt(this._element,"dv-resize-container-dragging",!0);const w=this._element.getBoundingClientRect();(x=c)!==null&&x!==void 0||(c={x:g.clientX-w.left,y:g.clientY-w.top});const _=Math.max(0,this.getMinimumWidth(w.width)),C=Math.max(0,this.getMinimumHeight(w.height));let N=b-c.y,S=y-c.x;if(this.options.transformDragPosition){const F=this.options.transformDragPosition({proposed:{top:N,left:S,width:w.width,height:w.height},container:{width:v.width,height:v.height},others:h,modifiers:{altKey:g.altKey,ctrlKey:g.ctrlKey,metaKey:g.metaKey,shiftKey:g.shiftKey}});F&&(N=F.top,S=F.left)}const k=Math.max(0,v.height-w.height+C),A=Math.max(0,v.width-w.width+_),I=Pn(N,-C,k),E=Pn(v.height-w.height-N,-C,k),D=Pn(S,-_,A),T=Pn(v.width-w.width-S,-_,A),H={};I<=E?H.top=I:H.bottom=E,D<=T?H.left=D:H.right=T,this.setBounds(H),u||(u=!0,this._onDidStartMoving.fire())}),rt(globalThis.window,"pointerup",f),rt(globalThis.window,"pointercancel",f))};this.addDisposables(rt(t,"pointerdown",o=>{if(o.defaultPrevented){o.preventDefault();return}TC(o)||s(t,o.pointerId)}),rt(this.options.content,"pointerdown",o=>{o.defaultPrevented||TC(o)||o.shiftKey&&s(this.options.content,o.pointerId)}),rt(this.options.content,"pointerdown",()=>{mc.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,rt(n,"pointerdown",o=>{o.preventDefault();let r=null;const a=ed(),l=o.pointerId;if(typeof n.setPointerCapture=="function")try{n.setPointerCapture(l)}catch{}const d=()=>{s.dispose(),this._onDidChangeEnd.fire()};s.value=new pt(rt(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,b,w,_;const C=()=>{const I=r.originalY+r.originalHeight>h.height?Math.max(0,h.height-or.MINIMUM_HEIGHT):Math.max(0,r.originalY+r.originalHeight-or.MINIMUM_HEIGHT);x=Pn(f,0,I),y=r.originalY+r.originalHeight-x,v=h.height-x-y},N=()=>{x=r.originalY-r.originalHeight;const I=x<0&&typeof this.options.minimumInViewportHeight=="number"?-x+this.options.minimumInViewportHeight:or.MINIMUM_HEIGHT,E=h.height-Math.max(0,x);y=Pn(f-x,I,E),v=h.height-x-y},S=()=>{const I=r.originalX+r.originalWidth>h.width?Math.max(0,h.width-or.MINIMUM_WIDTH):Math.max(0,r.originalX+r.originalWidth-or.MINIMUM_WIDTH);b=Pn(g,0,I),_=r.originalX+r.originalWidth-b,w=h.width-b-_},k=()=>{b=r.originalX-r.originalWidth;const I=b<0&&typeof this.options.minimumInViewportWidth=="number"?-b+this.options.minimumInViewportWidth:or.MINIMUM_WIDTH,E=h.width-Math.max(0,b);_=Pn(g-b,I,E),w=h.width-b-_};switch(t){case"top":C();break;case"bottom":N();break;case"left":S();break;case"right":k();break;case"topleft":C(),S();break;case"topright":C(),k();break;case"bottomleft":N(),S();break;case"bottomright":N(),k();break}const A={};x<=v?A.top=x:A.bottom=v,b<=w?A.left=b:A.right=w,A.height=y,A.width=_,this.setBounds(A)}),{dispose:()=>{if(a.release(),typeof n.releasePointerCapture=="function")try{n.releasePointerCapture(l)}catch{}}},rt(globalThis.window,"pointerup",d),rt(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(){mc.destroy(this._element),this._element.remove(),super.dispose()}};Bv.MINIMUM_HEIGHT=20;Bv.MINIMUM_WIDTH=20;var Mie=class extends pt{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 we,this.onDragStart=this._onDragStart.event,this._group=t,this._element=document.createElement("div"),this._element.className="dv-floating-titlebar",this.addDisposables(this._onDragStart,rt(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this._group)}),rt(this._element,"pointerdown",n=>{n.shiftKey&&RE(n)},!0)),this.dragSource=new iP({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 So(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 Rie=new Set(["AdvancedOverflow","AutoEdgeGroup","AutoHideEdgeGroup","ContextMenu","DndCompass","KeyboardDocking","KeyboardNavigation","LayoutHistory","License","MultiRowTabs","PinnedTabs","SmartGuides"]),LC=new Set;function mP(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 Rie.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 gP(e,t){const n=`${e}|${(t===void 0?[]:[].concat(t)).join("|")}`;LC.has(n)||(LC.add(n),console.error(mP(e,t)))}function Ms(e,t,n){if(e!==void 0)return e;gP(t,n)}var Lie=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 Oie=[];function zie(){return[...Oie]}const Gie=[{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=>hg(e.autoHideEdgeGroups)},{optionKey:"dockToEdgeGroups",reason:"dockToEdgeGroups",moduleName:"AutoEdgeGroup",when:e=>hg(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 Fie(e,t){const n=new Map;for(const s of Gie){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)gP(s,o)}const No={left:100,top:100,width:300,height:300};var Hie=class extends pt{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)}},Bie=class{get floatingGroups(){return this._floatingGroups}constructor(e){this._floatingGroups=[],this._host=e}add(e,t,n){const s=new Hie(e,t,n),o=new pt(e.api.onDidActiveChange(a=>{a.isActive&&t.bringToFront()}),(()=>{let a=-1,l=-1;return jr(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(),GE(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 $ie=So({name:"FloatingGroup",serviceKey:"floatingGroupService",create:e=>new Bie(e)});var Vie=class{constructor(e){this._entries=[],this._restorationCleanups=new Set,this._restorationPromise=Promise.resolve(),this._onDidRemove=new we,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){GE(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"?gt(gt({},o),{},{data:n.data[0].data}):gt(gt({},o),{},{grid:t})})}disposeAll(){for(const e of[...this._entries])e.disposable.dispose()}dispose(){this.cancelPendingRestorations(),this.disposeAll(),this._onDidRemove.dispose()}};const Wie=So({name:"PopoutWindow",serviceKey:"popoutWindowService",create:e=>new Vie(e)});var Uie=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",dse(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 Kie=So({name:"Watermark",serviceKey:"watermarkService",create:e=>new Uie(e),init:(e,t)=>(t.update(),new pt(Qs.any(e.onDidAdd,e.onDidRemove)(()=>{t.update()}),e.onDidViewVisibilityChangeMicroTaskQueue(()=>{t.update()})))});var qie=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 Yie=So({name:"EdgeGroup",serviceKey:"edgeGroupService",create:()=>new qie}),Xie={activationSize:{type:"pixels",value:10},size:{type:"pixels",value:20}},Zie={activationSize:{type:"pixels",value:32},size:{type:"pixels",value:20}};function OC(e,t){return typeof e.dndEdges=="object"&&e.dndEdges!==null?e.dndEdges:t&&hg(e.dockToEdgeGroups)?Zie:Xie}var Jie=class{constructor(e){this._host=e;const t=(s,o)=>{const r=On();return r?r.viewId!==e.id?!1:o==="center"?e.isGridEmpty():!0:o==="center"&&!e.isGridEmpty()?!1:e.dispatchUnhandledDragOver(s,o)},n=OC(e.options,!1);this._html5Target=Go.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=bo.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=OC({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 Qie=So({name:"RootDropTarget",serviceKey:"rootDropTargetService",create:e=>new Jie(e),init:(e,t)=>(t.setOptions(e.options),an.NONE)}),eoe={left:"createLeftHeaderActionComponent",right:"createRightHeaderActionComponent",prefix:"createPrefixHeaderActionComponent"};var toe=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[eoe[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 noe=So({name:"HeaderActions",serviceKey:"headerActionsService",create:e=>new toe(e),init:(e,t)=>new pt(e.onDidRemoveGroup(n=>{t.disposeGroup(n)}))}),zC=e=>e==="load"||e==="clear";function gc(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 soe=class extends pt{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:gc(n,"polite"),assertive:gc(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=>{zC(o.kind)&&this._suppressDepth++}),e.onDidMutateLayout(o=>{zC(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:gc(o,"polite"),assertive:gc(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=$E(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 ioe=So({name:"LiveRegion",serviceKey:"liveRegionService",create:e=>new soe(e)}),ooe=30,roe=-10;var aoe=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:ooe,offsetY:roe,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),an.from(()=>n.clearOverlay())}dispose(){}};const loe=So({name:"AdvancedDnD",serviceKey:"advancedDnDService",create:e=>new aoe(e)});var doe=class{constructor(e){this._host=e}attachToGroup(e){return new pt(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 coe=So({name:"TabGroupChips",serviceKey:"tabGroupChipsService",create:e=>new doe(e),init:(e,t)=>{const n=new Map;return new pt(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()}})}}),uoe=[$ie,Wie,Kie,Yie,Qie,noe,ioe,loe,coe];var hoe=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=sg(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 GC=-1;function poe(){const e=document.createElement("div");return e.tabIndex=-1,e}var FC=class extends pt{constructor(e,t){super(),this.element=e,this.accessor=t,this.map={},this._disposed=!1,this._generation=0,this.positionCache=new hoe,this.addDisposables(an.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=poe();p.className="dv-render-overlay",p.style.visibility="hidden",this.map[t.api.id]={panel:t,disposable:an.NONE,destroy:an.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=GC;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,b=v.clip,w=this.positionCache.getPosition(n.element),_=this.positionCache.getPosition(this.element),C=w.left-_.left,N=w.top-_.top,S=w.width,k=w.height;if(v.retainPreviousGeometry&&(S===0||k===0)){!t.api.isVisible&&!y&&(r.style.visibility="hidden",r.style.pointerEvents="none");return}if(v.retainPreviousGeometry=!1,v.positioned=!0,r.style.left=`${C}px`,r.style.top=`${N}px`,r.style.width=`${S}px`,r.style.height=`${k}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=""),b){var A,I;const E=this.element.ownerDocument.defaultView,D=(A=E?.scrollX)!==null&&A!==void 0?A:0,T=(I=E?.scrollY)!==null&&I!==void 0?I:0,H=b.top+T,F=b.left+D,O=Math.max(0,H-w.top),B=Math.max(0,F-w.left),Y=Math.max(0,w.left+S-(b.right+D)),U=Math.max(0,w.top+k-(b.bottom+T));r.style.clipPath=`inset(${O}px ${Y}px ${U}px ${B}px)`}else r.style.clipPath="";tt(r,"dv-render-overlay-float",t.group.api.location.type==="floating")});f.pendingUpdate===GC&&(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=an.from(()=>x.disconnect()),x.observe(f,{attributeFilter:["aria-level"],attributes:!0}),g()}):r.style.zIndex=""},h=new pt(c,new UE(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=an.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 HC(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 xP(e){return function(){var t=this,n=arguments;return new Promise(function(s,o){var r=e.apply(t,n);function a(d){HC(r,s,o,a,l,"next",d)}function l(d){HC(r,s,o,a,l,"throw",d)}a(void 0)})}}function foe(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 moe=class extends pt{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 we,this.onWillClose=this._onWillClose.event,this._onDidClose=new we,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 xP(function*(){var t,n;if(e._window)throw new Error("instance of popout window is already open");const s=`${e.options.url}`;foe(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 pt;e._window={value:r,disposable:a},a.addDisposables(an.from(()=>{r.close()}),rt(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),lse(u,globalThis.document.styleSheets,{nonce:e.options.nonce}),rt(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}},goe=class extends pt{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 xoe(e){if(!e.matchMedia)return!1;const t=e.matchMedia("(pointer: coarse)").matches,n=e.matchMedia("(pointer: fine)").matches;return t&&!n}function voe(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 pt,y=b=>{var w,_;if(e.isInside)return e.isInside(b);const C=b.target;return C instanceof Node?((w=(_=e.elements)===null||_===void 0?void 0:_.call(e))!==null&&w!==void 0?w:[]).some(N=>N.contains(C)):!1};if((u||h.length>0)&&v.addDisposables(rt(d,"keydown",b=>{(u&&b.key==="Escape"||h.includes(b.key))&&e.onDismiss()},c)),(p||e.onInsidePointerDown)&&v.addDisposables(rt(d,"pointerdown",b=>{if(y(b)){var w;(w=e.onInsidePointerDown)===null||w===void 0||w.call(e,b);return}!p||g()-x<f||e.onDismiss()},c)),e.resize&&v.addDisposables(rt(d,"resize",()=>{xoe(d)||e.onDismiss()})),e.focusOut){const b=_=>{var C,N;return e.isFocusInside?e.isFocusInside(_):((C=(N=e.elements)===null||N===void 0?void 0:N.call(e))!==null&&C!==void 0?C:[]).some(S=>S.contains(_))},w=_=>{const C=_.target;C instanceof Element&&!b(C)&&e.onDismiss()};d.addEventListener("focusin",w,c),v.addDisposables({dispose:()=>d.removeEventListener("focusin",w,c)})}return v}var BC=class extends pt{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(an.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=voe({window:this._window,onDismiss:()=>this.close(),elements:()=>this._active?[this._active]:[],keys:["Enter"],pointerDownGraceMs:l,resize:!0}),this._window.requestAnimationFrame(()=>{fse(s,this._root)})}close(){this._active&&(this._active.remove(),this._activeDisposable.dispose(),this._active=null)}},gf=class extends pt{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(an.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}},boe=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 we,this.onDidChange=this._onDidChange.event,this.snap=!1,this.priority="low",this._isCollapsed=!1,this._tabSizeDisposables=new pt,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(jr(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()}},woe=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 we,this.onDidChange=this._onDidChange.event}layout(e,t){this._layoutDockview(t,e)}setVisible(e){}dispose(){this._onDidChange.dispose()}},yoe=class{get element(){return this._element}constructor(e,t=0){this._onDidChange=new we,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 Sr(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()}},Soe=class{constructor(e,t,n,s=0,o=35){this._disposables=new pt,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 woe(t,n);this._middleColumn=new yoe(r,s),this._outerSplitview=new Sr(this._shellElement,{orientation:"HORIZONTAL",proportionalLayout:!1,margin:s}),this._middleIndex=0,this._outerSplitview.addView(this._middleColumn,{type:"distribute"},0),this._disposables.addDisposables(jr(this._shellElement,a=>{if(!this._shellElement.offsetParent||!LE(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 boe(gt({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 b;const w=(b=v.collapsedSize)!==null&&b!==void 0?b:t;x.updateSizing(w,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=gt({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=gt({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=gt({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=gt({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,b,w,_;(v=this._bottomView)===null||v===void 0||v.restoreExpandedSize(e.bottom.size),(y=this._bottomView)===null||y===void 0||y.setCollapsed((b=e.bottom.collapsed)!==null&&b!==void 0?b:!1),this._middleColumn.resizeView("bottom",e.bottom.collapsed&&(w=(_=this._bottomView)===null||_===void 0?void 0:_.collapsedSize)!==null&&w!==void 0?w:e.bottom.size),e.bottom.visible||this._middleColumn.setViewVisible("bottom",!1)}}dispose(){this._disposables.dispose(),this._shellElement.remove()}};function Coe(e){var t;return new dP((t=e.tabGroupColors)!==null&&t!==void 0?t:Ov,e.tabGroupAccent!=="off")}function xc(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 fg=()=>({dispose:()=>{}}),koe=fg;var joe=class extends BE{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=Ms(this._smartGuidesService,"SmartGuides","api.setSmartGuidesEnabled"))===null||t===void 0||t.setEnabled(e)}updateSmartGuidesOptions(e){var t;(t=Ms(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:fg}get onDidSnapTogether(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.onDidSnapTogether)!==null&&e!==void 0?e:fg}_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?gt(gt({},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 hP({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:On,kind:"edge"});if(this._onWillDrop.fire(n),n.defaultPrevented)return;const s=On();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 Fv({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:On}))}get headerActionsService(){return this._moduleRegistry.services.headerActionsService}get _layoutHistoryService(){return this._moduleRegistry.services.layoutHistoryService}undo(){var e;(e=Ms(this._layoutHistoryService,"LayoutHistory","api.undo"))===null||e===void 0||e.undo()}redo(){var e;(e=Ms(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:koe}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 lP(e,"edge",t,On);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:an.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=Pv(),this._deserializer=new Eie(this),this._moduleRegistry=new Lie,this._onWillDragPanel=new we,this.onWillDragPanel=this._onWillDragPanel.event,this._onWillDragGroup=new we,this.onWillDragGroup=this._onWillDragGroup.event,this._onDidDrop=new we,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new we,this.onWillDrop=this._onWillDrop.event,this._mutationDepth=0,this._pendingLocationChanges=new Map,this._origin="user",this._originDepth=0,this._onWillMutateLayout=new we,this.onWillMutateLayout=this._onWillMutateLayout.event,this._onDidMutateLayout=new we,this.onDidMutateLayout=this._onDidMutateLayout.event,this._onWillShowOverlay=new we,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onUnhandledDragOver=new we,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._onDidRemovePanel=new we,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidAddPanel=new we,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPopoutGroupSizeChange=new we,this.onDidPopoutGroupSizeChange=this._onDidPopoutGroupSizeChange.event,this._onDidPopoutGroupPositionChange=new we,this.onDidPopoutGroupPositionChange=this._onDidPopoutGroupPositionChange.event,this._onDidAddPopoutGroup=new we,this.onDidAddPopoutGroup=this._onDidAddPopoutGroup.event,this._onDidRemovePopoutGroup=new we,this.onDidRemovePopoutGroup=this._onDidRemovePopoutGroup.event,this._onDidChangePopouts=new we,this.onDidChangePopouts=this._onDidChangePopouts.event,this._onDidOpenPopoutWindowFail=new we,this.onDidOpenPopoutWindowFail=this._onDidOpenPopoutWindowFail.event,this._onDidStartFloatingGroupDrag=new we,this.onDidStartFloatingGroupDrag=this._onDidStartFloatingGroupDrag.event,this._onDidEndFloatingGroupDrag=new we,this.onDidEndFloatingGroupDrag=this._onDidEndFloatingGroupDrag.event,this._onDidLayoutFromJSON=new we,this.onDidLayoutFromJSON=this._onDidLayoutFromJSON.event,this._onDidActivePanelChange=new we({replay:!0}),this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidPanelPinnedChange=new we,this.onDidPanelPinnedChange=this._onDidPanelPinnedChange.event,this._onDidMovePanel=new we,this.onDidMovePanel=this._onDidMovePanel.event,this._onDidCreateTabGroup=new we,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new we,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new we,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new we,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new we,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new we,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,this._onDidMaximizedGroupChange=new we,this.onDidMaximizedGroupChange=this._onDidMaximizedGroupChange.event,this._inShellLayout=!1,this._onDidRemoveGroup=new we,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidEdgeGroupAutoHideChange=new we,this.onDidEdgeGroupAutoHideChange=this._onDidEdgeGroupAutoHideChange.event,this._onDidAddGroup=new we,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidOptionsChange=new we,this.onDidOptionsChange=this._onDidOptionsChange.event,this._onDidActiveGroupChange=new we,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._peekingGroups=new Set,this._moving=!1,this._options=t,this._tabGroupColorPalette=Coe(t);const l=t.modules,d=l??[...uoe,...zie()];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 BC(this.element),this._api=new Mv(this),this.disableResizing=!0,this.element.remove(),this._shellManager=new Soe(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 Fh(this._shellManager.element),this.rootDropTargetContainer=new gf(this._shellManager.element,{disabled:!0}),this.floatingDropTargetContainer=new gf(this._shellManager.element,{disabled:!1}),this.overlayRenderContainer=new FC(this._shellManager.element,this),this._floatingOverlayHost=document.createElement("div"),this._floatingOverlayHost.className="dv-floating-overlay-host",this._shellManager.element.appendChild(this._floatingOverlayHost),tt(this.gridview.element,"dv-dockview",!0),tt(this.element,"dv-debug",!!t.debug),this.updateTheme(),t.debug&&this.addDisposables(new goe(this)),this.addDisposables(an.from(()=>this._pendingLocationChanges.clear()),this.rootDropTargetContainer,this.floatingDropTargetContainer,rt(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()}),an.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 sd(h,{kind:"edge",panel:void 0,api:this._api,group:void 0,getData:On}))}),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=Ms(this._popoutWindowService,"PopoutWindow","api.addPopoutGroup");if(!l||e instanceof fc&&e.model.location.type==="edge")return Promise.resolve(!1);if(e instanceof Fr&&e.group.size===1)return this.addPopoutGroup(e.group,t);const d=use(this.gridview.element),c=this.element;function u(){var v,y;if(t?.position)return t.position;const b=(e instanceof fc?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+b.left,top:window.screenY+b.top,width:b.width,height:b.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 moe(`${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 pt(g,g.onDidClose(()=>{x.dispose()}));return g.open().then(v=>{var y,b;if(g.isDisposed)return!1;const w=(y=t?.referenceGroup)!==null&&y!==void 0?y:e instanceof Fr?e.group:e,_=e.api.location.type,C=w.element.parentElement!==null;let N;if(t?.overridePopoutGridview){var S;N=(S=t.overridePopoutGroup)!==null&&S!==void 0?S:w}else C?t?.overridePopoutGroup?N=t.overridePopoutGroup:(N=this.createGroup({id:p}),v&&this._onDidAddGroup.fire(N)):N=w;if(v===null)return this.handleBlockedPopout({group:N,referenceGroup:w,options:t,popoutWindowDisposable:x}),!1;const k=document.createElement("div");k.className="dv-overlay-render-container";const A=new FC(k,this);N.model.renderContainer=A;const I=(b=t?.overridePopoutGridview)!==null&&b!==void 0?b:this.createNestedGridview();t?.overridePopoutGridview||I.addView(N,js.Distribute,[0]),I.element.style.width="100%",I.element.style.height="100%",I.layout(g.window.innerWidth,g.window.innerHeight);let E=!1;const D=()=>{E||(E=!0,I.dispose())};let T,H=[];if(!t?.overridePopoutGroup&&!t?.overridePopoutGridview&&C)if(e instanceof Fr){const _e=e.group;this.movingLock(()=>{const De=w.model.removePanel(e);N.model.openPanel(De)}),H=[{panel:e,from:_e}]}else switch(this.movingLock(()=>xc({from:w,to:N})),H=N.panels.map(_e=>({panel:_e,from:w})),_){case"grid":w.api.setVisible(!1);break;case"floating":case"popout":var F;T=(F=this.floatingGroups.find(_e=>_e.group.api.id===e.api.id))===null||F===void 0?void 0:F.overlay.toJSON(),this.removeGroup(w);break}v.classList.add("dv-dockview"),v.style.overflow="hidden",v.appendChild(k),v.appendChild(I.element);const O=document.createElement("div"),B=new gf(O,{disabled:this.rootDropTargetContainer.disabled});v.appendChild(O),N.model.dropTargetContainer=B;const Y=new BC(v,g.window);if(x.addDisposables(Y),N.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f},t?.overridePopoutGridview){const _e=this.groups.filter(De=>I.element.contains(De.element));for(const De of _e)De.model.renderContainer=A,De.model.dropTargetContainer=B,De.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f}}C&&e.api.location.type==="grid"&&e.api.setVisible(!1),this.doSetGroupAndPanelActive(N);const U=l.observeGridviewSize(g,I,A);U&&x.addDisposables(U);const ee=new Fn;x.addDisposables(ee);const L=_e=>{ee.value=new pt(_e.api.onDidActiveChange(De=>{if(De.isActive){var me;(me=g.window)===null||me===void 0||me.focus()}}),_e.api.onWillFocus(()=>{var De;(De=g.window)===null||De===void 0||De.focus()}))};L(N);const Q={},V=C&&w&&this.getPanel(w.id),ce={window:g,popoutGroup:N,gridview:I,overlayRenderContainer:A,dropTargetContainer:B,getWindow:()=>g.window,popoutUrl:f,referenceGroup:V?w.id:void 0,popupService:Y,setAnchorGroup:_e=>{ce.popoutGroup=_e,L(_e)},disposable:{dispose:()=>(x.dispose(),Q.returnedGroup)}},ve=hse(g.window);x.addDisposables(ve,pse(g.window,()=>{this._onDidPopoutGroupSizeChange.fire({width:g.window.innerWidth,height:g.window.innerHeight,group:ce.popoutGroup})}),ve.event(()=>{this._onDidPopoutGroupPositionChange.fire({screenX:g.window.screenX,screenY:g.window.screenY,group:ce.popoutGroup})}),rt(g.window,"resize",()=>{I.layout(g.window.innerWidth,g.window.innerHeight)}),A,an.from(()=>this.disposePopoutWindow({group:N,referenceGroup:w,popoutGridview:I,isGroupAddedToDom:C,floatingBox:T,disposePopoutGridview:D,closeResult:Q}))),l.add(ce),this._onDidAddPopoutGroup.fire({id:ce.popoutGroup.id,group:ce.popoutGroup,window:ce.getWindow()});for(const{panel:_e,from:De}of H)this.fireDidMovePanel(_e,De);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(()=>xc({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(()=>xc({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(!Ms(this._floatingGroupService,"FloatingGroup","api.addFloatingGroup")||e instanceof fc&&e.model.location.type==="edge")return;let n,s=[];if(e instanceof Fr){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(()=>xc({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=No.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=No.top,typeof t.width=="number"?d.width=Math.max(t.width,0):d.width=No.width,typeof t.height=="number"?d.height=Math.max(t.height,0):d.height=No.height,d}return{left:typeof t?.x=="number"?Math.max(t.x,0):No.left,top:typeof t?.y=="number"?Math.max(t.y,0):No.top,width:typeof t?.width=="number"?Math.max(t.width,0):No.width,height:typeof t?.height=="number"?Math.max(t.height,0):No.height}}const a=r(),l=this.createNestedGridview();l.addView(n,js.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 HE(!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=Ms(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 Mie(this,t):void 0,v=new Bv(gt(gt({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 b=g.add(t,v,e);b.addDisposables(v.onDidStartMoving(()=>this._onDidStartFloatingGroupDrag.fire(t)),v.onDidChangeEnd(()=>this._onDidEndFloatingGroupDrag.fire(t))),x&&(b.setTitleBar(x),b.addDisposables(x,an.from(()=>b.setTitleBar(void 0)),x.onDragStart(w=>{this._onWillDragGroup.fire({nativeEvent:w,group:b.group})})));for(const w of n)w.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=gt(gt({},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:Ov),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){Fie(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(mP("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=Ms(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.pinEdgeGroup"))===null||t===void 0||t.pin(e)}autoHideEdgeGroup(e){var t;(t=Ms(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.autoHideEdgeGroup"))===null||t===void 0||t.autoHide(e)}peekEdgeGroup(e,t){var n;(n=Ms(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=Ms(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:lie(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 w of l)try{w.dispose()}catch(_){console.error("dockview: failed to dispose a temporary group created for reuseExistingPanels",_)}l.length=0};if(t?.reuseExistingPanels){const w=Object.keys(e.panels);let _;const C=()=>{const N=this.createGroup(),S=this._groups.get(N.api.id);return this._groups.delete(N.api.id),l.push(an.from(()=>{this.movingLock(()=>{for(const k of N.panels.slice())N.model.removePanel(k)}),S?.disposable.dispose(),N.dispose()})),N};try{for(const N of this.panels)if(w.includes(N.api.id)){o.set(N.api.id,N);let S;if(N.api.renderer==="always"&&N.api.isVisible)S=C();else{var c;(c=_)!==null&&c!==void 0||(_=C()),S=_}r.set(N.api.id,S),a.push({panel:N,temporaryGroup:S})}this.movingLock(()=>{a.forEach(({panel:N,temporaryGroup:S})=>{this.moveGroupOrPanel({from:{groupId:N.api.group.api.id,panelId:N.api.id},to:{group:S,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 w=this.width,_=this.height,C=S=>{const{id:k,locked:A,hideHeader:I,headerPosition:E,views:D,activeView:T}=S;if(typeof k!="string")throw new TypeError("dockview: group id must be of type string");const H=this.createGroup({id:k,locked:!!A,hideHeader:!!I,headerPosition:E});this._onDidAddGroup.fire(H);const F=[],O=D.filter(B=>h[B]);for(const B of O){const Y=o.get(B),U=r.get(B);if(U&&Y)this.movingLock(()=>{U.model.removePanel(Y)}),F.push(Y),Y.updateFromStateModel(h[B]);else{const ee=this._deserializer.fromJSON(h[B],H);F.push(ee)}}for(const B of F){const Y=typeof T=="string"&&T===B.id;o.has(B.api.id)?this.movingLock(()=>{H.model.openPanel(B,{skipSetActive:!Y,skipSetGroupActive:!0})}):H.model.openPanel(B,{skipSetActive:!Y,skipSetGroupActive:!0})}return S.tabGroups&&S.tabGroups.length>0&&H.model.restoreTabGroups(S.tabGroups),!H.activePanel&&H.panels.length>0&&H.model.openPanel(H.panels[H.panels.length-1],{skipSetGroupActive:!0}),H};this.gridview.deserialize(u,{fromJSON:S=>C(S.data)}),this._layoutFromShell(w,_),e.edgeGroups&&this.deserializeEdgeGroups(e.edgeGroups,h,o,r),this.deserializeFloatingWindows((f=e.floatingGroups)!==null&&f!==void 0?f:[],C);const N=this.deserializePopoutWindows((g=e.popoutGroups)!==null&&g!==void 0?g:[],C);if((x=this._popoutWindowService)===null||x===void 0||x.finishRestoration(N),(v=this._floatingGroupService)===null||v===void 0||v.constrainBounds(),typeof p=="string"){const S=this.getPanel(p);S&&this.doSetGroupAndPanelActive(S)}(y=this._watermarkService)===null||y===void 0||y.update()}catch(w){var b;console.error("dockview: failed to deserialize layout. Reverting changes",w);for(const _ of this.groups)for(const C of _.panels)this.removePanel(C,{removeEmptyGroup:!1,skipDispose:!1});for(const _ of this.groups)_.dispose(),this._groups.delete(_.id),this._onDidRemoveGroup.fire(_);throw(b=this._floatingGroupService)===null||b===void 0||b.disposeAll(),this.clear(),w}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=Ms(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?Ms(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(die(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(cie(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(PC(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=Fu(((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,gt(gt({},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=Ws(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,gt(gt({},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 Pie}addGroup(e){return this.mutation("add",()=>this._doAddGroup(e))}_doAddGroup(e){if(e){let o;if(uie(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(hie(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(PC(e.direction),e);return e.skipSetActive||this.doSetGroupAndPanelActive(u),u}const r=Fu(e.direction||"within"),a=Tn(o.element),l=Ws(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 xP(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=Ws(c.orientation,u,r);if(l.size<2){const[p,f]=lo(h);if(l.api.location.type==="grid"&&c===this.gridview){const[y,b]=lo(Tn(l.element));if(zE(y,p)){this.gridview.moveView(y,b,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 b=this.movingLock(()=>y.popoutGroup.model.removePanel(y.popoutGroup.panels[0],{skipSetActive:!0,skipSetActiveGroup:!0}));this.doRemoveGroup(l,{skipActive:!0});const w=Ws(c.orientation,Tn(n.element),r),_=this.createGroupAtLocation(w,void 0,void 0,c);this.movingLock(()=>_.model.openPanel(b,{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 b=this.createGroupAtLocation(h,void 0,void 0,c);this.movingLock(()=>b.model.openPanel(y,{skipSetGroupActive:!0})),this.doSetGroupAndPanelActive(b),this.fireDidMovePanel(y,l);return}const g=this.movingLock(()=>this.doRemoveGroup(l,{skipActive:!0,skipDispose:!0})),x=Tn(n.element),v=Ws(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=Ws(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 b of f)v.model.openPanel(b,{index:r,skipSetActive:!0,skipSetGroupActive:!0})});const y=v.model.createTabGroup({label:l,color:d,collapsed:c,componentParams:u});for(const b of f)v.model.addPanelToTabGroup(y.id,b.id);e.skipSetActive||this.doSetGroupAndPanelActive(v);for(const b of f)this.fireDidMovePanel(b,t)};let x;if(!o||o==="center"||!p)x=s;else{const v=Ws(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=Ws(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 fc(this,n,e);if(s.init({params:{},accessor:this}),!this._groups.has(s.id)){const o=new pt(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 fP(this,e.id,r,a),d=new Fr(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:Ei(t)}updateTheme(){var e,t,n,s,o,r,a,l;const d=(e=this._options.theme)!==null&&e!==void 0?e:Die;(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";tt(this.element,"dv-tab-group-indicator-none",p),this._shellManager&&tt(this._shellManager.element,"dv-tab-group-indicator-none",p);for(const f of this.groups)f.model.updateTabGroups()}},_oe=class extends BE{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 we,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidRemoveGroup=new we,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidAddGroup=new we,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidActiveGroupChange=new we,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=gt(gt({},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=Fu(t.direction);if(o==="center")throw new Error(`${o} not supported as an option`);const r=Tn(s.element),a=Ws(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=Fu(e.position.direction);if(d==="center")throw new Error(`${d} not supported as an option`);{const c=Tn(l.element);o=Ws(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 pt(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]=lo(Ws(this.gridview.orientation,o,n)),[l,d]=lo(Tn(s.element));if(zE(l,r)){this.gridview.moveView(l,d,a);return}const c=this.doRemoveGroup(s,{skipActive:!0,skipDispose:!0}),u=Tn(e.element),h=Ws(this.gridview.orientation,u,n);this.doAddGroup(c,h)}removeGroup(e){super.removeGroup(e)}dispose(){super.dispose(),this._onDidLayoutfromJSON.dispose()}},Noe=class extends Av{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 pt(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 we,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidAddView=new we,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new we,this.onDidRemoveView=this._onDidRemoveView.event,this._onDidLayoutChange=new we,this.onDidLayoutChange=this._onDidLayoutChange.event,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new Fh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.splitview=new Sr(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=gt(gt({},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:js.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 Sr(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,js.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()}},$C=class extends pt{get element(){return this._element}constructor(){super(),this._expandedIcon=eie(),this._collapsedIcon=sP(),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(rt(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);tt(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 Toe=Pv(),VC=22,WC=0,UC=Number.MAX_SAFE_INTEGER;var KC=class extends Yse{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}},Doe=class extends Av{get id(){return this._id}get panels(){return this.paneview.getPanes()}set paneview(e){this._paneview=e,this._disposable.value=new pt(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=Toe.next(),this._disposable=new Fn,this._viewDisposables=new Map,this._onDidLayoutfromJSON=new we,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidLayoutChange=new we,this.onDidLayoutChange=this._onDidLayoutChange.event,this._onDidDrop=new we,this.onDidDrop=this._onDidDrop.event,this._onDidAddView=new we,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new we,this.onDidRemoveView=this._onDidRemoveView.event,this._onUnhandledDragOver=new we,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 Fh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.paneview=new IC(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=gt(gt({},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 $C);const a=new KC({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:VC,minimumBodySize:WC,maximumBodySize:UC});this.doAddPanel(a);const l=typeof e.size=="number"?e.size:js.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 nd(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 gt({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 IC(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 $C);const g=new KC({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:VC,minimumBodySize:(c=a.minimumSize)!==null&&c!==void 0?c:WC,maximumBodySize:(u=a.maximumSize)!==null&&u!==void 0?u:UC});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 nd(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 pt(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()}},Ioe=class extends Rv{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 tP(e,t)),this._evaluatedMinimumSize=0,this._evaluatedMaximumSize=Number.POSITIVE_INFINITY,this._minimumSize=0,this._maximumSize=Number.POSITIVE_INFINITY,this._snap=!1,this._onDidChange=new we,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 gt(gt({},super.toJSON()),{},{minimumSize:t(this.minimumSize),maximumSize:e(this.maximumSize)})}updateConstraints(){this.api._onDidConstraintsChange.fire({maximumSize:this._evaluatedMaximumSize,minimumSize:this._evaluatedMinimumSize})}};function Eoe(e,t){return new joe(e,t).api}function Poe(e,t){return new VE(new Noe(e,t))}function Aoe(e,t){return new WE(new _oe(e,t))}function Moe(e,t){return new nd(new Doe(e,t))}function id(e){"@babel/helpers - typeof";return id=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},id(e)}function Roe(e,t){if(id(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(id(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Loe(e){var t=Roe(e,"string");return id(t)=="symbol"?t:t+""}function Ooe(e,t,n){return(t=Loe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qC(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 Es(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?qC(Object(n),!0).forEach(function(s){Ooe(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):qC(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}const vP=(e,t)=>{const[,n]=Ne.useState(0),s=Ne.useRef(e.componentProps);return Ne.useImperativeHandle(t,()=>({update:o=>{s.current=Es(Es({},s.current),o),n(r=>r+1)}}),[]),Ne.createElement(e.component,s.current)};vP.displayName="DockviewReactJsBridge";const zoe=(()=>{let e=1;return{next:()=>`dockview_react_portal_key_${(e++).toString()}`}})(),Goe=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=Es(Es({},this._initialProps),e)}createPortal(){if(this.disposed)throw new Error("invalid operation: resource is already disposed");if(!Foe(this.component))throw new Error("Dockview: Only React.memo(...), React.ForwardRef(...) and functional components are accepted as components");const e=Ne.createElement(Ne.forwardRef(vP),{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(Goe.Provider,{value:this.context},e):e,n=Ok.createPortal(t,this.parent,zoe.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 $h=()=>{const[e,t]=Ne.useState([]);return Ne.useDebugValue(`Portal count: ${e.length}`),[e,Ne.useCallback(n=>{t(o=>[...o,n]);let s=!1;return an.from(()=>{if(s)throw new Error("invalid operation: resource already disposed");s=!0,t(o=>o.filter(r=>r!==n))})},[])]};function Foe(e){return typeof e=="function"||!!e?.$$typeof}var YC=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._onDidFocus=new we,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new we,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()}},XC=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()}},ZC=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()}},Hoe=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 pt(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}})}},Boe=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()}},JC=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()}},QC=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 Rr(e,t){return e?n=>new Hoe(e,t,n):void 0}const vc="props.defaultTabComponent";function $oe(e){return pg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const bP=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=$h();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};pg.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},pg.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return;const l=Es({},e.tabComponents);e.defaultTabComponent&&(l[vc]=e.defaultTabComponent);const d={createLeftHeaderActionComponent:Rr(e.leftHeaderActionsComponent,{addPortal:r}),createRightHeaderActionComponent:Rr(e.rightHeaderActionsComponent,{addPortal:r}),createPrefixHeaderActionComponent:Rr(e.prefixHeaderActionsComponent,{addPortal:r}),createComponent:f=>new YC(f.id,e.components[f.name],{addPortal:r}),createTabComponent(f){return new XC(f.id,l[f.name],{addPortal:r})},createWatermarkComponent:e.watermarkComponent?()=>new ZC("watermark",e.watermarkComponent,{addPortal:r}):void 0,defaultTabComponent:e.defaultTabComponent?vc:void 0,createContextMenuItemComponent:f=>{if(f.component)return new Boe(f.id,f.component,{addPortal:r})}},c=$oe(e);if(e.tabGroupChipComponent){const f=e.tabGroupChipComponent;c.createTabGroupChipComponent=()=>new JC(f,{addPortal:r})}if(e.groupDragGhostComponent){const f=e.groupDragGhostComponent;c.createGroupDragGhostComponent=()=>new QC(f,{addPortal:r})}const u=Eoe(n.current,Es(Es({},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 JC(e.tabGroupChipComponent,{addPortal:r}):void 0})},[e.tabGroupChipComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createGroupDragGhostComponent:e.groupDragGhostComponent?()=>new QC(e.groupDragGhostComponent,{addPortal:r}):void 0})},[e.groupDragGhostComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new YC(l.id,e.components[l.name],{addPortal:r})})},[e.components]),Ne.useEffect(()=>{if(!s.current)return;const l=Es({},e.tabComponents);e.defaultTabComponent&&(l[vc]=e.defaultTabComponent),s.current.updateOptions({defaultTabComponent:e.defaultTabComponent?vc:void 0,createTabComponent(d){return new XC(d.id,l[d.name],{addPortal:r})}})},[e.tabComponents,e.defaultTabComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createWatermarkComponent:e.watermarkComponent?()=>new ZC("watermark",e.watermarkComponent,{addPortal:r}):void 0})},[e.watermarkComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createRightHeaderActionComponent:Rr(e.rightHeaderActionsComponent,{addPortal:r})})},[e.rightHeaderActionsComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createLeftHeaderActionComponent:Rr(e.leftHeaderActionsComponent,{addPortal:r})})},[e.leftHeaderActionsComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createPrefixHeaderActionComponent:Rr(e.prefixHeaderActionsComponent,{addPortal:r})})},[e.prefixHeaderActionsComponent]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});bP.displayName="DockviewComponent";var ek=class extends Ioe{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 VE(this._params.accessor)})}};function Voe(e){return ig.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Woe=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=$h();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};ig.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},ig.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return()=>{};const l=Poe(n.current,Es(Es({},Voe(e)),{createComponent:u=>new ek(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 ek(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Woe.displayName="SplitviewComponent";var tk=class extends pP{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 WE(this._params.accessor)})}};function Uoe(e){return dg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Koe=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=$h();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};dg.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},dg.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return()=>{};const l=Aoe(n.current,Es(Es({},Uoe(e)),{createComponent:u=>new tk(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 tk(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Koe.displayName="GridviewComponent";var bc=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 qoe(e){return ug.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Yoe=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=$h();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};ug.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},ug.map(l=>e[l])),Ne.useEffect(()=>{var l;if(!n.current)return()=>{};const d=(l=e.headerComponents)!==null&&l!==void 0?l:{},c=Moe(n.current,Es(Es({},qoe(e)),{createComponent:p=>new bc(p.id,e.components[p.name],{addPortal:r}),createHeaderComponent:p=>new bc(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 bc(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 bc(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)});Yoe.displayName="PaneviewComponent";function na(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Xoe(e,t,n){if(!na(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 wP(e,t){if(na(e)){if(e.type==="leaf"){const n=na(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=wP(s,t);return o?[o]:[]}):[];return n.length===0?void 0:{type:"branch",data:n,size:e.size}}}}function Zoe(e,t){if(!na(e)||!na(e.panels))return;const n={};for(const[a,l]of Object.entries(e.panels))Xoe(a,l,t)&&(n[a]=l);const s=new Set(Object.keys(n));if(s.size===0)return;const o=na(e.grid)?e.grid:void 0,r=o?wP(o.root,s):void 0;if(r)return{...e,panels:n,grid:{...o,root:r}}}function nk(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 Joe(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=nk(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||!nk(d)?null:d}function sk(e,t){const n=new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>]+))`,"i").exec(e);return n?n[1]??n[2]??n[3]??"":null}function Qoe(e,t,n){return e.replace(new RegExp(`\\b${t}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>]+)`,"i"),`${t}="${n}"`)}function ere(e){return e?.trim().toLowerCase().split(/\s+/).includes("stylesheet")??!1}function tre(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}catch{return null}}function nre(e,t){const n=[],s=(o,r,a,l)=>{const d=r[1]??"";if(!l(d))return;const c=sk(d,a);if(c===null)return;const u=Joe(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=>ere(sk(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 sre(e,t,n){const s=nre(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${Qoe(l.attrs,"src",`data:${u};base64,${d.base64}`)}>`;continue}const c=tre(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 ire="plugin-view.html";function ik(){return document.documentElement.classList.contains("dark")?"dark":"light"}function ore({pluginId:e,viewId:t,sessionId:n}){const{t:s}=J(),o=m_().find(r=>r.pluginId===e&&r.id===t);return o?i.jsx(yP,{pluginId:e,entry:o.entry,title:o.title,sessionId:n}):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 yP({pluginId:e,entry:t,title:n,sessionId:s,file:o}){const r=m.useRef(null),[a,l]=m.useState(null),d=m.useRef(s);d.current=s;const c=m.useRef(o);c.current=o;const u=m.useRef(null),h=m.useRef(null);m.useEffect(()=>{const g=r.current;if(!g)return;l(null);let x=!1,v=null;const y=()=>{try{v?.port1.postMessage(eO(ik()))}catch{}},b=new MutationObserver(y);b.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const w=window.electronAPI.extensionPlugins.onViewEvent(N=>{if(!(N.pluginId!==e||typeof N.name!="string"))try{v?.port1.postMessage(J5(N.name,N.data))}catch{}}),_=iO(async(N,S)=>{const k=await window.electronAPI.extensionPlugins.call({pluginId:e,method:"renderer.call",payload:{method:N,args:S},sessionId:d.current});if(!k.ok)throw new Error(k.error);return k.value}),C=async N=>{if(N.source!==g.contentWindow||N.data?.type!=="enso-view-ready")return;v?.port1.close();const S=new MessageChannel;v=S,u.current=S,S.port1.onmessage=D=>{const T=tO(D.data);if(T){window.electronAPI.extensionPlugins.viewStateSet(e,T);return}const H=nO(D.data);if(H!==null){h.current=H,c.current?.onEdit(H);return}_(D.data).then(F=>{F&&!x&&v===S&&S.port1.postMessage(F)})};const[k,A]=await Promise.all([window.electronAPI.extensionPlugins.asset(e,t),window.electronAPI.extensionPlugins.viewStateGet(e)]);if(x||v!==S)return;if(!k.ok){l(k.error);return}const I=await sre(sO(k.base64),t,async D=>{const T=await window.electronAPI.extensionPlugins.asset(e,D);return T.ok?{mime:T.mime,base64:T.base64}:null});if(x||v!==S)return;const E=c.current;g.contentWindow?.postMessage({type:"enso-view-init",html:I,theme:ik(),storage:A.ok?A.state:{},...E?{file:{rel:E.rel,text:E.text}}:{}},"*",[S.port2])};return window.addEventListener("message",C),g.src=new URL(ire,document.baseURI).href,()=>{x=!0,b.disconnect(),w(),window.removeEventListener("message",C),v?.port1.close(),u.current=null,g.removeAttribute("src")}},[e,t]);const p=o?.rel,f=o?.text;return m.useEffect(()=>{if(!(p===void 0||f===void 0)){if(h.current===f){h.current=null;return}try{u.current?.port1.postMessage(Q5(p,f))}catch{}}},[p,f]),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:n,className:"min-h-0 w-full flex-1 border-0 bg-background"})]})}function rre({conversationId:e,panelApi:t}){const{t:n}=J(),s=t.id.startsWith("btw:")?t.id.slice(4):t.id,o=ya(),r=Se(O=>O.virtualModels),a=Se(O=>O.defaultModel),l=Se(O=>O.projects),d=Se(O=>O.projectGroups),c=Fi(O=>O.snapshot),u=Fg(),[h,p]=m.useState("contextual"),[f,g]=m.useState(!1),[x]=m.useState(()=>D8(se.getState().conversations[e]?.messages??[])),v=se(Mf(O=>O.conversations[s]??null)),y=v?.title,b=v?.projectId,w=m.useMemo(()=>l.find(O=>O.id===b),[b,l]),_=m.useMemo(()=>eu(w,d),[w,d]),C=m.useMemo(()=>Rl({defaultModel:a,..._,lastProviderId:v?.lastProviderId,lastModelId:v?.lastModelId,providers:o,credentials:da(c),virtualModels:r}),[r,v?.lastModelId,v?.lastProviderId,_,a,c,o]),N=C.source==="none"?void 0:u.find(O=>O.id===C.providerId),S=C.source==="none"?"":C.modelId,k=C.source==="none"?"":Rf(C)?C.providerId:N?.id??"",A=m.useMemo(()=>I8(v?.messages??[]),[v?.messages]),I=m.useRef(null),E=v?.status==="running",D=f||(v?qj({started:v.started,sessionFile:v.sessionFile,messages:v.messages,spawning:v.spawning,status:v.status,historyLoadAttempted:v.historyLoadAttempted}):!0),T=m.useMemo(()=>{const O={name:"/compact",description:n("Compact the context now (/compact [summary focus])")},B=new Set([O.name]);return[O,...(v?.commands??[]).filter(Y=>!B.has(Y.name))]},[v?.commands,n]);m.useEffect(()=>{const O=se.getState().conversations[e],B=Se.getState();se.getState().ensureBtwConversation({id:s,projectId:O?.projectId??"",btwParentId:e,rolePrompt:Ww("contextual",x),lastProviderId:O?.lastProviderId??B.defaultModel?.providerId,lastModelId:O?.lastModelId??B.defaultModel?.modelId,reasoningEnabled:O?.reasoningEnabled??B.defaultReasoningEnabled,thinkingLevel:O?.thinkingLevel??B.defaultThinkingLevel,approvalMode:O?.approvalMode??"full",presetId:O?.presetId})},[e,s,x]),m.useEffect(()=>{y&&t.setTitle(y)},[t,y]);const H=O=>{O===h||f||(g(!0),(async()=>(se.getState().abort(s),await se.getState().resetBtwSession(s,Ww(O,x)),p(O),t.setTitle(n("Btw")),g(!1)))())},F=()=>{const O=P8(A);if(O){if(!jh(O)){Fe({type:"warning",title:n("No Composer for this selection")});return}yo()}};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(ok,{label:n("Contextual"),active:h==="contextual",onClick:()=>H("contextual")}),i.jsx(ok,{label:n("Tangent"),active:h==="tangent",onClick:()=>H("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:F,children:n("Insert into chat")})]}),v?i.jsx(LI,{conversationId:s,cwd:w?.path,emptyTitle:n("Btw"),timelineRef:I}):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:ji,children:[v?.retry?i.jsx(Mh,{retry:v.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(s)}}):null,i.jsx(Lg.Provider,{value:b?{conversationId:s,projectId:b,...w?.path?{cwd:w.path}:{}}:null,children:i.jsx(kv,{sessionId:s,tasks:v?.backgroundTasks??[],subagents:v?.subagents??[]},s)}),i.jsx(Vl,{approvals:v?.pendingApprovals??[],allowSession:!0,onRespond:(O,B)=>{window.electronAPI.agent.respondApproval(s,O,B)}}),i.jsx(wh,{asks:v?.pendingAsks??[],onAnswer:(O,B)=>{window.electronAPI.agent.respondAsk(s,O,B)}}),i.jsx(qI,{conversationId:s,queued:v?.queuedMessages??[]}),i.jsx(Sv,{isolated:!0,cwd:w?.path,commands:T,running:E,busy:D,locked:(v?.pendingApprovals??[]).length>0,focusKey:s,injectedDraft:v?.draftText,injectedImages:v?.draftImages,injectedDraftAppend:v?.draftAppend,onDraftConsumed:()=>se.getState().clearDraft(s),queuedCount:v?.queuedMessages?.length??0,onSteerQueued:()=>se.getState().steerQueued(s),autoFocus:!1,placeholder:n("Ask aside…"),toolbar:i.jsx(ih,{providers:u,activeAccount:Gg(o,v??void 0),virtualModels:r,providerId:k,modelId:S,reasoningEnabled:v?.reasoningEnabled??!1,thinkingLevel:v?.thinkingLevel??"medium",onSelect:(O,B)=>se.getState().setModel(s,O,B),onReasoningChange:O=>se.getState().setReasoning(s,O),onThinkingChange:O=>se.getState().setThinking(s,O),side:"top"}),onSend:O=>!k||!S||!w?!1:(I.current?.scrollToBottom(),se.getState().send(O.text,{providerId:k,modelId:S,cwd:w.path},O.images,s),!0),onAbort:()=>{se.getState().abort(s)}}),i.jsx(nE,{conversationId:s,cwd:w?.path})]})})]})}function ok({label:e,active:t,onClick:n}){return i.jsx("button",{type:"button",className:W("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 SP(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?xo({name:a.path,contents:u},{name:a.path,contents:h}):c.fileDiff;(p||!c)&&(f.cacheKey=Yx(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 are={theme:va,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0},lre={height:"100%",overflow:"auto"},dre=new Set;function CP({result:e,loading:t}){const{t:n}=J(),s=rd(are),[o,r]=m.useState(!1),[a,l]=m.useState(!1),d=m.useRef(new Map);m.useEffect(()=>{let h=!0;return ra().then(()=>{h&&r(!0)},()=>{h&&l(!0)}),()=>{h=!1}},[]);const c=m.useMemo(()=>SP(e?.ok?[e]:[],dre,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(VT,{className:"min-h-0 w-full flex-1",items:c,style:lre,options:s})})}function kP({tree:e,onToggle:t}){const{t:n}=J(),s=n(e?"List view":"Tree view");return i.jsx(fe,{variant:"ghost",size:"icon-xs",title:s,"aria-label":s,onClick:t,children:e?i.jsx(Ex,{className:"size-3.5"}):i.jsx(w6,{className:"size-3.5"})})}function jP({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($n,{"aria-hidden":"true",className:W("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(Cd,{"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 cre={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 _P({file:e,selected:t,onSelect:n,actions:s,showDirectory:o=!0}){const{t:r}=J(),a=e.path.lastIndexOf("/"),l=e.path.slice(a+1),d=e.path.slice(0,Math.max(0,a)),c=cre[e.status];return i.jsxs("div",{className:W("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(wo,{"aria-hidden":"true",className:W("size-3.5 shrink-0",c.color)}),i.jsx("span",{className:W("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:W("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 NP({title:e,hasSelection:t,navigation:n,actions:s,children:o}){const{t:r}=J(),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:W("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($n,{className:W("size-3.5 shrink-0",!c&&"-rotate-90")}),i.jsx("span",{className:W("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:W("flex min-h-0 flex-1 flex-col overflow-hidden",!c&&"hidden"),children:n})]}),i.jsx("div",{className:W("min-h-0 min-w-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex",t?"flex":"hidden"),children:o})]})})}function ure({request:e,head:t,tree:n,onToggleTree:s}){const{t:o}=J(),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),[b,w]=m.useState(null),[_,C]=m.useState([]),[N,S]=m.useState(!1),[k,A]=m.useState(null),[I,E]=m.useState(null),[D,T]=m.useState(null),[H,F]=m.useState(!1);return m.useEffect(()=>{let O=!0;return x(!0),y(null),window.electronAPI.git.history({...e,head:t??void 0,skip:d,limit:20}).then(B=>{O&&(B.ok?(l(Y=>d===0?B.commits:[...Y,...B.commits]),f(B.hasMore)):y(B.error))}).catch(()=>{O&&y("Could not load Git history.")}).finally(()=>{O&&x(!1)}),()=>{O=!1}},[e,t,d,u]),m.useEffect(()=>{if(!b)return;let O=!0;return S(!0),A(null),window.electronAPI.git.commitFiles({...e,hash:b.hash}).then(B=>{O&&(B.ok?C(B.files):A(B.error))}).catch(()=>{O&&A("Could not load the changed files.")}).finally(()=>{O&&S(!1)}),()=>{O=!1}},[e,b]),m.useEffect(()=>{if(!I||!b)return;let O=!0;return F(!0),window.electronAPI.git.commitDiff({...e,hash:b.hash,path:I}).then(B=>{O&&T(B)}).catch(()=>{O&&T({ok:!1,error:"Could not load the diff."})}).finally(()=>{O&&F(!1)}),()=>{O=!1}},[e,b,I]),i.jsxs(NP,{title:o("History"),hasSelection:I!==null,actions:i.jsx(kP,{tree:n,onToggle:s}),navigation:i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-1 pb-1",children:[a.map(O=>{const B=b?.hash===O.hash;return i.jsxs("div",{children:[i.jsxs("button",{type:"button","aria-expanded":B,"aria-controls":B?`${r}-${O.hash}`:void 0,className:W("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:`${O.subject}
|
|
110
|
-
${O.hash}
|
|
111
|
-
${O.author} · ${O.date}`,onClick:()=>{w(B?null:O),C([]),S(!B),A(null),E(null),T(null),F(!1)},children:[i.jsx($n,{"aria-hidden":"true",className:W("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:O.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:O.hash.slice(0,7)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:O.author}),i.jsx("time",{className:"shrink-0",dateTime:O.date,children:new Date(O.date).toLocaleDateString()})]})]})]}),B&&i.jsx("div",{id:`${r}-${O.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...")}):k?i.jsx("p",{role:"alert",className:"px-2 py-3 text-xs text-destructive",children:o(k)}):_.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(jP,{files:_,tree:n,children:Y=>i.jsx(_P,{file:Y,showDirectory:!n,selected:I===Y.path,onSelect:()=>{I!==Y.path&&(E(Y.path),T(null),F(!0))}})},O.hash)})]},O.hash)}),g&&i.jsx("div",{className:"flex justify-center p-3",children:i.jsx(Zt,{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(fe,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>c(a.length),children:o("Load more commits")}),v&&i.jsx(fe,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>h(O=>O+1),children:o("Retry")})]}),children:[b&&I&&i.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:`${b.subject} · ${I}`,children:[b.hash.slice(0,7)," · ",I]}),i.jsx(CP,{result:D,loading:H})]})}function hre({conversationId:e,projectId:t,disabled:n,unavailable:s,editWriteKey:o}){const{t:r}=J(),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,b]=m.useState("changes"),[w,_]=m.useState(!0),[C,N]=m.useState(""),[S,k]=m.useState(""),A=m.useRef(null),[I,E]=m.useState(null),[D,T]=m.useState(null),[H,F]=m.useState(null),[O,B]=m.useState(!1),[Y,U]=m.useState(0),ee=m.useRef(!1),L=m.useRef(!1),Q=m.useRef(0),V=m.useRef(0),ce=m.useCallback(async(Z=!1)=>{if(n||s||L.current||V.current!==0&&!Z)return;const ae=++Q.current;V.current=ae,Z&&u(!0);try{const be=await window.electronAPI.git.status(a);if(!ee.current||ae!==Q.current)return;be.ok?(d(be),p(null)):(d(null),p(be.error))}catch{ee.current&&ae===Q.current&&(d(null),p("Could not read Git status."))}finally{V.current===ae&&(V.current=0),ee.current&&ae===Q.current&&u(!1)}},[n,s,a]);m.useEffect(()=>{ee.current=!0;const Z=()=>{ce()},ae=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&ce()},5e3);return window.addEventListener("focus",Z),()=>{ee.current=!1,Q.current+=1,window.clearInterval(ae),window.removeEventListener("focus",Z)}},[ce]),m.useEffect(()=>{ce(!0)},[ce,o]),m.useEffect(()=>{if(!I||!l)return;(I.staged?l.staged:l.unstaged).some(ae=>ae.path===I.path)||(E(null),F(null),B(!1))},[I,l]),m.useEffect(()=>{if(!I||n||s||x!==null||y!=="changes")return;let Z=!0,ae=!1;const be=async()=>{if(!ae){ae=!0;try{const Ve=await window.electronAPI.git.fileDiff({...a,...I});Z&&F(Ve)}catch{Z&&F({ok:!1,error:"Could not load the diff."})}finally{ae=!1,Z&&B(!1)}}};be();const ze=()=>{be()},Ye=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&be()},5e3);return window.addEventListener("focus",ze),()=>{Z=!1,window.clearInterval(Ye),window.removeEventListener("focus",ze)}},[a,I,Y,n,s,y,x]);const ve=async(Z,ae,be)=>{if(!(L.current||n||s||c||!l)){L.current=!0,Q.current+=1,v(Z),g(null);try{const ze=await ae();if(!ee.current)return;ze.ok?be?.():g(ze.error)}catch{ee.current&&g("Could not complete the Git operation.")}finally{L.current=!1,ee.current&&(v(null),U(ze=>ze+1),ce(!0),se.getState().refreshWorktreeStatuses().catch(()=>{}))}}},_e=n||s||c||x!==null||!l,De=!_e&&!!C.trim()&&!!l?.staged.length,me=(Z,ae)=>{I?.path===Z.path&&I.staged===ae||(F(null),B(!0),E({path:Z.path,staged:ae}))},$=[{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")??[]}],z=S.trim().toLowerCase(),de=$.map(Z=>({...Z,files:Z.files.filter(ae=>ae.path.toLowerCase().includes(z))})),X=de.reduce((Z,ae)=>Z+ae.files.length,0),oe=()=>{De&&ve("Commit",()=>window.electronAPI.git.commit({...a,message:C}),()=>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(fe,{role:"tab","aria-selected":y==="changes",variant:y==="changes"?"secondary":"ghost",size:"xs",onClick:()=>b("changes"),children:[i.jsx($V,{className:"size-3.5"}),r("Changes")]}),i.jsxs(fe,{role:"tab","aria-selected":y==="history",variant:y==="history"?"secondary":"ghost",size:"xs",onClick:()=>b("history"),children:[i.jsx($o,{className:"size-3.5"}),r("History")]})]}),i.jsx(Mi,{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(er,{title:r("Fetch"),disabled:_e,onClick:()=>{ve("Fetch",()=>window.electronAPI.git.fetch(a))},children:i.jsx(od,{className:"size-3.5"})}),i.jsx(er,{title:r("Pull"),disabled:_e||!l?.upstream,onClick:()=>{ve("Pull",()=>window.electronAPI.git.pull(a))},children:i.jsx(Yu,{className:"size-3.5"})}),i.jsx(er,{title:r("Push"),disabled:_e||!l?.upstream,onClick:()=>{ve("Push",()=>window.electronAPI.git.push(a))},children:i.jsx(cd,{className:"size-3.5"})}),i.jsx(er,{title:r("Refresh"),disabled:n||s||x!==null||c,onClick:()=>{U(Z=>Z+1),ce(!0)},children:i.jsx(Ho,{className:W("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(Zt,{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...")}):y==="history"?i.jsx(ure,{request:a,head:l.head,tree:w,onToggleTree:()=>_(Z=>!Z)},`${l.head}:${Y}`):i.jsxs(NP,{title:r("Changed files"),hasSelection:I!==null,actions:i.jsx(kP,{tree:w,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(th,{ref:A,size:"sm",type:"search",value:S,onChange:Z=>k(Z.target.value),placeholder:r("Filter changed files…"),"aria-label":r("Filter changed files…")}),S.length>0&&i.jsx(eh,{align:"inline-end",children:i.jsx(fe,{type:"button",variant:"ghost",size:"icon-xs",title:r("Clear"),"aria-label":r("Clear"),onClick:()=>{k(""),A.current?.focus()},children:i.jsx(ln,{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(er,{title:r(Z.staged?"Unstage all":"Stage all"),disabled:_e,onClick:()=>{ve(Z.staged?"Unstage":"Stage",()=>window.electronAPI.git[Z.staged?"unstage":"stage"]({...a,paths:Z.files.map(ae=>ae.path)}))},children:Z.staged?i.jsx(T0,{className:"size-3.5"}):i.jsx(us,{className:"size-3.5"})})]}),i.jsx(jP,{files:Z.files,tree:w,children:ae=>i.jsx(_P,{file:ae,showDirectory:!w,selected:I?.path===ae.path&&I.staged===Z.staged,onSelect:()=>me(ae,Z.staged),actions:i.jsxs(i.Fragment,{children:[!Z.staged&&i.jsx(er,{title:r(ae.status==="untracked"?"Delete untracked file":"Discard changes"),disabled:_e||ae.status==="conflicted",onClick:()=>T(ae),children:i.jsx(pa,{className:"size-3.5"})}),i.jsx(er,{title:r(Z.staged?"Unstage":"Stage"),disabled:_e,onClick:()=>{ve(Z.staged?"Unstage":"Stage",()=>window.electronAPI.git[Z.staged?"unstage":"stage"]({...a,paths:[ae.path]}))},children:Z.staged?i.jsx(T0,{className:"size-3.5"}):i.jsx(us,{className:"size-3.5"})})]})})},z)]},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:C,"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(),oe())}}),i.jsxs(fe,{size:"xs",className:"mb-0.5 shrink-0",title:r("{{count}} staged files",{count:l.staged.length}),"aria-label":r("Commit"),disabled:!De,onClick:oe,children:[i.jsx(l6,{className:"size-3.5"}),r("Commit"),l.staged.length>0&&i.jsx("span",{className:"font-mono text-[11px]",children:l.staged.length})]})]})]}),children:[I&&i.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:I.path,children:[r(I.staged?"Staged changes":"Unstaged changes")," · ",I.path]}),i.jsx(CP,{result:H,loading:I!==null&&O})]}),i.jsx(ms,{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&&ve("Discard",()=>window.electronAPI.git.discard({...a,paths:[D.path],confirmUntracked:D.status==="untracked"}))}})]})}function er({title:e,disabled:t,onClick:n,children:s}){return i.jsx(fe,{variant:"ghost",size:"icon-xs",title:e,"aria-label":e,disabled:t,onClick:n,children:s})}const TP=28,pre={theme:va,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0,itemMetrics:{diffHeaderHeight:TP}},fre={height:"max-content",overflow:"auto"},mre={files:[],snapshots:{}},rk=[];function gre(e,t){return t?t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)?t:e?`${e.replace(/[/\\]+$/,"")}/${t}`:null:null}function xre({conversationId:e,projectId:t}){const{t:n}=J(),s=rd(pre),o=xn(ee=>ee.changesModeByConversation[e])??"all",r=xn(ee=>ee.setChangesMode),a=m.useRef(null),l=m.useRef(null),d=m.useRef(!1);m.useLayoutEffect(()=>{const ee=a.current,L=l.current,Q=ee?.querySelector('[aria-selected="true"]');!ee||!L||!Q||(d.current||(L.style.transition="none"),L.style.transform=`translate(${Q.offsetLeft}px, ${Q.offsetTop}px)`,L.style.width=`${Q.offsetWidth}px`,L.style.height=`${Q.offsetHeight}px`,d.current||(L.offsetWidth,L.style.transition="",d.current=!0))},[o]);const c=xn(ee=>ee.snapshotsByConversation[e]),u=xn(ee=>ee.saveSnapshots),h=xn(ee=>ee.loadSnapshots),p=se(ee=>g_(ee.conversations[e]?.messages??rk)),f=se(ee=>ee.workspaceRevisionByConversation[e]??0),g=se(ee=>!!ee.conversations[e]?.workspaceMigrating),x=Se(ee=>ee.projects.find(L=>L.id===t)),v=se(ee=>x?.kind==="scratch"?Vg({kind:"scratch",canonicalPath:x.path,conversationId:e})??void 0:ee.conversations[e]?.worktree?.path??x?.path),y=se(ee=>ee.conversations[e]?.status==="running"),b=m.useRef([]),w=m.useMemo(()=>{const ee=se.getState().conversations[e],Q=xr(ee?.messages??rk,y,ee?.customEntries??[],v).flatMap(V=>V.kind!=="tool"?[]:V.name==="apply_patch"?(V.fileChanges??[]).map(ce=>({path:ce.path,edits:null,writeContent:null,fileChange:ce})):V.state!=="ok"||V.name!=="edit"&&V.name!=="write"?[]:V.summary?V.name==="edit"&&!(V.edits&&V.edits.length>0)?[]:V.name==="write"&&V.writeContent==null?[]:[{path:V.summary,edits:V.edits,writeContent:V.writeContent}]:[]);return m9(b.current,Q)?b.current:(b.current=Q,Q)},[e,p,v,y]),[_,C]=m.useState(!1),[N,S]=m.useState({});m.useEffect(()=>{let ee=!0;return ra().then(()=>{ee&&C(!0)}),()=>{ee=!1}},[]),m.useEffect(()=>{o==="all"&&h(e)},[e,h,o]),m.useEffect(()=>{if(o!=="all"||g)return;const ee=[...new Set(w.map(Q=>Q.path))];let L=!0;return Promise.all(ee.map(async Q=>{const V=gre(v,Q),ce=V?await window.electronAPI.files.read(V):null;return[Q,ce]})).then(Q=>{if(!L)return;const V=Object.fromEntries(Q);S(ce=>g9(ce,V)?ce:V)}),()=>{L=!1}},[o,v,w,g,f]);const k=m.useMemo(()=>c?x9({tools:w,snapshots:c,currentByPath:N}):mre,[w,c,N]);m.useEffect(()=>{if(o!=="all"||!c)return;const ee=k.snapshots,L=Object.keys(ee);L.length===Object.keys(c).length&&L.every(Q=>c[Q]===ee[Q])||u(e,ee)},[k.snapshots,e,o,u,c]);const A=k.files,I=k.incompletePaths??[],[E,D]=m.useState(()=>new Set),T=m.useCallback(ee=>{D(L=>{const Q=new Set(L);return Q.delete(ee)||Q.add(ee),Q})},[]),H=m.useRef(new Map),F=m.useMemo(()=>SP(A,E,H.current),[A,E]),O=F.length>0&&F.every(ee=>ee.collapsed),B=()=>D(O?new Set:new Set(F.map(ee=>ee.id))),Y=m.useCallback(ee=>i.jsx(vre,{item:ee,onToggle:()=>T(ee.id)}),[T]),U=!_||!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(ak,{active:o==="all",onClick:()=>r(e,"all"),children:n("Session")}),i.jsx(ak,{active:o==="git",onClick:()=>r(e,"git"),children:n("Git")})]}),o==="all"&&F.length>0&&i.jsx("button",{type:"button",onClick:B,title:n(O?"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:O?i.jsx(Fj,{className:"h-3.5 w-3.5"}):i.jsx(fV,{className:"h-3.5 w-3.5"})})]}),i.jsx("div",{className:"min-h-0 flex-1",children:o==="git"?i.jsx(hre,{conversationId:e,projectId:t,disabled:g,unavailable:x?.kind==="ssh",editWriteKey:p},`${e}:${v}:${f}`):U||A.length===0&&I.length===0?i.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center text-sm text-muted-foreground",children:n(U?"Loading...":"No file changes in this conversation yet.")}):i.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[I.map(ee=>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:ee,children:ee}),i.jsx("div",{children:n("Diff unavailable because the original snapshot was truncated.")})]})]},ee)),A.length>0&&i.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:i.jsx(VT,{className:"min-h-0 w-full",items:F,style:fre,options:s,renderCustomHeader:Y})})]})})]})}function vre({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:TP},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(un,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):i.jsx($n,{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 ak({active:e,onClick:t,children:n}){return i.jsx("button",{type:"button",role:"tab",onClick:t,"aria-selected":e,className:W("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 bre(e,t){let n=0;for(const s of t)e.length>s.length&&e.endsWith(s)&&s.length>n&&(n=s.length);return n}function xf(e,t){const n=(e.split("/").at(-1)??"").toLowerCase();return t.map(s=>({viewer:s,length:bre(n,s.extensions)})).filter(s=>s.length>0).sort((s,o)=>o.length-s.length).map(s=>s.viewer)}const Ya=e=>`${e.pluginId}:${e.id}`;let DP=[];const mg=new Set;function lk(e){DP=e;for(const t of mg)t()}function wre(e){return mg.add(e),()=>mg.delete(e)}const dk=()=>DP;function yre(){return m.useSyncExternalStore(wre,dk,dk)}function Sre({conversationId:e,projectId:t,onOpenFile:n,onClose:s,menu:o}){const{t:r}=J(),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(b=>{v===a.current&&(p(b),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(Jt,{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(uk,{active:c==="names",onClick:()=>u("names"),label:r("File name"),icon:oO}),i.jsx(uk,{active:c==="content",onClick:()=>u("content"),label:r("Content"),icon:wo})]})]}),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=Dd(x.name,!1);return i.jsx(ck,{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:W("mt-0.5 size-3.5 shrink-0",Id(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(ck,{rel:x.relativePath,name:v,menu:o,onOpenFile:n,children:Cre(x,n)},IP(x))}):null:i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Type to search this workspace.")})})]})}function IP(e){return`${e.relativePath}:${e.line}:${e.column}`}function Cre(e,t){const n=e.relativePath.split("/").pop()||e.relativePath,s=Dd(n,!1);return i.jsxs("button",{type:"button","data-search-hit":IP(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:W("mt-0.5 size-3.5 shrink-0",Id(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 ck({rel:e,name:t,menu:n,onOpenFile:s,children:o}){return i.jsx(oh,{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 uk({active:e,onClick:t,label:n,icon:s}){return i.jsxs(fe,{type:"button",variant:"ghost",size:"sm",className:W("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 kre=/^data:image\/(png|jpe?g|gif|webp|bmp|x-icon|svg\+xml);/i;function jre(){return{...Md,attributes:{...Md.attributes,source:[]},protocols:{...Md.protocols,src:[...Md.protocols?.src??[],"data"]}}}function _re(){return e=>{rO(e,"element",t=>{if(t.tagName!=="img")return;const n=t.properties?.src;typeof n!="string"||!n.startsWith("data:")||kre.test(n)||delete t.properties.src})}}const Nre=[hO],Tre=jre(),Dre=[cO,[uO,Tre],_re],Ire=({children:e,node:t,...n})=>i.jsx("p",{className:"my-1.5 leading-relaxed first:mt-0 last:mb-0",...n,children:e}),Ere=({children:e,node:t,...n})=>i.jsx("h1",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),Pre=({children:e,node:t,...n})=>i.jsx("h2",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),Are=({children:e,node:t,...n})=>i.jsx("h3",{className:"mt-2 mb-1 text-sm font-semibold",...n,children:e}),Mre=({children:e,node:t,...n})=>i.jsx("ul",{className:"my-1.5 list-disc pl-5 space-y-0.5",...n,children:e}),Rre=({children:e,node:t,...n})=>i.jsx("ol",{className:"my-1.5 list-decimal pl-5 space-y-0.5",...n,children:e}),Lre=({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}),Ore=({children:e,node:t,...n})=>i.jsx("td",{className:"whitespace-nowrap border-b border-border/50 px-2 py-1",...n,children:e}),zre={p:Ire,h1:Ere,h2:Pre,h3:Are,ul:Mre,ol:Rre,th:Lre,td:Ore};function Gre({text:e,baseDirRel:t,resolveImage:n,resolveRemoteImage:s}){const o=m.useRef(new Map),r=m.useMemo(()=>({...aO,...zre,img:({node:d,src:c,alt:u,...h})=>i.jsx(Fre,{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(lO.Provider,{value:a,children:i.jsx("div",{style:pO(fO),children:i.jsx(dO,{remarkPlugins:Nre,rehypePlugins:Dre,components:r,urlTransform:l=>l,children:e})})})}function Fre({src:e,alt:t,rest:n,baseDirRel:s,resolveImage:o,resolveRemoteImage:r,cache:a}){const l=e?mO(e):"unsupported",d=l==="local"&&e?`local:${D0(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=D0(s,e);return g?o(g):Promise.resolve(null)})():r(gO(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 EP(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 wc(e){const t=EP(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 Hre(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:EP(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 $v="\0preview";function PP(e){return`${e}${$v}`}function AP(e){return e.endsWith($v)}function qr(e){return AP(e)?e.slice(0,-$v.length):e}function Bre(e,t){return e===t||e.startsWith(`${t}/`)}function gg(e,t){return Bre(qr(e),t)}function $re(e,t){const n=e.trim();return!n||n===t?"cancel":"commit"}function yc(e,t,n){const s=AP(e),o=qr(e);let r=null;return o===t?r=n:o.startsWith(`${t}/`)&&(r=n+o.slice(t.length)),r==null?null:s?PP(r):r}function Vre(e){return e==="preview"?"source":"preview"}function Sc(e,t,n){return e.some(s=>s.epoch>n&&gg(t,s.rel))}async function Wre(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 hk(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 xg(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 Ure={theme:va,disableFileHeader:!0,overflow:"scroll",preferredHighlighter:"shiki-js"};function Kre(e){return new CO(e)}function qre(e,t){return e?`${e}/${t}`:t}function Lr(e){return e.split("/").pop()||e}function Yre(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}const vf=[];function Xre({conversationId:e,projectId:t}){const{t:n}=J(),s=rd(Ure),o=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),r=se(K=>K.workspaceRevisionByConversation[e]??0),a=se(K=>!!K.conversations[e]?.workspaceMigrating),l=m.useCallback(K=>Wre(()=>window.electronAPI.workspaceFiles.read({...o,rel:K}),()=>{const he=se.getState();return{revision:he.workspaceRevisionByConversation[e]??0,migrating:!!he.conversations[e]?.workspaceMigrating}}),[e,o]),[d,c]=m.useState(!1),[u,h]=m.useState([]),[p,f]=m.useState(null),g=yre(),x=m.useRef(g);x.current=g;const v=wa(),[y,b]=m.useState(!0),w=m.useCallback(K=>{f(K),b(!1)},[]);m.useEffect(()=>{p||b(!0)},[p]);const[_,C]=m.useState(0),[N,S]=m.useState(()=>new Set),[k,A]=m.useState(!1),[I,E]=m.useState(null),[D,T]=m.useState(null),[H,F]=m.useState(null),O=Se(K=>K.projects.find(he=>he.id===t)),B=O?.kind!=="ssh",Y=m.useRef(u);Y.current=u;const U=m.useRef(p);U.current=p;const ee=m.useRef(null),L=m.useRef(null),Q=m.useRef(null),V=m.useRef(0),ce=m.useRef([]),ve=m.useCallback(K=>{V.current+=1,ce.current.push({epoch:V.current,rel:K}),ce.current.length>200&&ce.current.splice(0,100)},[]);m.useEffect(()=>{const K=Q.current;if(!K||!p)return;K.querySelector(`[data-file-tab="${CSS.escape(p)}"]`)?.scrollIntoView({inline:"nearest",block:"nearest"})},[p]),m.useEffect(()=>{let K=!0;return ra().then(()=>{K&&c(!0)}),()=>{K=!1}},[]);const _e=m.useCallback((K,he)=>{h(Ie=>Ie.map(Ee=>Ee.rel===K?hk(Ee,he):Ee))},[]),De=m.useCallback(K=>{Fe({title:n(K==="exists"?"A file or folder with that name already exists.":K==="invalid-name"?"Invalid name.":"Could not complete the file action.")})},[n]),me=m.useCallback(async(K,he)=>{if(Y.current.find(Je=>Je.rel===K)){he&&h(Je=>Je.map(ge=>ge.rel===K?{...ge,viewMode:he,viewer:void 0}:ge)),w(K);return}const Ee=V.current,Be=await l(K);if(!(!Be||Sc(ce.current,K,Ee))){if(!Be.ok){if(Be.error!=="too-large"){De(Be.error);return}h(Je=>[...Je,{rel:K,contents:"",draft:"",version:0,dirty:!1,conflict:!1,tooLarge:!0}]),w(K);return}h(Je=>[...Je,{rel:K,contents:Be.content,draft:Be.content,version:0,dirty:!1,conflict:!1,viewMode:he,viewer:he?void 0:(()=>{const ge=xf(K,x.current).find(qe=>qe.default);return ge?Ya(ge):void 0})()}]),w(K),window.electronAPI.workspaceFiles.watchStart({...o,rel:K})}},[De,l,o,w]),[$,z]=m.useState(null),de=m.useCallback(K=>{const he=Y.current,Ie=he.filter(Ee=>!K(Ee.rel));for(const Ee of he)K(Ee.rel)&&window.electronAPI.workspaceFiles.watchStop({...o,rel:Ee.rel});h(Ie),f(Ee=>Ee&&Ie.some(Be=>Be.rel===Ee)?Ee:Ie.at(-1)?.rel??null)},[o]),X=m.useCallback(K=>{de(he=>he===K)},[de]),oe=m.useCallback(K=>{if(Y.current.find(Ie=>Ie.rel===K)?.dirty){z({kind:"one",rel:K});return}X(K)},[X]);m.useEffect(()=>xO(e,()=>{const K=U.current;return!K||Y.current.length===0?!1:(oe(K),!0)}),[e,oe]),m.useEffect(()=>()=>{for(const K of Y.current)window.electronAPI.workspaceFiles.watchStop({...o,rel:K.rel})},[o]),m.useEffect(()=>{let K=!0;const he=window.electronAPI.workspaceFiles.onChange(Ie=>{Ie.conversationId!==e||!Y.current.find(Be=>Be.rel===Ie.rel)||l(Ie.rel).then(Be=>{K&&Be?.ok&&_e(Ie.rel,Be.content)})});return()=>{K=!1,he()}},[_e,e,l]);const Z=se(K=>K.conversations[e]?.status==="running"),ae=se(K=>O?.kind==="scratch"?Vg({kind:"scratch",canonicalPath:O.path,conversationId:e})??void 0:K.conversations[e]?.worktree?.path??O?.path),be=se(K=>K.conversations[e]?.historyBaseIndex),ze=se(K=>g_(K.conversations[e]?.messages??vf)),Ye=m.useMemo(()=>{const K=se.getState().conversations[e];return xr(K?.messages??vf,Z,K?.customEntries??[],ae).flatMap(he=>he.kind!=="tool"||he.state!=="ok"?[]:he.name!=="edit"&&he.name!=="write"?[]:he.summary?[he.summary]:[]).join(`
|
|
112
|
-
`)},[e,ze,ae,Z]);m.useEffect(()=>{let K=!0;const he=new Set(Ye?Ye.split(`
|
|
113
|
-
`):[]);for(const Ie of he)Y.current.some(Ee=>Ee.rel===Ie)&&l(Ie).then(Ee=>{K&&Ee?.ok&&_e(Ie,Ee.content)});return()=>{K=!1}},[_e,l,Ye]);const Ve=m.useRef(null),at=m.useRef(e),Ze=m.useRef(be),Et=m.useCallback(()=>C(K=>K+1),[]);m.useEffect(()=>{if(r===0||a)return;let K=!0;Et();for(const he of Y.current){const Ie=qr(he.rel),Ee=V.current;l(Ie).then(Be=>{!K||!Be||Sc(ce.current,Ie,Ee)||h(Je=>Je.map(ge=>ge.rel===he.rel?hk(ge,Be.ok?Be.content:null):ge))})}return()=>{K=!1}},[Et,l,a,r]);const Gt=m.useCallback(K=>{K&&S(he=>{if(he.has(K))return he;const Ie=new Set(he);return Ie.add(K),Ie})},[]),Pt=m.useCallback(K=>{K.length!==0&&S(he=>{let Ie=!1;const Ee=new Set(he);for(const Be of K)!Be||Ee.has(Be)||(Ee.add(Be),Ie=!0);return Ie?Ee:he})},[]);m.useEffect(()=>{const K=se.getState().conversations[e],he=be;(at.current!==e||Ze.current!==he)&&(at.current=e,Ze.current=he,Ve.current=null);const Ie=xr(K?.messages??vf,Z,K?.customEntries??[],ae),{refreshRels:Ee,nextSeen:Be}=Hre(Ie,Ve.current,vO(K?.messages??[]));Ve.current=Be,Ee.length!==0&&(Pt(Ee.flatMap(wc)),Et())},[Et,e,ze,Pt,be,ae,Z]);const ne=m.useCallback(K=>{S(he=>{const Ie=new Set(he);return Ie.has(K)?Ie.delete(K):Ie.add(K),Ie})},[]),ie=m.useCallback(K=>{Gt(K),E({parent:K,kind:"file"})},[Gt]),He=m.useCallback(K=>{Gt(K),E({parent:K,kind:"dir"})},[Gt]),St=m.useCallback(async(K,he=!1)=>{if(he){await me(K,"preview");return}const Ie=PP(K);if(Y.current.find(ge=>ge.rel===Ie)){w(Ie);return}const Be=V.current,Je=await l(K);if(!(!Je||Sc(ce.current,K,Be))){if(!Je.ok){De(Je.error);return}h(ge=>[...ge,{rel:Ie,contents:Je.content,draft:Je.content,version:0,dirty:!1,conflict:!1,preview:!0}]),w(Ie)}},[De,l,me,w]);m.useEffect(()=>bO(e,(K,he,Ie)=>{ee.current=he?{rel:K,line:he}:null;const Ee=L.current,Be=Y.current.find(Je=>Je.rel===K);if(he&&Ee?.rel===K&&U.current===K&&Be?.viewMode!=="preview"&&!Be?.viewer){ee.current=null,Ee.editor.focus({lineNumber:he});return}Ie==="markdown"&&!he?St(K,!0):me(K,!he&&xf(K,x.current).some(Je=>Je.default)?void 0:"source")}),[e,me,St]);const it=m.useCallback(K=>window.electronAPI.workspaceFiles.readImage({...o,rel:K}).then(he=>he.ok?he.dataUrl:null),[o]),je=m.useCallback(K=>window.electronAPI.workspaceFiles.fetchRemoteImage({...o,url:K}).then(he=>he.ok?he.dataUrl:null),[o]),ht=m.useCallback(async K=>{const he=await window.electronAPI.workspaceFiles.absPath({...o,rel:K});if(!he.ok||!he.local||!he.fileUrl){De(he.ok?"unsupported":he.error);return}const Ie=`browser:file:${e}:${K}`;$g({conversationId:e,tabId:Ie,title:Lr(K)});const Ee=await window.electronAPI.browser.navigate(Ie,e,he.fileUrl);Ee.ok||De(Ee.error)},[e,De,o]),$t=m.useCallback(async K=>{if(se.getState().conversations[e]?.workspaceMigrating){Fe({type:"error",title:n("Wait for the workspace operation to finish before saving.")});return}const he=Y.current.find(Je=>Je.rel===K);if(!he||he.preview)return;const Ie=he.draft,Ee=V.current,Be=await window.electronAPI.workspaceFiles.write({...o,rel:K,content:Ie});if(!Sc(ce.current,K,Ee)){if(!Be.ok){De(Be.error);return}h(Je=>Je.map(ge=>ge.rel===K?{...ge,contents:Ie,dirty:ge.draft!==Ie,conflict:!1}:ge))}},[e,De,o,n]),Oe=m.useCallback(K=>{h(he=>he.map(Ie=>Ie.rel===K?{...Ie,viewMode:Vre(Ie.viewMode)}:Ie))},[]),yt=m.useCallback((K,he)=>{h(Ie=>Ie.map(Ee=>Ee.rel===K?{...Ee,viewer:he}:Ee))},[]),Ht=m.useCallback((K,he)=>{h(Ie=>Ie.map(Ee=>Ee.rel===K?{...Ee,draft:he,dirty:he!==Ee.contents}:Ee))},[]);m.useEffect(()=>{const K=he=>{!(he.metaKey||he.ctrlKey)||he.key.toLowerCase()!=="s"||p&&(he.preventDefault(),$t(p))};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[p,$t]);const re=u.find(K=>K.rel===p)??null,$e=re&&!re.preview&&!re.tooLarge?xf(re.rel,g):[],st=re?.viewer?$e.find(K=>Ya(K)===re.viewer):void 0,Nt=m.useMemo(()=>({enabledSelectionAction:!0,renderSelectionAction(K){const he=document.createElement("button");return he.type="button",he.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",he.textContent=n("Send to conversation"),he.addEventListener("mouseenter",()=>{he.style.background="color-mix(in lab, currentColor 8%, transparent)"}),he.addEventListener("mouseleave",()=>{he.style.background="transparent"}),he.addEventListener("mousedown",Ie=>Ie.preventDefault()),he.addEventListener("click",()=>{const Ie=K.getSelectionText().trim(),Ee=p;if(!Ie||!Ee){K.close();return}const Be=K.selection.start.line+1;let Je=K.selection.end.line+1;K.selection.end.character===0&&Je>Be&&(Je-=1);const ge=Be===Je?`L${Be}`:`L${Be}-L${Je}`;Jl({kind:"file",id:`${Ee}#${ge}`,label:`${Lr(Ee)}#${ge}`,relativePath:`${Ee}#${ge}`}),yo(),K.close()}),he},onChange(K){const he=p;if(!he)return;const Ie=K.contents;h(Ee=>Ee.map(Be=>Be.rel===he?{...Be,draft:Ie,dirty:Ie!==Be.contents}:Be))},onAttach(K){if(!p)return;L.current={rel:p,editor:K};const he=ee.current;he?.rel===p&&(ee.current=null,K.focus({lineNumber:he.line}))}}),[p,n]),mt=m.useCallback(async(K,he)=>{const Ie=await window.electronAPI.workspaceFiles.rename({...o,rel:K,name:he});if(!Ie.ok){De(Ie.error);return}T(null);const Ee=Ie.rel;if(Ee){ve(K);for(const Be of Y.current){if(Be.preview||Be.tooLarge)continue;const Je=yc(Be.rel,K,Ee);Je!=null&&(window.electronAPI.workspaceFiles.watchStop({...o,rel:Be.rel}),window.electronAPI.workspaceFiles.watchStart({...o,rel:Je}))}h(Be=>Be.map(Je=>{const ge=yc(Je.rel,K,Ee);return ge==null?Je:{...Je,rel:ge}})),f(Be=>Be==null?Be:yc(Be,K,Ee)??Be),S(Be=>{let Je=!1;const ge=new Set;for(const qe of Be){const lt=yc(qe,K,Ee)??qe;lt!==qe&&(Je=!0),ge.add(lt)}return Je?ge:Be})}Et()},[Et,De,ve,o]);return i.jsxs(wO,{createEditor:Kre,children:[i.jsxs("div",{className:"flex h-full min-h-0 bg-background",children:[i.jsxs("div",{className:W("flex shrink-0 flex-col overflow-hidden text-sm",v?y?"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(fe,{variant:"ghost",size:"icon-sm",onClick:()=>A(K=>!K),"aria-label":n("Search"),"aria-pressed":k,children:i.jsx(ti,{})}),i.jsx(fe,{variant:"ghost",size:"icon-sm",onClick:Et,"aria-label":n("Refresh"),children:i.jsx(Ho,{})})]}),k?i.jsx(Sre,{conversationId:e,projectId:t,onOpenFile:K=>{me(K)},onClose:()=>A(!1),menu:{local:B,onPreview:K=>{St(K)},onBrowser:K=>{ht(K)},onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...o,rel:K}).then(he=>{he.ok||De(he.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...o,rel:K})},onNewFile:K=>{A(!1),Pt(wc(K)),ie(K)},onNewFolder:K=>{A(!1),Pt(wc(K)),He(K)},onRename:(K,he)=>{A(!1),Pt(wc(K)),T({rel:K,name:he,at:"tree"})},onDelete:(K,he)=>F({rel:K,name:he}),onSend:(K,he)=>{Jl({kind:"file",id:K,label:he,relativePath:K})}}}):i.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:i.jsx(oh,{target:{kind:"blank"},local:B,onNewFile:ie,onNewFolder:He,onCopyPath:()=>{},onCopyRel:()=>{},children:i.jsx("div",{className:"min-h-full",children:i.jsx(MP,{rel:"",depth:0,conversationId:e,projectId:t,treeEpoch:_,draft:I,renaming:D,local:B,expandedDirs:N,onToggleDir:ne,onOpen:me,onPreview:St,onBrowser:ht,onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...o,rel:K}).then(he=>{he.ok||De(he.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...o,rel:K})},onNewFile:ie,onNewFolder:He,onRenameStart:(K,he)=>T({rel:K,name:he,at:"tree"}),onDelete:(K,he)=>F({rel:K,name:he}),onDraftCancel:()=>E(null),onRenameCancel:()=>T(null),onDraftCommit:async(K,he,Ie)=>{const Be=await(he==="dir"?window.electronAPI.workspaceFiles.mkdir:window.electronAPI.workspaceFiles.createFile)({...o,rel:K||void 0,name:Ie});if(!Be.ok){De(Be.error);return}E(null),Et(),he==="file"&&Be.rel&&me(Be.rel)},onRenameCommit:(K,he)=>{mt(K,he)}})})})})]}),i.jsxs("div",{className:W("flex min-w-0 flex-1 flex-col",v&&y&&"hidden"),children:[u.length>0&&i.jsxs("div",{ref:Q,className:"flex h-[36px] shrink-0 items-center gap-1 overflow-x-auto border-b px-2",children:[v&&i.jsx("button",{type:"button",className:"flex shrink-0 items-center rounded-md px-1 text-muted-foreground hover:bg-muted/50",onClick:()=>b(!0),"aria-label":n("Files"),title:n("Files"),children:i.jsx(yO,{className:"h-4 w-4"})}),u.map(K=>{const he=D?.rel===K.rel&&D.at==="tab"&&!K.preview,Ie=i.jsxs("button",{type:"button","data-file-tab":K.rel,className:W("flex items-center gap-1.5 rounded-md px-2 py-1 text-xs",K.rel===p?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:()=>{he||f(K.rel)},onDoubleClick:Ee=>{K.preview||(Ee.preventDefault(),Ee.stopPropagation(),T({rel:K.rel,name:Lr(K.rel),at:"tab"}))},children:[he?i.jsx($u,{depth:0,kind:"file",variant:"tab",initial:D.name,onCancel:()=>T(null),onCommit:Ee=>{mt(K.rel,Ee)}}):i.jsxs("span",{className:"max-w-36 truncate",children:[Lr(K.preview?qr(K.rel):K.rel),K.preview?` ${n("Preview")}`:"",K.dirty?"*":""]}),i.jsx("button",{type:"button",className:"text-muted-foreground hover:text-destructive",onClick:Ee=>{Ee.stopPropagation(),oe(K.rel)},children:"×"})]});return i.jsxs(ho,{children:[i.jsx(po,{render:Ie}),i.jsxs(fo,{className:"min-w-40",children:[!K.preview&&i.jsx(Yt,{onClick:()=>T({rel:K.rel,name:Lr(K.rel),at:"tab"}),children:n("Rename")}),i.jsx(Yt,{onClick:()=>oe(K.rel),children:n("Close")}),i.jsx(Yt,{onClick:()=>{const Ee=Y.current,Be=K.rel,Je=Ee.some(ge=>ge.rel!==Be&&ge.dirty);de(ge=>ge!==Be&&!Ee.find(qe=>qe.rel===ge)?.dirty),Je&&z({kind:"others",rel:Be})},children:n("Close others")}),i.jsx(Yt,{onClick:()=>{const Ee=Y.current,Be=xg(Ee.map(ge=>ge.rel),K.rel,"right"),Je=Be.some(ge=>Ee.find(qe=>qe.rel===ge)?.dirty);de(ge=>Be.includes(ge)&&!Ee.find(qe=>qe.rel===ge)?.dirty),Je&&z({kind:"right",rel:K.rel})},children:n("Close tabs to the right")}),i.jsx(Yt,{onClick:()=>{const Ee=Y.current;de(Be=>!Ee.find(Je=>Je.rel===Be)?.dirty)},children:n("Close saved")}),i.jsx(Yt,{onClick:()=>{const Ee=Y.current,Be=Ee.some(Je=>Je.dirty);de(Je=>!Ee.find(ge=>ge.rel===Je)?.dirty),Be&&z({kind:"all"})},children:n("Close all")}),i.jsx(Yt,{onClick:()=>de(Ee=>Ee!==K.rel),children:n("Force close others")}),i.jsx(Yt,{onClick:()=>de(()=>!0),children:n("Force close all")})]})]},K.rel)})]}),re?.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(qr(re.rel)).then(K=>{K?.ok&&h(he=>he.map(Ie=>Ie.rel===re.rel?{...Ie,contents:K.content,draft:K.content,version:Ie.version+1,dirty:!1,conflict:!1}:Ie))})},children:n("Reload")})]}),i.jsxs("div",{className:"relative min-h-0 flex-1",children:[re&&!re.preview&&!re.tooLarge&&(ep(re.rel)||$e.length>0)&&i.jsx("div",{className:"absolute top-2 right-2 z-10 flex gap-1",children:st?i.jsxs(fe,{type:"button",variant:"outline",size:"sm","aria-label":n("View Source"),onClick:()=>yt(re.rel,void 0),children:[i.jsx(um,{className:"h-3.5 w-3.5"}),n("View Source")]}):i.jsxs(i.Fragment,{children:[$e.map(K=>i.jsxs(fe,{type:"button",variant:"outline",size:"sm","aria-label":K.title,title:K.pluginName,onClick:()=>yt(re.rel,Ya(K)),children:[i.jsx(I0,{className:"h-3.5 w-3.5"}),K.title]},Ya(K))),ep(re.rel)&&i.jsxs(fe,{type:"button",variant:"outline",size:"sm","aria-label":re.viewMode==="preview"?n("View Source"):n("Preview"),onClick:()=>Oe(re.rel),children:[re.viewMode==="preview"?i.jsx(um,{className:"h-3.5 w-3.5"}):i.jsx(I0,{className:"h-3.5 w-3.5"}),re.viewMode==="preview"?n("View Source"):n("Preview")]})]})}),!d||!re?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...")}):re.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.")}):st?i.jsx(yP,{pluginId:st.pluginId,entry:st.entry,title:st.title,sessionId:e,file:{rel:re.rel,text:re.draft,onEdit:K=>Ht(re.rel,K)}},`${re.rel}:${Ya(st)}`):re.preview||re.viewMode==="preview"&&ep(re.rel)?i.jsx("div",{className:"h-full overflow-auto px-3 py-2 text-sm",children:i.jsx(Gre,{text:re.preview?re.contents:re.draft,baseDirRel:Yre(qr(re.rel)),resolveImage:it,resolveRemoteImage:je})}):i.jsx(SO,{style:{height:"100%",overflow:"auto"},children:i.jsx(Zk,{file:{name:Lr(re.rel),contents:re.draft},disableWorkerPool:!0,edit:!0,editorOptions:Nt,options:s},`${re.rel}:${re.version}`)})]})]})]}),i.jsx(ms,{open:$!==null,onOpenChange:K=>{K||z(null)},title:n("Unsaved changes"),description:$?.kind==="one"?n("This file has unsaved changes. Close anyway?"):n("Some files have unsaved changes. Close anyway?"),confirmLabel:n("Close"),onConfirm:()=>{if($){if($.kind==="one"&&$.rel)X($.rel);else if($.kind==="others"&&$.rel){const K=$.rel;de(he=>he!==K)}else if($.kind==="right"&&$.rel){const K=$.rel,he=new Set(xg(Y.current.map(Ie=>Ie.rel),K,"right"));de(Ie=>he.has(Ie))}else de(()=>!0);z(null)}}}),i.jsx(ms,{open:H!==null,onOpenChange:K=>{K||F(null)},title:n("Delete"),description:n("Delete {{name}} permanently?",{name:H?.name??""}),confirmLabel:n("Delete"),onConfirm:()=>{if(!H)return;const{rel:K}=H;window.electronAPI.workspaceFiles.remove({...o,rel:K}).then(he=>{if(!he.ok){De(he.error);return}ve(K),de(Ie=>gg(Ie,K)),S(Ie=>{let Ee=!1;const Be=new Set;for(const Je of Ie){if(gg(Je,K)){Ee=!0;continue}Be.add(Je)}return Ee?Be:Ie}),F(null),Et()})}})]})}function $u({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"&&$re(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 MP({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=qre(e,c.name),h=r.expandedDirs.has(u);if(c.kind==="dir"){const f=r.renaming?.rel===u&&r.renaming.at==="tree"?i.jsx($u,{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(un,{className:W("h-3.5 w-3.5 shrink-0",h&&"rotate-90")}),(()=>{const g=Dd(c.name,!0,h);return i.jsx(g,{className:W("h-4 w-4 shrink-0",Id(c.name,!0))})})(),i.jsx("span",{className:"truncate",children:c.name})]});return i.jsxs("div",{children:[i.jsx(oh,{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(MP,{rel:u,depth:t+1,conversationId:n,projectId:s,treeEpoch:o,...r})]},u)}return i.jsx(Zre,{rel:u,name:c.name,depth:t,renaming:r.renaming?.rel===u&&r.renaming.at==="tree",handlers:r},u)}),d&&r.draft&&i.jsx($u,{depth:t,kind:r.draft.kind,initial:"",onCancel:r.onDraftCancel,onCommit:c=>r.onDraftCommit(e,r.draft.kind,c)})]})}function Zre({rel:e,name:t,depth:n,renaming:s,handlers:o}){const{setNodeRef:r,listeners:a,isDragging:l}=Jg({id:`workspace-file:${e}`,data:{type:"workspace-file",relativePath:e,name:t}}),d=s?i.jsx($u,{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=Dd(t,!1);return i.jsx(c,{className:W("h-4 w-4 shrink-0",Id(t,!1))})})(),i.jsx("span",{className:"truncate",children:t})]});return i.jsx(oh,{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)=>{Jl({kind:"file",id:c,label:u,relativePath:c})},children:d})}function pk(e){return e.closest(".dv-tabs-overflow-container")}function fk(e){const t=new Map;for(const n of e.children){if(!n.classList.contains("dv-tab"))continue;const s=n.querySelector("[data-panel-id]")?.getAttribute("data-panel-id");s&&t.set(s,n)}return t}function Jre(e){for(const t of e.children)if(t.classList.contains("dv-tab"))return!0;return!1}function Qre(e){const t=e.closest(".dv-popover-anchor"),n=e.parentElement;if(t&&n&&n.parentElement===t){n.remove();return}e.remove()}function mk(e,t){for(const n of t)n.parentElement===e&&n.remove();Jre(e)||Qre(e)}function eae({open:e,onClose:t,onFindNext:n,onFindPrevious:s,onClear:o,theme:r}){const{t:a}=J(),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 b=()=>({caseSensitive:u,wholeWord:p,regex:g}),w=N=>{if(!d){y(null);return}y(N==="next"?n(d,b()):s(d,b()))};if(!e)return null;const _=r?.background??"#1e1e1e",C=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:`${C}30`},children:[i.jsx("input",{ref:l,value:d,onChange:N=>{const S=N.target.value;c(S),S?y(n(S,b())):(o(),y(null))},onKeyDown:N=>{N.key==="Enter"?(N.preventDefault(),w(N.shiftKey?"prev":"next")):N.key==="Escape"&&(N.preventDefault(),t())},placeholder:a("Search..."),className:W("w-40 bg-transparent text-sm outline-none placeholder:opacity-50",v===!1&&d&&"text-red-400"),style:{color:C}}),i.jsx("button",{type:"button",onClick:()=>h(N=>!N),className:W("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:C},title:a("Case sensitive"),children:"Aa"}),i.jsx("button",{type:"button",onClick:()=>f(N=>!N),className:W("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:C},title:a("Whole word"),children:"W"}),i.jsx("button",{type:"button",onClick:()=>x(N=>!N),className:W("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:C},title:a("Regular expression"),children:".*"}),i.jsx("div",{className:"mx-1 h-4 w-px",style:{backgroundColor:`${C}30`}}),i.jsx("button",{type:"button",onClick:()=>w("prev"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:C},title:a("Previous match"),children:i.jsx(Kj,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:()=>w("next"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:C},title:a("Next match"),children:i.jsx($n,{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:C},title:a("Close"),children:i.jsx(ln,{className:"h-4 w-4"})})]})}function gk(e,t){const n=Ku(e);return t?TO(n):n}function tae({termId:e,conversationId:t,projectId:n,onTitle:s}){const{t:o}=J(),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=Se(D=>D.terminalTheme),g=Se(D=>D.terminalFontFamily),x=Se(D=>D.terminalFontSize),v=Ak()!==null,y=m.useRef(v);y.current=v;const[b,w]=m.useState(!1);m.useEffect(()=>{const D=r.current;if(!D)return;let T=!1,H=0,F;const O=()=>{if(T)return;if(!D.isConnected||D.clientWidth===0||D.clientHeight===0){H=requestAnimationFrame(O);return}const Y=Se.getState(),U=NO(e,D,{theme:gk(Y.terminalTheme,y.current),fontFamily:Y.terminalFontFamily,fontSize:Y.terminalFontSize});if(!U.opened){H=requestAnimationFrame(O);return}U.onTitle=L=>p.current?.(L);const ee=()=>{!D.isConnected||D.clientWidth===0||(U.fit.fit(),window.electronAPI.terminal.resize(e,U.term.cols,U.term.rows))};ee(),window.electronAPI.terminal.create({termId:e,conversationId:u.current,projectId:h.current,cols:U.term.cols,rows:U.term.rows}),U.term.focus(),a.current=U.term,F=new ResizeObserver(ee),F.observe(D)};document.fonts.load('14px "Enso Nerd Symbols"',"").then(O,Y=>{console.warn("Failed to load terminal icon font",Y),O()});const B=Y=>{(Y.metaKey||Y.ctrlKey)&&Y.key==="f"&&(Y.preventDefault(),Y.stopPropagation(),w(!0))};return D.addEventListener("keydown",B,!0),()=>{T=!0,cancelAnimationFrame(H),F?.disconnect(),D.removeEventListener("keydown",B,!0),a.current=null,kO(e)}},[e]),m.useEffect(()=>{jO(gk(f,v),g,x)},[f,g,x,v]);const _=m.useCallback((D,T)=>E0(e,D,"next",T),[e]),C=m.useCallback((D,T)=>E0(e,D,"prev",T),[e]),N=m.useCallback(()=>_O(e),[e]),S=()=>{const D=a.current?.getSelection().trim()??"";l.current=D,c(D.length>0)},k=()=>{const D=l.current||a.current?.getSelection().trim()||"";D&&(jh(D),yo(),a.current?.clearSelection(),c(!1))},A=()=>{const D=l.current||a.current?.getSelection().trim()||"";D&&navigator.clipboard.writeText(D)},I=Ku(f),E=i.jsx("div",{ref:r,"data-slot":"terminal-pane",className:"relative h-full w-full overflow-hidden p-2",style:{backgroundColor:I?.background,"--terminal-bg":I?.background},onContextMenu:S,children:i.jsx(eae,{open:b,onClose:()=>w(!1),onFindNext:_,onFindPrevious:C,onClear:N,theme:I})});return i.jsxs(ho,{children:[i.jsx(po,{render:E}),i.jsxs(fo,{className:"min-w-40",children:[i.jsx(Yt,{disabled:!d,onClick:A,children:o("Copy")}),i.jsx(Yt,{disabled:!d,onClick:k,children:o("Send to conversation")})]})]})}const RP={running:"bg-amber-500",completed:"bg-emerald-500",failed:"bg-destructive",cancelled:"bg-muted-foreground"},nae=[],sae={project:"Project",custom:"Custom",global:"Global",plugin:"Plugin",builtin:"Built-in"};function iae(e,t,n,s){const o=se.getState(),r=o.conversations[e],a=Se.getState(),l=a.projects.find(u=>u.id===r?.projectId);if(!r||!l)return!1;const d=Rl({defaultModel:a.defaultModel,...eu(l,a.projectGroups),lastProviderId:r.lastProviderId,lastModelId:r.lastModelId,providers:x_(),credentials:da(Fi.getState().snapshot),virtualModels:a.virtualModels});if(d.source==="none")return Fe({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(DO({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 oae({conversationId:e,preset:t,open:n,onToggle:s}){const{t:o}=J(),[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(sae[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||!iae(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(Jt,{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(fe,{type:"submit",size:"xs",disabled:l,children:[i.jsx(jg,{}),o("Run")]})})]}):null]})}function rae({conversationId:e}){const{t}=J(),[n,s]=m.useState([]),[o,r]=m.useState(null),a=Se(u=>u.disabledWorkflowPresets),l=se(u=>u.conversations[e]?.presetId),d=m.useCallback(()=>{let u=!1;return window.electronAPI.assets.listWorkflowPresets(e,l).then(h=>{u||s(h)}).catch(()=>{u||s([])}),()=>{u=!0}},[e,l]);m.useEffect(d,[d]);const c=n.filter(u=>u.source!=="builtin"||!a.includes(u.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(fe,{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(t_,{})}),i.jsx(fe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Refresh"),onClick:()=>d(),children:i.jsx(Ho,{})})]}),i.jsx("ul",{className:"space-y-1.5",children:c.map(u=>i.jsx(oae,{conversationId:e,preset:u,open:o===u.id,onToggle:()=>r(h=>h===u.id?null:u.id)},`${u.source}:${u.id}`))})]})}function aae(e,t){const n=se.getState();n.activeId!==e&&n.selectConversation(e),n.selectTab(e,t)}function lae({conversationId:e,member:t}){const{t:n}=J(),s=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:W("h-1.5 w-1.5 shrink-0 rounded-full",RP[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:()=>aae(e,o),children:s})}):i.jsx("li",{className:"text-xs",children:s})}function dae({conversationId:e}){const{t}=J(),n=Of(r=>r.byConversation[e])??nae,s=Of(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(rae,{conversationId:e}),o?i.jsx("div",{className:"flex justify-end",children:i.jsxs(fe,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>s(e),children:[i.jsx(Bg,{}),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:W("h-2 w-2 shrink-0 rounded-full",RP[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(fe,{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(ud,{})}):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:p4(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(lae,{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 Vv=m.createContext({}),LP=m.createContext(!1);function cae(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 OP(e,t){const n=e.panels.length;return n===0?t:`${t} ${n+1}`}function zP(e,t,n,s){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:OP(e,s),params:{conversationId:t,projectId:n}})}function GP(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 uae(e){return i.jsx(tae,{termId:e.api.id,conversationId:e.params.conversationId,projectId:e.params.projectId,onTitle:t=>e.api.setTitle(t)})}function hae(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(xre,{conversationId:t,projectId:n})}function FP(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 pae(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(Xre,{conversationId:t,projectId:n})}function HP(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 fae(e){const{conversationId:t}=e.params;return t?i.jsx(rre,{conversationId:t,panelApi:e.api}):null}function BP(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 mae(e){const{conversationId:t}=e.params;return t?i.jsx(jD,{conversationId:t,panelApi:e.api}):null}function $P(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 Wv(e){return Se(t=>AO(t,e))}function VP(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 gae(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(ore,{pluginId:n,viewId:s,sessionId:t??null})}function xae(e){const{conversationId:t}=e.params;return t?i.jsx(dae,{conversationId:t}):null}function vae(e,t){const n=e.group.panels.map(r=>r.id),s=new Set(xg(n,e.id,t)),o=[];for(const r of[...e.group.panels])s.has(r.id)&&(r.api.close(),o.push(r.id));return o}function bae(e){const{t}=J(),n=m.useRef(null),[s,o]=m.useState(e.api.isActive),[r,a]=m.useState(e.api.title??""),[l,d]=m.useState(e.params.favicon??null),[c,u]=m.useState(!1);m.useEffect(()=>{const g=e.api.onDidActiveChange(()=>o(e.api.isActive)),x=e.api.onDidTitleChange(()=>a(e.api.title??"")),v=e.api.onDidParametersChange(y=>{const b=y&&typeof y=="object"&&"favicon"in y?y.favicon??null:e.api.getParameters()?.favicon??null;d(b??null),u(!1)});return()=>{g.dispose(),x.dispose(),v.dispose()}},[e.api]);const h=e.api.id==="browser"||e.api.id.startsWith("browser:"),p=g=>{const x=n.current?pk(n.current):null,v=x?fk(x):null,y=vae(e.api,g);!x||!v||mk(x,y.flatMap(b=>{const w=v.get(b);return w?[w]:[]}))},f=i.jsxs("div",{ref:g=>{n.current=g},"data-side-tab":!0,"data-panel-id":e.api.id,"data-active":s||void 0,className:W("group/tab relative flex min-w-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",s?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),children:[e.api.id==="changes"?i.jsx(Dx,{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(Sg,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("plugin:")?i.jsx(qu,{pluginId:e.api.id.split(":")[1]??"",className:"h-3 w-3 shrink-0"}):h&&l&&!c?i.jsx("img",{src:l,alt:"",className:"h-3 w-3 shrink-0",onError:()=>u(!0)}):h?i.jsx(mo,{className:"h-3 w-3 shrink-0"}):i.jsx(Fo,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-32 truncate",children:r}),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:g=>g.stopPropagation(),onClick:g=>{g.preventDefault(),g.stopPropagation();const x=pk(g.currentTarget),v=x?fk(x).get(e.api.id):void 0;e.api.close(),x&&v&&mk(x,[v])},children:i.jsx(ln,{className:"h-3 w-3"})})]});return i.jsxs(ho,{children:[i.jsx(po,{render:f}),i.jsxs(fo,{className:"min-w-40",children:[i.jsx(Yt,{onClick:()=>p("self"),children:t("Close")}),i.jsx(Yt,{onClick:()=>p("others"),children:t("Close others")}),i.jsx(Yt,{onClick:()=>p("right"),children:t("Close tabs to the right")}),i.jsx(Yt,{onClick:()=>p("all"),children:t("Close all")})]})]})}function WP({onNewTerminal:e,onNewChanges:t,onNewFiles:n,onNewBrowser:s,onNewBtw:o,onNewWorkflow:r,onNewPluginView:a,compact:l}){const{t:d}=J(),c=m_();return i.jsxs(Hi,{children:[i.jsxs(Bi,{className:W("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(us,{className:"h-4 w-4"}),!l&&i.jsx("span",{children:d("New tab")})]}),i.jsxs($i,{align:l?"end":"center",className:"min-w-36",children:[i.jsxs(fn,{onClick:e,children:[i.jsx(Fo,{className:"h-4 w-4"}),d("Terminal")]}),i.jsxs(fn,{onClick:t,children:[i.jsx(Dx,{className:"h-4 w-4"}),d("Changes")]}),i.jsxs(fn,{onClick:n,children:[i.jsx(ni,{className:"h-4 w-4"}),d("Files")]}),i.jsxs(fn,{onClick:s,children:[i.jsx(mo,{className:"h-4 w-4"}),d("Browser")]}),i.jsxs(fn,{onClick:o,children:[i.jsx(vr,{className:"h-4 w-4"}),d("Btw")]}),r?i.jsxs(fn,{onClick:r,children:[i.jsx(Sg,{className:"h-4 w-4"}),d("Workflow")]}):null,a?c.map(u=>i.jsxs(fn,{onClick:()=>a(u),children:[i.jsx(qu,{pluginId:u.pluginId,className:"h-4 w-4"}),u.title]},`${u.pluginId}:${u.id}`)):null]})]})}function UP({containerApi:e,group:t}){const{t:n}=J(),{conversationId:s,projectId:o}=m.useContext(Vv),r=xn(f=>f.fullscreen),a=xn(f=>f.toggleFullscreen),l=Wv(o),d=wa(),c=m.useContext(LP),u=cae(e,t),h=xn(f=>f.toggleOpen),p=sh()==="windows";return i.jsxs("div",{className:"flex h-full items-center gap-0.5",children:[i.jsx(WP,{compact:!0,onNewTerminal:()=>{if(t){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:OP(e,n("Terminal")),params:{conversationId:s,projectId:o},position:{referenceGroup:t}});return}zP(e,s,o,n("Terminal"))},onNewChanges:()=>GP(e,s,o,n("Changes")),onNewFiles:()=>FP(e,s,o,n("Files")),onNewBrowser:()=>BP(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}HP(e,s,o,n("Btw"))},onNewWorkflow:l?()=>$P(e,s,o,n("Workflow")):void 0,onNewPluginView:f=>VP(e,s,o,f,t)}),i.jsx("button",{type:"button",className:W("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(LO,{className:"h-3.5 w-3.5"}):i.jsx(OO,{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(DN,{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 - ${zO}px)) - 19px)`}})]})}function wae(e){const{t}=J(),{conversationId:n,projectId:s}=m.useContext(Vv),o=Wv(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(UP,{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(WP,{onNewTerminal:()=>zP(e.containerApi,n,s,t("Terminal")),onNewChanges:()=>GP(e.containerApi,n,s,t("Changes")),onNewFiles:()=>FP(e.containerApi,n,s,t("Files")),onNewBrowser:()=>BP(e.containerApi,n,s,t("Browser")),onNewBtw:()=>HP(e.containerApi,n,s,t("Btw")),onNewWorkflow:o?()=>$P(e.containerApi,n,s,t("Workflow")):void 0,onNewPluginView:r=>VP(e.containerApi,n,s,r)})]})]})}function yae(e){return i.jsx(UP,{containerApi:e.containerApi,group:e.group})}const xk={terminal:uae,changes:hae,files:pae,browser:mae,btw:fae,workflow:xae,plugin:gae};function Sae(){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 Cae({conversationId:e,hidden:t}){const n=se(s=>s.conversations[e]?.projectId);return n?i.jsx("div",{className:W("absolute inset-0",t&&"hidden"),children:i.jsx(kae,{conversationId:e,projectId:n})}):null}function kae({conversationId:e,projectId:t}){const n=Sae(),s=Wv(t),[o,r]=m.useState(null);m.useEffect(()=>{s||o?.getPanel("workflow")?.api.close()},[o,s]);const a=l=>{MO(e,l.api);const d=xn.getState().layouts[e],c=Zoe(d,new Set(Object.keys(xk)));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,xn.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:")){se.getState().disposeBtwConversation(h.id.slice(4));return}RO(h.id),window.electronAPI.terminal.dispose(h.id)}}),r(l.api)};return i.jsx(Vv.Provider,{value:{conversationId:e,projectId:t},children:i.jsx("div",{className:"enso-side-dock h-full",children:i.jsx(bP,{components:xk,defaultTabComponent:bae,watermarkComponent:wae,rightHeaderActionsComponent:yae,theme:n?Nie:Tie,onReady:a})})})}function jae({width:e,resizing:t=!1,card:n=!1,titleRow:s=!1}){const{t:o}=J(),r=se(T=>T.activeId),a=xn(T=>r?!!T.uiByConversation[r]?.open:!1),l=wa(),c=xn(T=>T.fullscreen)||l&&a;m.useEffect(()=>{const T=window.electronAPI.browser.onReveal(F=>{f_(F.conversationId)||$g({conversationId:F.conversationId,tabId:F.tabId})}),H=window.electronAPI.browser.onTabClosed(F=>{IO(F.conversationId,F.tabId)});return window.electronAPI.browser.restoreTabs(),()=>{T(),H()}},[]),m.useEffect(()=>Of.subscribe((T,H)=>{for(const[F,O]of Object.entries(T.byConversation)){if(H.byConversation[F]===O)continue;const B=O.find(Y=>Y.status==="running");B&&EO({conversationId:F,runId:B.runId,title:o("Workflow")})}}),[o]),m.useEffect(()=>se.subscribe((T,H)=>{for(const F of Object.keys(H.conversations))T.conversations[F]||PO(F)}),[]);const u=se(T=>T.activeId),[h,p]=m.useState([]),f=se(T=>h.filter(H=>!!T.conversations[H]).join(`
|
|
115
|
-
`)),[g,x]=m.useState(c),[v,y]=m.useState(0),b=n&&!s?v_:Pg,w=zj(e,v,b),_=m.useRef(null),[C,N]=m.useState({id:u,from:u});u!==C.id&&N({id:u,from:C.id}),c&&!g&&x(!0),m.useEffect(()=>{const T=_.current?.parentElement;if(!T)return;const H=()=>{const O=getComputedStyle(T);y(T.clientWidth-parseFloat(O.paddingLeft)-parseFloat(O.paddingRight))};H();const F=new ResizeObserver(H);return F.observe(T),()=>F.disconnect()},[]),m.useEffect(()=>{C.from!==C.id&&N(T=>T.from===T.id?T:{...T,from:T.id})},[C.from,C.id]);const S=g?void 0:Math.max(0,w-(a&&!n?1:0)),k=u,A=Xq({resizing:t,conversationId:C.id??void 0,previousConversationId:C.from??void 0}),I=c?v||w:a?w:0,E=!!s&&!l;k&&!h.includes(k)&&p(T=>T.includes(k)?T:[...T,k]);const D=f===""?[]:f.split(`
|
|
116
|
-
`);return i.jsxs(i.Fragment,{children:[g&&!l?i.jsx("div",{className:"shrink-0",style:{width:w},"aria-hidden":!0}):null,i.jsxs(Rs.aside,{ref:_,"data-slot":"side-panel",initial:!1,animate:{width:I},style:g?{position:"absolute"}:{position:"relative",maxWidth:`max(0px, calc(100% - ${Oj+b}px))`},transition:xD({skip:A,cover:g,targetW:I}),onAnimationComplete:()=>{c||x(!1)},className:W("flex min-h-0 flex-col",E&&a?"overflow-clip [overflow-clip-margin:4px]":"overflow-hidden",a&&(E||!g)?"bg-transparent":E?"":"bg-background",g?E?"top-px right-[8px] bottom-[8px]":n?"top-0 right-[8px] bottom-[8px]":"inset-y-0 right-0":"shrink-0",E?W("no-drag -mt-[44px]",g?"rounded-b-[10px]":"rounded-br-[10px]"):n?W("rounded-[10px]",a&&"shadow-surface"):a&&"border-l"),"data-enso":"side-panel","data-title-row":E||void 0,children:[a&&(E||!g)?i.jsx(Tae,{titleRow:E,full:g}):null,a&&!g&&S!==void 0?i.jsx("div",{"aria-hidden":!0,className:W("pointer-events-none absolute right-0 bottom-0 bg-background",s?"top-[44px]":"top-0"),style:{left:S}}):null,i.jsx("div",{className:W("relative flex h-full min-h-0 flex-col",g&&"w-full",!a&&"invisible"),style:{width:S,clipPath:E?g?Nae:_ae:void 0},children:D.length>0?i.jsx("div",{className:"relative min-h-0 flex-1",children:i.jsx(LP.Provider,{value:E,children:D.map(T=>i.jsx(Cae,{conversationId:T,hidden:T!==k},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 _ae="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)",Nae="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 Tae({titleRow:e,full:t}){const n=m.useRef(null),s=xn(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=MN(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:W("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:W("pointer-events-none absolute inset-x-0 bottom-0 bg-background",e?W("top-[44px]",t?"rounded-[10px]":"rounded-r-[10px]"):"top-0")})]})}function Uv(){return ro()&&se.persist.hasHydrated()&&Se.persist.hasHydrated()}function vk(e,t){Uv()&&e>0&&(async()=>(t&&await se.getState().refreshWorktreeStatuses(),await se.getState().autoArchiveStaleConversations()))()}function bk(e){!Uv()||!(e>0)||se.getState().autoDeleteStaleArchived()}function Dae(){const e=Se(s=>s.autoArchiveIdleDays),t=Se(s=>s.autoArchiveMergedWorktrees),n=Se(s=>s.autoDeleteArchivedDays);m.useEffect(()=>{if(Uv()){vk(e,t),bk(n);return}const s=()=>{vk(e,t),bk(n)},o=[se.persist.onFinishHydration(s),Se.persist.onFinishHydration(s)];return()=>{for(const r of o)r()}},[e,t,n])}function Iae(){const e=se(t=>Math.min(999,GO(t.order,bv(t.conversations))));m.useEffect(()=>{window.electronAPI.app.setBadgeCount(e)},[e])}function Eae(){const e=Se(n=>n.generationStallTimeoutMin),{t}=J();m.useEffect(()=>{if(e<=0)return;const n=new Set,s=new Set,o=new Map,r=setInterval(()=>{if(!ro())return;const a=e*6e4,l=Date.now(),d=se.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=FO({shouldAbort:HO({status:c.status,spawning:c.spawning,lastOutputAt:VO(c,d.conversations),now:l,timeoutMs:a,hasLiveWork:BO({...$O(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)}),Fe(wk(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),Fe(wk(c,t("Stopped after repeated stalls"))))}},1e3);return()=>clearInterval(r)},[e,t])}function wk(e,t){const n=(e.coworkerName||e.title).split(`
|
|
117
|
-
`)[0].trim();return n?{type:"warning",title:n,description:t}:{type:"warning",title:t}}const Pae=3e4;let yk=Promise.resolve();function Aae(e,t=Pae){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=[se.subscribe(o),Se.subscribe(o)],a=setTimeout(()=>s(e()),t)})}function Mae(){return se.persist.hasHydrated()&&Se.persist.hasHydrated()}function Rae(){const{t:e}=J();m.useEffect(()=>{if(!ro())return;const t=()=>{yk=yk.then(async()=>{if(!await Aae(Mae))return;const s=await window.electronAPI.window.takeOpenFolders().catch(()=>[]);for(const o of s)try{const r=await Se.getState().addProject(o);if(!r){Fe({type:"error",title:e("Failed to add project")});continue}if(!await se.getState().newConversation(r.id)){Fe({type:"error",title:e("Failed to add project")});continue}MI()}catch(r){Fe({type:"error",title:e("Failed to add project"),description:r instanceof Error?r.message:String(r)})}}).catch(()=>{})},n=window.electronAPI.window.onOpenFolderRequested(t);return t(),n},[e])}async function Lae(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 Oae=3e4;function Sk(e,t=Oae){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=[se.subscribe(o),Fi.subscribe(o),Se.subscribe(o)],a=setTimeout(()=>s(e()),t)})}function zae(){const e=Fi.getState().snapshot.availability.status;return se.persist.hasHydrated()&&Se.persist.hasHydrated()&&e!=="unloaded"&&e!=="loading"}function Gae(){const{t:e}=J();m.useEffect(()=>{ro()&&(async()=>{const t=await window.electronAPI.updater.takeInterruptedSessions().catch(()=>[]);if(t.length===0||!await Sk(zae))return;const n=se.getState,s=await Lae(t,{conversation:o=>n().conversations[o],resume:o=>n().resumeConversation(o),retry:o=>window.electronAPI.agent.retry(o,{unfinishedOnly:!0}),waitUntil:Sk});s.length!==0&&Fe({type:"info",title:e("Continued {{count}} conversation(s) interrupted by the update",{count:s.length})})})()},[e])}const Ck="enso-win",KP="enso-win-flush",Cc="enso-win-pending",kk="enso-win-native";function Fae(e,t,n){return{maximized:n.maximized?e.maximized:t.maximized,fullscreen:n.fullscreen?e.fullscreen:t.fullscreen}}function Hae(e,t){return e||t}function Bae(e,t){document.documentElement.classList.toggle(KP,Hae(e,t))}function $ae(){m.useEffect(()=>{if(window.electronAPI?.env.platform!=="win32")return;const e=document.documentElement;e.classList.add(Ck,Cc),e.classList.add(kk);let t={maximized:!1,fullscreen:!1};const n={maximized:0,fullscreen:0};let s=!1,o=0,r;const a=()=>Bae(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=Fae(t,{maximized:g,fullscreen:x},{maximized:n.maximized!==f.maximized,fullscreen:n.fullscreen!==f.fullscreen}),e.classList.remove(Cc),a())}).catch(()=>{!s&&p===o&&e.classList.remove(Cc)})};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(Ck,KP,Cc,kk)}},[])}function Vae(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 jk(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 Wae(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||jk(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=jk(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 gs=(e,t)=>({ok:!1,code:e,error:t});async function Uae(e,t){if(e.op==="focusSession"){const a=e.payload.sessionId;if(typeof a!="string"||!a)return gs("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}):gs("NOT_FOUND","会话不在本窗口")}return gs("NOT_FOUND","会话不在本窗口")}if(e.op==="openChildRun"){const a=e.payload.parentId,l=e.payload.childId;return typeof a!="string"||!a?gs("BAD_REQUEST","缺少父会话 id"):typeof l!="string"||!l?gs("BAD_REQUEST","缺少子会话 id"):t.conversation(a)?(t.openChildRun(a,l),{ok:!0,value:null}):gs("NOT_FOUND","会话不在本窗口")}if(e.op==="focusSubagent"){const a=e.payload.sessionId,l=e.payload.agentId;return typeof a!="string"||!t.conversation(a)?gs("NOT_FOUND","会话不在本窗口"):typeof l!="string"||!l?gs("BAD_REQUEST","缺少子代理 id"):(t.focusSubagent(a,l),{ok:!0,value:null})}if(e.op==="ensureSession"){const a=t.conversation(e.sessionId);if(!a)return gs("NOT_FOUND","会话不在本窗口");if(a.parentId)return gs("UNSUPPORTED","子会话随主会话恢复");const l=await t.ensure(e.sessionId);return l?gs("SESSION_FAILED",l):{ok:!0,value:null}}if(e.op==="openPluginView"){if(!t.conversation(e.sessionId))return gs("NOT_FOUND","会话不在本窗口");const{pluginId:a,viewId:l,title:d}=e.payload;return typeof a!="string"||!a||typeof l!="string"||!l||typeof d!="string"||!d?gs("BAD_REQUEST","缺少视图标识"):(t.openPluginView?.(e.sessionId,{pluginId:a,viewId:l,title:d}),{ok:!0,value:null})}const n=t.conversation(e.sessionId);if(!n)return gs("NO_SESSION","发起调用的会话不在本窗口");const s=typeof e.payload.presetId=="string"?e.payload.presetId:void 0,o=await t.create(n.projectId,s);if(!o)return gs("CREATE_FAILED","新建会话失败");const r=e.payload.text;return typeof r=="string"&&r&&t.prefill(o,r),{ok:!0,value:{sessionId:o}}}const Kae={conversation:e=>se.getState().conversations[e]??null,focus:(e,t)=>{const n=se.getState();n.selectConversation(e),t!==e&&n.selectTab(e,t)},focusSubagent:(e,t)=>se.getState().focusSubagent(e,t),openChildRun:(e,t)=>se.getState().openChildRun(e,t),create:(e,t)=>se.getState().newConversation(e,t?{presetId:t}:void 0),prefill:qO,ensure:async e=>{const t=se.getState(),n=t.conversations[e];if(n?.started||n?.spawning)return null;await t.resumeConversation(e,{fresh:!0});const s=se.getState().conversations[e];return s?.started||s?.spawning?null:s?.error??"无法启动会话:请检查默认模型与登录状态"},openPluginView:(e,t)=>YO({conversationId:e,...t})};function qae(){return m.useEffect(()=>{const e=ZO(()=>XJ(se.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 Vae(d,s))Fe({type:"warning",title:`插件 ${u} 的检查连续失败,已临时放行`,description:`${h} 事件 30 秒内不再经过该插件;详情见设置里的插件日志`});const c=d.filter(u=>u.state==="enabled");UO(Object.fromEntries(d.flatMap(u=>u.icon?[[u.id,u.icon]]:[]))),P0(KO(d)),OS(yQ(d)),A0(c.flatMap(u=>u.views.map(h=>({pluginId:u.id,pluginName:u.name,...h})))),lk(c.flatMap(u=>(u.fileViewers??[]).map(h=>({pluginId:u.id,pluginName:u.name,...h})))),FS(c.flatMap(u=>u.triggers.filter(h=>h.symbol==="#").map(h=>({pluginId:u.id,name:h.name})))),await Wae(n,d,u=>XO(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"||l.op==="openPluginView"){Uae(l,Kae).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,...WO(l)})});return()=>{t+=1,r(),a(),P0([]),FS([]),A0([]),lk([]),OS([]);for(const l of n.values())l.dispose();n.clear()}},[]),null}function Yae(e,t=[]){return JSON.stringify({pinnedOrder:t,entries:e.map(n=>{const{updatedAt:s,...o}=n;return o})})}function Xae(e){return JSON.stringify(e)}function Zae(e,t,n=[]){const s=JO(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:e_,name:"Auto",models:o.map(r=>({id:r.id,label:r.name}))}),s}function Jae(e,t,n=[]){const s=Zae(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 Qae=300;let kc=null,_k=!1,vg=null;function ele(){const e=Se.getState(),t=se.getState(),n=Tv(e.projects,hr(Yc)),s=new Set(e.projects.filter(w=>w.kind==="scratch").map(w=>w.id)),o=n.filter(w=>w.kind!=="scratch"),r=new Set(hr(nl)),a=tz(nz(e.language),"Temporary chats"),l=new Map(e.projects.map(w=>[w.id,w.kind==="scratch"?a:Ao(w)])),d=new Map(e.projects.map(w=>[w.id,w.path])),c=new Map(e.projects.map(w=>[w.id,w.kind])),u=w=>{const _=(w.parentId?t.conversations[w.parentId]:void 0)??w;return c.get(_.projectId)==="scratch"?Vg({kind:"scratch",canonicalPath:d.get(_.projectId)??"",conversationId:_.id})??void 0:_.worktree?.path??d.get(w.projectId)},h=e.skills.filter(w=>w.enabled!==!1).map(w=>({name:`/skill:${w.name}`,description:w.description})),p=w=>{const _=eE(w.occupancy,w.contextWindow);return{id:w.id,title:w.parentId&&w.coworkerName||w.title,projectName:l.get(w.projectId)??"",projectId:w.projectId,...u(w)?{cwd:u(w)}:{},status:w.spawning?"running":w.status,updatedAt:b_(w),...w.parentId?{parentId:w.parentId}:{},...w.pinned===!0?{pinned:!0}:{},...w.archived===!0?{archived:!0}:{},...w.lastProviderId?{providerId:w.lastProviderId}:{},...w.lastModelId?{modelId:w.lastModelId}:{},...w.reasoningEnabled!==void 0?{reasoningEnabled:w.reasoningEnabled}:{},...w.thinkingLevel?{thinkingLevel:w.thinkingLevel}:{},...w.unread===!0?{unread:!0}:{},...w.pendingAsks&&w.pendingAsks.length>0?{pendingAskCount:w.pendingAsks.length}:{},...w.pendingApprovals&&w.pendingApprovals.length>0?{pendingApprovalCount:w.pendingApprovals.length}:{},...w.queuedMessages?.length?{queued:w.queuedMessages.map(C=>({id:C.id,text:C.text,...C.images?.length?{hasImages:!0}:{}}))}:{},...w.goal?{goal:{text:w.goal.text,status:w.goal.status,...w.goal.note?{note:w.goal.note}:{},autoTurns:w.goal.autoTurns}}:{},...h.length?{slashCommands:h}:{},..._?{context:_}:{},...w.usageTotals?{usageTotals:w.usageTotals}:{}}},f=t.order.map(w=>t.conversations[w]).filter(w=>!!w),g=new Set(t.order),x=Object.values(t.conversations).filter(w=>!!(w?.parentId&&g.has(w.parentId))),v=[...f,...x].map(p),y=e.scratchSessionsEnabled?v:v.filter(w=>!s.has(w.projectId)),b=Jae(x_(),Fi.getState().snapshot,e.virtualModels);return{catalog:y,pinnedOrder:hr(eg),projects:o.map(w=>({...kne(w),...r.has(w.id)?{archived:!0}:{}})),projectGroups:e.projectGroups,providers:b.entries,providersSettled:b.settled,projectPaths:e.projects.map(w=>({id:w.id,path:w.path})),theme:e.theme,terminal:Ku(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 tle(e){return Xae({catalog:Yae(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 nle(){return se.persist.hasHydrated()&&Se.persist.hasHydrated()}function Qi(){kc&&clearTimeout(kc),kc=setTimeout(()=>{if(kc=null,!ro()||!nle())return;const e=ele(),t=tle(e);t!==vg&&(vg=t,window.electronAPI.pair.pushCatalog(e))},Qae)}function sle(){_k||(_k=!0,Qi(),se.persist.onFinishHydration(Qi),Se.persist.onFinishHydration(Qi),se.subscribe((e,t)=>{(e.conversations!==t.conversations||e.order!==t.order)&&Qi()}),Fi.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Qi()}),QO.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Qi()}),Se.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()}),rne(Qi),ez(e=>{e&&(vg=null,Qi())}),window.electronAPI.pair.onResumeSession(e=>{M0(e),ro()&&(se.getState().markConversationRead(e),se.getState().resumeConversation(e))}),window.electronAPI.pair.onSessionCreated(e=>{M0(e.sessionId),ro()&&se.getState().adoptPairSession(e)}),window.electronAPI.pair.onSessionConfig(e=>{if(!ro())return;const t=se.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(!ro())return;const t=se.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 ile=3e4;async function ole(e,t=Date.now()){const{order:n,conversations:s,activeId:o}=se.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:b_(h)}]}),a=sz(r,e,t),l=se.getState();for(const u of a)l.removeConversation(u);const d=Date.now()+ile,c=()=>a.filter(u=>se.getState().conversations[u]);for(;c().length>0&&Date.now()<d;)await new Promise(u=>setTimeout(u,200));return a.length-c().length}const rle=e=>{const t=Uz(e);return t.length>0?t:k_(e)},Nk="enso-sidebar-width",Tk="enso-sidebar-collapsed";function bf(){const e=se.getState(),n=(e.activeId?e.conversations[e.activeId]:null)?.projectId??Se.getState().projects[0]?.id;n&&e.newConversation(n)}const jc="no-drag flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",Dk=200,Ik=420;function ale(){const e=Se(z=>z.onboarded),t=m.useSyncExternalStore(z=>Se.persist?.onFinishHydration?.(z)??(()=>{}),()=>Se.persist?.hasHydrated?.()??!0);iz(),Eae(),Dae(),Gae(),Rae(),Iae();const[n,s]=m.useState(!1),[o,r]=m.useState(null);$ae();const[a,l]=m.useState(()=>{const z=Number(localStorage.getItem(Nk));return Number.isFinite(z)&&z>=Dk?Math.min(z,Ik):280}),[d,c]=m.useState(()=>localStorage.getItem(Tk)==="1"),u=wa(),h=oz(),[p,f]=m.useState(!1),g=m.useCallback(()=>f(!1),[]);m.useEffect(()=>{u||f(!1)},[u]),m.useEffect(()=>se.subscribe((z,de)=>{z.activeId!==de.activeId&&f(!1)}),[]);const{t:x}=J(),v=Se(z=>z.chatWide),y=se(z=>z.activeId),b=xn(z=>y?!!z.uiByConversation[y]?.open:!1),w=xn(z=>z.uiByConversation[y??""]?.width??z.lastWidth),_=xn(z=>z.fullscreen),C=xn(z=>z.toggleOpen),N=ue(z=>z.panelOpen),S=ue(z=>z.togglePanel);m.useEffect(()=>{_&&!b&&xn.getState().setFullscreen(!1)},[b,_]),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(z=>{rz().finally(()=>{window.electronAPI.app.respondFlushPersist(z)})}),[]);const k=z=>{const de=o;de&&(r(null),window.electronAPI.app.respondCloseRequest(de,{action:z}))},[A,I]=m.useState(!1),E=m.useRef(null);m.useEffect(()=>{localStorage.setItem(Nk,String(a))},[a]),m.useEffect(()=>{localStorage.setItem(Tk,d?"1":"0")},[d]),m.useEffect(()=>window.electronAPI.window.onAgentComposerPrefill(z=>{se.getState().prefillAgent(z.typeKey,z.prompt)}),[]),m.useEffect(()=>window.electronAPI.resources.onSessionsCleanRequest(({requestId:z,request:de})=>{ole(de).catch(()=>0).then(X=>window.electronAPI.resources.sessionsCleanDone(z,X))}),[]),m.useEffect(()=>{sle()},[]),m.useEffect(()=>{const z=is.getState();if(window.electronAPI.remote){z.activeNodeId!=="local"&&z.switchNode("local");return}return z.bind()},[]);const D=is(z=>z.activeNodeId),T=D!=="local",H=zJ(),F=Se(z=>z.botModeEnabled),O=co(z=>z.mode);m.useEffect(()=>{const z=Se.persist?.hasHydrated?.()??!0;O==="bot"&&(z&&!F||T)&&co.getState().setMode("code")},[O,F,T]),m.useEffect(()=>{if(!F)return;const z=ue.getState().bind(),de=window.electronAPI.bots.onEvent(X=>{X.kind==="open"&&GJ(X)});return()=>{z(),de()}},[F]),m.useEffect(()=>window.electronAPI.agent.onFocusSession(z=>{se.getState().conversations[z]&&MI()}),[]);const B=m.useCallback(z=>{l(de=>Math.min(Ik,Math.max(Dk,de+z)))},[]),Y=Se(z=>z.keybindings);m.useEffect(()=>{const z=Li(Y),de=oe=>{const Z=se.getState(),ae=Z.activeId?Z.conversations[Z.activeId]:null;if(!ae)return;const be=[void 0,...ae.coworkerIds??[]];if(be.length<=1)return;const ze=be.indexOf(ae.activeTabId);Z.selectTab(ae.id,be[(ze+oe+be.length)%be.length])},X=oe=>{const Z=Pl(oe);if(!Z)return;if(Z===z["toggle-app-mode"]){if(!Se.getState().botModeEnabled||is.getState().activeNodeId!=="local")return;oe.preventDefault();const ze=co.getState();ze.setMode(ze.mode==="bot"?"code":"bot");return}const ae=is.getState().activeNodeId!=="local"||sc();if(sc()&&Z===z["toggle-side-panel"]){oe.preventDefault(),ue.getState().togglePanel();return}if(sc()&&Z===z["search-workspace"]){oe.preventDefault(),ue.getState().setSearchOpen(!0);return}if(!(ae&&["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===z[be]))){if(Z===z["toggle-sidebar"])oe.preventDefault(),hz(window.innerWidth)?f(be=>!be):c(be=>!be);else if(Z===z["open-settings"])oe.preventDefault(),window.electronAPI.window.openSettings();else if(Z===z["new-conversation"])oe.preventDefault(),bf();else if(Z===z["new-side-tab"])oe.preventDefault(),pz(oe.target)?fz():bf();else if(Z===z["new-btw-tab"])oe.preventDefault(),mz();else if(Z===z["next-tab"])oe.preventDefault(),de(1);else if(Z===z["prev-tab"])oe.preventDefault(),de(-1);else if(Z===z["toggle-side-panel"])oe.preventDefault(),xn.getState().toggleOpen();else if(Z===z["toggle-side-panel-fullscreen"])oe.preventDefault(),xn.getState().toggleFullscreen();else if(Z===z["close-side-tab"])oe.preventDefault(),gz();else if(Z===z["focus-composer"])oe.preventDefault(),yo();else if(Z===z["find-in-chat"])oe.preventDefault(),RI();else if(Z===z["search-workspace"])oe.preventDefault(),s(!0);else if(!ae){const be=xz(Xj(),Y,z).byBinding.get(Z);if(!be)return;oe.preventDefault();const ze=se.getState(),Ye=ze.activeId?ze.conversations[ze.activeId]:null;Og(be,Ye?Ye.activeTabId??Ye.id:null).then(Ve=>{Ve&&Fe({type:"error",title:be.title,description:Ve})})}}};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[Y]),m.useEffect(()=>{if(!b||!_)return;const z=de=>{de.key==="Escape"&&is.getState().activeNodeId==="local"&&(sc()||(de.preventDefault(),xn.getState().setFullscreen(!1)))};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[b,_]);const U=Oz(Lz(Xg,{activationConstraint:{distance:6}})),ee=sh(),L=ee!=="mobile"&&!T&&!H,Q=m.useCallback(z=>{const de=E.current;if(!de)return;const X=getComputedStyle(de),oe=de.clientWidth-parseFloat(X.paddingLeft)-parseFloat(X.paddingRight);xn.getState().nudgeWidth(-z,oe,L?v_:Pg)},[L]),V=F&&!T?i.jsx(VJ,{}):null,ce=L&&(ee==="mac"||ee==="windows"||ee==="web"),ve=ce&&b&&!u&&!H&&!T,_e=T?null:i.jsx("button",{type:"button",className:W("flex items-center justify-center rounded-md transition-colors hover:bg-accent/50",u?"h-9 w-9":L?jc:"h-7 w-7",(H?N:b)?"text-foreground":"text-muted-foreground"),onClick:H?S:C,"aria-label":x("Toggle side panel"),title:x("Toggle side panel"),children:i.jsx(DN,{className:"h-4 w-4"})}),De=i.jsx("button",{type:"button",className:W("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:()=>Se.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(ZV,{className:"h-4 w-4"}):i.jsx(s4,{className:"h-4 w-4"})}),me=i.jsxs(i.Fragment,{children:[De,_e]}),$=L?{trailing:De}:null;return i.jsxs("div",{"data-enso":"canvas",className:W("relative isolate flex flex-col",u?"h-dvh":"h-screen"),children:[i.jsx(az,{}),i.jsx(lz,{}),i.jsx(D4,{}),i.jsx(dz,{}),ee!=="mobile"?i.jsx(R0,{leading:i.jsxs("div",{className:"flex items-center gap-0.5",children:[!T&&i.jsx("div",{className:W(ee!=="mac"&&"flex justify-center",ee!=="mac"&&(L?"w-[48px]":"w-12")),children:i.jsx("button",{type:"button","data-enso":"sidebar-toggle",className:jc,onClick:()=>c(z=>!z),title:x(d?"Expand sidebar":"Collapse sidebar"),children:d?i.jsx(TN,{className:"h-4 w-4"}):i.jsx(Px,{className:"h-4 w-4"})})}),L&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-enso":"search-button",className:jc,onClick:()=>s(!0),title:x("Search anything"),children:i.jsx(ti,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"new-session",className:jc,onClick:bf,title:x("New conversation"),children:i.jsx(EN,{className:"h-4 w-4"})})]})]}),centered:(ve&&_?null:V)??void 0,className:W(ee!=="mac"&&!T&&"pl-0",L&&"border-b-0",L&&"bg-transparent",L&&ee==="mac"&&"pr-4"),actions:L?ve?void 0:_e:me}):i.jsx(R0,{title:"EnsoCode",centered:V??void 0,leading:u&&!T&&!H?i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("button",{type:"button","data-enso":"sidebar-toggle",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(j6,{className:"h-5 w-5"})}),!V&&i.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"EnsoCode"})]}):void 0,actions:me}),!L&&i.jsx(ww,{}),!L&&i.jsx(yw,{}),i.jsx("div",{className:"flex min-h-0 flex-1",children:T?i.jsx(Pne,{nodeId:D,sidebarWidth:a}):H?i.jsx(OJ,{sidebarWidth:a,collapsed:d,onToggleCollapse:()=>c(z=>!z),onResize:B}):i.jsxs(z3,{sensors:U,collisionDetection:rle,children:[u?i.jsxs(i.Fragment,{children:[i.jsx(fl,{children:p&&i.jsx(Rs.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(Rs.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:ea,inert:!p,children:i.jsx(hC,{width:Math.min(320,Math.round(h*.85)),collapsed:!1,onToggleCollapse:g,onOpenSearch:()=>s(!0),onNavigate:g})})]}):i.jsxs(i.Fragment,{children:[i.jsx(hC,{width:d?void 0:a,collapsed:d,onToggleCollapse:()=>c(z=>!z),onOpenSearch:()=>s(!0)}),!d&&i.jsx(Cu,{edge:L,onResize:B})]}),i.jsxs("div",{ref:E,className:W("relative flex min-h-0 min-w-0 flex-1",ce?"overflow-x-clip":"overflow-hidden",L&&"-mt-px -ml-px pt-px pr-[8px] pb-[8px] pl-px"),children:[i.jsxs("div",{"data-enso":"main",className:W("flex min-h-0 min-w-0 flex-1 flex-col bg-background",L&&"overflow-hidden rounded-[10px] shadow-surface",ve&&"rounded-r-none"),style:b&&_?{visibility:"hidden",transition:`visibility 0s ${Iu.duration}s`}:void 0,children:[i.jsx(qae,{}),i.jsx(cz.Provider,{value:$,children:i.jsx(fte,{})}),L&&i.jsx(ww,{}),L&&i.jsx(yw,{})]}),b&&!_&&!u&&i.jsx(Cu,{gap:L&&!ve,onResize:Q,onResizingChange:I}),i.jsx(jae,{width:w,resizing:A,card:L,titleRow:ce})]})]})}),t&&!e&&!window.electronAPI.remote&&i.jsx(Mne,{}),i.jsx(sse,{open:n,onOpenChange:s}),i.jsx(s_,{open:o!==null,onOpenChange:z=>{!z&&o&&k("cancel")},children:i.jsxs(i_,{className:"sm:max-w-sm",children:[i.jsxs(o_,{children:[i.jsx(r_,{className:"text-base",children:x("Confirm exit")}),i.jsx(a_,{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(l_,{variant:"bare",children:[i.jsx(uz,{render:i.jsx(fe,{variant:"outline",size:"sm"}),children:x("Cancel")}),i.jsx(fe,{size:"sm",onClick:()=>k("tray"),children:x("Minimize to tray")}),i.jsx(fe,{variant:"destructive",size:"sm",onClick:()=>k("quit"),children:x("Exit")})]})]})})]})}function lle(e){return new Worker(""+new URL("worker-DsKBD11i.js",import.meta.url).href,{type:"module",name:e?.name})}const dle={workerFactory:()=>new lle,poolSize:2},cle={theme:va,langs:[...bz],preferredHighlighter:"shiki-js"};function ule({children:e}){return i.jsx(vz,{poolOptions:dle,highlighterOptions:cle,children:e})}function Ek({conversations:e,activeId:t}){const n=document.documentElement.dataset,s=Ite(e),o=cE(t?e[t]:void 0,e);n.ensoActivity!==s&&(n.ensoActivity=s),n.ensoSession!==o&&(n.ensoSession=o)}function hle(){Ek(se.getState()),se.subscribe((e,t)=>{(e.conversations!==t.conversations||e.activeId!==t.activeId)&&Ek(e)})}wz();hle();yz();uj();Sz.createRoot(document.getElementById("root")).render(i.jsx(m.StrictMode,{children:i.jsx(ule,{children:i.jsx(ale,{})})}));
|