@ensocode/server 0.3.5 → 0.3.7
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-k76opPl1.js → abnfDiagram-VCTEODGH-2-rZfXru.js} +1 -1
- package/out/phone/assets/architecture-7GRP2DOG-yfAdIxfu.js +1 -0
- package/out/phone/assets/{architectureDiagram-5GKGNRK7-yxQH9IuZ.js → architectureDiagram-5GKGNRK7-vlXme2Q3.js} +1 -1
- package/out/phone/assets/{blockDiagram-I7D4REHJ-DoHteZpO.js → blockDiagram-I7D4REHJ-BD1NeeU7.js} +1 -1
- package/out/phone/assets/{c4Diagram-7LVT6UL2-DQVO6L4q.js → c4Diagram-7LVT6UL2-BLQd5mqT.js} +1 -1
- package/out/phone/assets/channel-D8BkMJGk.js +1 -0
- package/out/phone/assets/{chunk-4HAMMTFA-N9Rw4SGW.js → chunk-4HAMMTFA-CxF_O9R8.js} +1 -1
- package/out/phone/assets/{chunk-75Z2AOVW-DKJ8pOxp.js → chunk-75Z2AOVW-DmshWRC4.js} +1 -1
- package/out/phone/assets/{chunk-DU6HZSFF-BqGW8Nbd.js → chunk-DU6HZSFF-CZrdwMNN.js} +1 -1
- package/out/phone/assets/{chunk-F27PBJKO-PkFmkghF.js → chunk-F27PBJKO-ColBn-9C.js} +1 -1
- package/out/phone/assets/{chunk-GMAD6QVW-C9VeD3Jk.js → chunk-GMAD6QVW-CJN3ap1i.js} +1 -1
- package/out/phone/assets/{chunk-GVQU2GXP-COhntOeE.js → chunk-GVQU2GXP-h3qKgG9R.js} +1 -1
- package/out/phone/assets/{chunk-IMKFNOWR-B87ghLVD.js → chunk-IMKFNOWR-CZRKz_sn.js} +1 -1
- package/out/phone/assets/{chunk-L3NEJ4N5-C3N2izjg.js → chunk-L3NEJ4N5-CMO7DEvv.js} +1 -1
- package/out/phone/assets/{chunk-OSK3NFVY-DaAlvVhz.js → chunk-OSK3NFVY-C5uece6k.js} +1 -1
- package/out/phone/assets/{chunk-P2QGCYS3-BQpKr8IZ.js → chunk-P2QGCYS3-WgQBUDEk.js} +1 -1
- package/out/phone/assets/{chunk-POPQ4Y6H-B2TZMY6U.js → chunk-POPQ4Y6H-VHLT_ckM.js} +1 -1
- package/out/phone/assets/{chunk-PWAF6VOD-CgRhpUJy.js → chunk-PWAF6VOD-AIbXljX0.js} +1 -1
- package/out/phone/assets/{chunk-SHT3W25Y-BySMFA99.js → chunk-SHT3W25Y-Bxg4nJYZ.js} +1 -1
- package/out/phone/assets/{chunk-SVP7TREG-EDGanDUX.js → chunk-SVP7TREG-C4_nxyeQ.js} +1 -1
- package/out/phone/assets/{chunk-TICWLB2K-BtCZ8R2k.js → chunk-TICWLB2K-B5wDGVGC.js} +1 -1
- package/out/phone/assets/classDiagram-ZZMXUADV-CIHzXafb.js +1 -0
- package/out/phone/assets/classDiagram-v2-VYDZK3BY-CIHzXafb.js +1 -0
- package/out/phone/assets/{cynefin-OW5HDTMX-CdZmp44V.js → cynefin-OW5HDTMX-IUYlkNoA.js} +1 -1
- package/out/phone/assets/{cynefinDiagram-5FMLGOSQ-BCz9KwUb.js → cynefinDiagram-5FMLGOSQ-ciimhepC.js} +1 -1
- package/out/phone/assets/{dagre-GXQ25YYZ-CgFeNgh6.js → dagre-GXQ25YYZ-Dk3tslas.js} +1 -1
- package/out/phone/assets/{desk-C_b7mE6l.js → desk-9dPB4fYu.js} +1 -1
- package/out/phone/assets/{diagram-S7CK7UJ4-CwvaZIBf.js → diagram-S7CK7UJ4-BhDokNwG.js} +1 -1
- package/out/phone/assets/{diagram-UQ7AKVKN-DqnD4XoZ.js → diagram-UQ7AKVKN-CciyntsZ.js} +1 -1
- package/out/phone/assets/{diagram-VSXAHHWV-Kqc9GudQ.js → diagram-VSXAHHWV-BG3YhyOX.js} +1 -1
- package/out/phone/assets/{diagram-VX7I27RA-B_0DLDQ0.js → diagram-VX7I27RA-Wx7x7olQ.js} +1 -1
- package/out/phone/assets/{diagram-Z3DM3KII-CppKBEPW.js → diagram-Z3DM3KII-CcI8MVzR.js} +1 -1
- package/out/phone/assets/{ebnfDiagram-PWID7BFC-DeYPNCu9.js → ebnfDiagram-PWID7BFC-Cug1-9Ha.js} +1 -1
- package/out/phone/assets/{erDiagram-RLTQ6QDP-MsfxDUmk.js → erDiagram-RLTQ6QDP-kjxgMXRS.js} +1 -1
- package/out/phone/assets/eventmodeling-NTZA5JFV-CTu3xjKC.js +1 -0
- package/out/phone/assets/flowDiagram-HODETNUW-EMW1nWtZ.js +1 -0
- package/out/phone/assets/{ganttDiagram-EL5Y4UJY-DaScS1os.js → ganttDiagram-EL5Y4UJY-Ci67p8ni.js} +1 -1
- package/out/phone/assets/{gitGraph-4MIJSDKK-C-FzqpZm.js → gitGraph-4MIJSDKK-Bq5w_SFd.js} +1 -1
- package/out/phone/assets/{gitGraphDiagram-WWUBYQGX-4Yv-hAwf.js → gitGraphDiagram-WWUBYQGX-6MPAWIQP.js} +1 -1
- package/out/phone/assets/{info-A6RAGUB7-CGLEP4t7.js → info-A6RAGUB7-D05oiQx3.js} +1 -1
- package/out/phone/assets/{infoDiagram-27XIBGKW-DapEgYQa.js → infoDiagram-27XIBGKW-DEMR262W.js} +1 -1
- package/out/phone/assets/{ishikawaDiagram-5VMMS53U-D1B2lZSG.js → ishikawaDiagram-5VMMS53U-D54EdxMb.js} +1 -1
- package/out/phone/assets/{journeyDiagram-3NMN7TZE-BSAtMVJw.js → journeyDiagram-3NMN7TZE-BIEdfqGB.js} +1 -1
- package/out/phone/assets/{kanban-definition-UXKFOSKX-CfZ4oI7A.js → kanban-definition-UXKFOSKX-Ps-NZDsh.js} +1 -1
- package/out/phone/assets/{line-DAXmUM4p.js → line-DGUUioP5.js} +1 -1
- package/out/phone/assets/main-DYdpq0Gx.css +1 -0
- package/out/phone/assets/{main-B0yD1pMI.js → main-Do_3fZm7.js} +107 -107
- package/out/phone/assets/{mermaid-parser.core-IObm7oM0.js → mermaid-parser.core-BkNZLgza.js} +3 -3
- package/out/phone/assets/{mermaid.core-C1wA-mhD.js → mermaid.core-nEcMItTa.js} +4 -4
- package/out/phone/assets/{mindmap-definition-YA3MSWOX-3ph0EaB9.js → mindmap-definition-YA3MSWOX-DZvLJVDS.js} +1 -1
- package/out/phone/assets/{packet-AYTQ26CC-BbDAe9Au.js → packet-AYTQ26CC-BORABWaG.js} +1 -1
- package/out/phone/assets/{pegDiagram-XKGWAZYB-EsuDcX_3.js → pegDiagram-XKGWAZYB-CGyyPNG0.js} +1 -1
- package/out/phone/assets/{pie-WAS4IAKB-BQfIj1fu.js → pie-WAS4IAKB-DXKTNLO7.js} +1 -1
- package/out/phone/assets/{pieDiagram-E7YTZNPT-Cw19z5Ip.js → pieDiagram-E7YTZNPT-BHlAnBZb.js} +1 -1
- package/out/phone/assets/{quadrantDiagram-AXDQQJYC-Bqwz_sa8.js → quadrantDiagram-AXDQQJYC-CYx8zP0Z.js} +1 -1
- package/out/phone/assets/{radar-RG4KPBEZ-Dmp-89iD.js → radar-RG4KPBEZ-mYzEXGPZ.js} +1 -1
- package/out/phone/assets/{railroad-74A4TZTK-dq2H8w8Y.js → railroad-74A4TZTK-BpSoFKZI.js} +1 -1
- package/out/phone/assets/railroad-abnf-HS5TGJTU-C8SKwwnT.js +1 -0
- package/out/phone/assets/railroad-ebnf-LZEXJU2U-RhLt9QbJ.js +1 -0
- package/out/phone/assets/railroad-peg-WCYAUIDC-_H7Uu52_.js +1 -0
- package/out/phone/assets/{railroadDiagram-O6MQD6OU-D2Sbc7Wn.js → railroadDiagram-O6MQD6OU-BAlwhvnj.js} +1 -1
- package/out/phone/assets/{requirementDiagram-BXWQKSXE-CLNUqxbl.js → requirementDiagram-BXWQKSXE-C2R7ulaS.js} +1 -1
- package/out/phone/assets/{sankeyDiagram-P5KCCOFB-Dme5iwcw.js → sankeyDiagram-P5KCCOFB-c0sv5hNV.js} +1 -1
- package/out/phone/assets/{sequenceDiagram-WJ2MYXX4-C5dYSwPE.js → sequenceDiagram-WJ2MYXX4-Cz6Zq57N.js} +1 -1
- package/out/phone/assets/{stateDiagram-D77RDMKH-BuxkPvJ6.js → stateDiagram-D77RDMKH-DZhgDUa6.js} +1 -1
- package/out/phone/assets/stateDiagram-v2-MP3YSRHH-nNiD0itH.js +1 -0
- package/out/phone/assets/{swimlanes-42K2YHIH-DHyXnytv.js → swimlanes-42K2YHIH-ByNqwNMl.js} +1 -1
- package/out/phone/assets/swimlanesDiagram-VR7AAH4N-Dz8lzRW1.js +8 -0
- package/out/phone/assets/{timeline-definition-24CTP7MA-Bm8Z0u2Z.js → timeline-definition-24CTP7MA-CSFOYvnV.js} +1 -1
- package/out/phone/assets/{treeView-Q6P3EWNA-DFUxvDDO.js → treeView-Q6P3EWNA-CDqEDufz.js} +1 -1
- package/out/phone/assets/{treemap-WGGIJYW6-CMC-hwzt.js → treemap-WGGIJYW6-DfjCLTFL.js} +1 -1
- package/out/phone/assets/{vennDiagram-4TSXK5OY-CNL4gZsd.js → vennDiagram-4TSXK5OY-CjV_vvWy.js} +1 -1
- package/out/phone/assets/{wardley-WFR3VGLG-CHQoq9KJ.js → wardley-WFR3VGLG-Df2M8YsO.js} +1 -1
- package/out/phone/assets/{wardleyDiagram-VM6X3IG4-DAuBfK1O.js → wardleyDiagram-VM6X3IG4-B2bcg9of.js} +1 -1
- package/out/phone/assets/{xychartDiagram-S5SC5T6Z-B2T9ECKd.js → xychartDiagram-S5SC5T6Z-Fq1wBYKM.js} +1 -1
- package/out/phone/desk.html +1 -1
- package/out/phone/index.html +2 -2
- package/out/renderer/assets/{abnfDiagram-VCTEODGH-gdhrQbX6.js → abnfDiagram-VCTEODGH-DMPmG_xF.js} +1 -1
- package/out/renderer/assets/{arc-D6-Q4l2d.js → arc-DjMiWCQZ.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-5GKGNRK7-C4y0SbLT.js → architectureDiagram-5GKGNRK7-Dy1W4IYD.js} +1 -1
- package/out/renderer/assets/{blockDiagram-I7D4REHJ-DrsoSFRK.js → blockDiagram-I7D4REHJ-B8zx5UuN.js} +1 -1
- package/out/renderer/assets/{c4Diagram-7LVT6UL2-1DD8BlM8.js → c4Diagram-7LVT6UL2-D7MZ3XeI.js} +1 -1
- package/out/renderer/assets/channel-BCPz1zGb.js +1 -0
- package/out/renderer/assets/{chunk-2Q5K7J3B-DRyc0B7g.js → chunk-2Q5K7J3B-BEMGeNvl.js} +1 -1
- package/out/renderer/assets/{chunk-5VM5RSS4-BJe8SghE.js → chunk-5VM5RSS4-CTB_kPAW.js} +1 -1
- package/out/renderer/assets/{chunk-F27PBJKO-BIipq4SK.js → chunk-F27PBJKO-CDc0IpL4.js} +1 -1
- package/out/renderer/assets/{chunk-IMKFNOWR-D5Ak3Xd9.js → chunk-IMKFNOWR-5NElfs8W.js} +1 -1
- package/out/renderer/assets/{chunk-JWPE2WC7-BcaWCpW-.js → chunk-JWPE2WC7-DfZ55eH3.js} +1 -1
- package/out/renderer/assets/{chunk-POPQ4Y6H-C1TwLrrN.js → chunk-POPQ4Y6H-BK1Mb8zQ.js} +1 -1
- package/out/renderer/assets/{chunk-SVP7TREG-DDOXG_t3.js → chunk-SVP7TREG-BTCzRhBg.js} +1 -1
- package/out/renderer/assets/{chunk-TICWLB2K-BqT15hZi.js → chunk-TICWLB2K-BIdRdQio.js} +1 -1
- package/out/renderer/assets/{chunk-XXDRQBXY-D01ts6SC.js → chunk-XXDRQBXY-xdEJ7eED.js} +1 -1
- package/out/renderer/assets/classDiagram-ZZMXUADV-D5itFA4H.js +1 -0
- package/out/renderer/assets/classDiagram-v2-VYDZK3BY-D5itFA4H.js +1 -0
- package/out/renderer/assets/{cose-bilkent-JH36ORCC-C7NVrT2_.js → cose-bilkent-JH36ORCC-Dbeuy5zT.js} +1 -1
- package/out/renderer/assets/{cynefin-OW5HDTMX-2LxdFmSk.js → cynefin-OW5HDTMX-DYk68iql.js} +1 -1
- package/out/renderer/assets/{cynefinDiagram-5FMLGOSQ-_AN_Mulc.js → cynefinDiagram-5FMLGOSQ-CW9N3zhw.js} +1 -1
- package/out/renderer/assets/{cytoscape-fcose-COZkZZmX.js → cytoscape-fcose-BtmodGyv.js} +1 -1
- package/out/renderer/assets/{dagre-GXQ25YYZ-BUTwlM6j.js → dagre-GXQ25YYZ-xTaBduGi.js} +1 -1
- package/out/renderer/assets/{diagram-S7CK7UJ4-CseZZ-y2.js → diagram-S7CK7UJ4-Okomm8Ap.js} +1 -1
- package/out/renderer/assets/{diagram-UQ7AKVKN-Cb7llS-8.js → diagram-UQ7AKVKN-CvzlGwuY.js} +1 -1
- package/out/renderer/assets/{diagram-VSXAHHWV-CtuGqQvp.js → diagram-VSXAHHWV-BJtbgGmH.js} +1 -1
- package/out/renderer/assets/{diagram-VX7I27RA-BA8eov-1.js → diagram-VX7I27RA-vefJMKYp.js} +1 -1
- package/out/renderer/assets/{diagram-Z3DM3KII-VZOjj6Hg.js → diagram-Z3DM3KII-ChsgoF9h.js} +1 -1
- package/out/renderer/assets/{ebnfDiagram-PWID7BFC-YBIrle6d.js → ebnfDiagram-PWID7BFC-D9X9DUcr.js} +1 -1
- package/out/renderer/assets/{erDiagram-RLTQ6QDP-BiKyPEqW.js → erDiagram-RLTQ6QDP-C024iQV7.js} +1 -1
- package/out/renderer/assets/{flowDiagram-HODETNUW-7wmZyLHw.js → flowDiagram-HODETNUW-CPVYCBuI.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-EL5Y4UJY-D4j4GJaT.js → ganttDiagram-EL5Y4UJY-C65Z220Q.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-WWUBYQGX-BqveM1NI.js → gitGraphDiagram-WWUBYQGX-B2ZCfyVT.js} +1 -1
- package/out/renderer/assets/{globals-C9M_MZZV.js → globals-B4auqknW.js} +153 -153
- package/out/renderer/assets/globals-biae1A0_.css +1 -0
- package/out/renderer/assets/index-XLAcGpdw.js +117 -0
- package/out/renderer/assets/{infoDiagram-27XIBGKW-DLPLnIFP.js → infoDiagram-27XIBGKW-D7RgOT5Z.js} +1 -1
- package/out/renderer/assets/{ishikawaDiagram-5VMMS53U-48drIAMR.js → ishikawaDiagram-5VMMS53U-CEyzfHnV.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-3NMN7TZE-vjigqUq_.js → journeyDiagram-3NMN7TZE-C1GjLzvL.js} +1 -1
- package/out/renderer/assets/{kanban-definition-UXKFOSKX-CpsYVONZ.js → kanban-definition-UXKFOSKX-umALrvd6.js} +1 -1
- package/out/renderer/assets/{layout-DqfoORoO.js → layout-CPiirD-6.js} +1 -1
- package/out/renderer/assets/{linear-CJzBBHcp.js → linear-DeKsEgmD.js} +1 -1
- package/out/renderer/assets/{mermaid.core-DdrGP-Hn.js → mermaid.core-upLR8Tou.js} +5 -5
- package/out/renderer/assets/{mindmap-definition-YA3MSWOX-D68tLNxp.js → mindmap-definition-YA3MSWOX-CDpc91To.js} +1 -1
- package/out/renderer/assets/{pegDiagram-XKGWAZYB-DkgLTcrv.js → pegDiagram-XKGWAZYB-ZWCzr3Tm.js} +1 -1
- package/out/renderer/assets/{pieDiagram-E7YTZNPT-bz5NuX1w.js → pieDiagram-E7YTZNPT-Cli5NL_V.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-AXDQQJYC-o_VKLyJA.js → quadrantDiagram-AXDQQJYC-DyHSkgko.js} +1 -1
- package/out/renderer/assets/{railroadDiagram-O6MQD6OU-Dkf03e07.js → railroadDiagram-O6MQD6OU-BifUAJjm.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-BXWQKSXE-CBUz_3YU.js → requirementDiagram-BXWQKSXE-4vjbe8oI.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-P5KCCOFB-B0pjUr9g.js → sankeyDiagram-P5KCCOFB-BDHiusDD.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-WJ2MYXX4-ClugIL0e.js → sequenceDiagram-WJ2MYXX4-CfTMNjuO.js} +1 -1
- package/out/renderer/assets/settings-B1-ZqHbd.js +34 -0
- package/out/renderer/assets/{sizeCapture-INFHLROL-D6y0rctc.js → sizeCapture-INFHLROL-BInsctow.js} +1 -1
- package/out/renderer/assets/{stateDiagram-D77RDMKH-DiftQepS.js → stateDiagram-D77RDMKH-3R4s4xE6.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-DqJbnbM3.js +1 -0
- package/out/renderer/assets/{swimlanes-42K2YHIH-DhuTjCNj.js → swimlanes-42K2YHIH-CHnfm1qW.js} +1 -1
- package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-Gz8US82e.js +8 -0
- package/out/renderer/assets/{timeline-definition-24CTP7MA-CrXqgptd.js → timeline-definition-24CTP7MA-BSOSQ438.js} +1 -1
- package/out/renderer/assets/{vennDiagram-4TSXK5OY-CDm8SO8U.js → vennDiagram-4TSXK5OY-Bw_mOynV.js} +1 -1
- package/out/renderer/assets/{wardleyDiagram-VM6X3IG4-CxyunHwQ.js → wardleyDiagram-VM6X3IG4-DZF4RS4h.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-S5SC5T6Z-CvC5YMSy.js → xychartDiagram-S5SC5T6Z-DwVUcf5G.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 +5 -4
- package/out/server/chunks/{agent-_G_O-Cpa.js → agent-BlAuVqNp.js} +4 -2
- package/out/server/chunks/{gpuBackendInstall-Cb6TFh_8.js → gpuBackendInstall-C0fP_8jk.js} +4 -4
- package/out/server/chunks/{loadProvider-Be9Lu1Oi.js → loadProvider-1NxA7GHt.js} +2 -2
- package/out/server/chunks/{manifest-CB63GQ-i.js → manifest-CojWIAHB.js} +2 -2
- package/out/server/chunks/{workflowPresets-Djlp5LPV.js → workflowPresets-COTLnY4e.js} +71 -17
- package/out/server/index.js +310 -54
- package/out/server/plugin-host.js +33 -3
- package/package.json +1 -1
- package/out/phone/assets/architecture-7GRP2DOG-DFA8x3QF.js +0 -1
- package/out/phone/assets/channel-BBjWfdZr.js +0 -1
- package/out/phone/assets/classDiagram-ZZMXUADV-CXXjdIIU.js +0 -1
- package/out/phone/assets/classDiagram-v2-VYDZK3BY-CXXjdIIU.js +0 -1
- package/out/phone/assets/eventmodeling-NTZA5JFV-D4a6gbOs.js +0 -1
- package/out/phone/assets/flowDiagram-HODETNUW-BBTtB5oX.js +0 -1
- package/out/phone/assets/main-DNRbLxEx.css +0 -1
- package/out/phone/assets/railroad-abnf-HS5TGJTU-DddVaVQM.js +0 -1
- package/out/phone/assets/railroad-ebnf-LZEXJU2U-BjvyqMjh.js +0 -1
- package/out/phone/assets/railroad-peg-WCYAUIDC-lBl4CV1_.js +0 -1
- package/out/phone/assets/stateDiagram-v2-MP3YSRHH-Exd8xDBD.js +0 -1
- package/out/phone/assets/swimlanesDiagram-VR7AAH4N-B62_42fO.js +0 -8
- package/out/renderer/assets/channel-Sck-tAAK.js +0 -1
- package/out/renderer/assets/classDiagram-ZZMXUADV-DnB4QNNe.js +0 -1
- package/out/renderer/assets/classDiagram-v2-VYDZK3BY-DnB4QNNe.js +0 -1
- package/out/renderer/assets/globals-l3kDGoYH.css +0 -1
- package/out/renderer/assets/index-BzSTiwH2.js +0 -117
- package/out/renderer/assets/settings-DvhrDn2q.js +0 -34
- package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-DxB2-9tl.js +0 -1
- package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-CYDUqExO.js +0 -8
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
import{r as m,eP as Ne,eQ as Us,j as i,c as ot,eR as r0,eS as a0,eT as vA,eU as Wk,eV as bA,bi as Uk,q as ye,eW as fn,eX as Jh,eY as Nf,eZ as wA,e_ as yA,e$ as SA,dq as oe,f0 as Xr,cT as Dg,cA as is,f1 as de,f2 as CA,p as se,f3 as Ig,Z as Cn,J as ze,dj as Kk,au as oc,X as ln,aQ as kA,cO as mi,e as U,d2 as qk,cj as $o,aB as oa,f4 as jA,f5 as _A,f6 as Yk,cm as l0,bd as un,f7 as Xk,cn as va,bQ as ra,dv as yo,f8 as NA,ax as Eg,f9 as Pg,fa as TA,fb as DA,fc as IA,fd as EA,fe as Il,ff as ba,fg as ho,fh as PA,fi as AA,fj as MA,fk as xs,fl as jd,fm as RA,fn as LA,fo as El,fp as Pl,fq as Ai,fr as Zh,fs as OA,ft as _d,fu as Dr,fv as zA,fw as GA,fx as FA,fy as HA,fz as BA,fA as VA,fB as Qh,fC as Vr,fD as c0,fE as Jk,fF as d0,fG as $A,fH as WA,fI as Jr,fJ as UA,fK as ri,fL as KA,fM as dr,fN as Zk,fO as u0,fP as aa,fQ as qA,fR as Ec,fS as YA,fT as XA,fU as JA,fV as ZA,fW as h0,fX as Qk,fY as Tf,fZ as QA,f_ as eM,f$ as ej,g0 as tM,g1 as p0,g2 as tj,g3 as nM,g4 as sM,g5 as Df,g6 as iM,g7 as nj,g8 as oM,g9 as rM,ga as aM,gb as lM,gc as cM,gd as f0,ge as dM,gf as uM,gg as hM,gh as m0,gi as ep,gj as pM,gk as fM,gl as mM,gm as sj,gn as Gr,go as Za,gp as cr,gq as ij,gr as tp,gs as If,gt as gM,gu as Ku,gv as xM,gw as vM,gx as bM,gy as Aa,gz as wM,gA as yM,gB as SM,gC as oj,gD as CM,gE as kM,gF as jM,gG as _M,gH as NM,gI as rj,gJ as aj,gK as so,gL as TM,gM as DM,gN as g0,gO as IM,gP as qu,gQ as lj,cW as la,cU as rc,cV as wa,bu as ca,eA as Vs,$ as ac,gR as EM,gS as PM,gT as AM,gU as MM,gV as RM,gW as LM,gX as OM,gY as zM,gZ as GM,g_ as FM,g$ as HM,h0 as BM,a5 as Ag,ah as VM,h1 as $M,h2 as WM,h3 as UM,h4 as KM,h5 as qM,h6 as YM,h7 as XM,a6 as cj,h8 as JM,h9 as ZM,ha as QM,hb as eR,b as lc,hc as tR,hd as nR,he as sR,hf as iR,hg as oR,hh as rR,d as aR,hi as lR,hj as cR,hk as dR,hl as uR,dr as hR,ct as dj,eB as Yu,hm as pR,cZ as uj,hn as Zn,cz as Kn,bN as Xu,e7 as ti,ho as _s,hp as Un,hq as fR,bb as Ju,ba as mR,co as hj,bZ as Vn,hr as po,hs as fo,ht as mo,hu as Vt,hv as gR,aC as br,hw as xR,hx as vR,di as Zu,ch as pj,bk as Wo,hy as x0,ci as bR,hz as wR,at as Yt,hA as v0,hB as fj,hC as mj,hD as yR,hE as SR,hF as gj,hG as CR,hH as kR,hI as jR,hJ as _R,hK as NR,hL as TR,hM as DR,hN as IR,hO as ER,hP as PR,hQ as AR,hR as Pc,hS as gi,hT as xi,hU as vi,aR as ms,hV as MR,hW as RR,hX as LR,hY as OR,hZ as b0,bP as zR,h_ as GR,h$ as xj,i0 as FR,cp as Mg,i1 as HR,i2 as vj,i3 as BR,cH as So,s as vn,i4 as VR,v as bn,x as wn,y as yn,E as Mn,i5 as w0,i6 as $R,i7 as WR,eD as bj,i8 as UR,i9 as KR,ia as qR,B as xe,ib as Qu,ew as hi,b4 as Ef,em as y0,bJ as Rg,bf as Ma,bj as ni,dg as wj,ic as YR,id as yj,ie as XR,ig as JR,ih as ZR,ii as QR,ij as Pf,ik as Sj,il as e2,im as t2,bv as Hs,io as n2,ip as s2,iq as i2,ir as o2,is as r2,it as a2,iu as l2,iv as Cj,iw as S0,ix as C0,iy as c2,iz as k0,iA as Af,iB as Mf,iC as $r,iD as d2,iE as u2,iF as h2,iG as j0,iH as p2,iI as f2,iJ as m2,iK as _0,iL as g2,iM as np,iN as sp,iO as x2,df as cc,el as kj,bt as us,iP as dc,iQ as uc,bM as Bs,iR as v2,iS as b2,iT as w2,iU as y2,iV as S2,iW as C2,iX as k2,cl as go,iY as j2,iZ as jj,i_ as _2,i$ as Xd,j0 as _j,j1 as Jd,ei as N2,j2 as T2,ey as Nj,de as gr,cQ as Al,j3 as D2,j4 as Tj,j5 as N0,cJ as Oi,j6 as I2,j7 as E2,j8 as P2,j9 as Dj,bI as sn,ja as Ij,jb as A2,jc as M2,jd as xo,je as R2,jf as Ej,jg as Pj,jh as Aj,ji as Ml,jj as L2,jk as O2,jl as z2,jm as Rf,jn as G2,jo as F2,jp as H2,jq as B2,jr as V2,js as $2,jt as W2,ju as U2,jv as K2,jw as q2,z as As,bh as Y2,G as rs,jx as X2,bX as qt,bg as Lg,c2 as Mj,aS as di,I as Jt,jy as T0,jz as D0,jA as I0,F as hc,jB as Rl,cd as ip,eb as op,c3 as Qs,jC as J2,jD as Rj,jE as Z2,jF as Ss,jG as Q2,ek as Og,O as vs,P as bs,Q as ws,R as ys,T as os,bW as zg,jH as Lf,jI as Of,jJ as zf,bE as eh,bF as th,bG as Is,bH as oo,c1 as Lj,jK as Oj,jL as zj,jM as rl,jN as Zd,jO as Gj,jP as eL,jQ as tL,jR as nL,jS as Gg,jT as sL,jU as iL,jV as Fj,d_ as Hi,d$ as Bi,e1 as Vi,e5 as mn,jW as Hj,jX as Bj,jY as Vj,e3 as ya,cr as Fg,jZ as $j,j_ as nh,j$ as Ns,b_ as Wj,bT as oL,bU as rL,c4 as aL,k0 as lL,c6 as cL,k1 as dL,k2 as Uj,k3 as uL,k4 as hL,k5 as pL,k6 as fL,k7 as Kj,k8 as mL,k9 as gL,ka as xL,kb as wr,kc as Hg,kd as Qa,ke as Bg,kf as Vg,d7 as sh,d9 as ih,ck as ei,d8 as oh,ej as qj,ep as Sa,kg as vL,kh as Yj,ki as Xj,kj as bL,kk as al,av as rh,kl as Jj,km as $g,kn as Zj,cu as Ca,ko as Qj,kp as wL,db as yL,da as SL,kq as CL,A as kL,kr as jL,ks as _L,n as NL,kt as TL,ku as DL,kv as IL,m as EL,kw as PL,kx as AL,C as ML,f as e_,h as RL,i as LL,k as OL,S as zL,l as GL,o as FL,ky as HL,kz as BL,kA as VL,kB as $L,kC as WL,kD as UL,kE as t_,cN as ai,kF as KL,cq as da,eF as Gf,kG as qL,kH as YL,kI as Wg,kJ as n_,kK as s_,kL as i_,kM as ah,kN as XL,kO as JL,kP as ZL,bD as o_,bL as ir,bC as QL,kQ as e5,kR as r_,kS as Ir,bK as E0,bS as t5,kT as n5,b$ as P0,es as lh,kU as A0,eE as s5,kV as a_,kW as l_,kX as Ug,dP as i5,kY as c_,kZ as o5,k_ as r5,k$ as a5,l0 as d_,l1 as u_,l2 as Kg,ex as l5,l3 as c5,l4 as d5,l5 as u5,l6 as h5,l7 as rp,l8 as M0,l9 as p5,et as h_,la as f5,lb as qg,en as m5,cE as Os,cF as zs,lc as p_,ld as g5,le as x5,lf as v5,lg as b5,lh as w5,ez as Qd,li as y5,lj as S5,lk as C5,ll as k5,lm as f_,ln as j5,lo as _5,cw as N5,lp as T5,dI as m_,lq as Yg,lr as D5,dl as g_,ls as I5,lt as R0,lu as E5,lv as P5,d5 as A5,d4 as M5,dh as R5,eC as L5,lw as x_,lx as Ff,aD as v_,aE as b_,aF as w_,aG as y_,aH as S_,aI as C_,ly as Nd,lz as k_,er as O5,lA as Hf,lB as z5,aK as Xg,lC as eu,lD as tu,lE as Ll,dG as Bf,lF as G5,lG as F5,lH as H5,aN as ch,lI as Jg,e9 as L0,e8 as B5,lJ as hs,lK as In,lL as Mo,lM as j_,aO as V5,lN as nu,lO as Lo,ce as $5,cD as W5,lP as U5,lQ as __,lR as Fr,lS as K5,lT as N_,lU as q5,lV as Y5,lW as X5,cy as O0,lX as J5,lY as T_,lZ as z0,cs as Vf,e0 as Zg,l_ as Z5,cG as Q5,l$ as eO,m0 as tO,m1 as $f,m2 as nO,b3 as sO,cC as iO,m3 as oO,eo as rO,dx as aO,m4 as lO,dR as cO,dS as dO,cI as uO,m5 as hO,eq as pO,ea as fO,m6 as mO,m7 as gO,m8 as D_,m9 as Qg,ma as I_,mb as xO,mc as vO,md as bO,me as wO,mf as yO,mg as SO,mh as CO,mi as G0,mj as E_,mk as ex,dk as kO,ml as dh,mm as Ac,mn as jO,mo as _O,mp as NO,mq as TO,mr as DO,ms as IO,mt as EO,mu as PO,mv as AO,mw as MO,mx as F0,my as RO,mz as LO,mA as OO,cX as zO,bc as GO,mB as FO,mC as ap,bO as H0,cY as HO,c_ as BO,mD as VO,mE as $O,mF as B0,mG as WO,mH as UO,mI as KO,mJ as Wf,mK as P_,mL as qO,mM as YO,mN as XO,mO as JO,mP as A_,mQ as ZO,mR as QO,mS as ez,mT as tz,mU as nz,mV as sz,mW as ao,mX as iz,mY as oz,mZ as rz,m_ as az,m$ as lz,n0 as cz,n1 as dz,n2 as V0,n3 as $0,n4 as uz,cS as hz,n5 as pz,n6 as fz,n7 as mz,n8 as gz,n9 as xz,dy as vz,na as bz,nb as W0,nc as wz,nd as yz,ne as M_,e6 as Sz,nf as Cz,ng as kz,nh as jz,eM as _z,eN as Nz,eJ as Tz,eO as U0,eK as Dz,aJ as Iz,ni as Ez,nj as Pz,nk as Az,nl as Mz,nm as Rz,cP as Lz,nn as Oz,no as zz,eG as Gz,eH as Fz,eI as Hz}from"./globals-C9M_MZZV.js";function Bz(){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 uh=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ka(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function tx(e){return"nodeType"in e}function Ts(e){var t,n;return e?ka(e)?e:tx(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function nx(e){const{Document:t}=Ts(e);return e instanceof t}function pc(e){return ka(e)?!1:e instanceof Ts(e).HTMLElement}function R_(e){return e instanceof Ts(e).SVGElement}function ja(e){return e?ka(e)?e.document:tx(e)?nx(e)?e:pc(e)||R_(e)?e.ownerDocument:document:document:document}const bi=uh?m.useLayoutEffect:m.useEffect;function hh(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 Vz(){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 Ol(e,t){t===void 0&&(t=[e]);const n=m.useRef(e);return bi(()=>{n.current!==e&&(n.current=e)},t),n}function fc(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=hh(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 lp={};function mc(e,t){return m.useMemo(()=>{if(t)return t;const n=lp[e]==null?0:lp[e]+1;return lp[e]=n,e+"-"+n},[e,t])}function L_(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[c,d]of l){const u=r[c];u!=null&&(r[c]=u+e*d)}return r},{...t})}}const Zr=L_(1),ou=L_(-1);function $z(e){return"clientX"in e&&"clientY"in e}function ph(e){if(!e)return!1;const{KeyboardEvent:t}=Ts(e.target);return t&&e instanceof t}function Wz(e){if(!e)return!1;const{TouchEvent:t}=Ts(e.target);return t&&e instanceof t}function ru(e){if(Wz(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 $z(e)?{x:e.clientX,y:e.clientY}:null}const Gi=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[Gi.Translate.toString(e),Gi.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:s}=e;return t+" "+n+"ms "+s}}}),K0="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Uz(e){return e.matches(K0)?e:e.querySelector(K0)}const Kz={display:"none"};function qz(e){let{id:t,value:n}=e;return Ne.createElement("div",{id:t,style:Kz},n)}function Yz(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 Xz(){const[e,t]=m.useState("");return{announce:m.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const O_=m.createContext(null);function z_(e){const t=m.useContext(O_);m.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function Jz(){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 Zz={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
|
-
`},Qz={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 e3(e){let{announcements:t=Qz,container:n,hiddenTextDescribedById:s,screenReaderInstructions:o=Zz}=e;const{announce:r,announcement:a}=Xz(),l=mc("DndLiveRegion"),[c,d]=m.useState(!1);if(m.useEffect(()=>{d(!0)},[]),z_(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])),!c)return null;const u=Ne.createElement(Ne.Fragment,null,Ne.createElement(qz,{id:s,value:o.draggable}),Ne.createElement(Yz,{id:l,announcement:a}));return n?Us.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 t3(e,t){return m.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function n3(){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 s3(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function i3(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 o3(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return n-s}function r3(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return s-n}function a3(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 l3(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function c3(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 c=t.width*t.height,d=e.width*e.height,u=a*l,h=u/(c+d-u);return Number(h.toFixed(4))}return 0}const G_=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 c=c3(l,t);c>0&&o.push({id:a,data:{droppableContainer:r,value:c}})}}return o.sort(r3)};function d3(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 u3=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&&d3(s,l)){const d=a3(l).reduce((h,p)=>h+s3(s,p),0),u=Number((d/4).toFixed(4));o.push({id:a,data:{droppableContainer:r,value:u}})}}return o.sort(o3)};function h3(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function F_(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:wi}function p3(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 f3=p3(1);function H_(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 m3(e,t,n){const s=H_(t);if(!s)return e;const{scaleX:o,scaleY:r,x:a,y:l}=s,c=e.left-a-(1-o)*parseFloat(n),d=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:d,right:c+u,bottom:d+h,left:c}}const g3={ignoreTransform:!1};function _a(e,t){t===void 0&&(t=g3);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Ts(e).getComputedStyle(e);d&&(n=m3(n,d,u))}const{top:s,left:o,width:r,height:a,bottom:l,right:c}=n;return{top:s,left:o,width:r,height:a,bottom:l,right:c}}function q0(e){return _a(e,{ignoreTransform:!0})}function x3(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function v3(e,t){return t===void 0&&(t=Ts(e).getComputedStyle(e)),t.position==="fixed"}function b3(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 sx(e,t){const n=[];function s(o){if(t!=null&&n.length>=t||!o)return n;if(nx(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!pc(o)||R_(o)||n.includes(o))return n;const r=Ts(e).getComputedStyle(o);return o!==e&&b3(o,r)&&n.push(o),v3(o,r)?n:s(o.parentNode)}return e?s(e):n}function B_(e){const[t]=sx(e,1);return t??null}function cp(e){return!uh||!e?null:ka(e)?e:tx(e)?nx(e)||e===ja(e).scrollingElement?window:pc(e)?e:null:null}function V_(e){return ka(e)?e.scrollX:e.scrollLeft}function $_(e){return ka(e)?e.scrollY:e.scrollTop}function Uf(e){return{x:V_(e),y:$_(e)}}var ss;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ss||(ss={}));function W_(e){return!uh||!e?!1:e===document.scrollingElement}function U_(e){const t={x:0,y:0},n=W_(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 w3={x:.2,y:.2};function y3(e,t,n,s,o){let{top:r,left:a,right:l,bottom:c}=n;s===void 0&&(s=10),o===void 0&&(o=w3);const{isTop:d,isBottom:u,isLeft:h,isRight:p}=U_(e),f={x:0,y:0},g={x:0,y:0},x={height:t.height*o.y,width:t.width*o.x};return!d&&r<=t.top+x.height?(f.y=ss.Backward,g.y=s*Math.abs((t.top+x.height-r)/x.height)):!u&&c>=t.bottom-x.height&&(f.y=ss.Forward,g.y=s*Math.abs((t.bottom-x.height-c)/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 K_(e){return e.reduce((t,n)=>Zr(t,Uf(n)),wi)}function C3(e){return e.reduce((t,n)=>t+V_(n),0)}function k3(e){return e.reduce((t,n)=>t+$_(n),0)}function q_(e,t){if(t===void 0&&(t=_a),!e)return;const{top:n,left:s,bottom:o,right:r}=t(e);B_(e)&&(o<=0||r<=0||n>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const j3=[["x",["left","right"],C3],["y",["top","bottom"],k3]];class ix{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=sx(n),o=K_(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[r,a,l]of j3)for(const c of a)Object.defineProperty(this,c,{get:()=>{const d=l(s),u=o[r]-d;return this.rect[c]+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 _3(e){const{EventTarget:t}=Ts(e);return e instanceof t?e:ja(e)}function dp(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 Ws;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Ws||(Ws={}));function Y0(e){e.preventDefault()}function N3(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 Y_={start:[pn.Space,pn.Enter],cancel:[pn.Esc],end:[pn.Space,pn.Enter,pn.Tab]},T3=(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 X_{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(ja(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(Ws.Resize,this.handleCancel),this.windowListeners.add(Ws.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Ws.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,s=t.node.current;s&&q_(s),n(wi)}handleKeyDown(t){if(ph(t)){const{active:n,context:s,options:o}=this.props,{keyboardCodes:r=Y_,coordinateGetter:a=T3,scrollBehavior:l="smooth"}=o,{code:c}=t;if(r.end.includes(c)){this.handleEnd(t);return}if(r.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:d}=s.current,u=d?{x:d.left,y:d.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:C,maxScroll:_,minScroll:N}=U_(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&&!C||v===pn.Up&&!y;if(A&&k.x!==h.x){const D=x.scrollLeft+p.x,P=v===pn.Right&&D<=_.x||v===pn.Left&&D>=N.x;if(P&&!p.y){x.scrollTo({left:D,behavior:l});return}P?f.x=x.scrollLeft-D:f.x=v===pn.Right?x.scrollLeft-_.x:x.scrollLeft-N.x,f.x&&x.scrollBy({left:-f.x,behavior:l});break}else if(I&&k.y!==h.y){const D=x.scrollTop+p.y,P=v===pn.Down&&D<=_.y||v===pn.Up&&D>=N.y;if(P&&!p.x){x.scrollTo({top:D,behavior:l});return}P?f.y=x.scrollTop-D:f.y=v===pn.Down?x.scrollTop-_.y:x.scrollTop-N.y,f.y&&x.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(t,Zr(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()}}X_.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:s=Y_,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 X0(e){return!!(e&&"distance"in e)}function J0(e){return!!(e&&"delay"in e)}class ox{constructor(t,n,s){var o;s===void 0&&(s=_3(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=ja(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(Ws.Resize,this.handleCancel),this.windowListeners.add(Ws.DragStart,Y0),this.windowListeners.add(Ws.VisibilityChange,this.handleCancel),this.windowListeners.add(Ws.ContextMenu,Y0),this.documentListeners.add(Ws.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(J0(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(X0(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(Ws.Click,N3,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Ws.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 c=(n=ru(t))!=null?n:wi,d=ou(o,c);if(!s&&l){if(X0(l)){if(l.tolerance!=null&&dp(d,l.tolerance))return this.handleCancel();if(dp(d,l.distance))return this.handleStart()}if(J0(l)&&dp(d,l.tolerance))return this.handleCancel();this.handlePending(l,d);return}t.cancelable&&t.preventDefault(),a(c)}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 D3={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class rx extends ox{constructor(t){const{event:n}=t,s=ja(n.target);super(t,D3,s)}}rx.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 I3={move:{name:"mousemove"},end:{name:"mouseup"}};var Kf;(function(e){e[e.RightClick=2]="RightClick"})(Kf||(Kf={}));class E3 extends ox{constructor(t){super(t,I3,ja(t.event.target))}}E3.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return n.button===Kf.RightClick?!1:(s?.({event:n}),!0)}}];const up={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class P3 extends ox{constructor(t){super(t,up)}static setup(){return window.addEventListener(up.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(up.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 cl;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(cl||(cl={}));var lu;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(lu||(lu={}));function A3(e){let{acceleration:t,activator:n=cl.Pointer,canScroll:s,draggingRect:o,enabled:r,interval:a=5,order:l=lu.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:p}=e;const f=R3({delta:h,disabled:!r}),[g,x]=Vz(),v=m.useRef({x:0,y:0}),y=m.useRef({x:0,y:0}),b=m.useMemo(()=>{switch(n){case cl.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case cl.DraggableRect:return o}},[n,o,c]),w=m.useRef(null),C=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)},[]),_=m.useMemo(()=>l===lu.TreeOrder?[...d].reverse():d,[l,d]);m.useEffect(()=>{if(!r||!d.length||!b){x();return}for(const N of _){if(s?.(N)===!1)continue;const S=d.indexOf(N),k=u[S];if(!k)continue;const{direction:A,speed:I}=y3(N,k,b,t,p);for(const D of["x","y"])f[D][A[D]]||(I[D]=0,A[D]=0);if(I.x>0||I.y>0){x(),w.current=N,g(C,a),v.current=I,y.current=A;return}}v.current={x:0,y:0},y.current={x:0,y:0},x()},[t,C,s,x,r,a,JSON.stringify(b),JSON.stringify(f),g,d,_,u,JSON.stringify(p)])}const M3={x:{[ss.Backward]:!1,[ss.Forward]:!1},y:{[ss.Backward]:!1,[ss.Forward]:!1}};function R3(e){let{delta:t,disabled:n}=e;const s=iu(t);return fc(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 L3(e,t){const n=t!=null?e.get(t):void 0,s=n?n.node.current:null;return fc(o=>{var r;return t==null?null:(r=s??o)!=null?r:null},[s,t])}function O3(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 zl;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(zl||(zl={}));var qf;(function(e){e.Optimized="optimized"})(qf||(qf={}));const Z0=new Map;function z3(e,t){let{dragging:n,dependencies:s,config:o}=t;const[r,a]=m.useState(null),{frequency:l,measure:c,strategy:d}=o,u=m.useRef(e),h=v(),p=Ol(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=fc(y=>{if(h&&!n)return Z0;if(!y||y===Z0||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 C=w.node.current,_=C?new ix(c(C),C):null;w.rect.current=_,_&&b.set(w.id,_)}return b}return y},[e,r,n,h,c]);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(d){case zl.Always:return!1;case zl.BeforeDragging:return n;default:return!n}}}function ax(e,t){return fc(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function G3(e,t){return ax(e,t)}function F3(e){let{callback:t,disabled:n}=e;const s=hh(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 fh(e){let{callback:t,disabled:n}=e;const s=hh(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 H3(e){return new ix(_a(e),e)}function Q0(e,t,n){t===void 0&&(t=H3);const[s,o]=m.useState(null);function r(){o(c=>{if(!e)return null;if(e.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(e);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const a=F3({callback(c){if(e)for(const d of c){const{type:u,target:h}=d;if(u==="childList"&&h instanceof HTMLElement&&h.contains(e)){r();break}}}}),l=fh({callback:r});return bi(()=>{r(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),s}function B3(e){const t=ax(e);return F_(e,t)}const eb=[];function V3(e){const t=m.useRef(e),n=fc(s=>e?s&&s!==eb&&e&&t.current&&e.parentNode===t.current.parentNode?s:sx(e):eb,[e]);return m.useEffect(()=>{t.current=e},[e]),n}function $3(e){const[t,n]=m.useState(null),s=m.useRef(e),o=m.useCallback(r=>{const a=cp(r.target);a&&n(l=>l?(l.set(a,Uf(a)),new Map(l)):null)},[]);return m.useEffect(()=>{const r=s.current;if(e!==r){a(r);const l=e.map(c=>{const d=cp(c);return d?(d.addEventListener("scroll",o,{passive:!0}),[d,Uf(d)]):null}).filter(c=>c!=null);n(l.length?new Map(l):null),s.current=e}return()=>{a(e),a(r)};function a(l){l.forEach(c=>{const d=cp(c);d?.removeEventListener("scroll",o)})}},[o,e]),m.useMemo(()=>e.length?t?Array.from(t.values()).reduce((r,a)=>Zr(r,a),wi):K_(e):wi,[e,t])}function tb(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 W3(e){m.useEffect(()=>{if(!uh)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 U3(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 J_(e){return m.useMemo(()=>e?x3(e):null,[e])}const nb=[];function K3(e,t){t===void 0&&(t=_a);const[n]=e,s=J_(n?Ts(n):null),[o,r]=m.useState(nb);function a(){r(()=>e.length?e.map(c=>W_(c)?s:new ix(t(c),c)):nb)}const l=fh({callback:a});return bi(()=>{l?.disconnect(),a(),e.forEach(c=>l?.observe(c))},[e]),o}function Z_(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return pc(t)?t:e}function q3(e){let{measure:t}=e;const[n,s]=m.useState(null),o=m.useCallback(d=>{for(const{target:u}of d)if(pc(u)){s(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),r=fh({callback:o}),a=m.useCallback(d=>{const u=Z_(d);r?.disconnect(),u&&r?.observe(u),s(u?t(u):null)},[t,r]),[l,c]=su(a);return m.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const Y3=[{sensor:rx,options:{}},{sensor:X_,options:{}}],X3={current:{}},Td={draggable:{measure:q0},droppable:{measure:q0,strategy:zl.WhileDragging,frequency:qf.Optimized},dragOverlay:{measure:_a}};class dl 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 J3={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new dl,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:au},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Td,measureDroppableContainers:au,windowRect:null,measuringScheduled:!1},Q_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:au,draggableNodes:new Map,over:null,measureDroppableContainers:au},gc=m.createContext(Q_),e1=m.createContext(J3);function Z3(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new dl}}}function Q3(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 dl(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 dl(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 dl(e.droppable.containers);return r.delete(n),{...e,droppable:{...e.droppable,containers:r}}}default:return e}}function eG(e){let{disabled:t}=e;const{active:n,activatorEvent:s,draggableNodes:o}=m.useContext(gc),r=iu(s),a=iu(n?.id);return m.useEffect(()=>{if(!t&&!s&&r&&a!=null){if(!ph(r)||document.activeElement===r.target)return;const l=o.get(a);if(!l)return;const{activatorNode:c,node:d}=l;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const u of[c.current,d.current]){if(!u)continue;const h=Uz(u);if(h){h.focus();break}}})}},[s,t,o,a,r]),null}function t1(e,t){let{transform:n,...s}=t;return e!=null&&e.length?e.reduce((o,r)=>r({transform:o,...s}),n):n}function tG(e){return m.useMemo(()=>({draggable:{...Td.draggable,...e?.draggable},droppable:{...Td.droppable,...e?.droppable},dragOverlay:{...Td.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function nG(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 d=t?.node.current;if(!d||d.isConnected===!1)return;const u=n(d),h=F_(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=B_(d);p&&p.scrollBy({top:h.y,left:h.x})}},[t,a,l,s,n])}const mh=m.createContext({...wi,scaleX:1,scaleY:1});var Eo;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Eo||(Eo={}));const sG=m.memo(function(t){var n,s,o,r;let{id:a,accessibility:l,autoScroll:c=!0,children:d,sensors:u=Y3,collisionDetection:h=G_,measuring:p,modifiers:f,...g}=t;const x=m.useReducer(Q3,void 0,Z3),[v,y]=x,[b,w]=Jz(),[C,_]=m.useState(Eo.Uninitialized),N=C===Eo.Initialized,{draggable:{active:S,nodes:k,translate:A},droppable:{containers:I}}=v,D=S!=null?k.get(S):null,P=m.useRef({initial:null,translated:null}),T=m.useMemo(()=>{var K;return S!=null?{id:S,data:(K=D?.data)!=null?K:X3,rect:P}:null},[S,D]),z=m.useRef(null),[O,L]=m.useState(null),[V,X]=m.useState(null),F=Ol(g,Object.values(g)),ee=mc("DndDescribedBy",a),H=m.useMemo(()=>I.getEnabled(),[I]),Q=tG(p),{droppableRects:q,measureDroppableContainers:ne,measuringScheduled:me}=z3(H,{dragging:N,dependencies:[A.x,A.y],config:Q.droppable}),ke=L3(k,S),Me=m.useMemo(()=>V?ru(V):null,[V]),ge=pt(),$=G3(ke,Q.draggable.measure);nG({activeNode:S!=null?k.get(S):null,config:ge.layoutShiftCompensation,initialRect:$,measure:Q.draggable.measure});const W=Q0(ke,Q.draggable.measure,$),ue=Q0(ke?ke.parentElement:null),Z=m.useRef({activatorEvent:null,active:null,activeNode:ke,collisionRect:null,collisions:null,droppableRects:q,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:I,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),J=I.getNodeFor((n=Z.current.over)==null?void 0:n.id),ae=q3({measure:Q.dragOverlay.measure}),te=(s=ae.nodeRef.current)!=null?s:ke,pe=N?(o=ae.rect)!=null?o:W:null,Te=!!(ae.nodeRef.current&&ae.rect),$e=B3(Te?null:W),Ie=J_(te?Ts(te):null),Ze=V3(N?J??ke:null),Nt=K3(Ze),Ut=t1(f,{transform:{x:A.x-$e.x,y:A.y-$e.y,scaleX:1,scaleY:1},activatorEvent:V,active:T,activeNodeRect:W,containerNodeRect:ue,draggingNodeRect:pe,over:Z.current.over,overlayNodeRect:ae.rect,scrollableAncestors:Ze,scrollableAncestorRects:Nt,windowRect:Ie}),Pt=Me?Zr(Me,A):null,_t=$3(Ze),B=tb(_t),je=tb(_t,[W]),Ye=Zr(Ut,B),Tt=pe?f3(pe,Ut):null,Wt=T&&Tt?h({active:T,collisionRect:Tt,droppableRects:q,droppableContainers:H,pointerCoordinates:Pt}):null,le=l3(Wt,"id"),[ht,Ot]=m.useState(null),Fe=Te?Ut:Zr(Ut,je),jt=h3(Fe,(r=ht?.rect)!=null?r:null,W),Ft=m.useRef(null),cn=m.useCallback((K,fe)=>{let{sensor:De,options:Pe}=fe;if(z.current==null)return;const Ge=k.get(z.current);if(!Ge)return;const st=K.nativeEvent,we=new De({active:z.current,activeNode:Ge,event:st,options:Pe,context:Z,onAbort(it){if(!k.get(it))return;const{onDragAbort:Xt}=F.current,E={id:it};Xt?.(E),b({type:"onDragAbort",event:E})},onPending(it,yt,Xt,E){if(!k.get(it))return;const{onDragPending:M}=F.current,j={id:it,constraint:yt,initialCoordinates:Xt,offset:E};M?.(j),b({type:"onDragPending",event:j})},onStart(it){const yt=z.current;if(yt==null)return;const Xt=k.get(yt);if(!Xt)return;const{onDragStart:E}=F.current,R={activatorEvent:st,active:{id:yt,data:Xt.data,rect:P}};Us.unstable_batchedUpdates(()=>{E?.(R),_(Eo.Initializing),y({type:Qn.DragStart,initialCoordinates:it,active:yt}),b({type:"onDragStart",event:R}),L(Ft.current),X(st)})},onMove(it){y({type:Qn.DragMove,coordinates:it})},onEnd:Qe(Qn.DragEnd),onCancel:Qe(Qn.DragCancel)});Ft.current=we;function Qe(it){return async function(){const{active:Xt,collisions:E,over:R,scrollAdjustedTranslate:M}=Z.current;let j=null;if(Xt&&M){const{cancelDrop:G}=F.current;j={activatorEvent:st,active:Xt,collisions:E,delta:M,over:R},it===Qn.DragEnd&&typeof G=="function"&&await Promise.resolve(G(j))&&(it=Qn.DragCancel)}z.current=null,Us.unstable_batchedUpdates(()=>{y({type:it}),_(Eo.Uninitialized),Ot(null),L(null),X(null),Ft.current=null;const G=it===Qn.DragEnd?"onDragEnd":"onDragCancel";if(j){const he=F.current[G];he?.(j),b({type:G,event:j})}})}}},[k]),re=m.useCallback((K,fe)=>(De,Pe)=>{const Ge=De.nativeEvent,st=k.get(Pe);if(z.current!==null||!st||Ge.dndKit||Ge.defaultPrevented)return;const we={active:st};K(De,fe.options,we)===!0&&(Ge.dndKit={capturedBy:fe.sensor},z.current=Pe,cn(De,fe))},[k,cn]),Ue=O3(u,re);W3(u),bi(()=>{W&&C===Eo.Initializing&&_(Eo.Initialized)},[W,C]),m.useEffect(()=>{const{onDragMove:K}=F.current,{active:fe,activatorEvent:De,collisions:Pe,over:Ge}=Z.current;if(!fe||!De)return;const st={active:fe,activatorEvent:De,collisions:Pe,delta:{x:Ye.x,y:Ye.y},over:Ge};Us.unstable_batchedUpdates(()=>{K?.(st),b({type:"onDragMove",event:st})})},[Ye.x,Ye.y]),m.useEffect(()=>{const{active:K,activatorEvent:fe,collisions:De,droppableContainers:Pe,scrollAdjustedTranslate:Ge}=Z.current;if(!K||z.current==null||!fe||!Ge)return;const{onDragOver:st}=F.current,we=Pe.get(le),Qe=we&&we.rect.current?{id:we.id,rect:we.rect.current,data:we.data,disabled:we.disabled}:null,it={active:K,activatorEvent:fe,collisions:De,delta:{x:Ge.x,y:Ge.y},over:Qe};Us.unstable_batchedUpdates(()=>{Ot(Qe),st?.(it),b({type:"onDragOver",event:it})})},[le]),bi(()=>{Z.current={activatorEvent:V,active:T,activeNode:ke,collisionRect:Tt,collisions:Wt,droppableRects:q,draggableNodes:k,draggingNode:te,draggingNodeRect:pe,droppableContainers:I,over:ht,scrollableAncestors:Ze,scrollAdjustedTranslate:Ye},P.current={initial:pe,translated:Tt}},[T,ke,Wt,Tt,k,te,pe,q,I,ht,Ze,Ye]),A3({...ge,delta:A,draggingRect:Tt,pointerCoordinates:Pt,scrollableAncestors:Ze,scrollableAncestorRects:Nt});const ut=m.useMemo(()=>({active:T,activeNode:ke,activeNodeRect:W,activatorEvent:V,collisions:Wt,containerNodeRect:ue,dragOverlay:ae,draggableNodes:k,droppableContainers:I,droppableRects:q,over:ht,measureDroppableContainers:ne,scrollableAncestors:Ze,scrollableAncestorRects:Nt,measuringConfiguration:Q,measuringScheduled:me,windowRect:Ie}),[T,ke,W,V,Wt,ue,ae,k,I,q,ht,ne,Ze,Nt,Q,me,Ie]),xt=m.useMemo(()=>({activatorEvent:V,activators:Ue,active:T,activeNodeRect:W,ariaDescribedById:{draggable:ee},dispatch:y,draggableNodes:k,over:ht,measureDroppableContainers:ne}),[V,Ue,T,W,y,ee,k,ht,ne]);return Ne.createElement(O_.Provider,{value:w},Ne.createElement(gc.Provider,{value:xt},Ne.createElement(e1.Provider,{value:ut},Ne.createElement(mh.Provider,{value:jt},d)),Ne.createElement(eG,{disabled:l?.restoreFocus===!1})),Ne.createElement(e3,{...l,hiddenTextDescribedById:ee}));function pt(){const K=O?.autoScrollEnabled===!1,fe=typeof c=="object"?c.enabled===!1:c===!1,De=N&&!K&&!fe;return typeof c=="object"?{...c,enabled:De}:{enabled:De}}}),iG=m.createContext(null),sb="button",oG="Draggable";function lx(e){let{id:t,data:n,disabled:s=!1,attributes:o}=e;const r=mc(oG),{activators:a,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:p}=m.useContext(gc),{role:f=sb,roleDescription:g="draggable",tabIndex:x=0}=o??{},v=c?.id===t,y=m.useContext(v?mh:iG),[b,w]=su(),[C,_]=su(),N=U3(a,t),S=Ol(n);bi(()=>(h.set(t,{id:t,key:r,node:b,activatorNode:C,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===sb?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[s,f,x,v,g,u.draggable]);return{active:c,activatorEvent:l,activeNodeRect:d,attributes:k,isDragging:v,listeners:s?void 0:N,node:b,over:p,setNodeRef:w,setActivatorNodeRef:_,transform:y}}function xc(){return m.useContext(e1)}const rG="Droppable",aG={timeout:25};function vc(e){let{data:t,disabled:n=!1,id:s,resizeObserverConfig:o}=e;const r=mc(rG),{active:a,dispatch:l,over:c,measureDroppableContainers:d}=m.useContext(gc),u=m.useRef({disabled:n}),h=m.useRef(!1),p=m.useRef(null),f=m.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:v}={...aG,...o},y=Ol(x??s),b=m.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(y.current)?y.current:[y.current]),f.current=null},v)},[v]),w=fh({callback:b,disabled:g||!a}),C=m.useCallback((k,A)=>{w&&(A&&(w.unobserve(A),h.current=!1),k&&w.observe(k))},[w]),[_,N]=su(C),S=Ol(t);return m.useEffect(()=>{!w||!_.current||(w.disconnect(),h.current=!1,w.observe(_.current))},[_,w]),m.useEffect(()=>(l({type:Qn.RegisterDroppable,element:{id:s,key:r,disabled:n,node:_,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:c?.id===s,node:_,over:c,setNodeRef:N}}function lG(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 c=s?.key,d=s?.props.id;if(c==null||d==null){o(null);return}Promise.resolve(t(d,r)).then(()=>{o(null)})},[t,s,r]),Ne.createElement(Ne.Fragment,null,n,s?m.cloneElement(s,{ref:a}):null)}const cG={x:0,y:0,scaleX:1,scaleY:1};function dG(e){let{children:t}=e;return Ne.createElement(gc.Provider,{value:Q_},Ne.createElement(mh.Provider,{value:cG},t))}const uG={position:"fixed",touchAction:"none"},hG=e=>ph(e)?"transform 250ms ease":void 0,pG=m.forwardRef((e,t)=>{let{as:n,activatorEvent:s,adjustScale:o,children:r,className:a,rect:l,style:c,transform:d,transition:u=hG}=e;if(!l)return null;const h=o?d:{...d,scaleX:1,scaleY:1},p={...uG,width:l.width,height:l.height,top:l.top,left:l.left,transform:Gi.Transform.toString(h),transformOrigin:o&&s?i3(s,l):void 0,transition:typeof u=="function"?u(s):u,...c};return Ne.createElement(n,{className:a,style:p,ref:t},r)}),fG=e=>t=>{let{active:n,dragOverlay:s}=t;const o={},{styles:r,className:a}=e;if(r!=null&&r.active)for(const[l,c]of Object.entries(r.active))c!==void 0&&(o[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,c));if(r!=null&&r.dragOverlay)for(const[l,c]of Object.entries(r.dragOverlay))c!==void 0&&s.node.style.setProperty(l,c);return a!=null&&a.active&&n.node.classList.add(a.active),a!=null&&a.dragOverlay&&s.node.classList.add(a.dragOverlay),function(){for(const[c,d]of Object.entries(o))n.node.style.setProperty(c,d);a!=null&&a.active&&n.node.classList.remove(a.active)}},mG=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Gi.Transform.toString(t)},{transform:Gi.Transform.toString(n)}]},gG={duration:250,easing:"ease",keyframes:mG,sideEffects:fG({styles:{active:{opacity:"0"}}})};function xG(e){let{config:t,draggableNodes:n,droppableContainers:s,measuringConfiguration:o}=e;return hh((r,a)=>{if(t===null)return;const l=n.get(r);if(!l)return;const c=l.node.current;if(!c)return;const d=Z_(a);if(!d)return;const{transform:u}=Ts(a).getComputedStyle(a),h=H_(u);if(!h)return;const p=typeof t=="function"?t:vG(t);return q_(c,o.draggable.measure),p({active:{id:r,data:l.data,node:c,rect:o.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:a,rect:o.dragOverlay.measure(d)},droppableContainers:s,measuringConfiguration:o,transform:h})})}function vG(e){const{duration:t,easing:n,sideEffects:s,keyframes:o}={...gG,...e};return r=>{let{active:a,dragOverlay:l,transform:c,...d}=r;if(!t)return;const u={x:l.rect.left-a.rect.left,y:l.rect.top-a.rect.top},h={scaleX:c.scaleX!==1?a.rect.width*c.scaleX/l.rect.width:1,scaleY:c.scaleY!==1?a.rect.height*c.scaleY/l.rect.height:1},p={x:c.x-u.x,y:c.y-u.y,...h},f=o({...d,active:a,dragOverlay:l,transform:{initial:c,final:p}}),[g]=f,x=f[f.length-1];if(JSON.stringify(g)===JSON.stringify(x))return;const v=s?.({active:a,dragOverlay:l,...d}),y=l.node.animate(f,{duration:t,easing:n,fill:"forwards"});return new Promise(b=>{y.onfinish=()=>{v?.(),b()}})}}let ib=0;function bG(e){return m.useMemo(()=>{if(e!=null)return ib++,ib},[e])}const wG=Ne.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:s,style:o,transition:r,modifiers:a,wrapperElement:l="div",className:c,zIndex:d=999}=e;const{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggableNodes:g,droppableContainers:x,dragOverlay:v,over:y,measuringConfiguration:b,scrollableAncestors:w,scrollableAncestorRects:C,windowRect:_}=xc(),N=m.useContext(mh),S=bG(h?.id),k=t1(a,{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggingNodeRect:v.rect,over:y,overlayNodeRect:v.rect,scrollableAncestors:w,scrollableAncestorRects:C,transform:N,windowRect:_}),A=ax(p),I=xG({config:s,draggableNodes:g,droppableContainers:x,measuringConfiguration:b}),D=A?v.setRef:void 0;return Ne.createElement(dG,null,Ne.createElement(lG,{animation:I},h&&S?Ne.createElement(pG,{key:S,id:h.id,ref:D,as:l,activatorEvent:u,adjustScale:t,className:c,transition:r,rect:A,style:{zIndex:d,...o},transform:k},n):null))}),cx=m.createContext({});function dx(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const yG=typeof window<"u",cu=yG?m.useLayoutEffect:m.useEffect,gh=m.createContext(null);function ux(e,t){e.indexOf(t)===-1&&e.push(t)}function du(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const Fi=(e,t,n)=>n>t?t:n<e?e:n;let xh=()=>{};const Oo={},n1=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),s1=e=>typeof e=="object"&&e!==null,i1=e=>/^0[^.\s]+$/u.test(e);function o1(e){let t;return()=>(t===void 0&&(t=e()),t)}const Js=e=>e,bc=(...e)=>e.reduce((t,n)=>s=>n(t(s))),Gl=(e,t,n)=>{const s=t-e;return s?(n-e)/s:1};class hx{constructor(){this.subscriptions=[]}add(t){return ux(this.subscriptions,t),()=>du(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,Ks=e=>e/1e3,r1=(e,t)=>t?e*(1e3/t):0,a1=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,SG=1e-7,CG=12;function kG(e,t,n,s,o){let r,a,l=0;do a=t+(n-t)/2,r=a1(a,s,o)-e,r>0?n=a:t=a;while(Math.abs(r)>SG&&++l<CG);return a}function wc(e,t,n,s){if(e===t&&n===s)return Js;const o=r=>kG(r,0,1,e,n);return r=>r===0||r===1?r:a1(o(r),t,s)}const l1=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,c1=e=>t=>1-e(1-t),d1=wc(.33,1.53,.69,.99),px=c1(d1),u1=l1(px),h1=e=>e>=1?1:(e*=2)<1?.5*px(e):.5*(2-Math.pow(2,-10*(e-1))),fx=e=>1-Math.sin(Math.acos(e)),p1=c1(fx),f1=l1(fx),jG=wc(.42,0,1,1),_G=wc(0,0,.58,1),m1=wc(.42,0,.58,1),NG=e=>Array.isArray(e)&&typeof e[0]!="number",g1=e=>Array.isArray(e)&&typeof e[0]=="number",TG={linear:Js,easeIn:jG,easeInOut:m1,easeOut:_G,circIn:fx,circInOut:f1,circOut:p1,backIn:px,backInOut:u1,backOut:d1,anticipate:h1},DG=e=>typeof e=="string",ob=e=>{if(g1(e)){xh(e.length===4);const[t,n,s,o]=e;return wc(t,n,s,o)}else if(DG(e))return TG[e];return e},Mc=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function IG(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(d){r.has(d)&&(c.schedule(d),e()),d(a)}const c={schedule:(d,u=!1,h=!1)=>{const f=h&&s?t:n;return u&&r.add(d),f.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0;const u=t;t=n,n=u,t.forEach(l),t.clear(),s=!1,o&&(o=!1,c.process(d))}};return c}const EG=40;function x1(e,t){let n=!1,s=!0;const o={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,a=Mc.reduce((w,C)=>(w[C]=IG(r),w),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:p,render:f,postRender:g}=a,x=()=>{const w=Oo.useManualTiming,C=w?o.timestamp:performance.now();n=!1,w||(o.delta=s?1e3/60:Math.max(Math.min(C-o.timestamp,EG),1)),o.timestamp=C,o.isProcessing=!0,l.process(o),c.process(o),d.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:Mc.reduce((w,C)=>{const _=a[C];return w[C]=(N,S=!1,k=!1)=>(n||v(),_.schedule(N,S,k)),w},{}),cancel:w=>{for(let C=0;C<Mc.length;C++)a[Mc[C]].cancel(w)},state:o,steps:a}}const{schedule:_n,cancel:zo,state:cs,steps:hp}=x1(typeof requestAnimationFrame<"u"?requestAnimationFrame:Js,!0);let Dd;function PG(){Dd=void 0}const Cs={now:()=>(Dd===void 0&&Cs.set(cs.isProcessing||Oo.useManualTiming?cs.timestamp:performance.now()),Dd),set:e=>{Dd=e,queueMicrotask(PG)}},v1=e=>t=>typeof t=="string"&&t.startsWith(e),b1=v1("--"),AG=v1("var(--"),mx=e=>AG(e)?MG.test(e.split("/*")[0].trim()):!1,MG=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function rb(e){return typeof e!="string"?!1:e.split("/*")[0].includes("var(--")}const Na={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Fl={...Na,transform:e=>Fi(0,1,e)},Rc={...Na,default:1},ul=e=>Math.round(e*1e5)/1e5,gx=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function RG(e){return e==null}const LG=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,xx=(e,t)=>n=>!!(typeof n=="string"&&LG.test(n)&&n.startsWith(e)||t&&!RG(n)&&Object.prototype.hasOwnProperty.call(n,t)),w1=(e,t,n)=>s=>{if(typeof s!="string")return s;const[o,r,a,l]=s.match(gx);return{[e]:parseFloat(o),[t]:parseFloat(r),[n]:parseFloat(a),alpha:l!==void 0?parseFloat(l):1}},OG=e=>Fi(0,255,e),pp={...Na,transform:e=>Math.round(OG(e))},ur={test:xx("rgb","red"),parse:w1("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+pp.transform(e)+", "+pp.transform(t)+", "+pp.transform(n)+", "+ul(Fl.transform(s))+")"};function zG(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 Yf={test:xx("#"),parse:zG,transform:ur.transform},yc=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),eo=yc("deg"),zi=yc("%"),vt=yc("px"),GG=yc("vh"),FG=yc("vw"),ab={...zi,parse:e=>zi.parse(e)/100,transform:e=>zi.transform(e*100)},Wr={test:xx("hsl","hue"),parse:w1("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+zi.transform(ul(t))+", "+zi.transform(ul(n))+", "+ul(Fl.transform(s))+")"},$n={test:e=>ur.test(e)||Yf.test(e)||Wr.test(e),parse:e=>ur.test(e)?ur.parse(e):Wr.test(e)?Wr.parse(e):Yf.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?ur.transform(e):Wr.transform(e),getAnimatableNone:e=>{const t=$n.parse(e);return t.alpha=0,$n.transform(t)}},HG=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function BG(e){return isNaN(e)&&typeof e=="string"&&(e.match(gx)?.length||0)+(e.match(HG)?.length||0)>0}const y1="number",S1="color",VG="var",$G="var(",lb="${}",WG=/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 ua(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},o=[];let r=0;const l=t.replace(WG,c=>($n.test(c)?(s.color.push(r),o.push(S1),n.push($n.parse(c))):c.startsWith($G)?(s.var.push(r),o.push(VG),n.push(c)):(s.number.push(r),o.push(y1),n.push(parseFloat(c))),++r,lb)).split(lb);return{values:n,split:l,indexes:s,types:o}}function UG(e){return ua(e).values}function C1({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===y1?o+=ul(s[r]):a===S1?o+=$n.transform(s[r]):o+=s[r]}return o}}function KG(e){return C1(ua(e))}const qG=e=>typeof e=="number"?0:$n.test(e)?$n.getAnimatableNone(e):e,YG=(e,t)=>typeof e=="number"?t?.trim().endsWith("/")?e:0:qG(e);function XG(e){const t=ua(e);return C1(t)(t.values.map((s,o)=>YG(s,t.split[o])))}const pi={test:BG,parse:UG,createTransformer:KG,getAnimatableNone:XG};function fp(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 JG({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,c=2*n-l;o=fp(c,l,e+1/3),r=fp(c,l,e),a=fp(c,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,mp=(e,t,n)=>{const s=e*e,o=n*(t*t-s)+s;return o<0?0:Math.sqrt(o)},ZG=[Yf,ur,Wr],QG=e=>ZG.find(t=>t.test(e));function cb(e){const t=QG(e);if(!t)return!1;let n=t.parse(e);return t===Wr&&(n=JG(n)),n}const db=(e,t)=>{const n=cb(e),s=cb(t);if(!n||!s)return uu(e,t);const o={...n};return r=>(o.red=mp(n.red,s.red,r),o.green=mp(n.green,s.green,r),o.blue=mp(n.blue,s.blue,r),o.alpha=jn(n.alpha,s.alpha,r),ur.transform(o))},Xf=new Set(["none","hidden"]);function eF(e,t){return Xf.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function tF(e,t){return n=>jn(e,t,n)}function vx(e){return typeof e=="number"?tF:typeof e=="string"?mx(e)?uu:$n.test(e)?db:iF:Array.isArray(e)?k1:typeof e=="object"?$n.test(e)?db:nF:uu}function k1(e,t){const n=[...e],s=n.length,o=e.map((r,a)=>vx(r)(r,t[a]));return r=>{for(let a=0;a<s;a++)n[a]=o[a](r);return n}}function nF(e,t){const n={...e,...t},s={};for(const o in n)e[o]!==void 0&&t[o]!==void 0&&(s[o]=vx(e[o])(e[o],t[o]));return o=>{for(const r in s)n[r]=s[r](o);return n}}function sF(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 iF=(e,t)=>{const n=pi.createTransformer(t),s=ua(e),o=ua(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?Xf.has(e)&&!o.values.length||Xf.has(t)&&!s.values.length?eF(e,t):bc(k1(sF(s,o),o.values),n):uu(e,t)};function j1(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?jn(e,t,n):vx(e)(e,t)}const oF=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>_n.update(t,n),stop:()=>zo(t),now:()=>cs.isProcessing?cs.timestamp:Cs.now()}},_1=(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 bx(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 rF(e,t=100,n){const s=n({...e,keyframes:[0,t]}),o=Math.min(bx(s),hu);return{type:"keyframes",ease:r=>s.next(o*r).value/t,duration:Ks(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 Jf(e,t){return e*Math.sqrt(1-t*t)}const aF=12;function lF(e,t,n){let s=n;for(let o=1;o<aF;o++)s=s-e(s)/t(s);return s}const gp=.001;function cF({duration:e=Gn.duration,bounce:t=Gn.bounce,velocity:n=Gn.velocity,mass:s=Gn.mass}){let o,r,a=1-t;a=Fi(Gn.minDamping,Gn.maxDamping,a),e=Fi(Gn.minDuration,Gn.maxDuration,Ks(e)),a<1?(o=d=>{const u=d*a,h=u*e,p=u-n,f=Jf(d,a),g=Math.exp(-h);return gp-p/f*g},r=d=>{const h=d*a*e,p=h*n+n,f=Math.pow(a,2)*Math.pow(d,2)*e,g=Math.exp(-h),x=Jf(Math.pow(d,2),a);return(-o(d)+gp>0?-1:1)*((p-f)*g)/x}):(o=d=>{const u=Math.exp(-d*e),h=(d-n)*e+1;return-gp+u*h},r=d=>{const u=Math.exp(-d*e),h=(n-d)*(e*e);return u*h});const l=5/e,c=lF(o,r,l);if(e=Gs(e),isNaN(c))return{stiffness:Gn.stiffness,damping:Gn.damping,duration:e};{const d=Math.pow(c,2)*s;return{stiffness:d,damping:a*2*Math.sqrt(s*d),duration:e}}}const dF=["duration","bounce"],uF=["stiffness","damping","mass"];function ub(e,t){return t.some(n=>e[n]!==void 0)}function hF(e){let t={velocity:Gn.velocity,stiffness:Gn.stiffness,damping:Gn.damping,mass:Gn.mass,isResolvedFromDuration:!1,...e};if(!ub(e,uF)&&ub(e,dF))if(t.velocity=0,e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),o=s*s,r=2*Fi(.05,1,1-(e.bounce||0))*Math.sqrt(o);t={...t,mass:Gn.mass,stiffness:o,damping:r}}else{const n=cF({...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:c,damping:d,mass:u,duration:h,velocity:p,isResolvedFromDuration:f}=hF({...n,velocity:-Ks(n.velocity||0)}),g=p||0,x=d/(2*Math.sqrt(c*u)),v=a-r,y=Ks(Math.sqrt(c/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)_=Jf(y,x),N=(g+x*y*v)/_,w=I=>{const D=Math.exp(-x*y*I);return a-D*(N*Math.sin(_*I)+v*Math.cos(_*I))},S=x*y*N+v*_,k=x*y*v-N*_,C=I=>Math.exp(-x*y*I)*(S*Math.sin(_*I)+k*Math.cos(_*I));else if(x===1){w=D=>a-Math.exp(-y*D)*(v+(g+y*v)*D);const I=g+y*v;C=D=>Math.exp(-y*D)*(y*I*D-g)}else{const I=y*Math.sqrt(x*x-1);w=z=>{const O=Math.exp(-x*y*z),L=Math.min(I*z,300);return a-O*((g+x*y*v)*Math.sinh(L)+I*v*Math.cosh(L))/I};const D=(g+x*y*v)/I,P=x*y*D-v*I,T=x*y*v-D*I;C=z=>{const O=Math.exp(-x*y*z),L=Math.min(I*z,300);return O*(P*Math.sinh(L)+T*Math.cosh(L))}}const A={calculatedDuration:f&&h||null,velocity:I=>Gs(C(I)),next:I=>{if(!f&&x<1){const P=Math.exp(-x*y*I),T=Math.sin(_*I),z=Math.cos(_*I),O=a-P*(N*T+v*z),L=Gs(P*(S*T+k*z));return l.done=Math.abs(L)<=s&&Math.abs(a-O)<=o,l.value=l.done?a:O,l}const D=w(I);if(f)l.done=I>=h;else{const P=Gs(C(I));l.done=Math.abs(P)<=s&&Math.abs(a-D)<=o}return l.value=l.done?a:D,l},toString:()=>{const I=Math.min(bx(A),hu),D=_1(P=>A.next(I*P).value,I,30);return I+"ms "+D},toTransition:()=>{}};return A}pu.applyToOptions=e=>{const t=rF(e,100,pu);return e.ease=t.ease,e.duration=Gs(t.duration),e.type="keyframes",e};const pF=5;function N1(e,t,n){const s=Math.max(t-pF,0);return r1(n-e(s),t-s)}function Zf({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:o=10,bounceStiffness:r=500,modifyTarget:a,min:l,max:c,restDelta:d=.5,restSpeed:u}){const h=e[0],p={done:!1,value:h},f=k=>l!==void 0&&k<l||c!==void 0&&k>c,g=k=>l===void 0?c:c===void 0||Math.abs(l-k)<Math.abs(c-k)?l:c;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),C=k=>{const A=b(k),I=w(k);p.done=Math.abs(A)<=d,p.value=p.done?y:I};let _,N;const S=k=>{f(p.value)&&(_=k,N=pu({keyframes:[p.value,g(p.value)],velocity:N1(w,k,p.value),damping:o,stiffness:r,restDelta:d,restSpeed:u}))};return S(0),{calculatedDuration:null,next:k=>{let A=!1;return!N&&_===void 0&&(A=!0,C(k),S(k)),_!==void 0&&k>=_?N.next(k-_):(!A&&C(k),p)}}}function fF(e,t,n){const s=[],o=n||Oo.mix||j1,r=e.length-1;for(let a=0;a<r;a++){let l=o(e[a],e[a+1]);if(t){const c=Array.isArray(t)?t[a]||Js:t;l=bc(c,l)}s.push(l)}return s}function mF(e,t,{clamp:n=!0,ease:s,mixer:o}={}){const r=e.length;if(xh(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=fF(t,s,o),c=l.length,d=u=>{if(a&&u<e[0])return t[0];let h=0;if(c>1)for(;h<e.length-2&&!(u<e[h+1]);h++);const p=Gl(e[h],e[h+1],u);return l[h](p)};return n?u=>d(Fi(e[0],e[r-1],u)):d}function gF(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const o=Gl(0,t,s);e.push(jn(n,1,o))}}function xF(e){const t=[0];return gF(t,e.length-1),t}function vF(e,t){return e.map(n=>n*t)}function bF(e,t){return e.map(()=>t||m1).splice(0,e.length-1)}function hl({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const o=NG(s)?s.map(ob):ob(s),r={done:!1,value:t[0]},a=vF(n&&n.length===t.length?n:xF(t),e),l=mF(a,t,{ease:Array.isArray(o)?o:bF(t,o)});return{calculatedDuration:e,next:c=>(r.value=l(c),r.done=c>=e,r)}}const wF=e=>e!==null;function vh(e,{repeat:t,repeatType:n="loop"},s,o=1){const r=e.filter(wF),l=o<0||t&&n!=="loop"&&t%2===1?0:r.length-1;return!l||s===void 0?r[l]:s}const yF={decay:Zf,inertia:Zf,tween:hl,keyframes:hl,spring:pu};function T1(e){typeof e.type=="string"&&(e.type=yF[e.type])}class wx{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 wx{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;T1(t);const{type:n=hl,repeat:s=0,repeatDelay:o=0,repeatType:r,velocity:a=0}=t;let{keyframes:l}=t;const c=n||hl;c!==hl&&typeof l[0]!="number"&&(this.mixKeyframes=bc(SF,j1(l[0],l[1])),l=[0,100]);const d=c({...t,keyframes:l});r==="mirror"&&(this.mirroredGenerator=c({...t,keyframes:[...l].reverse(),velocity:-a})),d.calculatedDuration===null&&(d.calculatedDuration=bx(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+o,this.totalDuration=this.resolvedDuration*(s+1)-o,this.generator=d}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:c}=this;if(this.startTime===null)return s.next(0);const{delay:d=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-d*(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,C=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"&&(C=a)),w=Fi(0,1,I)*l}let _;b?(this.delayState.value=u[0],_=this.delayState):_=C.next(w),r&&!b&&(_.value=r(_.value));let{done:N}=_;!b&&c!==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!==Zf&&(_.value=vh(u,this.options,v,this.speed)),x&&x(_.value),S&&this.finish(),_}then(t,n){return this.finished.then(t,n)}get duration(){return Ks(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ks(t)}get time(){return Ks(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 N1(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=Ks(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=oF,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 CF(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const hr=e=>e*180/Math.PI,Qf=e=>{const t=hr(Math.atan2(e[1],e[0]));return em(t)},kF={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Qf,rotateZ:Qf,skewX:e=>hr(Math.atan(e[1])),skewY:e=>hr(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},em=e=>(e=e%360,e<0&&(e+=360),e),hb=Qf,pb=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),fb=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),jF={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:pb,scaleY:fb,scale:e=>(pb(e)+fb(e))/2,rotateX:e=>em(hr(Math.atan2(e[6],e[5]))),rotateY:e=>em(hr(Math.atan2(-e[2],e[0]))),rotateZ:hb,rotate:hb,skewX:e=>hr(Math.atan(e[4])),skewY:e=>hr(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function tm(e){return e.includes("scale")?1:0}function nm(e,t){if(!e||e==="none")return tm(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,o;if(n)s=jF,o=n;else{const l=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=kF,o=l}if(!o)return tm(t);const r=s[t],a=o[1].split(",").map(NF);return typeof r=="function"?r(a):a[r]}const _F=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return nm(n,t)};function NF(e){return parseFloat(e.trim())}const Ta=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Da=new Set([...Ta,"pathRotation"]),mb=e=>e===Na||e===vt,TF=new Set(["x","y","z"]),DF=Ta.filter(e=>!TF.has(e));function IF(e){const t=[];return DF.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Ro={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})=>nm(t,"x"),y:(e,{transform:t})=>nm(t,"y")};Ro.translateX=Ro.x;Ro.translateY=Ro.y;const xr=new Set;let sm=!1,im=!1,om=!1;function D1(){if(im){const e=Array.from(xr).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const o=IF(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)})}im=!1,sm=!1,xr.forEach(e=>e.complete(om)),xr.clear()}function I1(){xr.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(im=!0)})}function EF(){om=!0,I1(),D1(),om=!1}class yx{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?(xr.add(this),sm||(sm=!0,_n.read(I1),_n.resolveKeyframes(D1))):(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])}CF(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),xr.delete(this)}cancel(){this.state==="scheduled"&&(xr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const PF=e=>e.startsWith("--");function E1(e,t,n){PF(t)?e.style.setProperty(t,n):e.style[t]=n}const AF={};function P1(e,t){const n=o1(e);return()=>AF[t]??n()}const MF=P1(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),A1=P1(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),el=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,gb={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:el([0,.65,.55,1]),circOut:el([.55,0,1,.45]),backIn:el([.31,.01,.66,-.59]),backOut:el([.33,1.53,.69,.99])};function M1(e,t){if(e)return typeof e=="function"?A1()?_1(e,t):"ease-out":g1(e)?el(e):Array.isArray(e)?e.map(n=>M1(n,t)||gb.easeOut):gb[e]}function RF(e,t,n,{delay:s=0,duration:o=300,repeat:r=0,repeatType:a="loop",ease:l="easeOut",times:c}={},d=void 0){const u={[t]:n};c&&(u.offset=c);const h=M1(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 d&&(p.pseudoElement=d),e.animate(u,p)}function R1(e){return typeof e=="function"&&"applyToOptions"in e}function LF({type:e,...t}){return R1(e)&&A1()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class L1 extends wx{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:c}=t;this.isPseudoElement=!!r,this.allowFlatten=a,this.options=t,xh(typeof t.type!="string");const d=LF(t);this.animation=RF(n,s,o,d,r),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=vh(o,this.options,l,this.speed);this.updateMotionValue&&this.updateMotionValue(u),E1(n,s,u),this.animation.cancel()}c?.(),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 Ks(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ks(t)}get time(){return Ks(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 O1={anticipate:h1,backInOut:u1,circInOut:f1};function OF(e){return e in O1}function zF(e){typeof e.ease=="string"&&OF(e.ease)&&(e.ease=O1[e.ease])}const xp=10;class GF extends L1{constructor(t){zF(t),T1(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}),c=Math.max(xp,Cs.now()-this.startTime),d=Fi(0,xp,c-xp),u=l.sample(c).value,{name:h}=this.options;r&&h&&E1(r,h,u),n.setWithVelocity(l.sample(Math.max(0,c-d)).value,u,d),l.stop()}}const xb=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(pi.test(e)||e==="0")&&!e.startsWith("url("));function FF(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 HF(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=xb(o,t),l=xb(r,t);return!a||!l?!1:FF(e)||(n==="spring"||R1(n))&&s}function rm(e){e.duration=0,e.type="keyframes"}const z1=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),BF=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function VF(e){for(let t=0;t<e.length;t++)if(typeof e[t]=="string"&&BF.test(e[t]))return!0;return!1}const $F=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),WF=o1(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function UF(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:o,damping:r,type:a,keyframes:l}=e,c=t?.owner?.current;if(!(c instanceof HTMLElement)&&!(c instanceof SVGElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return WF()&&n&&(z1.has(n)||$F.has(n)&&VF(l))&&(n!=="transform"||!u)&&!d&&!s&&o!=="mirror"&&r!==0&&a!=="inertia"}const KF=40;class qF extends wx{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:o=0,repeatDelay:r=0,repeatType:a="loop",keyframes:l,name:c,motionValue:d,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:c,motionValue:d,element:u,...h},f=u?.KeyframeResolver||yx;this.keyframeResolver=new f(l,(g,x,v)=>this.onKeyframesResolved(g,x,p,!v),c,d,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,o){this.keyframeResolver=void 0;const{name:r,type:a,velocity:l,delay:c,isHandoff:d,onUpdate:u}=s;this.resolvedAt=Cs.now();let h=!0;HF(t,r,a,l)||(h=!1,(Oo.instantAnimations||!c)&&u?.(vh(t,s,n)),t[0]=t[t.length-1],rm(s),s.repeat=0);const f={startTime:o?this.resolvedAt?this.resolvedAt-this.createdAt>KF?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=h&&!d&&UF(f),x=f.motionValue?.owner?.current;let v;if(g)try{v=new GF({...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(),EF()),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 G1(e,t,n,s=0,o=1){const r=Array.from(e).sort((d,u)=>d.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 vb=30,YF=e=>!isNaN(parseFloat(e));class XF{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=YF(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 hx);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>vb)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,vb);return r1(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 ha(e,t){return new XF(e,t)}function F1(e,t){if(e?.inherit&&t){const{inherit:n,...s}=e;return{...t,...s}}return e}function Sx(e,t){const n=e?.[t]??e?.default??e;return n!==e?F1(n,e):n}const JF={type:"spring",stiffness:500,damping:25,restSpeed:10},ZF=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),QF={type:"keyframes",duration:.8},eH={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},tH=(e,{keyframes:t})=>t.length>2?QF:Da.has(e)?e.startsWith("scale")?ZF(t[1]):JF:eH,nH=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function sH(e){for(const t in e)if(!nH.has(t))return!0;return!1}const Cx=(e,t,n,s={},o,r)=>a=>{const l=Sx(s,e)||{},c=l.delay||s.delay||0;let{elapsed:d=0}=s;d=d-Gs(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...l,delay:-d,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};sH(l)||Object.assign(u,tH(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)&&(rm(u),u.delay===0&&(h=!0)),(Oo.instantAnimations||Oo.skipAnimations||o?.shouldSkipAnimations||l.skipAnimations)&&(h=!0,rm(u),u.delay=0),u.allowFlatten=!l.type&&!l.ease,h&&!r&&t.get()!==void 0){const p=vh(u.keyframes,l);if(p!==void 0){_n.update(()=>{u.onUpdate(p),u.onComplete()});return}}return l.isSync?new fu(u):new qF(u)},iH=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function oH(e){const t=iH.exec(e);if(!t)return[,];const[,n,s,o]=t;return[`--${n??s}`,o]}function H1(e,t,n=1){const[s,o]=oH(e);if(!s)return;const r=window.getComputedStyle(t).getPropertyValue(s);if(r){const a=r.trim();return n1(a)?parseFloat(a):a}return mx(o)?H1(o,t,n+1):o}function bb(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function kx(e,t,n,s){if(typeof t=="function"){const[o,r]=bb(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]=bb(s);t=t(n!==void 0?n:e.custom,o,r)}return t}function vr(e,t,n){const s=e.getProps();return kx(s,t,n!==void 0?n:s.custom,e)}const B1=new Set(["width","height","top","left","right","bottom",...Ta]),am=e=>Array.isArray(e);function rH(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,ha(n))}function aH(e){return am(e)?e[e.length-1]||0:e}function lH(e,t){const n=vr(e,t);let{transitionEnd:s={},transition:o={},...r}=n||{};r={...r,...s};for(const a in r){const l=aH(r[a]);rH(e,a,l)}}const ds=e=>!!(e&&e.getVelocity);function cH(e){return!!(ds(e)&&e.add)}function lm(e,t){const n=e.getValue("willChange");if(cH(n))return n.add(t);if(!n&&Oo.WillChange){const s=new Oo.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function jx(e){return e.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const dH="framerAppearId",V1="data-"+jx(dH);function $1(e){return e.props[V1]}const uH=typeof window<"u";function hH({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function W1(e,t,{delay:n=0,transitionOverride:s,type:o}={}){let{transition:r,transitionEnd:a,...l}=t;const c=e.getDefaultTransition();r=r?F1(r,c):c;const d=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&&hH(p,g))continue;const y={delay:n,...Sx(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(uH&&window.MotionHandoffAnimation){const N=$1(e);if(N){const S=window.MotionHandoffAnimation(N,g,_n);S!==null&&(y.startTime=S,w=!0)}}lm(e,g);const C=d??e.shouldReduceMotion;x.start(Cx(g,x,v,C&&B1.has(g)?{type:!1}:y,e,w));const _=x.animation;_&&h.push(_)}if(a){const g=()=>_n.update(()=>{a&&lH(e,a)});h.length?Promise.all(h).then(g):g()}return h}function cm(e,t,n={}){const s=vr(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(W1(e,s,n)):()=>Promise.resolve(),a=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:h}=o;return pH(e,t,c,d,u,h,n)}:()=>Promise.resolve(),{when:l}=o;if(l){const[c,d]=l==="beforeChildren"?[r,a]:[a,r];return c().then(()=>d())}else return Promise.all([r(),a(n.delay)])}function pH(e,t,n=0,s=0,o=0,r=1,a){const l=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),l.push(cm(c,t,{...a,delay:n+(typeof s=="function"?0:s)+G1(e.variantChildren,c,s,o,r)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(l)}function fH(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const o=t.map(r=>cm(e,r,n));s=Promise.all(o)}else if(typeof t=="string")s=cm(e,t,n);else{const o=typeof t=="function"?vr(e,t,n.custom):t;s=Promise.all(W1(e,o,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}const mH={test:e=>e==="auto",parse:e=>e},U1=e=>t=>t.test(e),K1=[Na,vt,zi,eo,FG,GG,mH],wb=e=>K1.find(U1(e));function gH(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||i1(e):!0}const xH=new Set(["brightness","contrast","saturate","opacity"]);function vH(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(gx)||[];if(!s)return e;const o=n.replace(s,"");let r=xH.has(t)?1:0;return s!==n&&(r*=100),t+"("+r+o+")"}const bH=/\b([a-z-]*)\(.*?\)/gu,dm={...pi,getAnimatableNone:e=>{const t=e.match(bH);return t?t.map(vH).join(" "):e}},um={...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))}},yb={...Na,transform:Math.round},wH={rotate:eo,pathRotation:eo,rotateX:eo,rotateY:eo,rotateZ:eo,scale:Rc,scaleX:Rc,scaleY:Rc,scaleZ:Rc,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:Fl,originX:ab,originY:ab,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,...wH,zIndex:yb,fillOpacity:Fl,strokeOpacity:Fl,numOctaves:yb},yH={...mu,color:$n,backgroundColor:$n,outlineColor:$n,fill:$n,stroke:$n,borderColor:$n,borderTopColor:$n,borderRightColor:$n,borderBottomColor:$n,borderLeftColor:$n,filter:dm,WebkitFilter:dm,mask:um,WebkitMask:um},q1=e=>yH[e],SH=new Set([dm,um]);function Y1(e,t){let n=q1(e);return SH.has(n)||(n=pi),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const CH=new Set(["auto","none","0"]);function kH(e,t,n){let s=0,o;for(;s<e.length&&!o;){const r=e[s];typeof r=="string"&&!CH.has(r)&&ua(r).values.length&&(o=e[s]),s++}if(o&&n)for(const r of t)e[r]=Y1(n,o)}class jH extends yx{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(),mx(h))){const p=H1(h,n.current);p!==void 0&&(t[u]=p),u===t.length-1&&(this.finalKeyframe=h)}}if(this.resolveNoneKeyframes(),!B1.has(s)||t.length!==2)return;const[o,r]=t,a=wb(o),l=wb(r),c=rb(o),d=rb(r);if(c!==d&&Ro[s]){this.needsMeasurement=!0;return}if(a!==l)if(mb(a)&&mb(l))for(let u=0;u<t.length;u++){const h=t[u];typeof h=="string"&&(t[u]=parseFloat(h))}else Ro[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let o=0;o<t.length;o++)(t[o]===null||gH(t[o]))&&s.push(o);s.length&&kH(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=Ro[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]=Ro[n](t.measureViewportBox(),window.getComputedStyle(t.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([l,c])=>{t.getValue(l).set(c)}),this.resolveNoneKeyframes()}}const _x=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function X1(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 hm=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function Id(e){return s1(e)&&"offsetHeight"in e&&!("ownerSVGElement"in e)}const{schedule:Nx}=x1(queueMicrotask,!1),oi={x:!1,y:!1};function J1(){return oi.x||oi.y}function _H(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 Z1(e,t){const n=X1(e),s=new AbortController,o={passive:!0,...t,signal:s.signal};return[n,o,()=>s.abort()]}function NH(e){return!(e.pointerType==="touch"||J1())}function TH(e,t,n={}){const[s,o,r]=Z1(e,n);return s.forEach(a=>{let l=!1,c=!1,d;const u=()=>{a.removeEventListener("pointerleave",g)},h=v=>{d&&(d(v),d=void 0),u()},p=v=>{l=!1,window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),c&&(c=!1,h(v))},f=()=>{l=!0,window.addEventListener("pointerup",p,o),window.addEventListener("pointercancel",p,o)},g=v=>{if(v.pointerType!=="touch"){if(l){c=!0;return}h(v)}},x=v=>{if(!NH(v))return;c=!1;const y=t(a,v);typeof y=="function"&&(d=y,a.addEventListener("pointerleave",g,o))};a.addEventListener("pointerenter",x,o),a.addEventListener("pointerdown",f,o)}),r}const Q1=(e,t)=>t?e===t?!0:Q1(e,t.parentElement):!1,Tx=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,DH=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function IH(e){return DH.has(e.tagName)||e.isContentEditable===!0}const EH=new Set(["INPUT","SELECT","TEXTAREA"]);function PH(e){return EH.has(e.tagName)||e.isContentEditable===!0}const Ed=new WeakSet;function Sb(e){return t=>{t.key==="Enter"&&e(t)}}function vp(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const AH=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Sb(()=>{if(Ed.has(n))return;vp(n,"down");const o=Sb(()=>{vp(n,"up")}),r=()=>vp(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 Cb(e){return Tx(e)&&!J1()}const kb=new WeakSet;function MH(e,t,n={}){const[s,o,r]=Z1(e,n),a=l=>{const c=l.currentTarget;if(!Cb(l)||kb.has(l))return;Ed.add(c),n.stopPropagation&&kb.add(l);const d=t(c,l),u={...o,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",p,u),window.removeEventListener("pointercancel",f,u),Ed.has(c)&&Ed.delete(c),Cb(g)&&typeof d=="function"&&d(g,{success:x})},p=g=>{h(g,c===window||c===document||n.useGlobalTarget||Q1(c,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),Id(l)&&(l.addEventListener("focus",d=>AH(d,o)),!IH(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),r}function Dx(e){return s1(e)&&"ownerSVGElement"in e}const Pd=new WeakMap;let Ad;const eN=(e,t,n)=>(s,o)=>o&&o[0]?o[0][e+"Size"]:Dx(s)&&"getBBox"in s?s.getBBox()[t]:s[n],RH=eN("inline","width","offsetWidth"),LH=eN("block","height","offsetHeight");function OH({target:e,borderBoxSize:t}){Pd.get(e)?.forEach(n=>{n(e,{get width(){return RH(e,t)},get height(){return LH(e,t)}})})}function zH(e){e.forEach(OH)}function GH(){typeof ResizeObserver>"u"||(Ad=new ResizeObserver(zH))}function FH(e,t){Ad||GH();const n=X1(e);return n.forEach(s=>{let o=Pd.get(s);o||(o=new Set,Pd.set(s,o)),o.add(t),Ad?.observe(s)}),()=>{n.forEach(s=>{const o=Pd.get(s);o?.delete(t),o?.size||Ad?.unobserve(s)})}}const Md=new Set;let Ur;function HH(){Ur=()=>{const e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Md.forEach(t=>t(e))},window.addEventListener("resize",Ur)}function BH(e){return Md.add(e),Ur||HH(),()=>{Md.delete(e),!Md.size&&typeof Ur=="function"&&(window.removeEventListener("resize",Ur),Ur=void 0)}}function jb(e,t){return typeof e=="function"?BH(e):FH(e,t)}function VH(e){return Dx(e)&&e.tagName==="svg"}const $H=[...K1,$n,pi],WH=e=>$H.find(U1(e)),_b=()=>({translate:0,scale:1,origin:0,originPoint:0}),Kr=()=>({x:_b(),y:_b()}),Nb=()=>({min:0,max:0}),Yn=()=>({x:Nb(),y:Nb()}),UH=new WeakMap;function bh(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Hl(e){return typeof e=="string"||Array.isArray(e)}const Ix=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Ex=["initial",...Ix];function wh(e){return bh(e.animate)||Ex.some(t=>Hl(e[t]))}function tN(e){return!!(wh(e)||e.variants)}function KH(e,t,n){for(const s in t){const o=t[s],r=n[s];if(ds(o))e.addValue(s,o);else if(ds(r))e.addValue(s,ha(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,ha(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},Px={current:!1},qH=typeof window<"u";function nN(){if(Px.current=!0,!!qH)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 Tb=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let xu={};function sN(e){xu=e}function YH(){return xu}class XH{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:o,skipAnimations:r,blockInitialAnimation:a,visualState:l},c={}){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=yx,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:d,renderState:u}=l;this.latestValues=d,this.baseTarget={...d},this.initialValues=n.initial?{...d}:{},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=c,this.blockInitialAnimation=!!a,this.isControllingVariants=wh(n),this.isVariantNode=tN(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];d[f]!==void 0&&ds(g)&&g.set(d[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,UH.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:(Px.current||nN(),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(),zo(this.notifyUpdate),zo(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&&z1.has(t)&&this.current instanceof HTMLElement){const{factory:a,keyframes:l,times:c,ease:d,duration:u}=n.accelerate,h=new L1({element:this.current,name:t,keyframes:l,times:c,ease:d,duration:Gs(u)}),p=a(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const s=Da.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<Tb.length;s++){const o=Tb[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=KH(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=ha(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"&&(n1(s)||i1(s))?s=parseFloat(s):!WH(s)&&pi.test(n)&&(s=Y1(t,n)),this.setBaseTarget(t,ds(s)?s.get():s)),ds(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=kx(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&&!ds(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 hx),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Nx.render(this.render)}}class iN extends XH{constructor(){super(...arguments),this.KeyframeResolver=jH}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;ds(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Uo{constructor(t){this.isMounted=!1,this.node=t}update(){}}function oN({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function JH({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function ZH(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 bp(e){return e===void 0||e===1}function pm({scale:e,scaleX:t,scaleY:n}){return!bp(e)||!bp(t)||!bp(n)}function or(e){return pm(e)||rN(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function rN(e){return Db(e.x)||Db(e.y)}function Db(e){return e&&e!=="0%"}function vu(e,t,n){const s=e-n,o=t*s;return n+o}function Ib(e,t,n,s,o){return o!==void 0&&(e=vu(e,o,s)),vu(e,n,s)+t}function fm(e,t=0,n=1,s,o){e.min=Ib(e.min,t,n,s,o),e.max=Ib(e.max,t,n,s,o)}function aN(e,{x:t,y:n}){fm(e.x,t.translate,t.scale,t.originPoint),fm(e.y,n.translate,n.scale,n.originPoint)}const Eb=.999999999999,Pb=1.0000000000001;function QH(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:c}=r.options;c&&c.props.style&&c.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,aN(e,a)),s&&or(r.latestValues)&&Rd(e,r.latestValues,r.layout?.layoutBox))}t.x<Pb&&t.x>Eb&&(t.x=1),t.y<Pb&&t.y>Eb&&(t.y=1)}function Di(e,t){e.min+=t,e.max+=t}function Ab(e,t,n,s,o=.5){const r=jn(e.min,e.max,o);fm(e,t,n,r,s)}function Mb(e,t){return typeof e=="string"?parseFloat(e)/100*(t.max-t.min):e}function Rd(e,t,n){const s=n??e;Ab(e.x,Mb(t.x,s.x),t.scaleX,t.scale,t.originX),Ab(e.y,Mb(t.y,s.y),t.scaleY,t.scale,t.originY)}function lN(e,t){return oN(ZH(e.getBoundingClientRect(),t))}function eB(e,t,n){const s=lN(e,n),{scroll:o}=t;return o&&(Di(s.x,o.offset.x),Di(s.y,o.offset.y)),s}const tB={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},nB=Ta.length;function sB(e,t,n){let s="",o=!0;for(let a=0;a<nB;a++){const l=Ta[a],c=e[l];if(c===void 0)continue;let d=!0;if(typeof c=="number")d=c===(l.startsWith("scale")?1:0);else{const u=parseFloat(c);d=l.startsWith("scale")?u===1:u===0}if(!d||n){const u=hm(c,mu[l]);if(!d){o=!1;const h=tB[l]||l;s+=`${h}(${u}) `}n&&(t[l]=u)}}const r=e.pathRotation;return r&&(o=!1,s+=`rotate(${hm(r,mu.pathRotation)}) `),s=s.trim(),n?s=n(t,o?"":s):o&&(s="none"),s}function Ax(e,t,n){const{style:s,vars:o,transformOrigin:r}=e;let a=!1,l=!1;for(const c in t){const d=t[c];if(Da.has(c)){a=!0;continue}else if(b1(c)){o[c]=d;continue}else{const u=hm(d,mu[c]);c.startsWith("origin")?(l=!0,r[c]=u):s[c]=u}}if(t.transform||(a||n?s.transform=sB(t,e.transform,n):s.transform&&(s.transform="none")),l){const{originX:c="50%",originY:d="50%",originZ:u=0}=r;s.transformOrigin=`${c} ${d} ${u}`}}function cN(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 Rb(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Ra={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(vt.test(e))e=parseFloat(e);else return e;const n=Rb(e,t.target.x),s=Rb(e,t.target.y);return`${n}% ${s}%`}},iB={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,c=n.y.scale*t.y;o[0+a]/=l,o[1+a]/=c;const d=jn(l,c,.5);return typeof o[2+a]=="number"&&(o[2+a]/=d),typeof o[3+a]=="number"&&(o[3+a]/=d),r(o)}},mm={borderRadius:{...Ra,applyTo:[..._x]},borderTopLeftRadius:Ra,borderTopRightRadius:Ra,borderBottomLeftRadius:Ra,borderBottomRightRadius:Ra,boxShadow:iB};function dN(e,{layout:t,layoutId:n}){return Da.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!mm[e]||e==="opacity")}function Mx(e,t,n){const s=e.style,o=t?.style,r={};if(!s)return r;for(const a in s)(ds(s[a])||o&&ds(o[a])||dN(a,e)||n?.getValue(a)?.liveStyle!==void 0)&&(r[a]=s[a]);return r}function oB(e){return window.getComputedStyle(e)}class rB extends iN{constructor(){super(...arguments),this.type="html",this.renderInstance=cN}mount(t){xh(!!t.style),super.mount(t)}readValueFromInstance(t,n){if(Da.has(n))return this.projection?.isProjecting?tm(n):_F(t,n);{const s=oB(t),o=(b1(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return lN(t,n)}build(t,n,s){Ax(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Mx(t,n,s)}}const aB={offset:"stroke-dashoffset",array:"stroke-dasharray"},lB={offset:"strokeDashoffset",array:"strokeDasharray"};function cB(e,t,n=1,s=0,o=!0){e.pathLength=1;const r=o?aB:lB;e[r.offset]=`${-s}`,e[r.array]=`${t} ${n}`}const uN=["transform","opacity","offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function hN(e,{attrX:t,attrY:n,attrScale:s,pathLength:o,pathSpacing:r=1,pathOffset:a=0,...l},c,d,u){if(Ax(e,l,d),c){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 uN)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&&cB(h,o,r,a,!1)}const pN=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"]),fN=e=>typeof e=="string"&&e.toLowerCase()==="svg";function dB(e,t,n,s){cN(e,t,void 0,s);for(const o in t.attrs)e.setAttribute(pN.has(o)?o:jx(o),t.attrs[o])}function mN(e,t,n){const s=Mx(e,t,n);for(const o in e)if(ds(e[o])||ds(t[o])){const r=Ta.indexOf(o)!==-1?"attr"+o.charAt(0).toUpperCase()+o.substring(1):o;s[r]=e[o]}return s}class uB extends iN{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Yn}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Da.has(n)){const s=q1(n);return s&&s.default||0}if(uN.includes(n)){const o=getComputedStyle(t)[n];if(typeof o=="string"&&o)return o.trim()}return n=pN.has(n)?n:jx(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return mN(t,n,s)}build(t,n,s){hN(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,o){dB(t,n,s,o)}mount(t){this.isSVGTag=fN(t.tagName),super.mount(t)}}const hB=Ex.length;function gN(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?gN(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<hB;n++){const s=Ex[n],o=e.props[s];(Hl(o)||o===!1)&&(t[s]=o)}return t}function xN(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 pB=[...Ix].reverse(),fB=Ix.length;function mB(e){return t=>Promise.all(t.map(({animation:n,options:s})=>fH(e,n,s)))}function gB(e){let t=mB(e),n=Lb(),s=!0,o=!1;const r=d=>(u,h)=>{const p=vr(e,h,d==="exit"?e.presenceContext?.custom:void 0);if(p){const{transition:f,transitionEnd:g,...x}=p;u={...u,...x,...g}}return u};function a(d){t=d(e)}function l(d){const{props:u}=e,h=gN(e.parent)||{},p=[],f=new Set;let g={},x=1/0;for(let y=0;y<fB;y++){const b=pB[y],w=n[b],C=u[b]!==void 0?u[b]:h[b],_=Hl(C),N=b===d?w.isActive:null;N===!1&&(x=y);let S=C===h[b]&&C!==u[b]&&_;if(S&&(s||o)&&e.manuallyAnimateOnMount&&(S=!1),w.protectedKeys={...g},!w.isActive&&N===null||!C&&!w.prevProp||bh(C)||typeof C=="boolean")continue;if(b==="exit"&&w.isActive&&N!==!0){w.prevResolvedValues&&(g={...g,...w.prevResolvedValues});continue}const k=xB(w.prevProp,C);let A=k||b===d&&w.isActive&&!S&&_||y>x&&_,I=!1;const D=Array.isArray(C)?C:[C];let P=D.reduce(r(b),{});N===!1&&(P={});const{prevResolvedValues:T={}}=w,z={...T,...P},O=X=>{A=!0,f.has(X)&&(I=!0,f.delete(X)),w.needsAnimating[X]=!0;const F=e.getValue(X);F&&(F.liveStyle=!1)};for(const X in z){const F=P[X],ee=T[X];if(g.hasOwnProperty(X))continue;let H=!1;am(F)&&am(ee)?H=!xN(F,ee)||k:H=F!==ee,H?F!=null?O(X):f.add(X):F!==void 0&&f.has(X)?O(X):w.protectedKeys[X]=!0}w.prevProp=C,w.prevResolvedValues=P,w.isActive&&(g={...g,...P}),(s||o)&&e.blockInitialAnimation&&(A=!1);const L=S&&k;A&&(!L||I)&&p.push(...D.map(X=>{const F={type:b};if(typeof X=="string"&&(s||o)&&!L&&e.manuallyAnimateOnMount&&e.parent){const{parent:ee}=e,H=vr(ee,X);if(ee.enteringChildren&&H){const{delayChildren:Q}=H.transition||{};F.delay=G1(ee.enteringChildren,e,Q)}}return{animation:X,options:F}}))}if(f.size){const y={};if(typeof u.initial!="boolean"){const b=vr(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),C=e.getValue(b);C&&(C.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 c(d,u){if(n[d].isActive===u)return Promise.resolve();e.variantChildren?.forEach(p=>p.animationState?.setActive(d,u)),n[d].isActive=u;const h=l(d);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:l,setActive:c,setAnimateFunction:a,getState:()=>n,reset:()=>{n=Lb(),o=!0}}}function xB(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!xN(t,e):!1}function er(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Lb(){return{animate:er(!0),whileInView:er(),whileHover:er(),whileTap:er(),whileDrag:er(),whileFocus:er(),exit:er()}}function gm(e,t){e.min=t.min,e.max=t.max}function si(e,t){gm(e.x,t.x),gm(e.y,t.y)}function Ob(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}const vN=1e-4,vB=1-vN,bB=1+vN,bN=.01,wB=0-bN,yB=0+bN;function ks(e){return e.max-e.min}function SB(e,t,n){return Math.abs(e-t)<=n}function zb(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>=vB&&e.scale<=bB||isNaN(e.scale))&&(e.scale=1),(e.translate>=wB&&e.translate<=yB||isNaN(e.translate))&&(e.translate=0)}function pl(e,t,n,s){zb(e.x,t.x,n.x,s?s.originX:void 0),zb(e.y,t.y,n.y,s?s.originY:void 0)}function Gb(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 CB(e,t,n,s){Gb(e.x,t.x,n.x,s?.x),Gb(e.y,t.y,n.y,s?.y)}function Fb(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){Fb(e.x,t.x,n.x,s?.x),Fb(e.y,t.y,n.y,s?.y)}function Hb(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 kB(e,t=0,n=1,s=.5,o,r=e,a=e){if(zi.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=Hb(e.min,t,n,l,o),e.max=Hb(e.max,t,n,l,o)}function Bb(e,t,[n,s,o],r,a){kB(e,t[n],t[s],t[o],t.scale,r,a)}const jB=["x","scaleX","originX"],_B=["y","scaleY","originY"];function Vb(e,t,n,s){Bb(e.x,t,jB,n?n.x:void 0,s?s.x:void 0),Bb(e.y,t,_B,n?n.y:void 0,s?s.y:void 0)}function $b(e){return e.translate===0&&e.scale===1}function wN(e){return $b(e.x)&&$b(e.y)}function Wb(e,t){return e.min===t.min&&e.max===t.max}function NB(e,t){return Wb(e.x,t.x)&&Wb(e.y,t.y)}function Ub(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function yN(e,t){return Ub(e.x,t.x)&&Ub(e.y,t.y)}function Kb(e){return ks(e.x)/ks(e.y)}function qb(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function Ti(e){return[e("x"),e("y")]}function TB(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:d,rotate:u,pathRotation:h,rotateX:p,rotateY:f,skewX:g,skewY:x}=n;d&&(s=`perspective(${d}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,c=e.y.scale*t.y;return(l!==1||c!==1)&&(s+=`scale(${l}, ${c})`),s||"none"}const DB=_x.length,Yb=e=>typeof e=="string"?parseFloat(e):e,Xb=e=>typeof e=="number"||vt.test(e);function IB(e,t,n,s,o,r){o?(e.opacity=jn(0,n.opacity??1,EB(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<DB;a++){const l=_x[a];let c=Jb(t,l),d=Jb(n,l);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||Xb(c)===Xb(d)?(e[l]=Math.max(jn(Yb(c),Yb(d),s),0),(zi.test(d)||zi.test(c))&&(e[l]+="%")):e[l]=d}(t.rotate||n.rotate)&&(e.rotate=jn(t.rotate||0,n.rotate||0,s))}function Jb(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const EB=SN(0,.5,p1),PB=SN(.5,.95,Js);function SN(e,t,n){return s=>s<e?0:s>t?1:n(Gl(e,t,s))}function AB(e,t,n){const s=ds(e)?e:ha(e);return s.start(Cx("",s,t,n)),s.animation}function Bl(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 RB{constructor(){this.children=[],this.isDirty=!1}add(t){ux(this.children,t),this.isDirty=!0}remove(t){du(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(MB),this.isDirty=!1,this.children.forEach(t)}}function LB(e,t){const n=Cs.now(),s=({timestamp:o})=>{const r=o-n;r>=t&&(zo(s),e(r-t))};return _n.setup(s,!0),()=>zo(s)}function Ld(e){return ds(e)?e.get():e}class OB{constructor(){this.members=[]}add(t){ux(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&&(du(this.members,s),s.unmount())}t.scheduleRender()}remove(t){if(du(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 Od={hasAnimatedSinceResize:!0,hasEverUpdated:!1},wp=["","X","Y","Z"],zB=1e3;let GB=0;function yp(e,t,n,s){const{latestValues:o}=t;o[e]&&(n[e]=o[e],t.setStaticValue(e,0),s&&(s[e]=0))}function CN(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=$1(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&&CN(s)}function kN({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:o}){return class{constructor(a={},l=t?.()){this.id=GB++,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(BB),this.nodes.forEach(qB),this.nodes.forEach(YB),this.nodes.forEach(VB)},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 c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new RB)}addEventListener(a,l){return this.eventHandlers.has(a)||this.eventHandlers.set(a,new hx),this.eventHandlers.get(a).add(l)}notifyListeners(a,...l){const c=this.eventHandlers.get(a);c&&c.notify(...l)}hasListeners(a){return this.eventHandlers.has(a)}mount(a){if(this.instance)return;this.isSVG=Dx(a)&&!VH(a),this.instance=a;const{layoutId:l,layout:c,visualElement:d}=this.options;if(d&&!d.current&&d.mount(a),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||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=LB(p,250),Od.hasAnimatedSinceResize&&(Od.hasAnimatedSinceResize=!1,this.nodes.forEach(ew)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&d&&(l||c)&&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||d.getDefaultTransition()||eV,{onLayoutAnimationStart:x,onLayoutAnimationComplete:v}=d.getProps(),y=!this.targetLayout||!yN(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={...Sx(g,"layout"),onPlay:x,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,b,w.path)}else h||ew(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(),zo(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(XB),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&&CN(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:c}=this.options;if(l===void 0&&!c)return;const d=this.getTransformTemplate();this.prevTransformTemplateValue=d?d(this.latestValues,""):void 0,this.updateSnapshot(),a&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){const c=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),c&&this.nodes.forEach(WB),this.nodes.forEach(Zb);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Qb);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(UB),this.nodes.forEach(KB),this.nodes.forEach(FB),this.nodes.forEach(HB)):this.nodes.forEach(Qb),this.clearAllSnapshots();const l=Cs.now();cs.delta=Fi(0,1e3/60,l-cs.timestamp),cs.timestamp=l,cs.isProcessing=!0,hp.update.process(cs),hp.preRender.process(cs),hp.render.process(cs),cs.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Nx.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach($B),this.sharedNodes.forEach(JB)}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 c=0;c<this.path.length;c++)this.path[c].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 c=s(this.instance);this.scroll={animationId:this.root.animationId,phase:a,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!o)return;const a=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,l=this.projectionDelta&&!wN(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,u=d!==this.prevTransformTemplateValue;a&&this.instance&&(l||or(this.latestValues)||u)&&(o(this.instance,d),this.shouldResetTransform=!1,this.scheduleRender())}measure(a=!0){const l=this.measurePageBox();let c=this.removeElementScroll(l);return a&&(c=this.removeTransform(c)),tV(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,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(nV))){const{scroll:d}=this.root;d&&(Di(l.x,d.offset.x),Di(l.y,d.offset.y))}return l}removeElementScroll(a){const l=Yn();if(si(l,a),this.scroll?.wasRoot)return l;for(let c=0;c<this.path.length;c++){const d=this.path[c],{scroll:u,options:h}=d;d!==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,c){const d=c||Yn();si(d,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(d.x,-h.scroll.offset.x),Di(d.y,-h.scroll.offset.y)),or(h.latestValues)&&Rd(d,h.latestValues,h.layout?.layoutBox)}return or(this.latestValues)&&Rd(d,this.latestValues,this.layout?.layoutBox),d}removeTransform(a){const l=Yn();si(l,a);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!or(d.latestValues))continue;let u;d.instance&&(pm(d.latestValues)&&d.updateSnapshot(),u=Yn(),si(u,d.measurePageBox())),Vb(l,d.latestValues,d.snapshot?.layoutBox,u)}return or(this.latestValues)&&Vb(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!==cs.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 c=!!this.resumingFrom||this!==l;if(!(a||c&&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=cs.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(),CB(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),aN(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||pm(this.parent.latestValues)||rN(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,c){this.relativeParent=a,this.linkedParentVersion=a.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Yn(),this.relativeTargetOrigin=Yn(),bu(this.relativeTargetOrigin,l,c,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 c=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(c=!1),l&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===cs.timestamp&&(c=!1),c)return;const{layout:d,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||!(d||u))return;si(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,p=this.treeScale.y;QH(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():(Ob(this.prevProjectionDelta.x,this.projectionDelta.x),Ob(this.prevProjectionDelta.y,this.projectionDelta.y)),pl(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==p||!qb(this.projectionDelta.x,this.prevProjectionDelta.x)||!qb(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=Kr(),this.projectionDelta=Kr(),this.projectionDeltaWithTransform=Kr()}setAnimationOrigin(a,l=!1,c){const d=this.snapshot,u=d?d.latestValues:{},h={...this.latestValues},p=Kr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const f=Yn(),g=d?d.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(QB));this.animationProgress=0;let C;const _=c?.interpolateProjection(a);this.mixTargetDelta=N=>{const S=N/1e3,k=_?.(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):(tw(p.x,a.x,S),tw(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),ZB(this.relativeTarget,this.relativeTargetOrigin,f,S),C&&NB(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=Yn()),si(C,this.relativeTarget)),v&&(this.animationValues=h,IB(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&&(zo(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=_n.update(()=>{Od.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ha(0)),this.motionValue.jump(0,!1),this.currentAnimation=AB(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(zB),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const a=this.getLead();let{targetWithTransforms:l,target:c,layout:d,latestValues:u}=a;if(!(!l||!c||!d)){if(this!==a&&this.layout&&d&&jN(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Yn();const h=ks(this.layout.layoutBox.x);c.x.min=a.target.x.min,c.x.max=c.x.min+h;const p=ks(this.layout.layoutBox.y);c.y.min=a.target.y.min,c.y.max=c.y.min+p}si(l,c),Rd(l,u),pl(this.projectionDeltaWithTransform,this.layoutCorrected,l,u)}}registerSharedNode(a,l){this.sharedNodes.has(a)||this.sharedNodes.set(a,new OB),this.sharedNodes.get(a).add(l);const d=l.options.initialPromotionConfig;l.promote({transition:d?d.transition:void 0,preserveFollowOpacity:d&&d.shouldPreserveFollowOpacity?d.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:c}={}){const d=this.getStack();d&&d.promote(this,c),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:c}=a;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(l=!0),!l)return;const d={};c.z&&yp("z",a,d,this.animationValues);for(let u=0;u<wp.length;u++)yp(`rotate${wp[u]}`,a,d,this.animationValues),yp(`skew${wp[u]}`,a,d,this.animationValues);a.render();for(const u in d)a.setStaticValue(u,d[u]),this.animationValues&&(this.animationValues[u]=d[u]);a.scheduleRender()}applyProjectionStyles(a,l){if(!this.instance||this.isSVG)return;if(!this.isVisible){a.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,a.visibility="",a.opacity="",a.pointerEvents=Ld(l?.pointerEvents)||"",a.transform=c?c(this.latestValues,""):"none";return}const d=this.getLead();if(!this.projectionDelta||!this.layout||!d.target){this.options.layoutId&&(a.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,a.pointerEvents=Ld(l?.pointerEvents)||""),this.hasProjected&&!or(this.latestValues)&&(a.transform=c?c({},""):"none",this.hasProjected=!1);return}a.visibility="";const u=d.animationValues||d.latestValues;this.applyTransformsToTarget();let h=TB(this.projectionDeltaWithTransform,this.treeScale,u);c&&(h=c(u,h)),a.transform=h;const{x:p,y:f}=this.projectionDelta;a.transformOrigin=`${p.origin*100}% ${f.origin*100}% 0`,d.animationValues?a.opacity=d===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:a.opacity=d===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const g in mm){if(u[g]===void 0)continue;const{correct:x,applyTo:v,isCSSVariable:y}=mm[g],b=h==="none"?u[g]:x(u[g],d);if(v){const w=v.length;for(let C=0;C<w;C++)a[v[C]]=b}else y?this.options.visualElement.renderState.vars[g]=b:a[g]=b}this.options.layoutId&&(a.pointerEvents=d===this?Ld(l?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(a=>a.currentAnimation?.stop()),this.root.nodes.forEach(Zb),this.root.sharedNodes.clear()}}}function FB(e){e.updateLayout()}function HB(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";gm(r?t.measuredBox[u]:t.layoutBox[u],n[u])}else jN(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=Kr();pl(a,n,t.layoutBox);const l=Kr();r?pl(l,e.applyTransform(s,!0),t.measuredBox):pl(l,n,t.layoutBox);const c=!wN(a);let d=!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),yN(g,x)||(d=!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:c,hasRelativeLayoutChanged:d})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function BB(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 VB(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function $B(e){e.clearSnapshot()}function Zb(e){e.clearMeasurements()}function WB(e){e.isLayoutDirty=!0,e.updateLayout()}function Qb(e){e.isLayoutDirty=!1}function UB(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function KB(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function ew(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function qB(e){e.resolveTargetDelta()}function YB(e){e.calcProjection()}function XB(e){e.resetSkewAndRotation()}function JB(e){e.removeLeadSnapshot()}function tw(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 nw(e,t,n,s){e.min=jn(t.min,n.min,s),e.max=jn(t.max,n.max,s)}function ZB(e,t,n,s){nw(e.x,t.x,n.x,s),nw(e.y,t.y,n.y,s)}function QB(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const eV={duration:.45,ease:[.4,0,.1,1]},sw=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),iw=sw("applewebkit/")&&!sw("chrome/")?Math.round:Js;function ow(e){e.min=iw(e.min),e.max=iw(e.max)}function tV(e){ow(e.x),ow(e.y)}function jN(e,t,n){return e==="position"||e==="preserve-aspect"&&!SB(Kb(t),Kb(n),.2)}function nV(e){return e!==e.root&&e.scroll?.wasRoot}const sV=kN({attachResizeListener:(e,t)=>Bl(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Sp={current:void 0},_N=kN({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Sp.current){const e=new sV({});e.mount(window),e.setOptions({layoutScroll:!0}),Sp.current=e}return Sp.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),Rx=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function rw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function iV(...e){return t=>{let n=!1;const s=e.map(o=>{const r=rw(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():rw(e[o],null)}}}}function oV(...e){return m.useCallback(iV(...e),e)}class rV extends m.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(Id(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,o=Id(s)&&s.offsetWidth||0,r=Id(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 aV({children:e,isPresent:t,anchorX:n,anchorY:s,root:o,pop:r}){const a=m.useId(),l=m.useRef(null),c=m.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:d}=m.useContext(Rx),u=r!==!1?e.props?.ref??e?.ref:void 0,h=oV(l,u);return m.useInsertionEffect(()=>{const{width:p,height:f,top:g,left:x,right:v,bottom:y,direction:b}=c.current;if(t||r===!1||!l.current||!p||!f)return;const w=b==="rtl",C=n==="left"?w?`right: ${v}`:`left: ${x}`:w?`left: ${x}`:`right: ${v}`,_=s==="bottom"?`bottom: ${y}`:`top: ${g}`;l.current.dataset.motionPopId=a;const N=document.createElement("style");d&&(N.nonce=d);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
|
-
${C}px !important;
|
|
11
|
-
${_}px !important;
|
|
12
|
-
}
|
|
13
|
-
`),()=>{l.current?.removeAttribute("data-motion-pop-id"),S.contains(N)&&S.removeChild(N)}},[t]),i.jsx(rV,{isPresent:t,childRef:l,sizeRef:c,pop:r,children:r===!1?e:m.cloneElement(e,{ref:h})})}const lV=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:o,presenceAffectsLayout:r,mode:a,anchorX:l,anchorY:c,root:d})=>{const u=dx(cV),h=m.useId(),p=m.useRef(n),f=m.useRef(s);cu(()=>{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(aV,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:d,children:e}),i.jsx(gh.Provider,{value:x,children:e})};function cV(){return new Map}function NN(e=!0){const t=m.useContext(gh);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 Lc=e=>e.key||"";function aw(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:c="top",root:d})=>{const[u,h]=NN(a),p=m.useMemo(()=>aw(e),[e]),f=a&&!u?[]:p.map(Lc),g=m.useRef(!0),x=m.useRef(p),v=dx(()=>new Map),y=m.useRef(new Set),[b,w]=m.useState(p),[C,_]=m.useState(p);cu(()=>{a&&!u&&!C.length&&h?.()},[u,a,C.length,h]),cu(()=>{g.current=!1,x.current=p;for(let k=0;k<C.length;k++){const A=Lc(C[k]);f.includes(A)?(v.delete(A),y.current.delete(A)):v.get(A)!==!0&&v.set(A,!1)}},[C,f.length,f.join("-")]);const N=[];if(p!==b){let k=[...p],A=0;for(const I of C){const D=f.indexOf(Lc(I));D===-1?(k.splice(A++,0,I),N.push(I)):A=D+N.length+1}return r==="wait"&&N.length&&(k=N),_(aw(k)),w(p),null}const{forceRender:S}=m.useContext(cx);return i.jsx(i.Fragment,{children:C.map(k=>{const A=Lc(k),I=a&&!u?!1:p===C||f.includes(A),D=()=>{if(y.current.has(A))return;if(v.has(A))y.current.add(A),v.set(A,!0);else return;let P=!0;v.forEach(T=>{T||(P=!1)}),P&&(S?.(),_(x.current),a&&h?.(),s&&s())};return i.jsx(lV,{isPresent:I,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:o,mode:r,root:d,onExitComplete:I?void 0:D,anchorX:l,anchorY:c,children:k},A)})})},TN=m.createContext({strict:!1}),lw={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 cw=!1;function dV(){if(cw)return;const e={};for(const t in lw)e[t]={isEnabled:n=>lw[t].some(s=>!!n[s])};sN(e),cw=!0}function DN(){return dV(),YH()}function uV(e){const t=DN();for(const n in e)t[n]={...t[n],...e[n]};sN(t)}const yh=m.createContext({});function hV(e,t){if(wh(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Hl(n)?n:void 0,animate:Hl(s)?s:void 0}}return e.inherit!==!1?t:{}}function pV(e){const{initial:t,animate:n}=hV(e,m.useContext(yh));return m.useMemo(()=>({initial:t,animate:n}),[dw(t),dw(n)])}function dw(e){return Array.isArray(e)?e.join(" "):e}const Lx=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function IN(e,t,n){for(const s in t)!ds(t[s])&&!dN(s,n)&&(e[s]=t[s])}function fV({transformTemplate:e},t){return m.useMemo(()=>{const n=Lx();return Ax(n,t,e),Object.assign({},n.vars,n.style)},[t])}function mV(e,t){const n=e.style||{},s={};return IN(s,n,e),Object.assign(s,fV(e,t)),s}function gV(e,t){const n={},s=mV(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 EN=()=>({...Lx(),attrs:{}});function xV(e,t,n,s){const o=m.useMemo(()=>{const r=EN();return hN(r,t,fN(s),e.transformTemplate,e.style),{...r.attrs,style:{...r.style}}},[t]);if(e.style){const r={};IN(r,e.style,e),o.style={...r,...o.style}}return o}const vV=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")||vV.has(e)}function bV(e,t){return e.startsWith("on")?!wu(e):t?.(e)??!wu(e)}function wV(e,t,n,s){const o={};for(const r in e)r==="values"&&typeof e.values=="object"||ds(e[r])||(bV(r,s)||n===!0&&wu(r)||!t&&!wu(r)||e.draggable&&r.startsWith("onDrag"))&&(o[r]=e[r]);return o}const yV=["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 Ox(e){return typeof e!="string"||e.includes("-")?!1:!!(yV.indexOf(e)>-1||/[A-Z]/u.test(e))}function SV(e,t,n,{latestValues:s},o,r=!1,a,l){const d=(a??Ox(e)?xV:gV)(t,s,o,e),u=wV(t,typeof e=="string",r,l),h=e!==m.Fragment?{...u,...d,ref:n}:{},{children:p}=t,f=m.useMemo(()=>ds(p)?p.get():p,[p]);return m.createElement(e,{...h,children:f})}function CV({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,o){return{latestValues:kV(n,s,o,e),renderState:t()}}function kV(e,t,n,s){const o={},r=s(e,{});for(const p in r)o[p]=Ld(r[p]);let{initial:a,animate:l}=e;const c=wh(e),d=tN(e);t&&d&&!c&&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"&&!bh(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f<p.length;f++){const g=kx(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 C=u?w.length-1:0;w=w[C]}w!==null&&(o[b]=w)}for(const b in x)o[b]=x[b]}}}return o}const PN=e=>(t,n)=>{const s=m.useContext(yh),o=m.useContext(gh),r=()=>CV(e,t,s,o);return n?r():dx(r)},jV=PN({scrapeMotionValuesFromProps:Mx,createRenderState:Lx}),_V=PN({scrapeMotionValuesFromProps:mN,createRenderState:EN}),NV=Symbol.for("motionComponentSymbol");function TV(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 AN=m.createContext({});function Hr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function DV(e,t,n,s,o,r){const{visualElement:a}=m.useContext(yh),l=m.useContext(TN),c=m.useContext(gh),d=m.useContext(Rx),u=d.reducedMotion,h=d.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:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:r}),f.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const g=p.current,x=m.useContext(AN);g&&!g.projection&&o&&(g.type==="html"||g.type==="svg")&&IV(p.current,n,o,x);const v=m.useRef(!1);m.useInsertionEffect(()=>{g&&v.current&&g.update(n,c)});const y=n[V1],b=m.useRef(!!y&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(y)&&window.MotionHasOptimisedAnimation?.(y));return cu(()=>{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 IV(e,t,n,s){const{layoutId:o,layout:r,drag:a,dragConstraints:l,layoutScroll:c,layoutRoot:d,layoutAnchor:u,layoutCrossfade:h}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:MN(e.parent)),e.projection.setOptions({layoutId:o,layout:r,alwaysMeasureLayout:!!a||l&&Hr(l),visualElement:e,animationType:typeof r=="string"?r:"both",initialPromotionConfig:s,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function MN(e){if(e)return e.options.allowProjection!==!1?e.projection:MN(e.parent)}function Cp(e,{forwardMotionProps:t=!1,type:n}={},s,o){s&&uV(s);const r=n?n==="svg":Ox(e),a=r?_V:jV;function l(d,u){let h;const p={...m.useContext(Rx),...d,layoutId:EV(d)},{isStatic:f,isValidProp:g}=p,x=pV(d),v=a(d,f);if(!f&&typeof window<"u"){PV();const y=AV(p);h=y.MeasureLayout,x.visualElement=DV(e,v,p,o,y.ProjectionNode,r)}return i.jsxs(yh.Provider,{value:x,children:[h&&x.visualElement?i.jsx(h,{visualElement:x.visualElement,...p}):null,SV(e,d,TV(v,x.visualElement,u),v,f,t,r,g)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=m.forwardRef(l);return c[NV]=e,c}function EV({layoutId:e}){const t=m.useContext(cx).id;return t&&e!==void 0?t+"-"+e:e}function PV(e,t){m.useContext(TN).strict}function AV(e){const t=DN(),{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 MV(e,t){if(typeof Proxy>"u")return Cp;const n=new Map,s=(r,a)=>Cp(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,Cp(a,void 0,e,t)),n.get(a))})}const RV=(e,t)=>t.isSVG??Ox(e)?new uB(t):new rB(t,{allowProjection:e!==m.Fragment});class LV extends Uo{constructor(t){super(t),t.animationState||(t.animationState=gB(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();bh(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 OV=0;class zV extends Uo{constructor(){super(...arguments),this.id=OV++,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=vr(this.node,r,a);if(l){const{transition:c,transitionEnd:d,...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 GV={animation:{Feature:LV},exit:{Feature:zV}};function Sc(e){return{point:{x:e.pageX,y:e.pageY}}}const FV=e=>t=>Tx(t)&&e(t,Sc(t));function ml(e,t,n,s){return Bl(e,t,FV(n),s)}const RN=({current:e})=>e?e.ownerDocument.defaultView:null,uw=(e,t)=>Math.abs(e-t);function HV(e,t){const n=uw(e.x,t.x),s=uw(e.y,t.y);return Math.sqrt(n**2+s**2)}const hw=new Set(["auto","scroll"]);class LN{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=Oc(this.lastRawMoveEventInfo,this.transformPagePoint));const g=kp(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,v=HV(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!v)return;const{point:y}=g,{timestamp:b}=cs;this.history.push({...y,timestamp:b});const{onStart:w,onMove:C}=this.handlers;x||(w&&w(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,g)},this.handlePointerMove=(g,x)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Oc(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=kp(g.type==="pointercancel"?this.lastMoveEventInfo:Oc(x,this.transformPagePoint),this.history);this.startEvent&&v&&v(g,w),y&&y(g,w)},!Tx(t))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=o||window;const c=Sc(t),d=Oc(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=cs;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,kp(d,this.history));const f={passive:!0,capture:!0};this.removeListeners=bc(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);(hw.has(s.overflowX)||hw.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(),zo(this.updatePoint)}}function Oc(e,t){return t?{point:t(e.point)}:e}function pw(e,t){return{x:e.x-t.x,y:e.y-t.y}}function kp({point:e},t){return{point:e,delta:pw(e,ON(t)),offset:pw(e,BV(t)),velocity:VV(t,.1)}}function BV(e){return e[0]}function ON(e){return e[e.length-1]}function VV(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const o=ON(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=Ks(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 $V(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 fw(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 WV(e,{top:t,left:n,bottom:s,right:o}){return{x:fw(e.x,n,o),y:fw(e.y,t,s)}}function mw(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 UV(e,t){return{x:mw(e.x,t.x),y:mw(e.y,t.y)}}function KV(e,t){let n=.5;const s=ks(e),o=ks(t);return o>s?n=Gl(t.min,t.max-s,e.min):s>o&&(n=Gl(e.min,e.max-o,t.min)),Fi(0,1,n)}function qV(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 xm=.35;function YV(e=xm){return e===!1?e=0:e===!0&&(e=xm),{x:gw(e,"left","right"),y:gw(e,"top","bottom")}}function gw(e,t,n){return{min:xw(e,t),max:xw(e,n)}}function xw(e,t){return typeof e=="number"?e:e[t]||0}const XV=new WeakMap;class JV{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(Sc(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=_H(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(zi.test(b)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(b=ks(C)*(parseFloat(b)/100))}}this.originPoint[y]=b}),x&&_n.update(()=>x(h,p),!1,!0),lm(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=QV(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)},c=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p,this.stop(h,p),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new LN(t,{onSessionStart:r,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:s,contextWindow:RN(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||!zc(t,o,this.currentDirection))return;const r=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=$V(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&&Hr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=WV(s.layoutBox,t):this.constraints=!1,this.elastic=YV(n),o!==this.constraints&&!Hr(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&Ti(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=qV(s.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Hr(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=eB(s,o.root,this.visualElement.getTransformPagePoint());let a=UV(o.layout.layoutBox,r);if(n){const l=n(JH(a));this.hasMutatedConstraints=!!l,l&&(a=oN(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:o,dragTransition:r,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=Ti(u=>{if(!zc(u,n,this.currentDirection))return;let h=c&&c[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(d).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return lm(this.visualElement,t),s.start(Cx(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(!zc(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],c=r.get()||0;r.set(t[n]-jn(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Hr(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 c=l.get();o[a]=KV({min:c,max:c},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(!zc(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:d}=this.constraints[a];l.set(jn(c,d,o[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;XV.set(this.visualElement,this);const t=this.visualElement.current,n=ml(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=d.target,f=p!==t&&PH(p);u&&h&&!f&&this.start(d)});let s;const o=()=>{const{dragConstraints:d}=this.getProps();Hr(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),s||(s=ZV(t,d.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=Bl(window,"resize",()=>this.scalePositionWithinConstraints()),c=r.addEventListener("didUpdate",(({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(Ti(h=>{const p=this.getAxisMotionValue(h);p&&(this.originPoint[h]+=d[h].translate,p.set(p.get()+d[h].translate))}),this.visualElement.render())}));return()=>{l(),n(),a(),c&&c(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:o=!1,dragConstraints:r=!1,dragElastic:a=xm,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:o,dragConstraints:r,dragElastic:a,dragMomentum:l}}}function vw(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function ZV(e,t,n){const s=jb(e,vw(n)),o=jb(t,vw(n));return()=>{s(),o()}}function zc(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function QV(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class e$ extends Uo{constructor(t){super(t),this.removeGroupControls=Js,this.removeListeners=Js,this.controls=new JV(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 jp=e=>(t,n)=>{e&&_n.update(()=>e(t,n),!1,!0)};class t$ extends Uo{constructor(){super(...arguments),this.removePointerDownListener=Js}onPointerDown(t){this.session=new LN(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:RN(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:o}=this.node.getProps();return{onSessionStart:jp(t),onStart:jp(n),onMove:jp(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 _p=!1;class n$ 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),_p&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Od.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}),_p=!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(),Nx.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:o}=t;_p=!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 zN(e){const[t,n]=NN(),s=m.useContext(cx);return i.jsx(n$,{...e,layoutGroup:s,switchLayoutGroup:m.useContext(AN),isPresent:t,safeToRemove:n})}const s$={pan:{Feature:t$},drag:{Feature:e$,ProjectionNode:_N,MeasureLayout:zN}};function bw(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,Sc(t)))}class i$ extends Uo{mount(){const{current:t}=this.node;t&&(this.unmount=TH(t,(n,s)=>(bw(this.node,s,"Start"),o=>bw(this.node,o,"End"))))}unmount(){}}class o$ extends Uo{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=bc(Bl(this.node.current,"focus",()=>this.onFocus()),Bl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function ww(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,Sc(t)))}class r$ extends Uo{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=MH(t,(o,r)=>(ww(this.node,r,"Start"),(a,{success:l})=>ww(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const vm=new WeakMap,Np=new WeakMap,a$=e=>{const t=vm.get(e.target);t&&t(e)},l$=e=>{e.forEach(a$)};function c$({root:e,...t}){const n=e||document;Np.has(n)||Np.set(n,{});const s=Np.get(n),o=JSON.stringify(t);return s[o]||(s[o]=new IntersectionObserver(l$,{root:e,...t})),s[o]}function d$(e,t,n){const s=c$(t);return vm.set(e,n),s.observe(e),()=>{vm.delete(e),s.unobserve(e)}}const u$={some:0,all:1};class h$ extends Uo{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=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,r&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:u,onViewportLeave:h}=this.node.getProps(),p=d?u:h;p&&p(c)};this.stopObserver=d$(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(p$(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function p$({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const f$={inView:{Feature:h$},tap:{Feature:r$},focus:{Feature:o$},hover:{Feature:i$}},m$={layout:{ProjectionNode:_N,MeasureLayout:zN}},g$={...GV,...f$,...s$,...m$},Rs=MV(g$,RV);function x$(){!Px.current&&nN();const[e]=m.useState(gu.current);return e}const v$=[["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"}]],b$=ot("alarm-clock",v$);const w$=[["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"}]],Vl=ot("archive-restore",w$);const y$=[["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"}]],Mi=ot("archive",y$);const S$=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],C$=ot("arrow-down-to-line",S$);const k$=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],j$=ot("arrow-up-right",k$);const _$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]],N$=ot("ban",_$);const T$=[["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"}]],yw=ot("bell-off",T$);const D$=[["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"}]],I$=ot("bookmark-plus",D$);const E$=[["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"}]],GN=ot("bug",E$);const P$=[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]],A$=ot("chevrons-down-up",P$);const M$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],R$=ot("circle-dot",M$);const L$=[["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"}]],O$=ot("circle-play",L$);const z$=[["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"}]],G$=ot("circle-question-mark",z$);const F$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],H$=ot("circle-stop",F$);const B$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],zx=ot("circle",B$);const V$=[["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"}]],FN=ot("clipboard-check",V$);const $$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],HN=ot("clock",$$);const W$=[["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"}]],bm=ot("code-xml",W$);const U$=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],K$=ot("code",U$);const q$=[["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"}]],Y$=ot("coins",q$);const X$=[["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"}]],J$=ot("compass",X$);const Z$=[["path",{d:"m15 10 5 5-5 5",key:"qqa56n"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]],Q$=ot("corner-down-right",Z$);const e6=[["path",{d:"M14 9 9 4 4 9",key:"1af5af"}],["path",{d:"M20 20h-7a4 4 0 0 1-4-4V4",key:"1blwi3"}]],t6=ot("corner-left-up",e6);const n6=[["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"}]],s6=ot("cpu",n6);const i6=[["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"}]],o6=ot("database",i6);const r6=[["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"}]],Sh=ot("ellipsis",r6);const a6=[["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"}]],l6=ot("file-diff",a6);const c6=[["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"}]],d6=ot("file-pen",c6);const u6=[["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"}]],h6=ot("file-plus",u6);const p6=[["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"}]],f6=ot("file",p6);const m6=[["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"}]],g6=ot("fold-horizontal",m6);const x6=[["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"}]],v6=ot("folder-git-2",x6);const b6=[["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"}]],yu=ot("folder-plus",b6);const w6=[["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"}]],Cc=ot("folder",w6);const y6=[["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",y6);const C6=[["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"}]],k6=ot("git-branch-plus",C6);const j6=[["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"}]],Ri=ot("git-branch",j6);const _6=[["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"}]],N6=ot("git-commit-horizontal",_6);const T6=[["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"}]],Gx=ot("git-compare",T6);const D6=[["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"}]],Sw=ot("hand",D6);const I6=[["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"}]],E6=ot("hourglass",I6);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"}]],Cw=ot("house",P6);const A6=[["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"}]],BN=ot("image-off",A6);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"}]],Ch=ot("image-plus",M6);const R6=[["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"}]],L6=ot("images",R6);const O6=[["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"}]],Fx=ot("inbox",O6);const z6=[["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"}]],G6=ot("list-tree",z6);const F6=[["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"}]],Hx=ot("list",F6);const H6=[["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"}]],B6=ot("mail",H6);const V6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],$6=ot("menu",V6);const W6=[["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"}]],yr=ot("message-circle",W6);const U6=[["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"}]],Go=ot("message-square-plus",U6);const K6=[["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"}]],pa=ot("messages-square",K6);const q6=[["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"}]],Y6=ot("package-minus",q6);const X6=[["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"}]],Bx=ot("panel-left-close",X6);const J6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],VN=ot("panel-left",J6);const Z6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],$N=ot("panel-right",Z6);const Q6=[["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"}]],e4=ot("pause",Q6);const t4=[["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"}]],Su=ot("pin-off",t4);const n4=[["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"}]],ci=ot("pin",n4);const s4=[["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"}]],i4=ot("repeat",s4);const o4=[["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"}]],Ko=ot("rotate-ccw-clock",o4);const r4=[["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"}]],Vx=ot("send",r4);const a4=[["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"}]],l4=ot("sliders-horizontal",a4);const c4=[["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"}]],d4=ot("square-dashed",c4);const u4=[["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"}]],WN=ot("square-pen",u4);const h4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]],UN=ot("square-slash",h4);const p4=[["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"}]],f4=ot("square-x",p4);const m4=[["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"}]],g4=ot("tag",m4);const x4=[["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"}]],Ia=ot("target",x4);const v4=[["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"}]],KN=ot("text-search",v4);const b4=[["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"}]],fa=ot("undo-2",b4);const w4=[["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"}]],y4=ot("unfold-horizontal",w4);const S4=[["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"}]],C4=ot("user-minus",S4);const k4=[["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",k4);const j4=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],_4=ot("user-round",j4);const N4=[["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"}]],T4=ot("wallet",N4),Tp=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e;function D4(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 c={status:n,originalCommand:Tp(s,16e3)};if(o!==void 0&&(c.rewrittenCommand=Tp(o,16e3)),l!==void 0&&(c.reason=Tp(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;c.inputTokens=r,c.outputTokens=a}return c}const I4=15e3;function E4(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 qN(e){if(e.length===0)return;const t="0 0, 100% 0, 100% 100%, 0 100%, 0 0",n=e.map(s=>`${P4(s).map(([o,r])=>`${jw(o)}px ${jw(r)}px`).join(", ")}, 0 0`);return`polygon(evenodd, ${[t,...n].join(", ")})`}const kw=6,jw=e=>Math.round(e*100)/100;function P4({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 d=[[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:kw+1},(f,g)=>{const x=(p+90*g/kw)*Math.PI/180;return[u+l*Math.cos(x),h+l*Math.sin(x)]}));return[...d,d[0]]}function _w(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 A4(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 M4(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 R4(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 L4=/^\[Referenced past chat "(.+)" — transcript file: (.+) \(pi session jsonl; read it if relevant\)\]$/,O4=/^@(\S.*)$/;function z4(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"?R4(t.label,t.sessionFile):bA(t)).join("")}function Nw(e,t){r0.lastIndex=t,a0.lastIndex=t;const n=r0.exec(e),s=a0.exec(e),o=n?{index:n.index,length:n[0].length,segment:{type:"chat",label:n[1],sessionFile:n[2]}}:null,r=s?vA(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 G4(e){const t=[];let n=0,s=Nw(e,0);for(;s;){const r=e.slice(n,s.index);for(const a of Tw(r))a.type==="text"&&a.text===""||t.push(a);t.push(s.segment),n=s.index+s.length,s=Nw(e,n)}const o=e.slice(n);if(o||t.length===0)for(const r of Tw(o))r.type==="text"&&r.text===""&&t.length>0||t.push(r);return t}const F4=/^(?:[A-Za-z]:[\\/])?(?:[\p{L}\p{N}_./\\-]*\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\p{L}\p{N}_./\\-]+[\\/])$/u,H4=/^"([^"\n]*(?:\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\\/]))"/,B4=/#L\d+(?:-L\d+)?$/;function V4(e){return e.replace(B4,"")}function kh(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).at(-1)||e}function Tw(e){return Wk(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
|
-
`?H4.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 c=(/^\S*/.exec(e.slice(o+1))?.[0]??"").replace(/[),.;!?]+$/,"");(r===" "||r===`
|
|
17
|
-
`)&&c&&F4.test(c)?(n+=e.slice(s,o),n&&(t.push({type:"text",text:n}),n=""),t.push({type:"file",path:c}),s=o+1+c.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 W4(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=L4.exec(a);if(l){o.unshift({label:l[1],sessionFile:l[2]});continue}if(O4.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 Dw(e){const t=z4(e.segments).trim(),n=e.segments.filter(o=>o.type!=="text").map(o=>o.type==="file"?{kind:"file",id:o.path,label:kh(o.path),relativePath:V4(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 U4={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 K4(){const e=Uk(),t=ye(x=>x.backgroundImageEnabled),n=ye(x=>x.backgroundSourceType),s=ye(x=>x.backgroundImagePath),o=ye(x=>x.backgroundFolderPath),r=ye(x=>x.backgroundUrlPath),a=ye(x=>x.backgroundRandomEnabled),l=ye(x=>x.backgroundRandomInterval),c=ye(x=>x.backgroundRefreshNonce),[d,u]=m.useState(0);m.useEffect(()=>{c>0&&u(x=>x+1)},[c]),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,d]);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(q4,{children:[e?.source==="user"&&i.jsx(Y4,{state:{sourceType:n,imagePath:s,folderPick:f,urlPath:r,tick:d},look:e}),e?.source==="theme"&&i.jsxs(JN,{look:e,children:[i.jsx(ZN,{image:"var(--enso-asset-background)",look:e}),i.jsx(QN,{mask:e.mask})]})]})}function q4({children:e}){const t=fn(s=>s.browserHoles),n=qN(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 YN=({blur:e,brightness:t,saturation:n})=>`blur(${e}px) brightness(${t}) saturate(${n})`,XN=({blur:e})=>e>0?`-${e*2}px`:"0";function Y4({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:Nf(s),video:Jh(s)};if(n==="folder"&&o)return{src:Nf(o),video:Jh(o)};if(n==="url"){const p=r.trim();if(/^https?:\/\//i.test(p))return{src:wA(p,a),video:Jh(p)}}return null},[n,s,o,r,a]),[c,d]=m.useState(null);if(m.useEffect(()=>{if(!l){d(null);return}if(l.video){d(l);return}let p=!1;const f=new Image;return f.onload=()=>{p||d(l)},f.src=l.src,()=>{p=!0}},[l]),!c)return null;const{src:u,video:h}=c;return i.jsxs(JN,{look:t,children:[h?i.jsx("video",{src:u,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"absolute",style:{inset:XN(t),width:"auto",height:"auto",minWidth:"100%",minHeight:"100%",objectFit:t.size==="contain"?"contain":"cover",filter:YN(t),transition:"filter 0.3s ease"}},u):i.jsx(ZN,{image:`url("${u}")`,look:t},u),i.jsx(QN,{mask:t.mask})]})}function JN({look:e,children:t}){return i.jsx("div",{"data-slot":"background-media",className:"absolute inset-0",style:{opacity:yA(e.opacity).wallpaperOpacity},children:t})}function ZN({image:e,look:t}){return i.jsx("div",{className:"absolute",style:{inset:XN(t),backgroundImage:e,...U4[t.size],filter:YN(t),transition:"filter 0.3s ease"}})}function QN({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 Cu(e,t,n,s){return{left:e,top:t,right:n,bottom:s,x:e,y:t,width:n-e,height:s-t}}function X4(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function eT(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((c,d)=>c.top-d.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(X4(l));else{const c=t[t.length-1];c.left=Math.min(c.left,l.left),c.right=Math.max(c.right,l.right),c.bottom=Math.max(c.bottom,l.bottom),c.width=c.right-c.left,c.height=c.bottom-c.top}n=l}return{lines:t,fallback:Cu(s,o,r,a)}}function tT(e,t,n){return e.findIndex(s=>t>s.left-2&&t<s.right+2&&n>s.top-2&&n<s.bottom+2)}function Iw(e){return Cu(e.left,e.top,e.right,e.bottom)}function J4(e,t,n){const{lines:s}=eT(e.getClientRects());if(s.length<2)return;const o=tT(s,t,n);return{x:t,y:n,lineIndex:o===-1?void 0:o,element:e}}function Z4(e,t,n){const{lines:s,fallback:o}=eT(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 Iw(s[n.lineIndex]);if(r!=null&&a!=null){const g=tT(s,r,a);if(g!==-1)return Iw(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 Cu(v.left,g.top,v.right,x.bottom)}const c=l==="l";let d=s[0].left,u=s[0].right,h=c?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,p=s[0],f=s[0];for(const g of s){d=Math.min(d,g.left),u=Math.max(u,g.right);const x=c?g.left:g.right;c&&x<h||!c&&x>h?(h=x,p=g,f=g):x===h&&(f=g)}return Cu(d,p.top,u,f.bottom)}function Q4(e){return"contextElement"in e&&e.contextElement?e.contextElement:SA(e)?e:void 0}function eW(e,t){function n(o){nT(e,o.currentTarget,o.clientX,o.clientY)}function s(o){t||n(o)}return{onFocus(){e.current=void 0},onMouseEnter:s,onMouseMove:s}}function nT(e,t,n,s){const o=J4(t,n,s);return e.current=o,o}function tW(e){return{name:"inline",async fn(t){const n=t.elements.reference;if(typeof n?.getClientRects!="function")return{};const s=Q4(n),o=e.current,r=o?.element===n||o?.element===s?o:void 0,a=Z4(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}}}}}const wm=10;function nW(e){const t=new Set,n=[];let s=0,o=0;for(const r of e){const a=r.path.trim();if(a){if(!r.isDirectory){s+=1;continue}t.has(a)||(t.add(a),o+=1,n.length<wm&&n.push(a))}}return{directories:n,skippedFiles:s,truncated:o>wm}}function sW(e){return e.types.includes("Files")&&e.entries.some(t=>t.isDirectory)}const iW=150;function oW(e,t=iW){let n=0,s=!1,o;const r=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},a=()=>{r(),n=0,s&&(s=!1,e(!1))},l=()=>{s||(s=!0,e(!0)),r(),o=setTimeout(a,t)};return{enter(c){c&&(n+=1,l())},over(c){c&&(n=Math.max(n,1),l())},leave(){s&&(n=Math.max(0,n-1),n===0&&a())},cancel:a,dispose:r}}function rW(e){const t=e.archivedIds.filter(o=>o!==e.projectId),n={...e.collapsed},s=e.knownIds.has(e.projectId);return s&&n[e.projectId]===!0&&(n[e.projectId]=!1),s&&e.latestConversationId?{archivedIds:t,collapsed:n,focus:{kind:"select",conversationId:e.latestConversationId}}:{archivedIds:t,collapsed:n,focus:{kind:"new"}}}const zd="enso-project-order",ym="enso-pinned-order",ro="enso-archived-projects",Ew="enso-pinned-projects",Sm=new Set;function Ei(e){try{const t=JSON.parse(localStorage.getItem(e)??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Io(e,t){localStorage.setItem(e,JSON.stringify(t));for(const n of Sm)n()}function sT(e){return Sm.add(e),()=>Sm.delete(e)}const iT="enso-collapsed-projects",Cm="enso-collapsed-projects-changed";function km(){try{const e=JSON.parse(localStorage.getItem(iT)??"{}");return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function aW(e){return window.addEventListener(Cm,e),()=>window.removeEventListener(Cm,e)}function lW(e){localStorage.setItem(iT,JSON.stringify(e)),window.dispatchEvent(new Event(Cm))}function cW(){try{const e=localStorage.getItem("enso-selected-project-group");return e?ye.getState().projectGroups.find(t=>t.id===e)?.id:void 0}catch{return}}function dW(e,t){return e.length===t.length&&e.every((n,s)=>n===t[s])}function uW(e){const t=e instanceof Error?e.message:String(e);return/not a directory/i.test(t)||/ENOENT|no such file/i.test(t)}function hW(e){const t=e instanceof Error?e.message:String(e);return/not a directory/i.test(t)}let Dp=Promise.resolve();function oT(e){return Dp=Dp.then(e).catch(()=>{}),Dp}async function rT(e,t){const n=ye.getState(),s=new Set(n.projects.map(l=>l.id)),o=await n.addProject(e,void 0,t??cW());if(!o)return;const r=oe.getState(),a=rW({projectId:o.id,knownIds:s,archivedIds:Ei(ro),collapsed:km(),latestConversationId:Xr(r.order,r.conversations,o.id)[0]});return dW(Ei(ro),a.archivedIds)||Io(ro,a.archivedIds),JSON.stringify(km())!==JSON.stringify(a.collapsed)&&lW(a.collapsed),{project:o,focus:a.focus}}async function aT(e,t){const n=oe.getState();if(e.focus.kind==="select"){await(t??n.selectConversation)(e.focus.conversationId);return}if(!await n.newConversation(e.project.id))throw new Error("Failed to create a conversation for the project.")}async function lT(e,t={}){const n=await rT(e,t.groupId);if(n)return await aT(n,t.onSelect),n.project}const Pw="enso-mode",uo=Dg()(e=>({mode:localStorage.getItem(Pw)==="bot"?"bot":"code",setMode:t=>{localStorage.setItem(Pw,t),e({mode:t})}}));function Gc(){return ye.getState().botModeEnabled&&is.getState().activeNodeId==="local"&&uo.getState().mode==="bot"}function pW(){const e=ye(s=>s.botModeEnabled),t=is(s=>s.activeNodeId==="local"),n=uo(s=>s.mode);return e&&t&&n==="bot"}async function fW(e){if(!ye.getState().botModeEnabled)return;const t=typeof e.chatId=="string"?e.chatId:void 0,n=typeof e.conversationId=="string"?e.conversationId:void 0,s=de.getState();t||await s.refreshDelegations(),is.getState().activeNodeId!=="local"&&is.getState().switchNode("local"),uo.getState().setMode("bot");const o=CA({chatId:t,conversationId:n},de.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 $x(){is.getState().activeNodeId!=="local"&&is.getState().switchNode("local"),uo.getState().setMode("code")}function Aw(e){try{return window.electronAPI.files.pathForFile(e)}catch{return""}}function mW(e){const t=e.dataTransfer?.items;if(t&&t.length>0){const n=[];for(let s=0;s<t.length;s+=1){const o=t[s];if(o.kind!=="file")continue;const r=o.getAsFile();if(!r)continue;const a=Aw(r),l=o.webkitGetAsEntry?.();n.push({path:a,isDirectory:l?l.isDirectory:r.size===0&&r.type===""})}return n}return Array.from(e.dataTransfer?.files??[]).map(n=>({path:Aw(n),isDirectory:n.size===0&&n.type===""}))}async function gW(e,t){const n=nW(e);let s=n.skippedFiles,o;for(const r of n.directories)try{o=await rT(r)??o}catch(a){if(hW(a)){s+=1;continue}if(uW(a))continue;ze({type:"error",title:t("Failed to add project"),description:a instanceof Error?a.message:String(a)})}if(o)try{await aT(o),$x()}catch(r){ze({type:"error",title:t("Failed to add project"),description:r instanceof Error?r.message:String(r)})}n.directories.length===0&&s===0&&ze({type:"error",title:t("Could not read the path of the dropped folder")}),s>0&&ze({type:"info",title:t("Only folders can be added as projects")}),n.truncated&&ze({type:"info",title:t("Only the first {{count}} folders were added",{count:wm})})}function xW(){const{t:e}=se(),[t,n]=m.useState(!1);return Ig(t),m.useEffect(()=>{if(window.electronAPI.remote)return;const s=oW(n),o=p=>Array.from(p.dataTransfer?.types??[]),r=p=>o(p).includes("Files"),a=p=>{r(p)&&(p.preventDefault(),s.enter(!0))},l=p=>{r(p)&&(p.preventDefault(),s.over(!0))},c=()=>s.leave(),d=()=>s.cancel(),u=p=>{p.key==="Escape"&&s.cancel()},h=p=>{if(s.cancel(),!r(p))return;p.preventDefault();const f=mW(p);sW({types:o(p),entries:f})&&(p.stopPropagation(),p.target?.dispatchEvent(new DragEvent("dragleave",{bubbles:!0})),oT(()=>gW(f,e)))};return window.addEventListener("dragenter",a,!0),window.addEventListener("dragover",l,!0),window.addEventListener("dragleave",c,!0),window.addEventListener("drop",h,!0),window.addEventListener("dragend",d,!0),window.addEventListener("blur",d),window.addEventListener("keydown",u,!0),()=>{window.removeEventListener("dragenter",a,!0),window.removeEventListener("dragover",l,!0),window.removeEventListener("dragleave",c,!0),window.removeEventListener("drop",h,!0),window.removeEventListener("dragend",d,!0),window.removeEventListener("blur",d),window.removeEventListener("keydown",u,!0),s.dispose()}},[e]),t?i.jsx("div",{className:"pointer-events-none fixed inset-0 flex items-center justify-center bg-background/70 backdrop-blur-[2px]",style:{zIndex:Cn.MODAL_BACKDROP},children:i.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-2xl border bg-card px-8 py-6 text-card-foreground shadow-lg",children:[i.jsx(yu,{className:"h-8 w-8 text-muted-foreground"}),i.jsx("p",{className:"text-sm font-medium",children:e("Drop folders to add projects")})]})}):null}function Mw(){const{t:e}=se(),[t,n]=m.useState(null),[s,o]=m.useState(!1),[r,a]=m.useState(!1),[l,c]=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 d=t.status==="available"&&r;if(t.status!=="downloaded"&&t.status!=="downloading"&&!d)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(Kk,{className:"h-3.5 w-3.5 shrink-0 text-blue-500"}):i.jsx(oc,{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??""}):d?e("New version {{version}} found",{version:u??""}):e("Downloading update… {{percent}}%",{percent:Math.round(t.progress?.percent??0)})}),(h||d)&&i.jsx("button",{type:"button",onClick:()=>c(!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")}),d&&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(kA,{open:l,onOpenChange:c,status:t})]})}const Ip="enso.zoomBanner.dismissedPercent";function vW(e,t){return e!==100&&e!==t}function bW(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function Ep(){return window.electronAPI.window.getZoomPercent()}function Rw(){const{t:e}=se(),[t,n]=m.useState(Ep),[s,o]=m.useState(()=>bW(localStorage.getItem(Ip)));return m.useEffect(()=>{const r=()=>n(Ep());return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),vW(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(Ip),o(null),n(Ep())},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(Ip,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 wW(e,t){return[t,...e.filter(n=>n.parentId===t.id).sort((n,s)=>n.createdAt-s.createdAt)]}function yW(e,t){return(t.activeThreadId?e.find(s=>s.id===t.activeThreadId&&s.parentId===t.id):void 0)??t}const SW=10,cT=e=>[...e].sort((t,n)=>n.activityAt-t.activityAt);function dT(e,t,n=SW){const s=cT(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 Lw(e,t,n){const s=t.trim().toLowerCase();return cT(e).filter(o=>(n==="all"||(n==="unread"?o.unread:o.running))&&(!s||`${o.title}
|
|
20
|
-
${o.preview??""}`.toLowerCase().includes(s)))}function ku({onResize:e,onResizingChange:t,gap:n=!1,edge:s=!1}){const[o,r]=m.useState(!1),a=m.useRef(0),l=m.useCallback(c=>{c.preventDefault(),r(!0),t?.(!0),a.current=c.clientX;const d=h=>{e(h.clientX-a.current),a.current=h.clientX},u=()=>{r(!1),t?.(!1),document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",u)};document.addEventListener("mousemove",d),document.addEventListener("mouseup",u)},[e,t]);return i.jsxs("div",{className:U("relative z-20 shrink-0",s?"w-0":n?"w-[8px]":"w-px bg-border"),children:[i.jsx("div",{onMouseDown:l,className:U("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 CW={"external-send":"Protected: external send",delete:"Protected: delete",payment:"Protected: payment",deploy:"Protected: deploy / production",secret:"Protected: secrets",destructive:"Protected: destructive command"};function uT(e,t){return t(CW[e])}const hT={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",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 Fo(e,t){const n=hT[e];return n?t(n):e}const kW={report:"Read report",wait:"Wait",stop:"Stop",dismiss:"Dismiss agent",list:"List agents"};function Wx(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 Ux({remainingMs:e,expiredLabel:t}){const{t:n}=se();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 jW={command:$o,"file-edit":d6,"file-write":h6,mcp:qk};function _W({kind:e,summary:t}){const[n,s]=m.useState(null);m.useEffect(()=>{if(e!=="command")return;let a=!0;return _A(t,"shellscript").then(l=>{a&&s({summary:t,html:l})}),()=>{a=!1}},[e,t]);const o=n?.summary===t?n.html:null,r=i.jsx(Yk,{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"&&o!=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:o}}),r]}):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}),r]})}const NW={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."},TW=400;function jh({approvals:e,onRespond:t,allowSession:n=!0,handoff:s=!0,clockOffset:o}){const{t:r}=se(),[a,l]=m.useState(null),[c,d]=m.useState(null),u=e[0],h=u?.requestId,p=Wx(u?.phase==="reviewing"?void 0:u?.expiresAt,o);if(m.useEffect(()=>{if(!h)return;const y=setTimeout(()=>d(h),TW);return()=>clearTimeout(y)},[h]),!u)return null;const f=jW[u.kind]??oa,g=u.phase==="reviewing",x=c!==u.requestId||a===u.requestId||p!==void 0&&p<=0,v=y=>{y!=="review"&&l(u.requestId),t(u.requestId,y)};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(oa,{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(g?"Assistant reviewing…":"Approval required")}),i.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-muted-foreground",children:[i.jsx(f,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate font-mono",children:u.toolCallId&&jA(u.toolCallId)?`${r("Isolated sandbox")} › ${Fo(u.tool,r)}`:Fo(u.tool,r)})]}),u.protected&&i.jsx("span",{className:"shrink-0 rounded bg-destructive/15 px-1.5 text-[10px] text-destructive",children:uT(u.protected,r)}),i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[i.jsx(Ux,{remainingMs:p,expiredLabel:"Timed out · denied"}),e.length>1&&i.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["1/",e.length]})]})]}),u.reviewFallback&&i.jsx("p",{className:"mt-1 text-[11px] text-amber-600 dark:text-amber-400",children:r(NW[u.reviewFallback])}),u.guard&&i.jsx("p",{className:"mt-1 text-[11px] text-destructive",title:u.guard.ruleId,children:r("dcg: {{reason}}",{reason:u.guard.reason})}),u.summary&&i.jsx(_W,{kind:u.kind,summary:u.summary}),!g&&i.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[s&&u.kind==="command"&&i.jsx("button",{type:"button",disabled:x,title:r("Send back for a safer command"),onClick:()=>v("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:x,title:r("Let the assistant decide"),onClick:()=>v("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:x,onClick:()=>v("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&&!u.protected&&i.jsx("button",{type:"button",disabled:x,onClick:()=>v("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:x,onClick:()=>v("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 Ow(e){return e>=0&&e<9?String(e+1):null}function DW(e,t){const n=t===void 0?-1:e?.indexOf(t)??-1;return n>=0?n:0}function IW(e,t,n){return n==="ArrowDown"?Math.min(e+1,t-1):n==="ArrowUp"?Math.max(e-1,0):null}function _h({asks:e,onAnswer:t,clockOffset:n,autoFocus:s=!0}){const{t:o}=se(),r=m.useRef(null),a=m.useRef([]),[l,c]=m.useState(""),[d,u]=m.useState(null),[h,p]=m.useState(()=>new Set),f=e[0],g=f?.requestId,x=Wx(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=DW(y,b),k=a.current[S];y&&S<y.length&&k?k.focus():r.current?.focus()},[s,g,v]),!f)return null;const C=d===f.requestId||x!==void 0&&x<=0,_=S=>{S.trim()&&(u(f.requestId),c(""),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(l0,{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||C)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),D=I>=0?IW(I,A,S.key):null;if(D!==null){S.preventDefault(),w(D);return}if(k instanceof HTMLInputElement&&(k.value.length>0||S.key==="Enter"))return;const P=Number(S.key)-1,T=y?.[P];if(Ow(P)&&T){S.preventDefault(),_(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(),c(z=>z+S.key),r.current?.focus()))},children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(l0,{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(Ux,{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=Ow(k);return i.jsxs("button",{ref:I=>{a.current[k]=I},type:"button",disabled:C,onClick:()=>_(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=>c(S.target.value),onKeyDown:S=>{S.nativeEvent.isComposing||S.key==="Enter"&&_(l)},disabled:C,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:C||!l.trim(),onClick:()=>_(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(Vx,{className:"h-3.5 w-3.5"})})]})]})}const Nh=0,qo=1,Ea=2,pT=4;function zw(e){return()=>e}function EW(e){e()}function fT(e,t){return n=>e(t(n))}function Gw(e,t){return()=>e(t)}function PW(e,t){return n=>e(t,n)}function Kx(e){return e!==void 0}function AW(...e){return()=>{e.map(EW)}}function Pa(){}function Th(e,t){return t(e),e}function MW(e,t){return t(e)}function Rn(...e){return e}function gn(e,t){return e(qo,t)}function $t(e,t){e(Nh,t)}function qx(e){e(Ea)}function Ln(e){return e(pT)}function St(e,t){return gn(e,PW(t,Nh))}function fi(e,t){const n=e(qo,s=>{n(),t(s)});return n}function Fw(e){let t,n;return s=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{s(t)},e)}}function mT(e,t){return e===t}function An(e=mT){let t;return n=>s=>{e(t,s)||(t=s,n(s))}}function Rt(e){return t=>n=>{e(n)&&t(n)}}function mt(e){return t=>fT(t,e)}function Ii(e){return t=>()=>{t(e)}}function Ve(e,...t){const n=RW(...t);return((s,o)=>{switch(s){case Ea:qx(e);return;case qo:return gn(e,n(o))}})}function Li(e,t){return n=>s=>{n(t=e(t,s))}}function Sr(e){return t=>n=>{e>0?e--:t(n)}}function lo(e){let t=null,n;return s=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,s(t)},e))}}function Zt(...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;gn(r,c=>{const d=n;n|=l,t[a]=c,d!==o&&n===o&&s&&(s(),s=null)})}),r=>a=>{const l=()=>{r([a].concat(t))};n===o?l():s=l}}function RW(...e){return t=>e.reduceRight(MW,t)}function LW(e){let t,n;const s=()=>t?.();return function(o,r){switch(o){case qo:return r?n===r?void 0:(s(),n=r,t=gn(e,r),t):(s(),Pa);case Ea:s(),n=null;return}}}function Je(e){let t=e;const n=rn();return((s,o)=>{switch(s){case Nh:t=o;break;case qo:{o(t);break}case pT:return t}return n(s,o)})}function fs(e,t){return Th(Je(t),n=>St(e,n))}function rn(){const e=[];return((t,n)=>{switch(t){case Nh:e.slice().forEach(s=>{s(n)});return;case Ea:e.splice(0);return;case qo:return e.push(n),()=>{const s=e.indexOf(n);s>-1&&e.splice(s,1)}}})}function Fs(e){return Th(rn(),t=>St(e,t))}const OW={singleton:!0};function hn(e,t=[],n=OW){const{singleton:s}=n;return{constructor:e,dependencies:t,id:zW(),singleton:s}}const zW=()=>Symbol("id");function GW(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(c=>n(c)));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;gn(r,c=>{n[a]=c,s|=l,s===o&&$t(t,n)})}),function(r,a){switch(r){case Ea:{qx(t);return}case qo:return s===o&&a(n),gn(t,a)}}}function Mt(e,t=mT){return Ve(e,An(t))}function jm(...e){return function(t,n){switch(t){case Ea:return;case qo:return AW(...e.map(s=>gn(s,n)))}}}const es={DEBUG:0,INFO:1,WARN:2,ERROR:3},FW={[es.DEBUG]:"debug",[es.ERROR]:"error",[es.INFO]:"log",[es.WARN]:"warn"},HW=()=>typeof globalThis>"u"?window:globalThis,Yo=hn(()=>{const e=Je(es.ERROR);return{log:Je((t,n,s=es.INFO)=>{const o=HW().VIRTUOSO_LOG_LEVEL??Ln(e);s>=o&&console[FW[s]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function BW(e){return"self"in e?e.document.documentElement:e}function gT(e){const t=BW(e);return t.ownerDocument.defaultView.getComputedStyle(t).direction==="rtl"}function pr(e,t){return gT(e)?-t:t}function Hw(e,t){return gT(e)?-t:t}function jr(e,t,n){return Yx(e,t,n).callbackRef}function Yx(e,t,n){const s=Ne.useRef(null);let o=a=>{};const r=Ne.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(a=>{const l=()=>{const c=a[0].target;c.offsetParent!==null&&e(c)};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 VW(e,t,n,s,o,r,a,l,c){const d=Ne.useCallback(u=>{const h=$W(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?pr(a,a.scrollLeft):a.scrollTop:f?l?pr(g,g.scrollX||g.document.documentElement.scrollLeft):g.scrollY||g.document.documentElement.scrollTop:l?pr(p,p.scrollLeft):p.scrollTop;s({scrollHeight:x,scrollTop:Math.max(y,0),viewportHeight:v}),r?.(l?Bw("column-gap",getComputedStyle(u).columnGap,o):Bw("row-gap",getComputedStyle(u).rowGap,o)),h!==null&&e(h)},[e,t,o,r,a,s,l]);return Yx(d,n,c)}function $W(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 c=parseInt(l.dataset.index,10),d=parseFloat(l.dataset.knownSize),u=t(l,n);if(u===0&&s("Zero-sized element, this should not happen",{child:l},es.ERROR),u===d)continue;const h=r[r.length-1];r.length===0||h.size!==u||h.endIndex!==c-1?r.push({endIndex:c,size:u,startIndex:c}):r[r.length-1].endIndex++}return r}function Bw(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 xT(e,t,n){const s=Ne.useRef(null),o=Ne.useCallback(c=>{if(!c?.offsetParent)return;const d=c.getBoundingClientRect(),u=d.width;let h,p;if(t){const f=t.getBoundingClientRect(),g=d.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,d.top),h=d.top+f.scrollY}s.current={listHeight:d.height,offsetTop:h,visibleHeight:p,visibleWidth:u},e(s.current)},[e,t]),{callbackRef:r,ref:a}=Yx(o,!0,n),l=Ne.useCallback(()=>{o(a.current)},[o,a]);return Ne.useEffect(()=>{if(t){t.addEventListener("scroll",l);const d=new ResizeObserver(()=>{requestAnimationFrame(l)});return d.observe(t),()=>{t.removeEventListener("scroll",l),d.unobserve(t)}}const c=a.current?.ownerDocument.defaultView;return c?.addEventListener("scroll",l),c?.addEventListener("resize",l),()=>{c?.removeEventListener("scroll",l),c?.removeEventListener("resize",l)}},[l,t,a]),r}const Ds=hn(()=>{const e=rn(),t=rn(),n=Je(0),s=rn(),o=Je(0),r=rn(),a=rn(),l=Je(0),c=Je(0),d=Je(0),u=Je(0),h=rn(),p=rn(),f=Je(!1),g=Je(!1),x=Je(!1);return St(Ve(e,mt(({scrollTop:v})=>v)),t),St(Ve(e,mt(({scrollHeight:v})=>v)),a),St(t,o),{deviation:n,fixedFooterHeight:d,fixedHeaderHeight:c,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 vT(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:c}=t(e[a]);r.push({end:l-1,start:s,value:o}),s=l,o=c}return r.push({end:1/0,start:s,value:o}),r}function kn(e){return e===Wl}function Ul(e,t){if(!kn(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(kn(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 kn(e)?yT(t,n,1):t===e.k?Jn(e,{k:t,v:n}):t<e.k?Vw(Jn(e,{l:Ls(e.l,t,n)})):Vw(Jn(e,{r:Ls(e.r,t,n)}))}function Qr(){return Wl}function ea(e,t,n){if(kn(e))return[];const s=yi(e,t)[0];return WW(Nm(e,s,n))}function _m(e,t){if(kn(e))return Wl;const{k:n,l:s,r:o}=e;if(t===n){if(kn(s))return o;if(kn(o))return s;const[r,a]=wT(s);return Gd(Jn(e,{k:r,l:bT(s),v:a}))}return t<n?Gd(Jn(e,{l:_m(s,t)})):Gd(Jn(e,{r:_m(o,t)}))}function fr(e){return kn(e)?[]:[...fr(e.l),{k:e.k,v:e.v},...fr(e.r)]}function Nm(e,t,n){if(kn(e))return[];const{k:s,l:o,r,v:a}=e;let l=[];return s>t&&(l=l.concat(Nm(o,t,n))),s>=t&&s<=n&&l.push({k:s,v:a}),s<=n&&(l=l.concat(Nm(r,t,n))),l}function Gd(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(Pp(t))return ST(Jn(e,{lvl:n-1}));if(!kn(t)&&!kn(t.r))return Jn(t.r,{l:Jn(t,{r:t.r.l}),lvl:n,r:Jn(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}if(Pp(e))return Tm(Jn(e,{lvl:n-1}));if(!kn(s)&&!kn(s.l)){const o=s.l,r=Pp(o)?s.lvl-1:s.lvl;return Jn(o,{l:Jn(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:Tm(Jn(s,{l:o.r,lvl:r}))})}throw new Error("Unexpected empty nodes")}function Jn(e,t){return yT(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 bT(e){return kn(e.r)?e.l:Gd(Jn(e,{r:bT(e.r)}))}function Pp(e){return kn(e)||e.lvl>e.r.lvl}function wT(e){return kn(e.r)?[e.k,e.v]:wT(e.r)}function yT(e,t,n,s=Wl,o=Wl){return{k:e,l:s,lvl:n,r:o,v:t}}function Vw(e){return Tm(ST(e))}function ST(e){const{l:t}=e;return!kn(t)&&t.lvl===e.lvl?Jn(t,{r:Jn(e,{l:t.r})}):e}function Tm(e){const{lvl:t,r:n}=e;return!kn(n)&&!kn(n.r)&&n.lvl===t&&n.r.lvl===t?Jn(n,{l:Jn(e,{r:n.l}),lvl:t+1}):e}function WW(e){return vT(e,({k:t,v:n})=>({index:t,value:n}))}function CT(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 Xx=hn(()=>({recalcInProgress:Je(!1)}),[],{singleton:!0});function kT(e,t,n){return e[ju(e,t,n)]}function ju(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=ju(e,t,s),r=ju(e,n,s,o);return e.slice(o,r+1)}function Ho(e,t){return Math.round(e.getBoundingClientRect()[t])}function Dh(e){return!kn(e.groupOffsetTree)}function Jx({index:e},t){return t===e?0:t<e?-1:1}function KW(){return{groupIndices:[],groupOffsetTree:Qr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Qr()}}function qW(e,t){let n=kn(e)?0:1/0;for(const s of t){const{endIndex:o,size:r,startIndex:a}=s;if(n=Math.min(n,a),kn(e)){e=Ls(e,0,r);continue}const l=ea(e,a-1,o+1);if(l.some(t8(s)))continue;let c=!1,d=!1;for(const{end:u,start:h,value:p}of l)c?(o>=h||r===p)&&(e=_m(e,h)):(d=p!==r,c=!0),u>o&&o>=h&&p!==r&&(e=Ls(e,o+1,p));d&&(e=Ls(e,a,r))}return[e,n]}function YW(e){return e.groupIndex!==void 0}function XW({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}=kT(t,e,Jx),a=e-s,l=r*a+(a-1)*n+o;return l>0?l+n:l}function jT(e,t){if(!Dh(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function _T(e,t,n){if(YW(e))return t.groupIndices[e.groupIndex]+1;const s=e.index==="LAST"?n:e.index;let o=jT(s,t);return o=Math.max(0,Math.min(n,o)),o}function JW(e,t,n,s=0){return s>0&&(t=Math.max(t,kT(e,s,Jx).offset)),vT(UW(e,t,n,XW),e8)}function ZW(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&&kn(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]=qW(a,t);if(a===r)return e;const{lastIndex:c,lastOffset:d,lastSize:u,offsetTree:h}=Dm(e.offsetTree,l,a,o);return{groupIndices:n,groupOffsetTree:n.reduce((p,f)=>Ls(p,f,ql(f,h,o)),Qr()),lastIndex:c,lastOffset:d,lastSize:u,offsetTree:h,sizeTree:a}}function QW(e){return fr(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 $w(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 Dm(e,t,n,s){let o=e,r=0,a=0,l=0,c=0;if(t===0)o=[];else{c=ju(o,t-1,Jx),l=o[c].offset;const d=yi(n,t-1);r=d[0],a=d[1],o.length&&o[c].size===yi(n,t)[1]&&(c-=1),o=o.slice(0,c+1)}for(const{start:d,value:u}of ea(n,t,1/0)){const h=d-r,p=h*a+l+h*s;o.push({index:d,offset:p,size:u}),r=d,l=p,a=u}return{lastIndex:r,lastOffset:l,lastSize:a,offsetTree:o}}function e8(e){return{index:e.index,value:e}}function t8(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 n8={offsetHeight:"height",offsetWidth:"width"},$i=hn(([{log:e},{recalcInProgress:t}])=>{const n=rn(),s=rn(),o=fs(s,0),r=rn(),a=rn(),l=Je(0),c=Je([]),d=Je(void 0),u=Je(void 0),h=Je(void 0),p=Je(void 0),f=Je((S,k)=>Ho(S,n8[k])),g=Je(void 0),x=Je(0),v=KW(),y=fs(Ve(n,Zt(c,e,x),Li(ZW,v),An()),v),b=fs(Ve(c,An(),Li((S,k)=>({current:k,prev:S.current}),{current:[],prev:[]}),mt(({prev:S})=>S)),[]);St(Ve(c,Rt(S=>S.length>0),Zt(y,x),mt(([S,k,A])=>{const I=S.reduce((D,P,T)=>Ls(D,P,ql(P,k.offsetTree,A)||T),Qr());return{...k,groupIndices:S,groupOffsetTree:I}})),y),St(Ve(s,Zt(y),Rt(([S,{lastIndex:k}])=>S<k),mt(([S,{lastIndex:k,lastSize:A}])=>[{endIndex:k,size:A,startIndex:S}])),n),St(d,u);const w=fs(Ve(d,mt(S=>S===void 0)),!0);St(Ve(u,Rt(S=>S!==void 0&&kn(Ln(y).sizeTree)),mt(S=>{const k=Ln(h),A=Ln(c).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),St(Ve(p,Rt(S=>S!==void 0&&S.length>0&&kn(Ln(y).sizeTree)),mt(S=>{const k=[];let A=S[0],I=0;for(let D=1;D<S.length;D++){const P=S[D];P!==A&&(k.push({endIndex:D-1,size:A,startIndex:I}),A=P,I=D)}return k.push({endIndex:S.length-1,size:A,startIndex:I}),k})),n),St(Ve(c,Zt(h,u),Rt(([,S,k])=>S!==void 0&&k!==void 0),mt(([S,k,A])=>{const I=[];for(let D=0;D<S.length;D++){const P=S[D],T=S[D+1];I.push({startIndex:P,endIndex:P,size:k}),T!==void 0&&I.push({startIndex:P+1,endIndex:T-1,size:A})}return I})),n);const C=Fs(Ve(n,Zt(y),Li(({sizes:S},[k,A])=>({changed:A!==S,sizes:A}),{changed:!1,sizes:v}),mt(S=>S.changed)));gn(Ve(l,Li((S,k)=>({diff:S.prev-k,prev:k}),{diff:0,prev:0}),mt(S=>S.diff)),S=>{const{groupIndices:k}=Ln(y);if(S>0)$t(t,!0),$t(r,S+$w(S,k));else if(S<0){const A=Ln(b);A.length>0&&(S-=$w(-S,A)),$t(a,S)}}),gn(Ve(l,Zt(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 _=Fs(r);St(Ve(r,Zt(y),mt(([S,k])=>{const A=k.groupIndices.length>0,I=[],D=k.lastSize;if(A){const P=Ul(k.sizeTree,0);let T=0,z=0;for(;T<S;){const L=k.groupIndices[z],V=k.groupIndices.length===z+1?1/0:k.groupIndices[z+1]-L-1;I.push({endIndex:L,size:P,startIndex:L}),I.push({endIndex:L+1+V-1,size:D,startIndex:L+1}),z++,T+=V+1}const O=fr(k.sizeTree);return T!==S&&O.shift(),O.reduce((L,{k:V,v:X})=>{let F=L.ranges;return L.prevSize!==0&&(F=[...L.ranges,{endIndex:V+S-1,size:L.prevSize,startIndex:L.prevIndex}]),{prevIndex:V+S,prevSize:X,ranges:F}},{prevIndex:S,prevSize:0,ranges:I}).ranges}return fr(k.sizeTree).reduce((P,{k:T,v:z})=>({prevIndex:T+S,prevSize:z,ranges:[...P.ranges,{endIndex:T+S-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:D,ranges:[]}).ranges})),n);const N=Fs(Ve(a,Zt(y,x),mt(([S,{offsetTree:k},A])=>{const I=-S;return ql(I,k,A)})));return St(Ve(a,Zt(y,x),mt(([S,k,A])=>{if(k.groupIndices.length>0){if(kn(k.sizeTree))return k;let D=Qr();const P=Ln(b);let T=0,z=0,O=0;for(;T<-S;){O=P[z];const L=P[z+1]-O-1;z++,T+=L+1}if(D=fr(k.sizeTree).reduce((L,{k:V,v:X})=>Ls(L,Math.max(0,V+S),X),D),T!==-S){const L=Ul(k.sizeTree,O);D=Ls(D,0,L);const V=yi(k.sizeTree,-S+1)[1];D=Ls(D,1,V)}return{...k,sizeTree:D,...Dm(k.offsetTree,0,D,A)}}const I=fr(k.sizeTree).reduce((D,{k:P,v:T})=>Ls(D,Math.max(0,P+S),T),Qr());return{...k,sizeTree:I,...Dm(k.offsetTree,0,I,A)}})),y),{beforeUnshiftWith:_,data:g,defaultItemSize:u,firstItemIndex:l,fixedItemSize:d,fixedGroupSize:h,gap:x,groupIndices:c,heightEstimates:p,itemSize:f,listRefresh:C,shiftWith:a,shiftWithOffset:N,sizeRanges:n,sizes:y,statefulTotalCount:o,totalCount:s,trackItemSizes:w,unshiftWith:r}},Rn(Yo,Xx),{singleton:!0});function s8(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const NT=hn(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:s,scrollTop:o}])=>{const r=rn(),a=rn(),l=Fs(Ve(r,mt(s8)));return St(Ve(l,mt(c=>c.totalCount)),n),St(Ve(l,mt(c=>c.groupIndices)),e),St(Ve(Bn(o,t,s),Rt(([c,d])=>Dh(d)),mt(([c,d,u])=>yi(d.groupOffsetTree,Math.max(c-u,0),"v")[0]),An(),mt(c=>[c])),a),{groupCounts:r,topItemsIndexes:a}},Rn($i,Ds)),Xo=hn(([{log:e}])=>{const t=Je(!1),n=Fs(Ve(t,Rt(s=>s),An()));return gn(t,s=>{s&&Ln(e)("props updated",{},es.DEBUG)}),{didMount:n,propsReady:t}},Rn(Yo),{singleton:!0}),i8=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function TT(e){const t=typeof e=="number"?{index:e}:{...e};return t.align||(t.align="start"),(!t.behavior||!i8)&&(t.behavior="auto"),t.offset===void 0&&(t.offset=0),t}const kc=hn(([{gap:e,listRefresh:t,sizes:n,totalCount:s},{fixedFooterHeight:o,fixedHeaderHeight:r,footerHeight:a,headerHeight:l,scrollingInProgress:c,scrollTo:d,smoothScrollTargetReached:u,viewportHeight:h},{log:p}])=>{const f=rn(),g=rn(),x=Je(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),$t(c,!1)}return St(Ve(f,Zt(n,h,s,x,l,a,p),Zt(e,r,o),mt(([[C,_,N,S,k,A,I,D],P,T,z])=>{const O=TT(C),{align:L,behavior:V,offset:X}=O,F=S-1,ee=_T(O,_,F);let H=ql(ee,_.offsetTree,P)+A;L==="end"?(H+=T+yi(_.sizeTree,ee)[1]-N+z,ee===F&&(H+=I)):L==="center"?H+=(T+yi(_.sizeTree,ee)[1]-N+z)/2:H-=k,X!==void 0&&X!==0&&(H+=X);const Q=q=>{w(),q?(D("retrying to scroll to",{location:C},es.DEBUG),$t(f,C)):($t(g,!0),D("list did not change, scroll successful",{},es.DEBUG))};if(w(),V==="smooth"){let q=!1;b=gn(t,ne=>{q=q||ne}),v=fi(u,()=>{Q(q)})}else v=fi(Ve(t,o8(150)),Q);return y=setTimeout(()=>{w()},1200),$t(c,!0),D("scrolling from index to",{behavior:V,index:ee,top:H},es.DEBUG),{behavior:V,top:H}})),d),{scrollTargetReached:g,scrollToIndex:f,topListHeight:x}},Rn($i,Ds,Yo),{singleton:!0});function o8(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return s=>{s&&(t(!0),clearTimeout(n))}}}function Zx(e,t){e===0?t():requestAnimationFrame(()=>{Zx(e-1,t)})}function Qx(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 Im(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 jc=hn(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:s},{scrollTargetReached:o,scrollToIndex:r},{didMount:a}])=>{const l=Je(!0),c=Je(0),d=Je(!0);return St(Ve(a,Zt(c),Rt(([u,h])=>!Im(h)),Ii(!1)),l),St(Ve(a,Zt(c),Rt(([u,h])=>!Im(h)),Ii(!1)),d),gn(Ve(Bn(t,a),Zt(l,n,e,d),Rt(([[,u],h,{sizeTree:p},f,g])=>u&&(!kn(p)||Kx(f))&&!h&&!g),Zt(c)),([,u])=>{if(u===void 0){$t(l,!0),$t(d,!0);return}fi(o,()=>{$t(d,!0)}),Zx(4,()=>{fi(s,()=>{$t(l,!0)}),$t(r,u)})}),{initialItemFinalLocationReached:d,initialTopMostItemIndex:c,scrolledToInitialItem:l}},Rn($i,Ds,kc,Xo),{singleton:!0});function DT(e,t){return Math.abs(e-t)<1.01}const Yl="up",gl="down",r8="none",a8={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},l8=0,_c=hn(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:s,scrollTop:o,viewportHeight:r}])=>{const a=Je(!1),l=Je(!0),c=rn(),d=rn(),u=Je(4),h=Je(l8),p=fs(Ve(jm(Ve(Mt(o),Sr(1),Ii(!0)),Ve(Mt(o),Sr(1),Ii(!1),Fw(100))),An()),!1),f=fs(Ve(jm(Ve(n,Ii(!0)),Ve(n,Ii(!1),Fw(200))),An()),!1);St(Ve(Bn(Mt(o),Mt(h)),mt(([b,w])=>b<=w),An()),l),St(Ve(l,lo(50)),d);const g=Fs(Ve(Bn(s,Mt(r),Mt(t),Mt(e),Mt(u)),Li((b,[{scrollHeight:w,scrollTop:C},_,N,S,k])=>{const A=C+_-w>-k,I={scrollHeight:w,scrollTop:C,viewportHeight:_};if(A){let P,T;return C>b.state.scrollTop?(P="SCROLLED_DOWN",T=b.state.scrollTop-C):(P="SIZE_DECREASED",T=b.state.scrollTop-C||b.scrollTopDelta),{atBottom:!0,atBottomBecause:P,scrollTopDelta:T,state:I}}let D;return I.scrollHeight>b.state.scrollHeight?D="SIZE_INCREASED":_<b.state.viewportHeight?D="VIEWPORT_HEIGHT_DECREASING":C<b.state.scrollTop?D="SCROLLING_UPWARDS":D="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:D,state:I}},a8),An((b,w)=>b!==void 0&&b.atBottom===w.atBottom))),x=fs(Ve(s,Li((b,{scrollHeight:w,scrollTop:C,viewportHeight:_})=>{if(!DT(b.scrollHeight,w)){const N=w-(C+_)<1;return b.scrollTop!==C&&N?{changed:!0,jump:b.scrollTop-C,scrollHeight:w,scrollTop:C}:{changed:!0,jump:0,scrollHeight:w,scrollTop:C}}return{changed:!1,jump:0,scrollHeight:w,scrollTop:C}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Rt(b=>b.changed),mt(b=>b.jump)),0);St(Ve(g,mt(b=>b.atBottom)),a),St(Ve(a,lo(50)),c);const v=Je(gl);St(Ve(s,mt(({scrollTop:b})=>b),An(),Li((b,w)=>Ln(f)?{direction:b.direction,prevScrollTop:w}:{direction:w<b.prevScrollTop?Yl:gl,prevScrollTop:w},{direction:gl,prevScrollTop:0}),mt(b=>b.direction)),v),St(Ve(s,lo(50),Ii(r8)),v);const y=Je(0);return St(Ve(p,Rt(b=>!b),Ii(0)),y),St(Ve(o,lo(100),Zt(p),Rt(([b,w])=>w),Li(([b,w],[C])=>[w,C],[0,0]),mt(([b,w])=>w-b)),y),{atBottomState:g,atBottomStateChange:c,atBottomThreshold:u,atTopStateChange:d,atTopThreshold:h,isAtBottom:a,isAtTop:l,isScrolling:p,lastJumpDueToItemResize:x,scrollDirection:v,scrollVelocity:y}},Rn(Ds)),Xl="top",Jl="bottom",Ww="none";function Uw(e,t,n){return typeof e=="number"?n===Yl&&t===Xl||n===gl&&t===Jl?e:0:n===Yl?t===Xl?e.main:e.reverse:t===Jl?e.main:e.reverse}function Kw(e,t){return typeof e=="number"?e:e[t]??0}const ev=hn(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:s,viewportHeight:o}])=>{const r=rn(),a=Je(0),l=Je(0),c=Je(0),d=fs(Ve(Bn(Mt(s),Mt(o),Mt(n),Mt(r,Kl),Mt(c),Mt(a),Mt(t),Mt(e),Mt(l)),mt(([u,h,p,[f,g],x,v,y,b,w])=>{const C=u-b,_=v+y,N=Math.max(p-C,0);let S=Ww;const k=Kw(w,Xl),A=Kw(w,Jl);return f-=b,f+=p+y,g+=p+y,g-=b,f>u+_-k&&(S=Yl),g<u-N+h+A&&(S=gl),S!==Ww?[Math.max(C-p-Uw(x,Xl,S)-k,0),C-N-y+h+Uw(x,Jl,S)+A]:null}),Rt(u=>u!==null),An(Kl)),[0,0]);return{increaseViewportBy:l,listBoundary:r,overscan:c,topListHeight:a,visibleRange:d}},Rn(Ds),{singleton:!0});function c8(e,t,n){if(Dh(t)){const s=jT(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 Ap={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Fd(e,t,n,s,o,r){const{lastIndex:a,lastOffset:l,lastSize:c}=o;let d=0,u=0;if(e.length>0){d=e[0].offset;const x=e[e.length-1];u=x.offset+x.size}const h=n-a,p=l+h*c+(h-1)*s,f=d,g=p-u;return{bottom:u,firstItemIndex:r,items:qw(e,o,r),offsetBottom:g,offsetTop:d,top:f,topItems:qw(t,o,r),topListHeight:t.reduce((x,v)=>v.size+x,0),totalCount:n}}function IT(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,c=Qx(t,l),d=Array.from({length:l}).map((u,h)=>({data:r[h+c],index:h+c,offset:0,size:0}));return Fd(d,[],l,o,n,s)}function qw(e,t,n){if(e.length===0)return[];if(!Dh(t))return e.map(d=>({...d,index:d.index+n,originalIndex:d.index}));const s=e[0].index,o=e[e.length-1].index,r=[],a=ea(t.groupOffsetTree,s,o);let l,c=0;for(const d of e){(!l||l.end<d.index)&&(l=a.shift(),c=t.groupIndices.indexOf(l.start));let u;d.index===l.start?u={index:c,type:"group"}:u={groupIndex:c,index:d.index-(c+1)+n},r.push({...u,data:d.data,offset:d.offset,originalIndex:d.index,size:d.size})}return r}function Yw(e,t){return e===void 0?0:typeof e=="number"?e:e[t]??0}const _r=hn(([{data:e,firstItemIndex:t,gap:n,sizes:s,totalCount:o},r,{listBoundary:a,topListHeight:l,visibleRange:c},{initialTopMostItemIndex:d,scrolledToInitialItem:u},{topListHeight:h},p,{didMount:f},{recalcInProgress:g}])=>{const x=Je([]),v=Je(0),y=rn(),b=Je(0);St(r.topItemsIndexes,x);const w=fs(Ve(Bn(f,g,Mt(c,Kl),Mt(o),Mt(s),Mt(d),u,Mt(x),Mt(t),Mt(n),Mt(b),e),Rt(([S,k,,A,,,,,,,,I])=>{const D=I!==void 0&&I.length!==A;return S&&!k&&!D}),mt(([,,[S,k],A,I,D,P,T,z,O,L,V])=>{const X=I,{offsetTree:F,sizeTree:ee}=X,H=Ln(v);if(A===0)return{...Ap,totalCount:A};if(S===0&&k===0)return H===0?{...Ap,totalCount:A}:IT(H,D,I,z,O,V||[]);if(kn(ee))return H>0?null:Fd(c8(Qx(D,A),X,V),[],A,O,X,z);const Q=[];if(T.length>0){const $=T[0],W=T[T.length-1];let ue=0;for(const Z of ea(ee,$,W)){const J=Z.value,ae=Math.max(Z.start,$),te=Math.min(Z.end,W);for(let pe=ae;pe<=te;pe++)Q.push({data:V?.[pe],index:pe,offset:ue,size:J}),ue+=J}}if(!P)return Fd([],Q,A,O,X,z);const q=T.length>0?T[T.length-1]+1:0,ne=JW(F,S,k,q);if(ne.length===0)return null;const me=A-1,ke=Th([],$=>{for(const W of ne){const ue=W.value;let Z=ue.offset,J=W.start;const ae=ue.size;if(ue.offset<S){J+=Math.floor((S-ue.offset+O)/(ae+O));const pe=J-W.start;Z+=pe*ae+pe*O}J<q&&(Z+=(q-J)*ae,J=q);const te=Math.min(W.end,me);for(let pe=J;pe<=te&&!(Z>=k);pe++)$.push({data:V?.[pe],index:pe,offset:Z,size:ae}),Z+=ae+O}}),Me=Yw(L,Xl),ge=Yw(L,Jl);if(ke.length>0&&(Me>0||ge>0)){const $=ke[0],W=ke[ke.length-1];if(Me>0&&$.index>q){const ue=Math.min(Me,$.index-q),Z=[];let J=$.offset;for(let ae=$.index-1;ae>=$.index-ue;ae--){const te=ea(ee,ae,ae)[0]?.value??$.size;J-=te+O,Z.unshift({data:V?.[ae],index:ae,offset:J,size:te})}ke.unshift(...Z)}if(ge>0&&W.index<me){const ue=Math.min(ge,me-W.index);let Z=W.offset+W.size+O;for(let J=W.index+1;J<=W.index+ue;J++){const ae=ea(ee,J,J)[0]?.value??W.size;ke.push({data:V?.[J],index:J,offset:Z,size:ae}),Z+=ae+O}}}return Fd(ke,Q,A,O,X,z)}),Rt(S=>S!==null),An()),Ap);St(Ve(e,Rt(Kx),mt(S=>S?.length)),o),St(Ve(w,mt(S=>S.topListHeight)),h),St(h,l),St(Ve(w,mt(S=>[S.top,S.bottom])),a),St(Ve(w,mt(S=>S.items)),y);const C=Fs(Ve(w,Rt(({items:S})=>S.length>0),Zt(o,e),Rt(([{items:S},k])=>S[S.length-1].originalIndex===k-1),mt(([,S,k])=>[S-1,k]),An(Kl),mt(([S])=>S))),_=Fs(Ve(w,lo(200),Rt(({items:S,topItems:k})=>S.length>0&&S[0].originalIndex===k.length),mt(({items:S})=>S[0].index),An())),N=Fs(Ve(w,Rt(({items:S})=>S.length>0),mt(({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(CT)));return{endReached:C,initialItemCount:v,itemsRendered:y,listState:w,minOverscanItemCount:b,rangeChanged:N,startReached:_,topItemsIndexes:x,...p}},Rn($i,NT,ev,jc,kc,_c,Xo,Xx),{singleton:!0}),ET=hn(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:s},{listState:o}])=>{const r=rn(),a=fs(Ve(Bn(n,e,s,t,o),mt(([l,c,d,u,h])=>l+c+d+u+h.offsetBottom+h.bottom)),0);return St(Mt(a),r),{totalListHeight:a,totalListHeightChanged:r}},Rn(Ds,_r),{singleton:!0}),d8=hn(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Je(!1),s=fs(Ve(Bn(n,e,t),Rt(([o])=>o),mt(([,o,r])=>Math.max(0,o-r)),lo(0),An()),0);return{alignToBottom:n,paddingTopAddition:s}},Rn(Ds,ET),{singleton:!0}),PT=hn(()=>({context:Je(null)})),u8=({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,AT=hn(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:s,fixedHeaderHeight:o,headerHeight:r,scrollingInProgress:a,scrollTop:l,viewportHeight:c},{scrollToIndex:d}])=>{const u=rn();return St(Ve(u,Zt(t,c,n,r,o,s,l),Zt(e),mt(([[h,p,f,g,x,v,y,b],w])=>{const{calculateViewLocation:C=u8,done:_,...N}=h,S=_T(h,p,g-1),k=ql(S,p.offsetTree,w)+x+v,A=k+yi(p.sizeTree,S)[1],I=b+v,D=b+f-y,P=C({itemBottom:A,itemTop:k,locationParams:N,viewportBottom:D,viewportTop:I});return P===null?_?.():_&&fi(Ve(a,Rt(T=>!T),Sr(Ln(a)?1:2)),_),P}),Rt(h=>h!==null)),d),{scrollIntoView:u}},Rn($i,Ds,kc,_r,Yo),{singleton:!0});function Xw(e){return e===!1?!1:e==="smooth"?"smooth":"auto"}const h8=(e,t)=>typeof e=="function"?Xw(e(t)):t&&Xw(e),p8=hn(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:s},{atBottomState:o,isAtBottom:r},{scrollToIndex:a},{scrolledToInitialItem:l},{didMount:c,propsReady:d},{log:u},{scrollingInProgress:h},{context:p},{scrollIntoView:f}])=>{const g=Je(!1),x=rn();let v=null;function y(_){$t(a,{align:"end",behavior:_,index:"LAST"})}gn(Ve(Bn(Ve(Mt(t),Sr(1)),c),Zt(Mt(g),r,l,h),mt(([[_,N],S,k,A,I])=>{let D=N&&A,P="auto";return D&&(P=h8(S,k||I),D=D&&P!==!1),{followOutputBehavior:P,shouldFollow:D,totalCount:_}}),Rt(({shouldFollow:_})=>_)),({followOutputBehavior:_,totalCount:N})=>{v!==null&&(v(),v=null),Ln(n)===void 0?v=fi(e,()=>{Ln(u)("following output to ",{totalCount:N},es.DEBUG),y(_),v=null}):requestAnimationFrame(()=>{Ln(u)("following output to ",{totalCount:N},es.DEBUG),y(_)})});function b(_){const N=fi(o,S=>{_&&!S.atBottom&&S.notAtBottomBecause==="SIZE_INCREASED"&&v===null&&(Ln(u)("scrolling to bottom due to increased size",{},es.DEBUG),y("auto"))});setTimeout(N,100)}gn(Ve(Bn(Mt(g),t,d),Rt(([_,,N])=>_!==!1&&N),Li(({value:_},[,N])=>({refreshed:_===N,value:N}),{refreshed:!1,value:0}),Rt(({refreshed:_})=>_),Zt(g,t)),([,_])=>{Ln(l)&&b(_!==!1)}),gn(x,()=>{b(Ln(g)!==!1)}),gn(Bn(Mt(g),o),([_,N])=>{_!==!1&&!N.atBottom&&N.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&y("auto")});const w=Je(null),C=rn();return St(jm(Ve(Mt(s),mt(_=>_?.length??0)),Ve(Mt(t))),C),gn(Ve(Bn(Ve(C,Sr(1)),c),Zt(Mt(w),l,h,p),mt(([[_,N],S,k,A,I])=>N&&k&&S?.({context:I,totalCount:_,scrollingInProgress:A})),Rt(_=>!!_),lo(0)),_=>{v!==null&&(v(),v=null),Ln(n)===void 0?v=fi(e,()=>{Ln(u)("scrolling into view",{}),$t(f,_),v=null}):requestAnimationFrame(()=>{Ln(u)("scrolling into view",{}),$t(f,_)})}),{autoscrollToBottom:x,followOutput:g,scrollIntoViewOnChange:w}},Rn($i,_c,kc,jc,Xo,Yo,Ds,PT,AT)),f8=hn(([{data:e,firstItemIndex:t,gap:n,sizes:s},{initialTopMostItemIndex:o},{initialItemCount:r,listState:a},{didMount:l}])=>(St(Ve(l,Zt(r),Rt(([,c])=>c!==0),Zt(o,s,t,n,e),mt(([[,c],d,u,h,p,f=[]])=>IT(c,d,u,h,p,f))),a),{}),Rn($i,jc,_r,Xo),{singleton:!0}),m8=hn(([{didMount:e},{scrollTo:t},{listState:n}])=>{const s=Je(0);return gn(Ve(e,Zt(s),Rt(([,o])=>o!==0),mt(([,o])=>({top:o}))),o=>{fi(Ve(n,Sr(1),Rt(r=>r.items.length>1)),()=>{requestAnimationFrame(()=>{$t(t,o)})})}),{initialScrollTop:s}},Rn(Xo,Ds,_r),{singleton:!0}),MT=hn(([{scrollVelocity:e}])=>{const t=Je(!1),n=rn(),s=Je(!1);return St(Ve(e,Zt(s,t,n),Rt(([o,r])=>r!==!1&&r!==void 0),mt(([o,r,a,l])=>{const{enter:c,exit:d}=r;if(a){if(d(o,l))return!1}else if(c(o,l))return!0;return a}),An()),t),gn(Ve(Bn(t,e,n),Zt(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(_c),{singleton:!0}),tv=hn(([{scrollContainerState:e,scrollTo:t}])=>{const n=rn(),s=rn(),o=rn(),r=Je(!1),a=Je(void 0);return St(Ve(Bn(n,s),mt(([{scrollTop:l,viewportHeight:c},{offsetTop:d,listHeight:u}])=>({scrollHeight:u,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),St(Ve(t,Zt(s),mt(([l,{offsetTop:c}])=>({...l,top:l.top+c}))),o),{customScrollParent:a,useWindowScroll:r,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:s}},Rn(Ds)),g8=hn(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:s},{initialTopMostItemIndex:o},{didMount:r},{useWindowScroll:a,windowScrollContainerState:l,windowViewportRect:c}])=>{const d=rn(),u=Je(void 0),h=Je(null),p=Je(null);return St(l,h),St(c,p),gn(Ve(d,Zt(t,s,a,h,p,n)),([f,g,x,v,y,b,w])=>{const C=QW(g.sizeTree);v&&y!==null&&b!==null&&(x=y.scrollTop-b.offsetTop),x-=w,f({ranges:C,scrollTop:x})}),St(Ve(u,Rt(Kx),mt(x8)),o),St(Ve(r,Zt(u),Rt(([,f])=>f!==void 0),An(),mt(([,f])=>f.ranges)),e),{getState:d,restoreStateFrom:u}},Rn($i,Ds,jc,Xo,tv));function x8(e){return{align:"start",index:0,offset:e.scrollTop}}const v8=hn(([{topItemsIndexes:e}])=>{const t=Je(0);return St(Ve(t,Rt(n=>n>=0),mt(n=>Array.from({length:n}).map((s,o)=>o))),e),{topItemCount:t}},Rn(_r));function RT(e){let t=!1,n;return(()=>(t||(t=!0,n=e()),n))}const b8=RT(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),w8=hn(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:s},{isAtBottom:o,isScrolling:r,lastJumpDueToItemResize:a,scrollDirection:l},{listState:c},{beforeUnshiftWith:d,gap:u,shiftWithOffset:h,sizes:p},{log:f},{recalcInProgress:g}])=>{const x=Fs(Ve(c,Zt(a),Li(([,y,b,w],[{bottom:C,items:_,offsetBottom:N,totalCount:S},k])=>{const A=C+N;let I=0;return b===S&&y.length>0&&_.length>0&&(_[0].originalIndex===0&&y[0].originalIndex===0||(I=A-w,I!==0&&(I+=k))),[I,_,S,A]},[0,[],0,0]),Rt(([y])=>y!==0),Zt(s,l,n,o,f,g),Rt(([,y,b,w,,,C])=>!C&&!w&&y!==0&&b===Yl),mt(([[y],,,,,b])=>(b("Upward scrolling compensation",{amount:y},es.DEBUG),y))));function v(y){y>0?($t(t,{behavior:"auto",top:-y}),$t(e,0)):($t(e,0),$t(t,{behavior:"auto",top:-y}))}return gn(Ve(x,Zt(e,r)),([y,b,w])=>{w&&b8()?$t(e,b-y):v(-y)}),gn(Ve(Bn(fs(r,!1),e,g),Rt(([y,b,w])=>!y&&!w&&b!==0),mt(([y,b])=>b),lo(1)),v),St(Ve(h,mt(y=>({top:-y}))),t),gn(Ve(d,Zt(p,u),mt(([y,{groupIndices:b,lastSize:w,sizeTree:C},_])=>{function N(D){return D*(w+_)}if(b.length===0)return N(y);let S=0;const k=Ul(C,0);let A=0,I=0;for(;A<y;){A++,S+=k;let D=b.length===I+1?1/0:b[I+1]-b[I]-1;A+D>y&&(S-=k,D=y-A+1),A+=D,S+=N(D),I++}return S})),y=>{$t(e,y),requestAnimationFrame(()=>{$t(t,{top:y}),requestAnimationFrame(()=>{$t(e,0),$t(g,!1)})})}),{deviation:e}},Rn(Ds,_c,_r,$i,Yo,Xx)),y8=hn(([e,t,n,s,o,r,a,l,c,d,u])=>({...e,...t,...n,...s,...o,...r,...a,...l,...c,...d,...u}),Rn(ev,f8,Xo,MT,ET,m8,d8,tv,AT,Yo,PT)),LT=hn(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:s,fixedGroupSize:o,gap:r,groupIndices:a,heightEstimates:l,itemSize:c,sizeRanges:d,sizes:u,statefulTotalCount:h,totalCount:p,trackItemSizes:f},{initialItemFinalLocationReached:g,initialTopMostItemIndex:x,scrolledToInitialItem:v},y,b,w,C,{scrollToIndex:_},N,{topItemCount:S},{groupCounts:k},A])=>{const{listState:I,minOverscanItemCount:D,topItemsIndexes:P,rangeChanged:T,...z}=C;return St(T,A.scrollSeekRangeChanged),St(Ve(Bn(A.windowViewportRect,y.headerHeight,y.fixedHeaderHeight),mt(([O,L,V])=>Math.max(L+V+1,O.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:d,topItemCount:S,topItemsIndexes:P,totalCount:p,...w,groupIndices:a,itemSize:c,listState:I,minOverscanItemCount:D,scrollToIndex:_,statefulTotalCount:h,trackItemSizes:f,rangeChanged:T,...z,...A,...y,sizes:u,...b}},Rn($i,jc,Ds,g8,p8,_r,kc,w8,v8,NT,y8));function S8(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 Fc=typeof document>"u"?Ne.useEffect:Ne.useLayoutEffect;function OT(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 c(v,y){v.propsReady!==void 0&&$t(v.propsReady,!1);for(const b of s){const w=v[t.required[b]];$t(w,y[b])}for(const b of o)if(b in y){const w=v[t.optional[b]];$t(w,y[b])}v.propsReady!==void 0&&$t(v.propsReady,!0)}function d(v){return r.reduce((y,b)=>(y[b]=w=>{const C=v[t.methods[b]];$t(C,w)},y),{})}function u(v){return a.reduce((y,b)=>(y[b]=LW(v[t.events[b]]),y),{})}const h=Ne.forwardRef(function(v,y){const{children:b,...w}=v,[C]=Ne.useState(()=>Th(GW(e),S=>{c(S,w)})),[_]=Ne.useState(Gw(u,C));Fc(()=>{for(const S of a)S in w&&gn(_[S],w[S]);return()=>{Object.values(_).map(qx)}},[w,_,C]),Fc(()=>{c(C,w)}),Ne.useImperativeHandle(y,zw(d(C)));const N=n;return i.jsx(l.Provider,{value:C,children:n===void 0?b:i.jsx(N,{...S8([...s,...o,...a],w),children:b})})}),p=v=>{const y=Ne.useContext(l);return Ne.useCallback(b=>{$t(y[v],b)},[y,v])},f=v=>{const y=Ne.useContext(l)[v],b=Ne.useCallback(w=>gn(y,w),[y]);return Ne.useSyncExternalStore(b,()=>Ln(y),()=>Ln(y))},g=v=>{const y=Ne.useContext(l)[v],[b,w]=Ne.useState(Gw(Ln,y));return Fc(()=>gn(y,C=>{C!==b&&w(zw(C))}),[y,b]),b},x=parseInt(Ne.version,10)>=18?f:g;return{Component:h,useEmitter:(v,y)=>{const b=Ne.useContext(l)[v];Fc(()=>gn(b,y),[y,b])},useEmitterValue:x,usePublisher:p}}const zT=Ne.createContext(void 0),GT=Ne.createContext(void 0),Mp="-webkit-sticky",Jw="sticky",nv=RT(()=>{if(typeof document>"u")return Jw;const e=document.createElement("div");return e.style.position=Mp,e.style.position===Mp?Mp:Jw}),FT=typeof document>"u"?Ne.useEffect:Ne.useLayoutEffect;function Rp(e){return"self"in e}function C8(e){return"body"in e}function HT(e,t,n,s=Pa,o,r){const a=Ne.useRef(null),l=Ne.useRef(null),c=Ne.useRef(null),d=Ne.useCallback(p=>{let f,g,x;const v=p.target;if(C8(v)||Rp(v)){const b=Rp(v)?v:v.defaultView;x=r===!0?pr(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?pr(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():Xk.flushSync(y),l.current!==null&&(x===l.current||x<=0||x===f-g)&&(l.current=null,t(!0),c.current&&(clearTimeout(c.current),c.current=null))},[e,t,r]);Ne.useEffect(()=>{const p=o??a.current;return s(o??a.current),d({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",d,{passive:!0}),()=>{s(null),p.removeEventListener("scroll",d)}},[a,d,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;Rp(f)?(v=Math.max(Ho(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?pr(f,f.scrollX):f.scrollY):(v=f[r===!0?"scrollWidth":"scrollHeight"],x=Ho(f,r===!0?"width":"height"),y=r===!0?pr(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,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,l.current=null,t(!0)},1e3)):l.current=null,r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},left:Hw(f,w)}),f.scrollTo(p)}function h(p){r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},...p.top===void 0?{}:{left:Hw(a.current,p.top)}}),a.current.scrollBy(p)}return{scrollByCallback:h,scrollerRef:a,scrollToCallback:u}}function sv(e){return e}const k8=hn(()=>{const e=Je(l=>`Item ${l}`),t=Je(l=>`Group ${l}`),n=Je({}),s=Je(sv),o=Je("div"),r=Je(Pa),a=(l,c=null)=>fs(Ve(n,mt(d=>d[l]),An()),c);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")}}),j8=hn(([e,t])=>({...e,...t}),Rn(LT,k8)),_8=({height:e})=>i.jsx("div",{style:{height:e}}),N8={overflowAnchor:"none",position:nv(),zIndex:1},BT={overflowAnchor:"none"},T8={...BT,display:"inline-block",height:"100%"},Zw=Ne.memo(function({showTopList:e=!1}){const t=zt("listState"),n=qs("sizeRanges"),s=zt("useWindowScroll"),o=zt("customScrollParent"),r=qs("windowScrollContainerState"),a=qs("scrollContainerState"),l=o||s?r:a,c=zt("itemContent"),d=zt("context"),u=zt("groupContent"),h=zt("trackItemSizes"),p=zt("itemSize"),f=zt("log"),g=qs("gap"),x=zt("horizontalDirection"),{callbackRef:v}=VW(n,p,h,e?Pa:l,f,g,o,x,zt("skipAnimationFrameInResizeObserver")),[y,b]=Ne.useState(0);ov("deviation",z=>{y!==z&&b(z)});const w=zt("EmptyPlaceholder"),C=zt("ScrollSeekPlaceholder")??_8,_=zt("ListComponent"),N=zt("ItemComponent"),S=zt("GroupComponent"),k=zt("computeItemKey"),A=zt("isSeeking"),I=zt("groupIndices").length>0,D=zt("alignToBottom"),P=zt("initialItemFinalLocationReached"),T=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginInlineStart:y===0?D?"auto":0:y,paddingInlineEnd:t.offsetBottom,paddingInlineStart:t.offsetTop,whiteSpace:"nowrap"}:{marginTop:y===0?D?"auto":0:y,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...P?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&w!==null&&w!==void 0?i.jsx(w,{...ps(w,d)}):i.jsx(_,{...ps(_,d),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:T,children:(e?t.topItems:t.items).map(z=>{const O=z.originalIndex,L=k(O+t.firstItemIndex,z.data,d);return A?m.createElement(C,{...ps(C,d),height:z.size,index:z.index,key:L,type:z.type||"item",...z.type==="group"?{}:{groupIndex:z.groupIndex}}):z.type==="group"?m.createElement(S,{...ps(S,d),"data-index":O,"data-item-index":z.index,"data-known-size":z.size,key:L,style:N8},u(z.index,d)):m.createElement(N,{...ps(N,d),...P8(N,z.data),"data-index":O,"data-item-group-index":z.groupIndex,"data-item-index":z.index,"data-known-size":z.size,key:L,style:x?T8:BT},I?c(z.index,z.groupIndex,z.data,d):c(z.index,z.data,d))})})}),D8={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},I8={outline:"none",overflowX:"auto",position:"relative"},iv=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:void 0}),VT=(e,t,n=0)=>({...iv(e),position:t?"relative":"absolute",top:t?-n:0}),E8={position:nv(),top:0,width:"100%",zIndex:1};function ps(e,t){if(typeof e!="string")return{context:t}}function P8(e,t){return{item:typeof e=="string"?void 0:t}}const A8=Ne.memo(function(){const e=zt("HeaderComponent"),t=qs("headerHeight"),n=zt("HeaderFooterTag"),s=jr(Ne.useMemo(()=>r=>{t(Ho(r,"height"))},[t]),!0,zt("skipAnimationFrameInResizeObserver")),o=zt("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null}),M8=Ne.memo(function(){const e=zt("FooterComponent"),t=qs("footerHeight"),n=zt("HeaderFooterTag"),s=jr(Ne.useMemo(()=>r=>{t(Ho(r,"height"))},[t]),!0,zt("skipAnimationFrameInResizeObserver")),o=zt("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null});function $T({useEmitter:e,useEmitterValue:t,usePublisher:n}){return Ne.memo(function({children:s,style:o,context:r,...a}){const l=n("scrollContainerState"),c=t("ScrollerComponent"),d=n("smoothScrollTargetReached"),u=t("scrollerRef"),h=t("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:f,scrollToCallback:g}=HT(l,d,c,u,void 0,h);return e("scrollTo",g),e("scrollBy",p),i.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:f,style:{...h?I8:D8,...o},tabIndex:0,...a,...ps(c,r),children:s})})}function WT({useEmitter:e,useEmitterValue:t,usePublisher:n}){return Ne.memo(function({children:s,style:o,context:r,...a}){const l=n("windowScrollContainerState"),c=t("ScrollerComponent"),d=n("smoothScrollTargetReached"),u=t("totalListHeight"),h=t("deviation"),p=t("customScrollParent"),f=Ne.useRef(null),g=t("scrollerRef"),{scrollByCallback:x,scrollerRef:v,scrollToCallback:y}=HT(l,d,c,g,p);return FT(()=>(v.current=p??f.current?.ownerDocument.defaultView,()=>{v.current=null}),[v,p]),e("windowScrollTo",y),e("scrollBy",x),i.jsx(c,{ref:f,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...u===0?void 0:{height:u+h}},...a,...ps(c,r),children:s})})}const R8=({children:e})=>{const t=Ne.useContext(zT),n=qs("viewportHeight"),s=qs("fixedItemHeight"),o=zt("alignToBottom"),r=zt("horizontalDirection"),a=Ne.useMemo(()=>fT(n,c=>Ho(c,r?"width":"height")),[n,r]),l=jr(a,!0,zt("skipAnimationFrameInResizeObserver"));return Ne.useEffect(()=>{t&&(n(t.viewportHeight),s(t.itemHeight))},[t,n,s]),i.jsx("div",{"data-viewport-type":"element",ref:l,style:iv(o),children:e})},L8=({children:e})=>{const t=Ne.useContext(zT),n=qs("windowViewportRect"),s=qs("fixedItemHeight"),o=zt("customScrollParent"),r=zt("useWindowScroll"),a=zt("topListHeight"),l=xT(n,o,zt("skipAnimationFrameInResizeObserver")),c=zt("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:VT(c,r,a),children:e})},O8=({children:e})=>{const t=zt("TopItemListComponent")??"div",n=zt("headerHeight"),s={...E8,marginTop:`${n}px`},o=zt("context");return i.jsx(t,{style:s,...ps(t,o),children:e})},z8=Ne.memo(function(e){const t=zt("useWindowScroll"),n=zt("topItemsIndexes").length>0,s=zt("customScrollParent"),o=zt("context");return i.jsxs(s||t?H8:F8,{...e,context:o,children:[n&&i.jsx(O8,{children:i.jsx(Zw,{showTopList:!0})}),i.jsxs(s||t?L8:R8,{children:[i.jsx(A8,{}),i.jsx(Zw,{}),i.jsx(M8,{})]})]})}),{Component:G8,useEmitter:ov,useEmitterValue:zt,usePublisher:qs}=OT(j8,{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"}},z8),F8=$T({useEmitter:ov,useEmitterValue:zt,usePublisher:qs}),H8=WT({useEmitter:ov,useEmitterValue:zt,usePublisher:qs}),B8=G8,V8=hn(()=>{const e=Je(d=>i.jsxs("td",{children:["Item $",d]})),t=Je(null),n=Je(d=>i.jsxs("td",{colSpan:1e3,children:["Group ",d]})),s=Je(null),o=Je(null),r=Je({}),a=Je(sv),l=Je(Pa),c=(d,u=null)=>fs(Ve(r,mt(h=>h[d]),An()),u);return{components:r,computeItemKey:a,context:t,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:o,fixedHeaderContent:s,itemContent:e,groupContent:n,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder"),TableBodyComponent:c("TableBody","tbody"),TableComponent:c("Table","table"),TableFooterComponent:c("TableFoot","tfoot"),TableHeadComponent:c("TableHead","thead"),TableRowComponent:c("TableRow","tr"),GroupComponent:c("Group","tr")}});Rn(LT,V8);nv();const Qw={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},$8={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:ey,floor:_u,max:xl,min:Lp,round:ty}=Math;function ny(e,t,n){return Array.from({length:t-e+1}).map((s,o)=>({data:n===null?null:n[o+e],index:o+e}))}function W8(e){return{...$8,items:e}}function Hc(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 K8=hn(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:s},{footerHeight:o,headerHeight:r,scrollBy:a,scrollContainerState:l,scrollTo:c,scrollTop:d,smoothScrollTargetReached:u,viewportHeight:h},p,f,{didMount:g,propsReady:x},{customScrollParent:v,useWindowScroll:y,windowScrollContainerState:b,windowScrollTo:w,windowViewportRect:C},_])=>{const N=Je(0),S=Je(0),k=Je(Qw),A=Je({height:0,width:0}),I=Je({height:0,width:0}),D=rn(),P=rn(),T=Je(0),z=Je(null),O=Je({column:0,row:0}),L=rn(),V=rn(),X=Je(!1),F=Je(0),ee=Je(!0),H=Je(!1),Q=Je(!1);gn(Ve(g,Zt(F),Rt(([ge,$])=>!Im($))),()=>{$t(ee,!1)}),gn(Ve(Bn(g,ee,I,A,F,H),Rt(([ge,$,W,ue,,Z])=>ge&&!$&&W.height!==0&&ue.height!==0&&!Z)),([,,,,ge])=>{if(ge===void 0){$t(ee,!0);return}$t(H,!0),Zx(1,()=>{$t(D,ge)}),fi(Ve(d),()=>{$t(t,[0,0]),$t(ee,!0)})}),St(Ve(V,Rt(ge=>ge!=null&&ge.scrollTop>0),Ii(0)),S),gn(Ve(g,Zt(V),Rt(([,ge])=>ge!=null)),([,ge])=>{ge&&($t(A,ge.viewport),$t(I,ge.item),$t(O,ge.gap),ge.scrollTop>0&&($t(X,!0),fi(Ve(d,Sr(1)),$=>{$t(X,!1)}),$t(c,{top:ge.scrollTop})))}),St(Ve(A,mt(({height:ge})=>ge)),h),St(Ve(Bn(Mt(A,Hc),Mt(I,Hc),Mt(O,(ge,$)=>ge!==void 0&&ge.column===$.column&&ge.row===$.row),Mt(d)),mt(([ge,$,W,ue])=>({gap:W,item:$,scrollTop:ue,viewport:ge}))),L),St(Ve(Bn(Mt(N),s,Mt(O,U8),Mt(I,Hc),Mt(A,Hc),Mt(z),Mt(S),Mt(X),Mt(ee),Mt(F)),Rt(([,,,,,,,ge])=>!ge),mt(([ge,[$,W],ue,Z,J,ae,te,,pe,Te])=>{const{column:$e,row:Ie}=ue,{height:Ze,width:Nt}=Z,{width:Ut}=J;if(te===0&&(ge===0||Ut===0))return Qw;if(Nt===0){const ht=Qx(Te,ge),Ot=ht+Math.max(te-1,0);return W8(ny(ht,Ot,ae))}const Pt=UT(Ut,Nt,$e);let _t,B;pe?$===0&&W===0&&te>0?(_t=0,B=te-1):(_t=Pt*_u(($+Ie)/(Ze+Ie)),B=Pt*ey((W+Ie)/(Ze+Ie))-1,B=Lp(ge-1,xl(B,Pt-1)),_t=Lp(B,xl(0,_t))):(_t=0,B=-1);const je=ny(_t,B,ae),{bottom:Ye,top:Tt}=sy(J,ue,Z,je),Wt=ey(ge/Pt),le=Wt*Ze+(Wt-1)*Ie-Ye;return{bottom:Ye,itemHeight:Ze,items:je,itemWidth:Nt,offsetBottom:le,offsetTop:Tt,top:Tt}})),k),St(Ve(z,Rt(ge=>ge!==null),mt(ge=>ge.length)),N),St(Ve(Bn(A,I,k,O),Rt(([ge,$,{items:W}])=>W.length>0&&$.height!==0&&ge.height!==0),mt(([ge,$,{items:W},ue])=>{const{bottom:Z,top:J}=sy(ge,ue,$,W);return[J,Z]}),An(Kl)),t);const q=Je(!1);St(Ve(d,Zt(q),mt(([ge,$])=>$||ge!==0)),q);const ne=Fs(Ve(Bn(k,N),Rt(([{items:ge}])=>ge.length>0),Zt(q),Rt(([[ge,$],W])=>{const ue=ge.items[ge.items.length-1].index===$-1;return(W||ge.bottom>0&&ge.itemHeight>0&&ge.offsetBottom===0&&ge.items.length===$)&&ue}),mt(([[,ge]])=>ge-1),An())),me=Fs(Ve(Mt(k),Rt(({items:ge})=>ge.length>0&&ge[0].index===0),Ii(0),An())),ke=Fs(Ve(Mt(k),Zt(X),Rt(([{items:ge},$])=>ge.length>0&&!$),mt(([{items:ge}])=>({endIndex:ge[ge.length-1].index,startIndex:ge[0].index})),An(CT),lo(0)));St(ke,f.scrollSeekRangeChanged),St(Ve(D,Zt(A,I,N,O),mt(([ge,$,W,ue,Z])=>{const J=TT(ge),{align:ae,behavior:te,offset:pe}=J;let Te=J.index;Te==="LAST"&&(Te=ue-1),Te=xl(0,Te,Lp(ue-1,Te));let $e=Em($,Z,W,Te);return ae==="end"?$e=ty($e-$.height+W.height):ae==="center"&&($e=ty($e-$.height/2+W.height/2)),pe!==void 0&&pe!==0&&($e+=pe),{behavior:te,top:$e}})),c);const Me=fs(Ve(k,mt(ge=>ge.offsetBottom+ge.bottom)),0);return St(Ve(C,mt(ge=>({height:ge.visibleHeight,width:ge.visibleWidth}))),A),{customScrollParent:v,data:z,deviation:T,footerHeight:o,gap:O,headerHeight:r,increaseViewportBy:e,initialItemCount:S,itemDimensions:I,overscan:n,restoreStateFrom:V,scrollBy:a,scrollContainerState:l,scrollHeight:P,scrollTo:c,scrollToIndex:D,scrollTop:d,smoothScrollTargetReached:u,totalCount:N,useWindowScroll:y,viewportDimensions:A,windowScrollContainerState:b,windowScrollTo:w,windowViewportRect:C,...f,gridState:k,horizontalDirection:Q,initialTopMostItemIndex:F,totalListHeight:Me,...p,endReached:ne,propsReady:x,rangeChanged:ke,startReached:me,stateChanged:L,stateRestoreInProgress:X,..._}},Rn(ev,Ds,_c,MT,Xo,tv,Yo));function UT(e,t,n){return xl(1,_u((e+n)/(_u(t)+n)))}function sy(e,t,n,s){const{height:o}=n;if(o===void 0||s.length===0)return{bottom:0,top:0};const r=Em(e,t,n,s[0].index);return{bottom:Em(e,t,n,s[s.length-1].index)+o,top:r}}function Em(e,t,n,s){const o=UT(e.width,n.width,t.column),r=_u(s/o),a=r*n.height+xl(0,r-1)*t.row;return a>0?a+t.row:a}const q8=hn(()=>{const e=Je(h=>`Item ${h}`),t=Je({}),n=Je(null),s=Je("virtuoso-grid-item"),o=Je("virtuoso-grid-list"),r=Je(sv),a=Je("div"),l=Je(Pa),c=(h,p=null)=>fs(Ve(t,mt(f=>f[h]),An()),p),d=Je(!1),u=Je(!1);return St(Mt(u),d),{components:t,computeItemKey:r,context:n,FooterComponent:c("Footer"),HeaderComponent:c("Header"),headerFooterTag:a,itemClassName:s,ItemComponent:c("Item","div"),itemContent:e,listClassName:o,ListComponent:c("List","div"),readyStateChanged:d,reportReadyState:u,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),Y8=hn(([e,t])=>({...e,...t}),Rn(K8,q8)),X8=Ne.memo(function(){const e=En("gridState"),t=En("listClassName"),n=En("itemClassName"),s=En("itemContent"),o=En("computeItemKey"),r=En("isSeeking"),a=Ys("scrollHeight"),l=En("ItemComponent"),c=En("ListComponent"),d=En("ScrollSeekPlaceholder"),u=En("context"),h=Ys("itemDimensions"),p=Ys("gap"),f=En("log"),g=En("stateRestoreInProgress"),x=Ys("reportReadyState"),v=jr(Ne.useMemo(()=>y=>{const b=y.parentElement.parentElement.scrollHeight;a(b);const w=y.firstChild;if(w!==null){const{height:C,width:_}=w.getBoundingClientRect();h({height:C,width:_})}p({column:iy("column-gap",getComputedStyle(y).columnGap,f),row:iy("row-gap",getComputedStyle(y).rowGap,f)})},[a,h,p,f]),!0,!1);return FT(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),g?null:i.jsx(c,{className:t,ref:v,...ps(c,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(d,{...ps(d,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))})})}),J8=Ne.memo(function(){const e=En("HeaderComponent"),t=Ys("headerHeight"),n=En("headerFooterTag"),s=jr(Ne.useMemo(()=>r=>{t(Ho(r,"height"))},[t]),!0,!1),o=En("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null}),Z8=Ne.memo(function(){const e=En("FooterComponent"),t=Ys("footerHeight"),n=En("headerFooterTag"),s=jr(Ne.useMemo(()=>r=>{t(Ho(r,"height"))},[t]),!0,!1),o=En("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...ps(e,o)})}):null}),Q8=({children:e})=>{const t=Ne.useContext(GT),n=Ys("itemDimensions"),s=Ys("viewportDimensions"),o=jr(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:iv(!1),children:e})},eU=({children:e})=>{const t=Ne.useContext(GT),n=Ys("windowViewportRect"),s=Ys("itemDimensions"),o=En("customScrollParent"),r=En("useWindowScroll"),a=xT(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:VT(!1,r),children:e})},tU=Ne.memo(function({...e}){const t=En("useWindowScroll"),n=En("customScrollParent"),s=n||t?sU:nU,o=n||t?eU:Q8,r=En("context");return i.jsx(s,{...e,...ps(s,r),children:i.jsxs(o,{children:[i.jsx(J8,{}),i.jsx(X8,{}),i.jsx(Z8,{})]})})}),{useEmitter:KT,useEmitterValue:En,usePublisher:Ys}=OT(Y8,{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"}},tU),nU=$T({useEmitter:KT,useEmitterValue:En,usePublisher:Ys}),sU=WT({useEmitter:KT,useEmitterValue:En,usePublisher:Ys});function iy(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 iU({className:e}){return i.jsx("svg",{viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",className:U("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 oU={rows:new Set,expanded:new Set};function rU(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 c=e.rows.has(l.key);if(l.explore.steps){a.add(l.key),c&&!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 d=l.children[0]?.key??"",u=l.children.at(-1)?.key??"",h=!c&&e.rows.has(d)&&e.rows.has(u);if(!h&&!e.expanded.has(l.key))continue;const p=n(h?d: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 aU({loading:e=!1,runStartedAt:t}){if(!e)return t}function lU(e){return e==="right"||e==="off"?e:"left"}function cU(e,t,n){return e!=="off"&&!t&&n>=2}const Bc=40;function dU({items:e,activeKey:t,onJump:n}){const s=ye(g=>g.chatWide),o=lU(ye(g=>g.navRailSide)),[r,a]=m.useState(null);if(!cU(o,s,e.length))return null;const l=o==="right",c=Math.max(0,e.findIndex(g=>g.key===t)),d=Math.min(Math.max(0,c-Math.floor(Bc/2)),Math.max(0,e.length-Bc)),u=e.slice(d,d+Bc),h=d>0,p=d+Bc<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:U("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:U("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:U("flex h-[7px] w-10 items-center",l&&"justify-end"),children:i.jsx("span",{className:U("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:U("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 Hd="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 qT(e){return e.content.filter(t=>t.type==="text").map(t=>t.text??"").join("").trim()}function uU(e){const t=[];for(const n of e){if(n.role!=="user"&&n.role!=="assistant")continue;const s=qT(n);s&&t.push(`${n.role==="user"?"User":"Assistant"}: ${s}`)}return t.slice(-40).join(`
|
|
21
|
-
`)}function hU(e){for(const t of[...e].reverse()){if(t.role!=="assistant")continue;const n=qT(t);if(n)return n}return""}function oy(e,t){if(e!=="contextual")return Hd;const n=t.trim();return n?`${Hd}
|
|
22
|
-
|
|
23
|
-
# Main conversation (background only)
|
|
24
|
-
${n}`:Hd}function pU(e){return e.startsWith(Hd)}function fU(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 mU({message:e}){const{t}=se(),n={queued:t("Queued"),running:t("In progress"),completed:t("Completed"),failed:t("Failed"),canceled:t("Canceled")},s=e.kind==="routine"?HN:e.kind==="group"?pa:e.kind==="delegation-task"?va:e.kind==="delegation-retry"||e.kind==="delegation-check-failed"?ra:Q$,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(pa,{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 YT=new Map;let qr;function gU(e){if(qr?.revision===e)return qr.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 c of a.email){const d=c.codePointAt(0)??0;d>=32&&d!==127&&(l+=c)}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:YT})),n={revision:e,request:t,data:void 0};return qr=n,t.then(s=>{qr===n&&(n.data=s)}),t}function xU(){const e=yo(s=>s.snapshot.revision),[t,n]=m.useState(()=>qr?.revision===e?qr.data:void 0);return m.useEffect(()=>{let s=!1;return gU(e).then(o=>{s||n(o)}),()=>{s=!0}},[e]),t?.revision===e?t.emails:YT}function ry(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 rv(e,t,n){return`${e}:${ry(t)}:${ry(n,1)}`}const vU=/(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c|$)/g,bU=/(?:\x1b\[|\x9b)[0-?]*[ -/]*(?:[@-~]|$)/g;function Si(e){return e.replace(vU,"").replace(bU,"")}function wU(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 yU(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 SU(e){let t=0,n=0,s=0,o=0,r=0,a=0,l=0,c=0,d=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=yU(x);y!==void 0&&(l+=y);const b=wU(x);b!==void 0&&(d+=b,u+=1);const w=x.usage?.output??0;y!==void 0&&y>0&&w>0&&(h+=y,p+=w),v&&(f!==null&&(c+=Math.max(0,v.stepStartMs-f)),f=v.completedMs??null)}const g=s+r+a;return{turns:t,steps:n,llmMs:l,toolMs:c,inputTokens:g,outputTokens:o,cacheHitPercent:g===0?null:Math.round(r/g*100),ttftAvgMs:u>0?d/u:null,tokensPerSecond:h>0&&p>0?Math.round(p/(h/1e3)*10)/10:null}}function CU(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 ay=Dg(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}})})),kU={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 jU({value:e}){const t=NA(e),{t:n}=se();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(kU[t.reason])]})]})]})}function _U({ask:e,waiting:t}){const{t:n}=se(),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(ly,{selected:o===e.answer,text:o},o)),s!==null&&i.jsx(ly,{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 ly({selected:e,text:t,label:n}){const{t:s}=se(),o=e?Eg:zx;return i.jsxs("li",{"data-selected":e||void 0,className:U("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:U("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 NU=/^Subagent ".*" \(agentId [^,\s]+, runId [^)\s]+\) \S+ after .+\.$/gm,TU=/^The following is the subagent's report: .*$\n?/m,DU=/<usage>([\s\S]*?)<\/usage>/,Op=(e,t)=>{const n=new RegExp(`^${t}: (\\d+)$`,"m").exec(e);return n?Number(n[1]):null};function IU(e){const t=e.indexOf(`
|
|
27
|
-
`),n=t<0?e:e.slice(0,t);let s=t<0?"":e.slice(t+1),o=null;const r=DU.exec(s);if(r){s=s.slice(0,r.index);const a=Op(r[1],"subagent_tokens"),l=Op(r[1],"tool_uses"),c=Op(r[1],"duration_ms");a!==null&&l!==null&&c!==null&&(o={tokens:a,toolUses:l,durationMs:c})}return{header:n,report:s.replace(TU,"").trim(),usage:o}}function EU(e){const t=e.trim(),n=[...t.matchAll(NU)].map(s=>s.index);return n[0]!==0?null:n.map((s,o)=>IU(t.slice(s,n[o+1]).replace(/\n+---\s*$/,"").trim()))}const Ih=m.createContext(null);function Wi(){return m.useContext(Ih)}const PU=["system","memory","tools","skills","files","results","chat"];function XT(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 PU.flatMap(s=>{const o=n.get(s)??0;return o<=0?[]:[{kind:s,tokens:o,width:Math.round(o/t*1e3)/10}]})}const Vc=8,cy=(e,t)=>e.reduce((n,s)=>n+(s.tag===t?s.n??1:1),0),dy=e=>e.reduce((t,n)=>t+n.tokens,0);function uy(e,t){const n=e?.find(o=>o.kind===t)?.items??[];if(n.length<=Vc)return n;if(t==="chat"){const o=n.filter(c=>c.tag==="compacted"),r=n.filter(c=>c.tag!=="compacted"),a=Vc-o.length-1,l=r.slice(0,r.length-a);return[...o,{name:"earlier",tag:"turns",n:cy(l,"turns"),tokens:dy(l)},...r.slice(r.length-a)]}const s=n.slice(Vc-1);return[...n.slice(0,Vc-1),{name:"other",tag:"more",n:cy(s,"more"),tokens:dy(s)}]}function AU(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 MU(e,t){return!e||e<=0||t===void 0||t>=e?null:Math.round((1-t/e)*100)}const zp=e=>({type:"settings",link:{category:e,rowId:`${e}.root`}});function RU(e,t,n){const s=()=>{const o=Pg(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()??zp("instructions"):null;case"tools":return t.tag==="more"?null:zp(t.tag==="mcp"?"mcp":"tools");case"skills":return t.tag==="more"?null:zp("skills");default:return null}}const LU=new TextEncoder,OU=new TextDecoder("utf-8",{ignoreBOM:!0}),zU=/[\uD800-\uDFFF]/,Pm=1024;let Yr=new Uint8Array(Pm);function GU(){Yr.length!==Pm&&(Yr=new Uint8Array(Pm))}function as(e){if(e.length===0)return e;if(zU.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;Yr.length<t&&(Yr=new Uint8Array(t));const{written:n}=LU.encodeInto(e,Yr);return OU.decode(Yr.subarray(0,n))}const FU=4096,HU=.5;function BU(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=$U(e,s);o!=null&&(t.hunkContent.splice(n,1,...o),n+=o.length-1)}VU(t,e)}}function VU(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,c=a?o.additionLineIndex:o.deletionLineIndex,d=a?o.additions:o.deletions,u=l[c]??"";if(u.trim()!=="")continue;let h=!0;for(let v=1;v<d;v++)if(l[c+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 $U(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)>FU)return null;const c=[];for(let x=0;x<n;x++)c.push(hy(e.deletionLines[o+x]??""));const d=[];for(let x=0;x<s;x++)d.push(hy(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+=UU(c[y+(u?0:x)],d[y+(u?x:0)]);x===0?p=v+a*HU: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 WU=/\s+/g;function hy(e){return e.replace(WU,"")}function UU(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 KU(e,t){try{return qU(e,t)}finally{GU()}}function qU(e,{cacheKey:t,isGitDiff:n=PA.test(e),oldFile:s,newFile:o,throwOnError:r=!1}={}){let a=0;const l=QU(e,"@@ ");let c;const d=s==null||o==null;let u=0,h=0;for(const p of l){const f=JT(p),g=f[0];if(g==null){if(r)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",p);continue}const x=JU(g);let v=0,y=0;if(x==null||c==null){if(c!=null){if(r)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",p);continue}c={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:d,additionLines:!d&&s!=null&&o!=null?py(o.contents):[],deletionLines:!d&&s!=null&&o!=null?py(s.contents):[],cacheKey:my(t)},c.additionLines.length===1&&o?.contents===""&&(c.additionLines.length=0),c.deletionLines.length===1&&s?.contents===""&&(c.deletionLines.length=0);for(const A of f){if(A.startsWith("diff --git")){const D=A.trim().match(TA),P=D?.[1]??D?.[2],T=D?.[3]??D?.[4];if(P==null||T==null){if(r)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",A);continue}c.name=as(T.trim()),P!==T&&(c.prevName=as(P.trim()));continue}const I=A.startsWith("---")||A.startsWith("+++")?A.match(n?DA:IA):null;if(I!=null){const[,D,P]=I;if(D==="---"&&P!=="/dev/null"){const T=as(P.trim());c.prevName=T,c.name=T}else D==="+++"&&P!=="/dev/null"&&(c.name=as(P.trim()))}else if(n){if(A.startsWith("new mode ")&&(c.mode=as(A.slice(8).trim())),A.startsWith("old mode ")&&(c.prevMode=as(A.slice(8).trim())),A.startsWith("new file mode")&&(c.type="new",c.mode=as(A.slice(13).trim())),A.startsWith("deleted file mode")&&(c.type="deleted",c.mode=as(A.slice(17).trim())),A.startsWith("similarity index")&&(A.startsWith("similarity index 100%")?c.type="rename-pure":c.type="rename-changed"),A.startsWith("index ")){const[,D,P,T]=A.trim().match(EA)??[];D!=null&&(c.prevObjectId=as(D)),P!=null&&(c.newObjectId=as(P)),T!=null&&(c.mode=as(T))}A.startsWith("rename from ")&&(c.prevName=as(A.slice(12).trim())),A.startsWith("rename to ")&&(c.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:C,deletionStart:_}=x;u=d?u:_-1,h=d?h:C-1;const N={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:x.additionCount,additionStart:C,additionLines:v,deletionCount:x.deletionCount,deletionStart:_,deletionLines:y,deletionLineIndex:u,additionLineIndex:h,hunkContent:[],hunkContext:my(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&&YU(I)&&!XU(I))throw Error("parsePatchContent: hunk has more lines than expected");break}const D=I[0];if(D!=="+"&&D!=="-"&&D!==" "&&D!=="\\"){if(r)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${D}", full line: "${I}"`),console.error("processFile: invalid rawLine:",I);continue}const P=e7(D);if(P==="addition"){if(r&&S>=N.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const T=Gp(I);(b==null||b.type!=="change")&&(b=Fp("change",u,h),N.hunkContent.push(b)),h++,S++,d&&c.additionLines.push(T),b.additions++,v++,w="addition"}else if(P==="deletion"){if(r&&k>=N.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const T=Gp(I);(b==null||b.type!=="change")&&(b=Fp("change",u,h),N.hunkContent.push(b)),u++,k++,d&&c.deletionLines.push(T),b.deletions++,y++,w="deletion"}else if(P==="context"){if(r&&(k>=N.deletionCount||S>=N.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const T=Gp(I);(b==null||b.type!=="context")&&(b=Fp("context",u,h),N.hunkContent.push(b)),h++,u++,S++,k++,d&&(c.deletionLines.push(T),c.additionLines.push(T)),b.lines++,w="context"}else if(P==="metadata"&&b!=null){if(b.type==="context"?(N.noEOFCRAdditions=!0,N.noEOFCRDeletions=!0):w==="deletion"?N.noEOFCRDeletions=!0:w==="addition"&&(N.noEOFCRAdditions=!0),d&&(w==="addition"||w==="context")){const T=c.additionLines.length-1;T>=0&&(c.additionLines[T]=Il(c.additionLines[T]))}if(d&&(w==="deletion"||w==="context")){const T=c.deletionLines.length-1;T>=0&&(c.deletionLines[T]=Il(c.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(ba(N.additionStart,N.additionCount)-a,0),c.hunks.push(N),a=ho(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=c.splitLineCount+N.collapsedBefore,N.unifiedLineStart=c.unifiedLineCount+N.collapsedBefore,c.splitLineCount+=N.collapsedBefore+N.splitLineCount,c.unifiedLineCount+=N.collapsedBefore+N.unifiedLineCount}if(c!=null){if(r&&d&&!n&&c.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(c.hunks.length>0&&!d&&c.additionLines.length>0&&c.deletionLines.length>0){const p=c.hunks[c.hunks.length-1],f=ho(p.additionStart,p.additionCount),g=c.additionLines.length,x=Math.max(g-f,0);c.splitLineCount+=x,c.unifiedLineCount+=x}return n||(c.prevName!=null&&c.name!==c.prevName?c.hunks.length>0?c.type="rename-changed":c.type="rename-pure":(s==null||s.contents==="")&&o!=null&&o.contents!==""?c.type="new":s!=null&&s.contents!==""&&(o==null||o.contents==="")&&(c.type="deleted")),c.type!=="rename-pure"&&c.type!=="rename-changed"&&(c.prevName=void 0),BU(c),c}}function py(e){const t=JT(e);for(let n=0;n<t.length;n++)t[n]=as(t[n]);return t}function JT(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 YU(e){const t=e[0];return t==="+"||t==="-"||t===" "}function XU(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 JU(e){if(!e.startsWith("@@ -"))return;let t=4;const n=$c(e,t);if(n==null)return;const s=n.value;t=n.endIndex;let o=1;if(e[t]===","){const u=$c(e,t+1);if(u==null)return;o=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const r=$c(e,t);if(r==null)return;const a=r.value;t=r.endIndex;let l=1;if(e[t]===","){const u=$c(e,t+1);if(u==null)return;l=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let c;const d=t+3;return e[d]===" "&&(c=ZU(e.slice(d+1))),{additionCount:l,additionStart:a,deletionCount:o,deletionStart:s,hunkContext:c}}function $c(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 ZU(e){return e.endsWith(`\r
|
|
32
|
-
`)?e.slice(0,-2):e.endsWith(`
|
|
33
|
-
`)?e.slice(0,-1):e}function QU(e,t){if(e.length===0)return[""];const n=`
|
|
34
|
-
${t}`,s=e.startsWith(t)?0:fy(e,n,0);if(s===-1)return[e];const o=[];s>0&&o.push(e.slice(0,s));let r=s;for(;;){const a=fy(e,n,r+1);if(a===-1)break;o.push(e.slice(r,a)),r=a}return o.push(e.slice(r)),o}function fy(e,t,n){const s=e.indexOf(t,n);return s===-1?-1:s+1}function my(e){return e==null?e:as(e)}function e7(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Gp(e){const t=e.slice(1);return as(t===""?`
|
|
35
|
-
`:t)}function Fp(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 t7 extends AA{constructor(){super(...arguments),this.tokenize=s7}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 n7=new t7;function gy(e,t,n){return n7.diff(e,t,n)}function s7(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 i7(e){for(let t=0;t<e.length;t++)if(e[t]<" "||e[t]>"~"||e[t]==='"'||e[t]==="\\")return!0;return!1}function _o(e){if(!i7(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 xy={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function vy(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 c=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;gy(n,s,Object.assign(Object.assign({},l),{callback:h=>{const p=d(h);u(p)}}))}else return d(gy(n,s,l));function d(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],C=w.lines||r7(w.value);if(w.lines=C,w.added||w.removed){if(!f){const _=u[b-1];f=v,g=y,_&&(x=c>0?h(_.lines.slice(-c)):[],f-=x.length,g-=x.length)}for(const _ of C)x.push((w.added?"+":"-")+_);w.added?y+=C.length:v+=C.length}else{if(f)if(C.length<=c*2&&b<u.length-2)for(const _ of h(C))x.push(_);else{const _=Math.min(C.length,c);for(const S of h(C.slice(0,_)))x.push(S);const N={oldStart:f,oldLines:v-f+_,newStart:g,newLines:y-g+_,lines:x};p.push(N),f=0,g=0,x=[]}v+=C.length,y+=C.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 Am(e,t){var n,s,o,r,a,l;if(t||(t=xy),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=>Am(u,t)).join(`
|
|
42
|
-
`)}const c=[];if(e.isGit){if(t=xy,!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/")),c.push("diff --git "+_o(u)+" "+_o(h)),e.isDelete&&c.push("deleted file mode "+((n=e.oldMode)!==null&&n!==void 0?n:"100644")),e.isCreate&&c.push("new file mode "+((s=e.newMode)!==null&&s!==void 0?s:"100644")),e.oldMode&&e.newMode&&!e.isDelete&&!e.isCreate&&(c.push("old mode "+e.oldMode),c.push("new mode "+e.newMode)),e.isRename&&(c.push("rename from "+_o(((o=e.oldFileName)!==null&&o!==void 0?o:"").replace(/^a\//,""))),c.push("rename to "+_o(((r=e.newFileName)!==null&&r!==void 0?r:"").replace(/^b\//,"")))),e.isCopy&&(c.push("copy from "+_o(((a=e.oldFileName)!==null&&a!==void 0?a:"").replace(/^a\//,""))),c.push("copy to "+_o(((l=e.newFileName)!==null&&l!==void 0?l:"").replace(/^b\//,""))))}else t.includeIndex&&e.oldFileName==e.newFileName&&e.oldFileName!==void 0&&c.push("Index: "+e.oldFileName),t.includeUnderline&&c.push("===================================================================");const d=e.hunks.length>0;t.includeFileHeaders&&e.oldFileName!==void 0&&e.newFileName!==void 0&&(!e.isGit||d)&&(c.push("--- "+_o(e.oldFileName)+(e.oldHeader?" "+e.oldHeader:"")),c.push("+++ "+_o(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;c.push("@@ -"+p+","+h.oldLines+" +"+f+","+h.newLines+" @@");for(const g of h.lines)c.push(g)}return c.join(`
|
|
43
|
-
`)+`
|
|
44
|
-
`}function o7(e,t,n,s,o,r,a){if(typeof a=="function"&&(a={callback:a}),a?.callback){const{callback:l}=a;vy(e,t,n,s,o,r,Object.assign(Object.assign({},a),{callback:c=>{l(c?Am(c,a.headerOptions):void 0)}}))}else{const l=vy(e,t,n,s,o,r,a);return l?Am(l,a?.headerOptions):void 0}}function r7(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 a7="/dev/null";function vo(e,t,n,s=!1){if(e===null&&t===null)throw new Error("parseDiffFromFile: You must pass oldFile, newFile, or both");const o=e??by(),r=t??by(),a=KU(o7(o.name,r.name,o.contents,r.contents,o.header,r.header,n),{cacheKey:(()=>{const c=e?.cacheKey??e?.name,d=t?.cacheKey??t?.name;return c!=null&&d!=null?c+":"+d:c??d})(),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 by(){return{name:a7,contents:""}}function l7(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function c7(e){return{...e,hunks:e.hunks.map(t=>({...t,hunkContent:t.hunkContent.map(n=>({...n}))})),deletionLines:[...e.deletionLines],additionLines:[...e.additionLines]}}function Mm(e){return e!==""?e.split(MA):[]}function Rm(e,t,n){const s=e==="clone"?c7(t):t;if(!s.isPartial)throw new Error("hydratePartialDiff: fileDiff must be partial");switch(s.type){case"change":case"rename-changed":return d7(s,h7(s,n),wy(s,n));case"rename-pure":{const o=wy(s,n);p7(s,n);const r=Mm(o.contents);return s.isPartial=!1,s.deletionLines=r,s.additionLines=r,ZT(s,null,o),s}}throw new Error(`hydratePartialDiff: ${s.type} diffs cannot be hydrated from loaded files`)}function d7(e,t,n){const s=Mm(t.contents),o=Mm(n.contents),{hunks:r,splitLineCount:a,unifiedLineCount:l}=u7(e.hunks,o.length);return e.hunks=r,e.splitLineCount=a,e.unifiedLineCount=l,e.isPartial=!1,e.deletionLines=s,e.additionLines=o,ZT(e,t,n),e}function u7(e,t){let n=0,s=0,o=0;const r=[];for(const a of e){const l=Math.max(a.additionStart-1,0),c=Math.max(a.deletionStart-1,0);let d=l,u=c,h=0,p=0,f=0,g=0;const x=[];for(const y of a.hunkContent){if(y.type==="context"){x.push({...y,additionLineIndex:d,deletionLineIndex:u}),d+=y.lines,u+=y.lines,f+=y.lines,g+=y.lines;continue}x.push({...y,additionLineIndex:d,deletionLineIndex:u}),d+=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(ba(a.additionStart,a.additionCount)-o,0);r.push({...a,collapsedBefore:v,additionLineIndex:l,deletionLineIndex:c,additionLines:h,deletionLines:p,hunkContent:x,splitLineStart:n+v,unifiedLineStart:s+v,splitLineCount:f,unifiedLineCount:g}),n+=v+f,s+=v+g,o=ho(a.additionStart,a.additionCount)}if(r.length>0){const a=r[r.length-1],l=ho(a.additionStart,a.additionCount),c=Math.max(t-l,0);n+=c,s+=c}return{hunks:r,splitLineCount:n,unifiedLineCount:s}}function h7(e,t){if(t.oldFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile`);return t.oldFile}function wy(e,t){if(t.newFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires newFile`);return t.newFile}function p7(e,t){if(t.oldFile!==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile to be null`)}function f7(e,t,n){return e.cacheKey!=null?`${e.cacheKey}:hydrated`:m7(t,n)}function ZT(e,t,n){const s=f7(e,t,n);if(s==null){delete e.cacheKey;return}e.cacheKey=s}function m7(e,t){return e!=null&&t!=null?e.cacheKey!=null&&t.cacheKey!=null?`${e.cacheKey}:${t.cacheKey}`:void 0:e?.cacheKey??t?.cacheKey}var g7=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 Wc(e){return xs({tagName:"div",properties:{"data-content-buffer":"","data-buffer-size":e,style:`grid-row: span ${e};min-height:calc(${e} * 1lh)`}})}function Uc(e){return xs({tagName:"div",children:[xs({tagName:"span",children:[jd("No newline at end of file")]})],properties:{"data-no-newline":"","data-line-type":e,"data-column-content":""}})}function Hp(e){return xs({tagName:"div",children:[RA({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 Er({type:e,content:t,expandIndex:n,chunked:s=!1,slotName:o,isFirstHunk:r,isLastHunk:a}){let l=0;const c=[];if(e==="metadata"&&t!=null&&c.push(xs({tagName:"div",children:[jd(t)],properties:{"data-separator-wrapper":""}})),(e==="line-info"||e==="line-info-basic")&&t!=null){const d=[];n!=null&&(s?(r||(d.push(Hp("up")),l++),a||(d.push(Hp("down")),l++)):(d.push(Hp(!r&&!a?"both":r?"down":"up")),l++)),d.push(xs({tagName:"div",children:[xs({tagName:"span",children:[jd(t)],properties:{"data-unmodified-lines":""}})],properties:{"data-separator-content":""}})),s&&n!=null&&d.push(xs({tagName:"div",children:[jd("Expand all")],properties:{role:"button","data-expand-button":"","data-expand-all-button":""}})),c.push(xs({tagName:"div",children:d,properties:{"data-separator-wrapper":"","data-separator-multi-button":l>1?"":void 0}}))}return e==="custom"&&o!=null&&c.push(xs({tagName:"slot",properties:{name:o}})),xs({tagName:"div",children:c,properties:{"data-separator":c.length===0?"simple":e,"data-expand-index":n,"data-separator-first":r?"":void 0,"data-separator-last":a?"":void 0}})}function x7(e,t){return`hunk-separator-${e}-${t}`}function v7(e){const t=e.at(-1);return t==null?0:Math.max(ho(t.additionStart,t.additionCount),ho(t.deletionStart,t.deletionCount))}function Lm(e){return e.startingLine===0&&e.totalLines===1/0&&e.bufferBefore===0&&e.bufferAfter===0}function no(e,t){const n=vo({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 b7(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 w7(e){for(const t of e)if(t.trim().length>0)return!1;return!0}function Om(e,t){return t.length>0&&t.length<e.deletionLines.length&&w7(t)}function Nu(e,t,n){const s=e.deletionLines.join(""),o=b7(t.length,s),r=vo({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 Bd(e,t){return Nu(e,[""],t)}function QT(e,t){if(e.additionLines.length===0)return Bd(e,t);if(Om(e,e.additionLines))return Nu(e,e.additionLines,t);const n=e.additionLines,s=no(e,t);return eD(s,n),s}function y7(e){return e.length>1&&e.at(-1)===""}function eD(e,t){if(!y7(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&&ho(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,lv(e);return}}}function S7(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||Il(a)===Il(l))return qi(e,no(e,n))}const o=C7(e,s);if(o.size===0)return qi(e,no(e,n));for(const r of o)if(!j7(e,r,n))return qi(e,no(e,n));return lv(e),LA(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 C7(e,t){const n=new Set;for(const s of t){const o=k7(e,s);if(o==null)return new Set;n.add(o)}return n}function k7(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 j7(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=vo({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:(_7(s,l),tD(e,t),!0)}function tD(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 _7(e,t){const n=e.additionLineIndex,s=e.deletionLineIndex;e.hunkContent=t.hunkContent.map(o=>nD(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,av(e)}function nD(e,t,n){return{...e,additionLineIndex:e.additionLineIndex+t,deletionLineIndex:e.deletionLineIndex+n}}function av(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 lv(e){let t=0,n=0,s=0;for(const o of e.hunks)o.collapsedBefore=Math.max(ba(o.additionStart,o.additionCount)-s,0),o.splitLineStart=t+o.collapsedBefore,o.unifiedLineStart=n+o.collapsedBefore,av(o),t+=o.collapsedBefore+o.splitLineCount,n+=o.collapsedBefore+o.unifiedLineCount,s=ho(o.additionStart,o.additionCount);if(e.hunks.length>0){const o=e.hunks[e.hunks.length-1],r=Math.max(e.additionLines.length-ho(o.additionStart,o.additionCount),0);t+=r,n+=r}e.splitLineCount=t,e.unifiedLineCount=n}const yy=new WeakMap;function N7(e){return e.length>1&&e[e.length-1]===""?e.slice(0,-1):e}function T7(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 zm(e,t){const n=e.hunks,s=e.additionLines,o=N7(s),r=o===s?e:{...e,additionLines:o},a=O7(n,L7(r,t),e.deletionLines.length),l=F7(r,a);if(e.additionLines=o,e.hunks=l,e.editSessionDirty=!0,$7(e),eD(e,s),!!B7(n,e.hunks))return{regions:a.map(c=>c.previousSpan)}}function D7(e,t,n,s){const o=Array.from(new Set(t)).filter(c=>c>=0&&c<e.additionLines.length).sort((c,d)=>c-d);if(o.length===0)return;const{hunks:r}=e;let a,l=0;for(const c of o){for(;l<r.length;){const h=r[l];if(c<Tu(h)+h.additionCount)break;l++}const d=r[l],u=d==null?void 0:Tu(d);if(u==null||c<u||a!=null&&a!==l)return zm(e,n);a=l}if(a!=null){if(I7(e,o,a,s,n)){e.editSessionDirty=!0;return}return zm(e,n)}}function I7(e,t,n,s,o){if(s==null||o?.ignoreWhitespace===!0||o?.stripTrailingCr===!0)return!1;const r=E7(e),a=e.hunks[n];if(a.hunkContent.some(P7))return!1;for(const l of t){const c=s.get(l),d=e.additionLines[l];if(c==null||d==null||r.has(c)||r.has(d))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 E7(e){const t=yy.get(e);if(t?.lines===e.deletionLines)return t.set;const n=new Set(e.deletionLines);return yy.set(e,{lines:e.deletionLines,set:n}),n}function P7(e){return e?.type==="change"&&(e.additions===0||e.deletions===0)}function A7(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),c=a==null?void 0:e.get(a.firstIndex),d=l?.fromStart??0,u=c?.fromEnd??0;(d>0||u>0)&&n.set(o,{fromStart:d,fromEnd:u})}return n}function M7(e,t,n){const s=[];if(e.isPartial)return s;for(const[r,a]of e.hunks.entries()){const l=El({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:t,hunkIndex:r,collapsedContextThreshold:n});if(l.rangeSize<=n)continue;const c=Cr(a),d=c-l.rangeSize;l.fromStart>0&&s.push([d,d+l.fromStart]),l.fromEnd>0&&s.push([c-l.fromEnd,c])}const o=Pl({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=Cr(r)+r.deletionCount;s.push([a,a+o.fromStart])}return s}function R7(e,t){const n=new Map;if(t.length===0)return n;const s=(r,a,l)=>{if(l<=a)return;let c=0,d=0;for(const[u,h]of t)h<=a||u>=l||(u<=a&&(c=Math.max(c,Math.min(h,l)-a)),h>=l&&(d=Math.max(d,l-Math.max(u,a))));(c>0||d>0)&&n.set(r,{fromStart:c,fromEnd:d})};for(const[r,a]of e.hunks.entries()){const l=Cr(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,Cr(o)+o.deletionCount,e.deletionLines.length),n}function Gm(e,t){return e.editSessionDirty!==!0?!1:(e.editSessionDirty=void 0,Object.assign(e,e.additionLines.length<=1&&e.additionLines.join("")===""?no(e,t):QT(e,t)),!0)}function L7(e,t){if(T7(e.deletionLines,e.additionLines)==null)return[];const n=vo({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 c of a.hunkContent){if(c.type==="context"){o+=c.lines,r+=c.lines;continue}const d=nD(c,0,0);d.additions===0&&(d.additionLineIndex=o),d.deletions===0&&(d.deletionLineIndex=r),s.push(d),o+=d.additions,r+=d.deletions}}return s}function O7(e,t,n){const s=e.map((a,l)=>{const c=Cr(a);return{deletionStart:c,deletionEnd:c+a.deletionCount,blocks:[],previousSpan:{firstIndex:l,lastIndex:l}}}),o=[];let r=0;for(const a of t){const l=a.deletionLineIndex,c=l+a.deletions;for(;r<s.length&&s[r].deletionEnd<l;)o.push(s[r]),r++;let d=o.length>0&&z7(l,c,o[o.length-1])?o.pop():void 0;for(;r<s.length&&s[r].deletionStart<=c;)d=G7(d,s[r]),r++;if(d==null){let u=l,h=c;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--:c<f&&h++}d={deletionStart:u,deletionEnd:h,blocks:[],previousSpan:void 0}}d.deletionStart=Math.min(d.deletionStart,l),d.deletionEnd=Math.max(d.deletionEnd,c),d.blocks.push(a),o.push(d)}for(;r<s.length;)o.push(s[r]),r++;return o}function z7(e,t,n){return e<=n.deletionEnd&&t>=n.deletionStart}function G7(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 F7(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,c=[];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");Sy(c,h,o,s),s+=h,o+=p,c.push({...u}),s+=u.deletions,o+=u.additions}const d=r.deletionEnd-s;if(d<0)throw new Error("buildRegionHunks: block exceeds its old-side region");Sy(c,d,o,s),s+=d,o+=d,n.push(H7(e,{additionStart:l,additionEnd:o,deletionStart:r.deletionStart,deletionEnd:r.deletionEnd},c))}if(e.deletionLines.length-s!==e.additionLines.length-o)throw new Error("buildRegionHunks: trailing context mismatch");return n}function H7(e,t,n){const s=t.additionEnd-t.additionStart,o=t.deletionEnd-t.deletionStart;let r=0,a=0;for(const c of n)c.type==="change"&&(r+=c.additions,a+=c.deletions);const l={collapsedBefore:0,additionStart:Kc(t.additionStart,s),additionCount:s,additionLines:r,additionLineIndex:ky(t.additionStart,s),deletionStart:Kc(t.deletionStart,o),deletionCount:o,deletionLines:a,deletionLineIndex:ky(t.deletionStart,o),hunkContent:n,hunkSpecs:`@@ -${Kc(t.deletionStart,o)},${o} +${Kc(t.additionStart,s)},${s} @@`,splitLineStart:0,splitLineCount:0,unifiedLineStart:0,unifiedLineCount:0,noEOFCRAdditions:!1,noEOFCRDeletions:!1};return av(l),l}function Sy(e,t,n,s){t>0&&e.push({type:"context",lines:t,additionLineIndex:n,deletionLineIndex:s})}function B7(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(Cr(s)!==Cr(o)||s.deletionCount!==o.deletionCount||Tu(s)!==Tu(o)||s.additionCount!==o.additionCount||s.splitLineCount!==o.splitLineCount||!V7(s,o))return!0}return!1}function V7(e,t){const n=Cy(e),s=Cy(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*Cy(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 Tu(e){return ba(e.additionStart,e.additionCount)}function Cr(e){return ba(e.deletionStart,e.deletionCount)}function Kc(e,t){return t===0?e:e+1}function ky(e,t){return t===0?e-1:e}function $7(e){lv(e);for(let t=0;t<e.hunks.length;t++)tD(e,t)}let W7=-1;var U7=class{options;onRenderUpdate;workerManager;__id=`diff-hunks-renderer:${++W7}`;highlighter;diff;expandedHunks=new Map;deletionAnnotations={};additionAnnotations={};computedLang="text";renderCache;editSessionActive=!1;constructor(e={theme:Ai},t,n){this.options=e,this.onRenderUpdate=t,this.workerManager=n,n?.isWorkingPool()!==!0&&(this.highlighter=Zh(e.theme??Ai)?OA():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,Bd(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||_d(e.diff)||Xc(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);Dr(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)??zA}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[d,u]of e){const h=r[d]?.properties??{},p=u.map(v=>v[2]).join(""),f=d<o.additionLines.length,g=f?o.additionLines[d]??"":"",x=Il(g);f&&(o.additionLines[d]=GA(g,p),x!==p&&(a.push(d),l.set(d,g))),r[d]={type:"element",tagName:"div",properties:{"data-line":h["data-line"]??d+1,"data-line-index":h["data-line-index"]??d,"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 c=!1;if(a.length>0)if(this.editSessionActive&&!o.isPartial){if(!n)if(o.additionLines.length<=1&&o.additionLines.join("")==="")Object.assign(o,Bd(o,this.options.parseDiffOptions)),this.markEditSessionPass(o),c=!0;else if(Om(o,o.additionLines))Object.assign(o,Nu(o,o.additionLines,this.options.parseDiffOptions)),this.markEditSessionPass(o),c=!0;else{const d=D7(o,a,this.options.parseDiffOptions,l);this.applyExpansionRemap(d),c=d!=null}}else Object.assign(o,S7(o,a,this.options.parseDiffOptions));return s.baseThemeType=t,this.renderCache.isDirty=!0,c}applyExpansionRemap(e){e!=null&&(this.expandedHunks=A7(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=X7(e,s),n.code.additionLines=Y7(s,t.additionLines,n.code.additionLines,e),t.additionLines.length<=1&&t.additionLines.join("")===""?(Object.assign(t,Bd(t,this.options.parseDiffOptions)),n.code.additionLines[0]=Fm(0,e.getLineText(0)),this.markEditSessionPass(t)):this.editSessionActive?this.applySessionDocumentChange(t):Object.assign(t,QT(t,this.options.parseDiffOptions)),this.renderCache.isDirty=!0}applySessionDocumentChange(e){const{parseDiffOptions:t}=this.options,n=e.additionLines;if(Om(e,n)){Object.assign(e,Nu(e,n,t)),this.markEditSessionPass(e);return}this.applyExpansionRemap(zm(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=>FA(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:c=1,expansionLineCount:d=100,hunkSeparators:u="line-info",lineDiffType:h="word-alt",maxLineDiffLength:p=1e3,overflow:f="scroll",stickyHeader:g=!1,theme:x=Ai,headerRenderMode:v="default",tokenizeMaxLineLength:y=1e3,tokenizeMaxLength:b=HA,useTokenTransformer:w=!1,useCSSClasses:C=!1}=this.options;return{diffIndicators:e,diffStyle:t,disableBackground:n,disableFileHeader:s,disableLineNumbers:o,disableVirtualizationBuffers:r,collapsed:a,expandUnchanged:l,collapsedContextThreshold:c,expansionLineCount:d,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:C}}async initializeHighlighter(){return this.highlighter=await BA(VA(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=Xc(e,this.getTokenizeMaxLength());let s=this.workerManager?.getDiffResultCache(e);s!=null&&!Dr(t,s.options)&&(s=void 0),this.renderCache??={diff:e,highlighted:!n&&!_d(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??Qh(e.name),this.initializeHighlighter())}getLocalHighlightTheme(){return this.workerManager?.getDiffRenderOptions().theme??this.options.theme??Ai}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}:!Vr(e,n.diff)||!Dr(t,n.options)?{options:t,forceHighlight:!0}:{options:t,forceHighlight:!1}}renderDiff(e=this.renderCache?.diff,t=c0){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,c=!l||_d(e)||Xc(e,this.getTokenizeMaxLength()),d=!Vr(e,this.renderCache.diff),u=!Jk(this.renderCache.renderRange,t);if(!this.editSessionActive&&this.workerManager?.isWorkingPool()===!0){const h=this.renderCache.result==null&&this.renderCache.highlighted&&!c&&!d&&Lm(t);h&&(this.renderCache.highlightPending=!0),!h&&(c||this.renderCache.result==null||!this.renderCache.highlighted&&(d||u))&&(this.renderCache.diff=e,this.renderCache.options=o,this.renderCache.highlighted=!1,(this.renderCache.result==null||d||u||r)&&(this.renderCache.result=this.workerManager.getPlainDiffAST(e,t.startingLine,t.totalLines,Lm(t)||n?!0:this.expandedHunks,s)),this.renderCache.renderRange=t),!c&&l&&(!this.renderCache.highlighted||r)&&this.workerManager.highlightDiffAST(this,e)}else{this.computedLang=e.lang??Qh(e.name);const h=this.highlighter!=null&&Zh(o.theme),p=this.highlighter!=null&&d0(this.computedLang),f=!c&&p;if(this.highlighter!=null&&h&&(r||c||!this.renderCache.highlighted&&f||this.renderCache.result==null)){const{result:g,options:x}=this.renderDiffWithHighlighter(e,this.highlighter,c||!p);this.renderCache={diff:e,options:x,highlighted:f,result:g,renderRange:void 0}}(!h||!c&&!p)&&this.asyncHighlight(e).then(({result:g,options:x})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.applyHighlightResult(e,g,x,!c)})}return this.renderCache.result!=null?this.processDiffResult(this.renderCache.diff,t,this.renderCache.result):void 0}async asyncRender(e,t=c0){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 $A({type:"diff",diffIndicators:s,disableBackground:o,disableLineNumbers:r,overflow:a,split:e,totalLines:t,customProperties:n})}async asyncHighlight(e){const t=Xc(e,this.getTokenizeMaxLength());this.computedLang=t?"text":e.lang??Qh(e.name);const n=this.highlighter!=null&&Zh(this.getLocalHighlightTheme()),s=t||this.highlighter!=null&&d0(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=WA(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(Jr({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]=Fm(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||!Dr(this.renderCache.options,n)||!Vr(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||!Dr(t,n.options)))return n}hasHighlightedRenderCache(e,t){const{renderCache:n}=this;return n?.result!=null&&n.highlighted&&Vr(e,n.diff)&&Dr(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:c,collapsedContextThreshold:d,hunkSeparators:u}=this.getOptionsWithDefaults(),h=this.renderCache?.isDirty??!1;this.diff=e;const p=r==="unified",f=Q7(e,this.options.loadDiffFiles!=null),g=!e.isPartial||f;let x=[],v=[],y=[];const b=[],{additionLines:w,deletionLines:C}=n,_={rowCount:0,hunkSeparators:u,additionsContentAST:x,deletionsContentAST:v,unifiedContentAST:y,unifiedGutterAST:Ec(),deletionsGutterAST:Ec(),additionsGutterAST:Ec(),expansionLineCount:c,hunkData:b,incrementRowCount(L=1){_.rowCount+=L},pushToGutter(L,V){switch(L){case"unified":_.unifiedGutterAST.children.push(V);break;case"deletions":_.deletionsGutterAST.children.push(V);break;case"additions":_.additionsGutterAST.children.push(V);break}}},N=UA({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"?(_.pushToGutter("additions",ri(void 0,"buffer",this.size)),x?.push(Wc(this.size))):(_.pushToGutter("deletions",ri(void 0,"buffer",this.size)),v?.push(Wc(this.size))),this.size=0,this.side=void 0}}},k=(L,V,X,F,ee)=>{_.pushToGutter(L,YA(V,X,F,ee))};function A(L){S.flush(),r==="unified"?Bp("unified",L,_):(Bp("deletions",L,_),Bp("additions",L,_))}this.pushFileLevelAnnotations(e,r,t,_),Jr({diff:e,diffStyle:r,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:l?!0:this.expandedHunks,collapsedContextThreshold:d,callback:({hunkIndex:L,hunk:V,collapsedBefore:X,collapsedAfter:F,additionLine:ee,deletionLine:H,type:Q})=>{const q=H!=null?H.splitLineIndex:ee.splitLineIndex,ne=ee!=null?ee.unifiedLineIndex:H.unifiedLineIndex;r==="split"&&Q!=="change"&&S.flush(),X>0&&A({hunkIndex:L,collapsedLines:X,rangeSize:Math.max(V?.collapsedBefore??0,0),hunkSpecs:V?.hunkSpecs,isFirstHunk:L===0,isLastHunk:!1,isExpandable:g});const me=r==="unified"?ne:q,ke={type:Q,hunkIndex:L,lineIndex:me,unifiedLineIndex:ne,splitLineIndex:q,deletionLine:H,additionLine:ee};if(r==="unified"){const J=this.getUnifiedInjectedRowsForLine?.(ke);J?.before!=null&&_y(J.before,_);let ae=H!=null?C[H.lineIndex]:void 0,te=ee!=null?w[ee.lineIndex]:void 0;if(ae==null&&te==null){const $e="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error($e,{file:e.name}),new Error($e)}const pe=Q==="change"?ee!=null?"change-addition":"change-deletion":Q,Te=this.getUnifiedLineDecoration({type:Q,lineType:pe,additionLineIndex:ee?.lineIndex,deletionLineIndex:H?.lineIndex});k("unified",Te.gutterLineType,ee!=null?ee.lineNumber:H.lineNumber,`${ne},${q}`,Te.gutterProperties),te!=null?te=Yc(te,Te.contentProperties,h&&ee!=null?{"data-line":ee.lineNumber,"data-line-index":`${ne},${q}`}:void 0):ae!=null&&(ae=Yc(ae,Te.contentProperties,h&&H!=null?{"data-line":H.lineNumber,"data-line-index":`${ne},${q}`}:void 0)),qc({diffStyle:"unified",type:Q,deletionLine:ae,additionLine:te,unifiedSpan:this.getAnnotations("unified",H?.lineNumber,ee?.lineNumber,L,me),createAnnotationElement:$e=>this.createAnnotationElement($e),context:_}),J?.after!=null&&_y(J.after,_)}else{const J=this.getSplitInjectedRowsForLine?.(ke);J?.before!=null&&Ny(J.before,_,S);let ae=H!=null?C[H.lineIndex]:void 0,te=ee!=null?w[ee.lineIndex]:void 0;const pe=this.getSplitLineDecoration({side:"deletions",type:Q,lineIndex:H?.lineIndex}),Te=this.getSplitLineDecoration({side:"additions",type:Q,lineIndex:ee?.lineIndex});if(ae==null&&te==null){const Ze="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(Ze,{file:e.name}),new Error(Ze)}const $e=(()=>{if(Q==="change"){if(te==null)return"additions";if(ae==null)return"deletions"}})();$e!=null?(S.side!=null&&S.side!==$e&&S.flush(),S.side=$e,S.increment()):Q==="change"&&S.flush();const Ie=this.getAnnotations("split",H?.lineNumber,ee?.lineNumber,L,me);if(Ie!=null&&S.size>0&&S.flush(),H!=null){const Ze=Yc(ae,pe.contentProperties,h?{"data-line":H.lineNumber,"data-line-index":`${H.unifiedLineIndex},${q}`}:void 0);k("deletions",pe.gutterLineType,H.lineNumber,`${H.unifiedLineIndex},${q}`,pe.gutterProperties),Ze!=null&&(ae=Ze)}if(ee!=null){const Ze=Yc(te,Te.contentProperties,h?{"data-line":ee.lineNumber,"data-line-index":`${ee.unifiedLineIndex},${q}`}:void 0);k("additions",Te.gutterLineType,ee.lineNumber,`${ee.unifiedLineIndex},${q}`,Te.gutterProperties),Ze!=null&&(te=Ze)}qc({diffStyle:"split",type:Q,additionLine:te,deletionLine:ae,...Ie,createAnnotationElement:Ze=>this.createAnnotationElement(Ze),context:_}),J?.after!=null&&Ny(J.after,_,S)}const Me=r==="split"&&V!=null&&q===V.splitLineStart+V.splitLineCount-1,ge=L===e.hunks.length-1&&V!=null&&(r==="split"?q===V.splitLineStart+V.splitLineCount-1:ne===V.unifiedLineStart+V.unifiedLineCount-1),$=Me?V.noEOFCRDeletions:!1,W=Me?V.noEOFCRAdditions:!1,ue=(H?.noEOFCR??!1)||$,Z=(ee?.noEOFCR??!1)||W;if(Z||ue){if(r==="split"&&S.flush(),ue){const J=Q==="context"||Q==="context-expanded"?Q:"change-deletion";r==="unified"?(_.unifiedContentAST.push(Uc(J)),_.pushToGutter("unified",ri(J,"metadata",1))):(_.deletionsContentAST.push(Uc(J)),_.pushToGutter("deletions",ri(J,"metadata",1)),Z||(_.pushToGutter("additions",ri(void 0,"buffer",1)),_.additionsContentAST.push(Wc(1))))}if(Z){const J=Q==="context"||Q==="context-expanded"?Q:"change-addition";r==="unified"?(_.unifiedContentAST.push(Uc(J)),_.pushToGutter("unified",ri(J,"metadata",1))):(_.additionsContentAST.push(Uc(J)),_.pushToGutter("additions",ri(J,"metadata",1)),ue||(_.pushToGutter("deletions",ri(void 0,"buffer",1)),_.deletionsContentAST.push(Wc(1))))}_.incrementRowCount(1)}u!=="simple"&&u!=="metadata"&&(F>0||ge&&f)&&A({hunkIndex:Q==="context-expanded"?L:L+1,collapsedLines:ge&&f?"unknown":F,rangeSize:N,hunkSpecs:void 0,isFirstHunk:!1,isLastHunk:!0,isExpandable:g}),_.incrementRowCount(1)}}),r==="split"&&S.flush();const I=Math.max(v7(e.hunks),e.additionLines.length??0,e.deletionLines.length??0),D=t.bufferBefore>0||t.bufferAfter>0,P=!p&&e.type!=="deleted",T=!p&&e.type!=="new",z=_.rowCount>0||D;x=P&&z?x:void 0,v=T&&z?v:void 0,y=p&&z?y:void 0;const O=this.createPreElement(v!=null&&x!=null,I);return{unifiedGutterAST:p&&z?_.unifiedGutterAST.children:void 0,unifiedContentAST:y,deletionsGutterAST:T&&z?_.deletionsGutterAST.children:void 0,deletionsContentAST:v,additionsGutterAST:P&&z?_.additionsGutterAST.children:void 0,additionsContentAST:x,hunkData:b,preNode:O,themeStyles:s,baseThemeType:o,headerElement:a?void 0:this.renderHeader(this.diff),totalLines:I,rowCount:_.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=Ec(n);return o.properties.style=`grid-row: span ${t.rowCount}`,[o,KA(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 dr(this.renderFullAST(e,t))}renderPartialHTML(e,t){return t==null?dr(e):dr(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(!Zk(n))return;const o=e.type!=="new"?jy(u0(this.deletionAnnotations)):[],r=e.type!=="deleted"?jy(u0(this.additionAnnotations)):[];if(o.length===0&&r.length===0)return;const a=-1,l=-1,{createAnnotationElement:c}=this;if(t==="unified"){qc({diffStyle:t,type:"context",unifiedSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:o.concat(r)},createAnnotationElement:c,context:s});return}qc({diffStyle:t,type:"context",deletionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:o},additionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:r},createAnnotationElement:c,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(aa(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(aa(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 qA({fileOrDiff:e,mode:t,stickyHeader:n})}};function jy(e){return e?.map(t=>aa(t))??[]}const K7=new Intl.PluralRules("en-US");function q7(e){return`${e} unmodified line${K7.select(e)==="one"?"":"s"}`}function _y(e,t){for(const n of e)t.unifiedContentAST.push(n.content),t.pushToGutter("unified",n.gutter),t.incrementRowCount(1)}function Ny(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 qc({diffStyle:e,type:t,deletionLine:n,additionLine:s,unifiedSpan:o,deletionSpan:r,additionSpan:a,createAnnotationElement:l,context:c}){let d=!1;if(e==="unified"){if(s!=null?c.unifiedContentAST.push(s):n!=null&&c.unifiedContentAST.push(n),o!=null){const u=t==="change"?n!=null?"change-deletion":"change-addition":t;c.unifiedContentAST.push(l(o)),c.pushToGutter("unified",ri(u,"annotation",1)),d=!0}}else if(e==="split"){if(n!=null&&c.deletionsContentAST.push(n),s!=null&&c.additionsContentAST.push(s),r!=null){const u=t==="change"?n!=null?"change-deletion":"context":t;c.deletionsContentAST.push(l(r)),c.pushToGutter("deletions",ri(u,"annotation",1)),d=!0}if(a!=null){const u=t==="change"?s!=null?"change-addition":"context":t;c.additionsContentAST.push(l(a)),c.pushToGutter("additions",ri(u,"annotation",1)),d=!0}}d&&c.incrementRowCount(1)}function Bp(e,{hunkIndex:t,collapsedLines:n,rangeSize:s,hunkSpecs:o,isFirstHunk:r,isLastHunk:a,isExpandable:l},c){if(typeof n=="number"&&n<=0)return;const d=e==="unified"?c.unifiedContentAST:e==="deletions"?c.deletionsContentAST:c.additionsContentAST;if(c.hunkSeparators==="metadata"){o!=null&&(c.pushToGutter(e,Er({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),d.push(Er({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),e!=="additions"&&c.incrementRowCount(1));return}if(c.hunkSeparators==="simple"){t>0&&(c.pushToGutter(e,Er({type:"simple",isFirstHunk:r,isLastHunk:!1})),d.push(Er({type:"simple",isFirstHunk:r,isLastHunk:!1})),e!=="additions"&&c.incrementRowCount(1));return}const u=x7(e,t),h=s>c.expansionLineCount,p=l?t:void 0,f=typeof n=="number"?q7(n):"More unchanged context may be available";c.pushToGutter(e,Er({type:c.hunkSeparators,content:f,expandIndex:p,chunked:h,slotName:u,isFirstHunk:r,isLastHunk:a})),d.push(Er({type:c.hunkSeparators,content:f,expandIndex:p,chunked:h,slotName:u,isFirstHunk:r,isLastHunk:a})),e!=="additions"&&c.incrementRowCount(1),c.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 Yc(e,t,n){return e==null||e.type!=="element"||t==null&&n==null?e:{...e,properties:{...e.properties,...t,...n}}}function Ty(e){return e.length>0&&e[e.length-1]===""?e.length-1:e.length}function Y7(e,t,n,s){const o=Ty(e),r=Ty(t),a=Math.min(o,r);let l=0;for(;l<a&&e[l]===t[l];)l++;let c=0;for(;c<a-l&&e[o-1-c]===t[r-1-c];)c++;const d=new Array(t.length);for(let u=0;u<l;u++)d[u]=n[u];for(let u=0;u<c;u++)d[r-1-u]=n[o-1-u];o<e.length&&r<t.length&&(d[t.length-1]=n[e.length-1]);for(let u=e.length;u<t.length;u++)d[u]??=n[u];for(let u=l;u<t.length;u++)d[u]??=Fm(u,s.getLineText(u));return d}function Fm(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 X7(e,t){const n=[],s=Z7(t);for(let o=0;o<e.lineCount;o++){const r=e.getLineText(o,!0);n.push(o<e.lineCount-1&&!J7(r)?r+s:r)}return n}function J7(e){return e.endsWith(`
|
|
52
|
-
`)||e.endsWith("\r")}function Z7(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 Xc(e,t){return Math.max(e.additionLines.length,e.deletionLines.length)>t}function Q7(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function e9(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side&&e.metadata===t.metadata}function t9(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 Hm(e,t=300){let n;try{await Promise.race([e(),new Promise(s=>{n=setTimeout(s,t)})])}finally{n!=null&&clearTimeout(n)}}function Bm({oldFile:e,newFile:t},n){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)throw new Error(`${n}: Pass null for an intentionally missing oldFile or newFile side`);if(e===null){if(t===null)throw new Error(`${n}: You must pass oldFile, newFile, or both`);return{oldFile:e,newFile:t}}return t===null?{oldFile:e,newFile:t}:{oldFile:e,newFile:t}}}function n9(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:XA(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 s9(e){return e.isPartial&&(e.type==="change"||e.type==="rename-changed"||e.type==="rename-pure")}let i9=-1;var sD=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file-diff:${++i9}`;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:Ai},n,s=!1){this.options=t,this.workerManager=n,this.isContainerManaged=s,this.hunksRenderer=this.createHunksRenderer(t),this.resizeManager=new JA,this.scrollSyncManager=new g7,this.interactionManager=new ZA("diff",h0(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 n9(t)}createHunksRenderer(t){return new U7(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 c=n==="deletions"?l.deletionStart:l.additionStart,d=n==="deletions"?l.deletionCount:l.additionCount;let u=ba(c,d)+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+d){if(l===o){const f=t-(u+d);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(h0(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&&!Qk(this.appliedThemeCSS.theme,this.options.theme??Ai)}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){Tf(this.handleEditSessionRender),this.emitPostRender(!0),this.editor?.cleanUp(t),this.editor=void 0,this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.pendingFiles=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,t||(this.lineAnnotations=[]),this.clearAuxiliaryNodes(),this.annotationCache.clear(),this.pre=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.placeHolder?.remove(),this.placeHolder=void 0,this.lastRenderedHeaderHTML=void 0,t||(this.cachedHeaderHTML=void 0),this.errorWrapper?.remove(),this.errorWrapper=void 0,this.spriteSVG=void 0,this.lastRowCount=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,t?this.hunksRenderer.recycle():(this.hunksRenderer.cleanUp(),this.workerManager=void 0,this.fileDiff=void 0,this.deletionFile=void 0,this.additionFile=void 0),this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,this.enabled=!1}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate({fileContainer:t,prerenderedHTML:n,preventEmit:s=!1,lineAnnotations:o,fileDiff:r,...a}){if(!this.enabled)throw new Error("FileDiff.hydrate: attempting to call hydrate after cleaned up");if(this.fileContainer!=null)throw new Error("FileDiff.hydrate: hydrate can only be called before the instance has rendered or hydrated");const l=Bm(a,"FileDiff.hydrate"),c=l?.oldFile,d=l?.newFile;this.hydrateElements(t,n),a9(this.pre,o9({fileDiff:r,oldFile:c,newFile:d}),this.options.collapsed)||l9(this.headerElement,r9({fileDiff:r,oldFile:c,newFile:d}),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),QA(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?vo(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||!s9(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||(Rm("merge",t,n),this.setHydratedState(n),await Hm(()=>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:c,...d}){const u=Bm(d,"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:c,y=this.hasThemeChanged(),b=u!=null,w=b&&(!Dy(h,this.deletionFile)||!Dy(p,this.additionFile));let C=t!=null&&t!==this.fileDiff;const _=r!=null&&(r.length>0||this.lineAnnotations.length>0)?r!==this.lineAnnotations:!1;if(!f&&Jk(v,this.renderRange)&&!s&&!_&&!y&&(t!=null&&t===this.fileDiff||t==null&&!w))return this.applyCachedThemeState(g);let N;t==null&&b&&(w||this.fileDiff==null)&&(N=vo(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&&(C=!0,this.fileDiff=N),C&&(this.cachedHeaderHTML=void 0),r!=null&&this.setLineAnnotations(r),this.fileDiff==null)return!1;this.fileDiff.editSessionDirty===!0&&this.shouldSelfHealEditSession()&&(Gm(this.fileDiff,this.options.parseDiffOptions),this.hunksRenderer.refreshHighlightedResult()),x&&this.loadFilesIfNecessary(),this.hunksRenderer.setOptions(this.getHunksRendererOptions(this.options)),this.syncInteractionOptions(),this.hunksRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling: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,eM);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,_,w||C||y)&&this.applyPartialRender({previousRenderRange:S,renderRange:v}))){const D=this.hunksRenderer.renderDiff(this.fileDiff,v);if(D==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(a,D.themeStyles,g,D.baseThemeType),D.headerElement!=null&&this.applyHeaderToDOM(D.headerElement,a),D.additionsContentAST!=null||D.deletionsContentAST!=null||D.unifiedContentAST!=null?this.applyHunksToDOM(I,D):this.pre!=null&&(this.pre.remove(),this.pre=void 0),this.renderSeparators(D.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||Lm(t))return t;const{diffStyle:s="split",expandUnchanged:o=!1,collapsedContextThreshold:r=1}=this.options;let a,l;return Jr({diff:n,diffStyle:s,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r,callback:({additionLine:c})=>{c!=null&&(a??=c.lineNumber,l=c.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=M7(t,this.hunksRenderer.getExpandedHunksMap(),n);return Gm(t,this.options.parseDiffOptions),this.hunksRenderer.setExpandedHunksMap(R7(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 ej({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 tM({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]=p0(h);if(t<p){const g=El({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=Pl({fileDiff:n,hunkIndex:n.hunks.length-1,expandedHunks:a,collapsedContextThreshold:o,errorPrefix:"FileDiff.revealLine"});if(l==null||l.renderAll)return!1;const c=n.hunks[n.hunks.length-1],[,d]=p0(c);return t<d+l.fromStart||t>=d+l.rangeSize?!1:(this.expandHunk(n.hunks.length,"up",t-(d+l.fromStart)+1+r),!0)}shouldSelfHealEditSession(){return this.editor==null}escalateEditSessionRender(){tj(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||_d(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||!t9(o,a.hunkData)){a?.element.remove();const l=document.createElement("div");l.style.display="contents",l.slot=o.slotName;const c=n(o,this);c!=null&&l.appendChild(c),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}-${aa(o)}`;let a=this.annotationCache.get(r);if(a==null||!e9(o,a.annotation)){a?.element.remove();const l=n(o);if(l==null)continue;a={element:nM(aa(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=sM();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:Df(s)&&s.hasAttribute("data-theme-css")?(this.themeCSSStyle??=s,this.hasAdoptedThemeCSS=!0):Df(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=iM;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??dr(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:c}=this.options;if(r!=null){const p=r(s)??void 0;this.headerCustom=this.upsertHeaderSlotElement(n,this.headerCustom,nj,p),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0;return}const d=a?.(s)??void 0,u=l?.(s)??void 0,h=c?.(s)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(n,this.headerPrefix,oM,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(n,this.headerFilenameSuffix,rM,u),this.headerMetadata=this.upsertHeaderSlotElement(n,this.headerMetadata,aM,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??=lM(),this.unsafeCSSStyle.parentNode!==n&&n.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=cM(t),this.appliedUnsafeCSS=t)}}applyThemeState(t,n,s,o){const r=t.shadowRoot??t.attachShadow({mode:"open"}),a=o??s,l=this.options.theme??Ai,c=typeof l=="string"?l:{...l},d=f0(r);if(this.themeCSSStyle?.parentNode===r&&this.appliedThemeCSS?.themeStyles===n&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=c;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===r){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:c,themeStyles:n,themeType:a,baseThemeType:o,scrollbarGutter:d};return}this.themeCSSStyle=dM({shadowRoot:r,currentNode:this.themeCSSStyle,themeCSS:mM(n,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:c,themeStyles:n,themeType:a,baseThemeType:o,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const t=this.fileContainer?.shadowRoot;t==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=uM(this.themeCSSStyle.textContent??"",f0(t)))}shouldGuardRebuildScroll(){return this.editor!=null&&hM()}applyHunksToDOM(t,n){this.shouldGuardRebuildScroll()?m0(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=No(n[0]),a=No(n[1]);return r==null||a==null?!1:(o.gutter.innerHTML=dr(r),o.content.innerHTML=dr(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=[],c=this.hunksRenderer.renderCodeAST("unified",n),d=this.hunksRenderer.renderCodeAST("deletions",n),u=this.hunksRenderer.renderCodeAST("additions",n);this.editor?.__captureFocusForDOMReplacement(),c!=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=ep({code:this.codeUnified,columnType:"unified",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeUnified,c,n.rowCount)||(this.codeUnified.innerHTML=this.hunksRenderer.renderPartialHTML(c)),l.push(this.codeUnified)):d!=null||u!=null?(d!=null?(a=this.codeDeletions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions=ep({code:this.codeDeletions,columnType:"deletions",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeDeletions,d,n.rowCount)||(this.codeDeletions.innerHTML=this.hunksRenderer.renderPartialHTML(d)),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=ep({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 c=this.getCodeColumns(l,o,a,r);if(c==null)return!1;const d=t.startingLine,u=n.startingLine,h=d+t.totalLines,p=u+n.totalLines,f=Math.max(d,u),g=Math.min(h,p);if(g<=f)return!1;const x=Math.max(0,f-d),v=Math.max(0,h-g),y=this.trimColumns({columns:c,trimStart:x,trimEnd:v,previousStart:d,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})},C=w(u,Math.max(f-u,0));if(C==null&&u<f)return!1;const _=w(g,Math.max(p-g,0));if(_==null&&p>g)return!1;const N=(S,k)=>{if(S!=null){if(l==="unified"&&!Array.isArray(c))this.insertPartialHTML(l,c,S,k);else if(l==="split"&&Array.isArray(c))this.insertPartialHTML(l,c,S,k);else throw new Error("FileDiff.applyPartialRender.applyChunk: invalid chunk application");b+=S.rowCount}};return this.cleanupErrorWrapper(),N(C,"afterbegin"),N(_,"beforeend"),this.lastRowCount!==b&&(this.applyRowSpan(l,c,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=No(a?.[0]),c=No(a?.[1]);for(const[d,u]of[[r.gutter,l],[r.content,c]])if(u!=null&&d.childElementCount===u.length)for(let h=0;h<u.length;h++){const p=d.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=No(s?.[0]),r=No(s?.[1]),a=()=>{for(const[l,c]of[[n.gutter,o],[n.content,r]])c!=null&&(l.innerHTML=dr(c));t.rowCount!==this.lastRowCount&&(this.applyRowSpan("unified",n,t.rowCount),this.lastRowCount=t.rowCount)};this.shouldGuardRebuildScroll()?m0(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=No(n[0]),r=No(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 c=s>=0;if(t==null)return 0;const d=Array.from(t.content.children),u=Array.from(t.gutter.children);if(d.length!==u.length)throw new Error("FileDiff.trimColumnRows: columns do not match");for(;a<d.length&&!(n<=0&&!c&&!l);){const h=u[a],p=d[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||c&&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||c&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in p.dataset){(n>0||c&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="metadata"&&"noNewline"in p.dataset){(n>0||c&&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(c){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 c=Math.max(0,o-r),d=s-r;if(d<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?c:0,f=h?d:-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:c=!1,overflow:d="scroll",diffStyle:u="split"}=this.options,h={type:"diff",diffIndicators:a,disableBackground:l,disableLineNumbers:c,overflow:d,split:u==="unified"?!1:n!=null&&s!=null,totalLines:o,customProperties:r};pM(h,this.appliedPreAttributes)||(fM(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 Dy(e,t){return e==null||t==null?e==null&&t==null:sj(e,t)}function o9({fileDiff:e,oldFile:t,newFile:n}){return e!=null&&e.hunks.length>0||t!=null||n!=null}function r9({fileDiff:e,oldFile:t,newFile:n}){return e!=null||t!=null||n!=null}function a9(e,t,n=!1){return!n&&e==null&&t}function l9(e,t,n=!1){return e==null&&t&&!n}function No(e){if(!(e==null||e.type!=="element"))return e.children??[]}function c9({fileDiff:e,metrics:t,disableFileHeader:n,hunkSeparators:s,expandUnchanged:o,expandedHunks:r,collapsedContextThreshold:a,canHydratePartialDiff:l}){let c=Gr(t,n),d=c;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=El({isPartial:e.isPartial,rangeSize:f.collapsedBefore,expandedHunks:u,hunkIndex:p,collapsedContextThreshold:a}),x=(g.fromStart+g.fromEnd)*t.lineHeight;if(c+=x,d+=x,g.collapsedLines>0){const b=Za({type:s,metrics:t,hunkIndex:p,hunkSpecs:f.hunkSpecs})?.totalHeight??0;c+=b,d+=b}c+=f.splitLineCount*t.lineHeight,d+=f.unifiedLineCount*t.lineHeight;const v=d9(f);c+=v.split*t.lineHeight,d+=v.unified*t.lineHeight;const y=p===h?Pl({fileDiff:e,hunkIndex:p,expandedHunks:u,collapsedContextThreshold:a,errorPrefix:"computeEstimatedDiffHeights"}):void 0;if(y!=null){const b=(y.fromStart+y.fromEnd)*t.lineHeight;if(c+=b,d+=b,y.collapsedLines>0){const w=cr({type:s,metrics:t})?.totalHeight??0;c+=w,d+=w}}else if(p===h&&e.isPartial&&l){const b=cr({type:s,metrics:t})?.totalHeight??0;c+=b,d+=b}}if(e.hunks.length>0){const p=ij(t);c+=p,d+=p}return{splitHeight:c,unifiedHeight:d}}function d9(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 u9(e,t)}function u9(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 Vm=3e3;let h9=-1;var iD=class extends sD{__id=`little-virtualized-file-diff:${++h9}`;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=tp(n)}setMetrics(e,t=!1){const n=tp(e);!t&&If(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||!gM(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=!Ku(t,e),s=n&&v9(t,e);super.setOptions(e),s&&this.resetLayoutCache({forceSimpleRecompute:!0,includeEstimatedHeights:b9(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&&Zk(this.renderRange)){const r=p9(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 c=l.dataset.lineIndex;if(c==null)continue;const d=y9(c,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(d)??0,g=u-p;g!==f&&(e=!0,this.cache.measuredHeightDeltaTotal+=g-f,g===0?this.cache.heightDeltas.delete(d):this.cache.heightDeltas.set(d,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=!Vr(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=tp(n.metrics),a=!0,l=!0);const{collapsed:c=!1,expandUnchanged:d=!1}=this.options;return this.currentCollapsed!==c&&(this.currentCollapsed=c,a=!0),this.currentExpandUnchanged!==d&&(this.currentExpandUnchanged=d,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(),c=this.getHunkSeparatorType(),d=l==="split"?n[1]:n[0];this.approximateLayoutCheckpoints();const u=Gr(this.metrics,s),h=this.getLayoutCheckpointBeforeLineIndex(d);let p=h?.top??u+this.cache.fileAnnotationHeight;if(r)return{top:u,height:0};let f;return Jr({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 C=l==="split"?w?.splitLineIndex??b?.splitLineIndex:w?.unifiedLineIndex??b?.unifiedLineIndex;if(C==null)throw new Error("VirtualizedFileDiff.getLinePosition: missing line index data");if(v>0){const N=Za({type:c,metrics:this.metrics,hunkIndex:g,hunkSpecs:x?.hunkSpecs});if(N!=null){if(p+=N.gapBefore,d>=C-v&&d<C)return f={top:p,height:N.height},!0;p+=N.height+N.gapAfter}}const _=this.getLineHeight(C,(w?.noEOFCR??!1)||(b?.noEOFCR??!1));if(C===d)return f={top:p,height:_},!0;if(p+=_,y>0){const N=cr({type:c,metrics:this.metrics});if(N!=null){if(d>C&&d<=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 c=l?.top??Gr(this.metrics,t)+this.cache.fileAnnotationHeight,d;return Jr({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=Za({type:a,metrics:this.metrics,hunkIndex:u,hunkSpecs:h?.hunkSpecs});b!=null&&(c+=b.totalHeight)}if(c>=e&&(g!=null?d={lineNumber:g.lineNumber,side:"deletions",top:c}:x!=null&&(d={lineNumber:x.lineNumber,side:"additions",top:c}),d!=null))return!0;const y=this.getLineHeight(v,(x?.noEOFCR??!1)||(g?.noEOFCR??!1));if(c+=y,f>0){const b=cr({type:a,metrics:this.metrics});b!=null&&(c+=b.totalHeight)}return!1}}),d}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=Rm("clone",e,t);if(await Hm(()=>this.primeHighlightCache(n)),!this.enabled||this.fileDiff!==e)return;this.pendingHydratedDiff={expectedDiff:e,nextDiff:n,files:t}}else{if(Rm("merge",e,t),this.setHydratedState(t),await Hm(()=>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}},c=a.expansionLineCountOverride??s;(a.direction==="up"||a.direction==="both")&&(l.fromStart+=c),(a.direction==="down"||a.direction==="both")&&(l.fromEnd+=c),r.set(a.hunkIndex,l)}return ej({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=Gr(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}=c9({fileDiff:e,metrics:this.metrics,disableFileHeader:t,hunkSeparators:this.getHunkSeparatorType(),expandUnchanged:n,expandedHunks:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:s,canHydratePartialDiff:Vp(e,this.options.loadDiffFiles!=null)});this.cache.estimatedSplitHeight=o,this.cache.estimatedUnifiedHeight=r}validateComputedHeight(e=this.fileDiff){if(this.fileContainer==null||e==null)return;const t=this.fileContainer.getBoundingClientRect();t.height!==this.height?console.log("VirtualizedFileDiff.computeApproximateSize: computed height doesnt match",{name:e.name,elementHeight:t.height,computedHeight:this.height}):console.log("VirtualizedFileDiff.computeApproximateSize: computed height IS CORRECT")}render({fileContainer:e,fileDiff:t,forceRender:n=!1,lineAnnotations:s,...o}={}){const r=Bm(o,"VirtualizedFileDiff.render"),a=r!=null,l=r?.oldFile,c=r?.newFile,d=a&&(!Py(l,this.deletionFile)||!Py(c,this.additionFile));let u=t??this.fileDiff;t==null&&a&&(d||this.fileDiff==null)&&(u=vo(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&&!Vr(this.fileDiff,u),v=g||d;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 _=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(_==null)throw new Error("VirtualizedFileDiff.render: simple virtualizer is not available");_.connect(e,this),this.isVisible=_.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=c),x&&(this.cachedHeaderHTML=void 0),this.renderPlaceholder(this.height);const y=this.virtualizer.getWindowSpecs(),b=this.top??0,w=this.computeRenderRangeFromWindow(u,b,y),C=super.render({fileDiff:u,fileContainer:e,renderRange:w,lineAnnotations:s,forceRender:(h??n)||f||x,...r,...o});return this.isSimpleMode()&&C&&this.getSimpleVirtualizer()?.requestHeightReconcile(this),C}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 w9(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=Vp(e,this.options.loadDiffFiles!=null),a=this.getDiffStyle(),l=this.getHunkSeparatorType(),c=n?!0:this.hunksRenderer.getExpandedHunksMap(),d=f9(this.cache.heightDeltas);let u=Gr(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 C=m9(b);for(;C<w;){const _=C-b,N=u+(_>0?x:0)+_*this.metrics.lineHeight+g9(y,_)*this.metrics.lineHeight+Iy(d,g,g+_);this.cache.checkpoints.push({renderedLineIndex:C,lineIndex:g+_,top:N}),C+=Vm}u+=x+f*this.metrics.lineHeight+y.length*this.metrics.lineHeight+Iy(d,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=El({isPartial:e.isPartial,rangeSize:g.collapsedBefore,expandedHunks:c,hunkIndex:f,collapsedContextThreshold:s}),v=x.collapsedLines>0?Za({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?Pl({fileDiff:e,hunkIndex:f,expandedHunks:c,collapsedContextThreshold:s,errorPrefix:"VirtualizedFileDiff"}):void 0,w=b!=null&&b.collapsedLines>0?cr({type:l,metrics:this.metrics})?.totalHeight??0:f===o&&r?cr({type:l,metrics:this.metrics})?.totalHeight??0:0,C=b!=null?b.fromStart+b.fromEnd:0,_=a==="split"?g.splitLineCount:g.unifiedLineCount,N=a==="split"?g.splitLineStart:g.unifiedLineStart;p({rowCount:_,startLineIndex:N,preSeparatorHeight:y,postSeparatorHeight:C===0?w:0,metadataOffsets:x9({diffStyle:a,hunk:g,rowCount:_})}),b!=null&&C>0&&p({rowCount:C,startLineIndex:N+_,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,c]of e.hunks.entries()){const d=t==="split"?c.splitLineCount:c.unifiedLineCount;n+=d;const u=Math.max(c.collapsedBefore,0),{fromStart:h,fromEnd:p,renderAll:f}=El({isPartial:e.isPartial,rangeSize:u,expandedHunks:r,hunkIndex:l,collapsedContextThreshold:o});u>0&&(n+=f?u:h+p)}const a=Pl({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:c}=this.metrics,d=this.getDiffStyle(),u=this.getHunkSeparatorType(),h=Vp(e,this.options.loadDiffFiles!=null),p=this.height;let f=this.getLayoutLineCount(e,d);const g=Gr(this.metrics,o),x=e.hunks.length>0?ij(this.metrics):0,{fileAnnotationHeight:v}=this.cache,y=g+v,b=Math.max(0,p-g-v-x),w=this.hasFileAnnotations(e),C=t+g,_=v>0&&w&&C<s&&C+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,d);const N=Math.ceil(Math.max(s-n,0)/c),S=Math.ceil(N/l)*l+l,k=S/l,A=k,I=[],D=(n+s)/2,P=this.getLayoutCheckpointBeforeTop(Math.max(0,n-t-S*c*2),l);let T=t+(P?.top??y),z=P?.renderedLineIndex??0,O,L,V;if(Jr({diff:e,diffStyle:d,startingLine:P?.renderedLineIndex??0,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:Me,hunk:ge,collapsedBefore:$,collapsedAfter:W,deletionLine:ue,additionLine:Z})=>{const J=Z!=null?Z.splitLineIndex:ue.splitLineIndex,ae=Z!=null?Z.unifiedLineIndex:ue.unifiedLineIndex,te=(Z?.noEOFCR??!1)||(ue?.noEOFCR??!1),pe=Me===e.hunks.length-1&&ge!=null&&(d==="split"?J===ge.splitLineStart+ge.splitLineCount-1:ae===ge.unifiedLineStart+ge.unifiedLineCount-1),Te=($>0?Za({type:u,metrics:this.metrics,hunkIndex:Me,hunkSpecs:ge?.hunkSpecs}):void 0)?.totalHeight??0;T+=Te;const $e=z%l===0,Ie=Math.floor(z/l);if($e&&(I[Ie]=T-(t+y+Te),V!=null)){if(V<=0)return!0;V--}const Ze=this.getLineHeight(d==="split"?J:ae,te);if(T>n-Ze&&T<s&&(O??=Ie),L==null&&T+Ze>D&&(L=Ie),V==null&&T>=s&&$e&&(V=A),z++,T+=Ze,W>0||pe&&h){const Nt=cr({type:u,metrics:this.metrics});Nt!=null&&(T<s&&T+Nt.totalHeight>n&&(O??=Ie),L==null&&T+Nt.totalHeight>D&&(L=Ie),T+=Nt.totalHeight)}return!1}}),O==null)if(_)O=0,L=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-g-x};L??=O;const X=Math.round(L-k/2),F=Math.max(0,Math.ceil(f/l)-k),ee=Math.max(0,Math.min(X,F)),H=ee*l,Q=X<0?S+X*l:S,q=I[ee]??0,ne=H===0?0:v+q,me=ee+Q/l,ke=me<I.length?b-I[me]:b-(T-t-y);return{startingLine:H,totalLines:Q,bufferBefore:ne,bufferAfter:Math.max(0,ke)}}};function p9(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===xM&&(t=Math.max(t??0,o.getBoundingClientRect().height))}return t}function f9(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 Iy({lineIndexes:e,prefixTotals:t},n,s){if(n>=s||e.length===0)return 0;const o=Ey(e,n);return(t[Ey(e,s)]??0)-(t[o]??0)}function Ey(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 m9(e){return Math.ceil(e/Vm)*Vm}function g9(e,t){let n=0;for(const s of e)s<t&&n++;return n}function x9({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 v9(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 b9(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 Vp(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function w9(e){return typeof e=="function"?"custom":e??"line-info"}function Py(e,t){return e==null||t==null?e==null&&t==null:sj(e,t)}function y9(e,t){const[n,s]=e.split(",").map(Number);return t==="split"?s:n}function oD(e,t){return e==null||t==null?e===t:e.header!==t.header||e.footer!==t.footer?!1:S9(e.items,t.items)}function S9(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 C9(e,t,n){const s=document.createElement("div");return s.style.display="flow-root",e==="header"?(s.setAttribute(vM,""),t.before(s)):(s.setAttribute(bM,""),t.after(s)),n?.observe(s),s}function _i(e){const t=window.devicePixelRatio??1;return Math.round(e*t)/t}const k9=["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"],j9=["theme","disableLineNumbers","overflow","themeType","disableFileHeader","disableVirtualizationBuffers","preferredHighlighter","useCSSClasses","useTokenTransformer","tokenizeMaxLineLength","tokenizeMaxLength","unsafeCSS","lineHoverHighlight","enableTokenInteractionsOnWhitespace","enableGutterUtility","__debugPointerEvents","enableLineSelection","controlledSelection","disableErrorHandling"],Ay=["renderCustomHeader","renderHeaderPrefix","renderHeaderFilenameSuffix","renderHeaderMetadata","renderAnnotation","renderGutterUtility","onPostRender","onGutterUtilityClick","onLineClick","onLineNumberClick","onLineEnter","onLineLeave","onTokenClick","onTokenEnter","onTokenLeave"],My=["onLineSelected","onLineSelectionStart","onLineSelectionChange","onLineSelectionEnd"],rD=Symbol("CodeView.itemOptionsState");function Ry(e,t){Object.defineProperty(e,rD,{configurable:!1,enumerable:!1,value:t})}function La(e){return e[rD]}function Yi(e,t,n){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get(){return n(this)}})}const _9=120,Ly=1,Oy="--diffs-overflow-override",cv=12e6,aD=1e6,lD=2e6,N9=cv-lD,zy=cv-aD;function T9(e){if(e==null)throw new Error("CodeView: createEditor is required for items with edit: true")}const D9=(()=>{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 I9=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=Aa;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:Ai},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??wM}getItemTopOffset(){return this.getLayout().paddingTop+this.header.height}computeMetricsCache(t){return this.itemMetricsCache={hunkLineCount:t?.hunkLineCount??Aa.hunkLineCount,lineHeight:t?.lineHeight??Aa.lineHeight,diffHeaderHeight:t?.diffHeaderHeight??Aa.diffHeaderHeight,hunkSeparatorHeight:t?.hunkSeparatorHeight,spacing:t?.spacing??Aa.spacing,paddingTop:t?.paddingTop,paddingBottom:t?.paddingBottom},this.itemMetricsCache}getSmoothScrollSettings(){return this.options.smoothScrollSettings??yM}shouldDisablePointerEvents(){return this.options.pointerEventsOnScroll!==!0}shouldValidateItemHeights(){return SM&&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)<Ly||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),D9&&!this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Oy,"hidden"),this.codeOverflowFix=!0),this.scrollInteractionFixTimer=setTimeout(this.restoreScrollInteractions,_9)}restoreScrollInteractions=()=>{this.clearScrollInteractionTimer(),this.pointerEventsDisabled&&(this.stickyContainer.style.removeProperty("pointer-events"),this.pointerEventsDisabled=!1),this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Oy,"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??C9(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(){Tf(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(oj),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))R9(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 l7()?"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 c=this.createItem(l,this.items.length,o);this.items.push(c),this.idToItem.set(c.item.id,c),this.instanceToItem.set(c.instance,c),c.height=E9(c),o+=c.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;P9(n,t)&&this.invalidateElementPool(),this.options=t;const r=this.computeMetricsCache(t.itemMetrics),a=!If(o,r),l=!If(s,this.getLayout());l&&this.syncLayout();const c=a||A9(n,t);if(c){const u=this.pendingLayoutReset;this.pendingLayoutReset={metrics:a?r:u?.metrics,resetFileLayoutCache:!0,resetDiffLayoutCache:!0,includeEstimatedDiffHeights:u?.includeEstimatedDiffHeights===!0||a||M9(n,t)}}(l||c)&&(this.markLayoutDirtyFromIndex(0),this.scrollDirty=!0),Ku(n,t)||this.renderOptionsRevision++,this.syncItemEditors();const d=n.renderCodeViewHeader!==t.renderCodeViewHeader||n.renderCodeViewFooter!==t.renderCodeViewFooter;!this.isContainerManaged&&(this.items.length>0||d)&&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?(Tf(this.computeRenderRangeAndEmit),this.computeRenderRangeAndEmit()):tj(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=O9(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 iD(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 CM(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&&kM(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){T9(s);const a={id:n},l=s({onChange:(c,d)=>{const u=this.idToItem.get(a.id);u!=null&&(a.lastChange={item:u.item,file:c,lineAnnotations:d},this.options.onItemEditChange?.(u.item,c,d))}});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,c=a==null?r?.item??l?.item:l?.item??a.item;c?.type==="diff"&&(a==null&&r!=null&&r.type==="diff"&&r.instance.completeEditSession()&&(this.markItemLayoutDirty(r),this.render()),Gm(c.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 j9)Yi(t,n,()=>this.options[n]);Yi(t,"stickyHeader",()=>this.options.stickyHeaders),Yi(t,"collapsed",n=>{const s=La(n);if(s!=null)return this.getItemOptions(s,"file")?.item.collapsed});for(const n of Ay)this.defineItemSharedCallback(t,"file",n);for(const n of My)this.defineItemSelectionCallback(t,"file",n);return t}createDiffOptionsPrototype(){const t={};for(const n of k9)Yi(t,n,()=>this.options[n]);Yi(t,"stickyHeader",()=>this.options.stickyHeaders),Yi(t,"hunkSeparators",()=>this.options.hunkSeparators),Yi(t,"collapsed",n=>{const s=La(n);if(s!=null)return this.getItemOptions(s,"diff")?.item.collapsed});for(const n of Ay)this.defineItemSharedCallback(t,"diff",n);for(const n of My)this.defineItemSelectionCallback(t,"diff",n);return t}createFileOptions(t){const n=Object.create(this.fileOptionsPrototype);return Ry(n,{id:t}),n}createDiffOptions(t){const n=Object.create(this.diffOptionsPrototype);return Ry(n,{id:t}),n}updateItemOptionsId(t,n){const s=La(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=La(o);if(r==null)return;const a=r.callbackCache??={};let l=a[s];return l==null&&(l=((...c)=>{const d=this.getItemOptions(r,n);if(d==null)return;const u=this.options[s];return u?.(...c,d)}),a[s]=l),l})}defineItemSelectionCallback(t,n,s){Yi(t,s,o=>{const r=La(o);if(r==null)return;const a=r.callbackCache??={};let l=a[s];return l==null&&(l=(c=>{const d=this.getItemOptions(r,n);if(d==null)return;const u=c==null?null:{id:d.item.id,range:c};this.options.controlledSelection!==!0&&(c!=null||this.selectedLines?.id===d.item.id)&&this.applySelectedLines(u,{notify:!1}),this.options.onSelectedLinesChange?.(u);const h=this.options[s];return h?.(c,d)}),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,c=new Map;let d;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)&&(d=Math.min(d??u,u))):d=Math.min(d??u,u),n[u]!==f&&(d=Math.min(d??u,u)),r.push(f),a.set(h.id,f),l.set(f.instance,f)}if(d==null){if(o.size===0)return;d=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;c.set(h.item.id,h),this.releaseRenderedItem(h);const p=Math.max(r.length-1,0);d=Math.min(d??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(d),this.scrollDirty=!0,this.render(),c.size>0?c: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()>zy}getPagedScrollHeight(){return this.shouldRebaseScroll()?Math.min(this.getScrollHeight(),cv):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>zy&&n<r,l=s<aD&&n>0;return s<0||s>o||a||l?this.resolveScrollPageWindow(t,l?Math.min(N9,o):lD):{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 ${Gy(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),c=a+this.getHeight();if(!(o-s<=l&&r+s>=c)){if(o-s<l)return{...t,align:"start"};if(r+s>c)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 ${Gy(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,c=r.top,d=c+r.height,u=Math.min(a,c);return{top:u,height:Math.max(l,d)-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,c=t.velocity+r*l;return{position:n+(l+c*o)*a,velocity:(c*(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:c}=this.getSmoothScrollSettings();return Math.abs(s-r)<=l&&Math.abs(a)<=c?(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),c=!r&&(this.renderState.scrollTop===-1||Math.abs(l-this.renderState.scrollTop)>n+this.config.overscrollSize*2);c&&(a=void 0),this.windowSpecs=jM({scrollTop:l-this.header.height,height:n,scrollHeight:this.getScrollHeight(),fitPerfectly:c,fitPerfectlyOverscroll:this.getFitPerfectlyOverscroll(),overscrollSize:this.config.overscrollSize});let d=s;(this.pendingScrollTarget!=null&&l!==d||this.needsScrollPageUpdate(l))&&(this.applyScrollFix(l,d,this.windowSpecs),d=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(),By(this.stickyContainer,k.element,x),A.virtualizedSetup(),Hy(k,k.element)&&(k.renderedOptionsRevision=this.renderOptionsRevision,v.add(k)),x=k.element):(By(this.stickyContainer,k.element,x),Hy(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 C=w!=null?w-o:0;let _=l,N=!1;if(this.pendingScrollTarget!=null){const S=this.advanceScrollAnimation(t,C);S!=null?(_=S,N=!0):_=o}else _=w??l;_!==d&&(this.applyScrollFix(_,d,this.windowSpecs),d=_),N&&this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),this.renderState.scrollTop=_i(d),this.updateStickyPositioning(),this.validateStickyContainerHeight(),this.fixContainerFocus(),(c||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)>=Ly){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 c=l-r;this.applyScrollFix(l,r,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 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 c=l!=null?this.resolveAnchoredScrollTop(l):void 0;if(c!=null){const d=c-a;this.applyScrollFix(c,a,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 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:c}=this.renderState;if(r===-1||a===-1)return;const d=this.getHeight();if(!(l===-1||c===-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+d)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:c,scrollPageOffset:d}=this.resolvePagedScrollPosition(o),u=c,h=a!==d;o===this.renderState.scrollTop&&o===r&&u===l&&!h||(this.suspendScrollInteractions(),(u!==l||h)&&(this.scrollPageOffset=d,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);oD(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 E9(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 P9(e,t){return!Qk(e.theme??Ai,t.theme??Ai)||(e.themeType??"system")!==(t.themeType??"system")||e.unsafeCSS!==t.unsafeCSS}function A9(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 M9(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 R9(e){return e instanceof SVGElement?!0:Df(e)&&(e.hasAttribute("data-core-css")||e.hasAttribute("data-theme-css")||e.hasAttribute("data-unsafe-css"))}function Gy(e){const t=Fy(e.start,e.side),n=Fy(e.end,e.endSide??e.side);return t===n?t:`${t}-${n}`}function Fy(e,t){return t==null?`${e}`:`${t==="deletions"?"D":"A"}${e}`}function Hy(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 By(e,t,n){if(n==null){e.firstChild!==t&&e.prepend(t);return}n.nextSibling!==t&&n.after(t)}function L9(e){return(e.annotations?.length??0)>0}function O9(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)L9(r.item)&&o.push(r);return o.length>0?o:void 0}function z9({hunkIndex:e,lineIndex:t,conflictIndex:n}){return`merge-conflict-action-${e}-${t}-${n}`}function G9(e,t){const n=t.hunks[e.hunkIndex];if(n!=null)return{hunkIndex:e.hunkIndex,lineIndex:F9(n,e.startContentIndex)}}function F9(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 cD({fileDiff:e,actions:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderMergeConflictUtility:c,lineAnnotations:d,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:nj,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&&d?.map((v,y)=>i.jsx("div",{slot:aa(v),children:a(v)},y)),t!=null&&c!=null&&h!=null&&t.map(v=>{if(v==null)return;const y=H9(v,e);return i.jsx("div",{slot:y,style:_M,children:c(v,h)},y)}),l!=null&&i.jsx("div",{slot:"gutter-utility-slot",style:NM,children:l(u)})]})}function H9(e,t){const n=G9(e,t);return n!=null?z9({hunkIndex:n.hunkIndex,lineIndex:n.lineIndex,conflictIndex:e.conflictIndex}):void 0}const Vy=typeof window>"u"?m.useEffect:m.useLayoutEffect;function $y(e){return{instance:void 0,items:void 0,controlled:e,managedOptions:void 0,disableFlushSync:!1,slotCoordinator:void 0}}function B9(e,t){const{className:n,containerRef:s,disableWorkerPool:o=!1,editorOptions:r,initialItems:a,items:l,onItemEditChange:c,onItemEditComplete:d,onScroll:u,onSelectedLinesChange:h,options:p,renderAnnotation:f,renderCodeViewFooter:g,renderCodeViewHeader:x,renderCustomHeader:v,renderGutterUtility:y,renderHeaderFilenameSuffix:b,renderHeaderMetadata:w,renderHeaderPrefix:C,selectedLines:_,style:N}=e,S=l!==void 0,k=rj(),A=m.useContext(aj),I=m.useRef($y(S)),D=v!=null,P=f!=null,T=y!=null,z=D||C!=null||b!=null||w!=null,O=z||P||T,L=x!=null,V=g!=null,X=so($=>{h?.($)}),F=_!==void 0,ee=so($=>{if(k==null)throw new Error("CodeView: EditContext is not attached");const W=k({...r,...$});if(W==null)throw new Error("CodeView: EditProvider.createEditor must return an editor instance");return W}),H=so(($,W,ue)=>{c?.($,W,ue)}),Q=so(($,W,ue)=>{d?.($,W,ue)}),q=m.useMemo(()=>U9({options:p,hasCustomHeader:D,hasGutterRenderer:T,hasCodeViewHeader:L,hasCodeViewFooter:V,onSelectedLinesChange:h!=null?X:void 0,controlledSelection:F,createEditor:k!=null?ee:void 0,onItemEditChange:c!=null?H:void 0,onItemEditComplete:d!=null?Q:void 0}),[k,F,ee,H,Q,X,V,L,D,T,c,d,h,p]),[ne]=m.useState(()=>W9()),[,me]=m.useState({}),ke=so($=>{I.current.instance!=null&&($==null||$!==I.current.instance.getContainerElement())&&(I.current.instance.cleanUp(),ne.publish(void 0),I.current=$y(S)),$!=null&&$!==I.current.instance?.getContainerElement()&&(I.current.instance=new I9(q,o?void 0:A,!0),I.current.instance.setup($)),typeof s=="function"?s($):s!=null&&(s.current=$)}),Me=so($=>{I.current.disableFlushSync?ne.publish($):Us.flushSync(()=>{ne.publish($)})}),ge=m.useMemo(()=>{if(!(!z&&!P&&!T&&!L&&!V))return{hasHeaderRenderers:z,hasAnnotationRenderer:P,hasGutterRenderer:T,onSnapshotChange:Me}},[Me,P,T,z,L,V]);return Vy(()=>u!=null?I.current.instance?.subscribeToScroll(u):void 0),Vy(()=>{const{instance:$,controlled:W,items:ue,managedOptions:Z,slotCoordinator:J}=I.current;if($!=null)try{I.current.disableFlushSync=!0;let ae=!1;if(Ku(q,Z)||(I.current.managedOptions=q,$.setOptions(q),ae=!0),W!==S){console.error("CodeView: cannot switch between controlled and uncontrolled modes. Remount with a new key instead.");return}if(S)l!==ue&&($9(ue,l)?I.current.items=l:V9(ue,l)?(I.current.items=l,$.addItems(l.slice(ue.length))):(I.current.items=l,$.setItems(l),ae=!0));else if(ue==null){const Te=a??[];I.current.items=Te,Te.length>0&&($.setItems(Te),ae=!0)}_!==void 0&&$.setSelectedLines(_,{notify:!1});const te=$.setSlotCoordinator(ge);let pe=!1;ge!==J&&((ge==null||J==null)&&(pe=!0),I.current.slotCoordinator=ge),(ae||te)&&$.render(!0),te&&ge==null&&ne.publish(void 0),pe&&me({})}finally{I.current.disableFlushSync=!1}}),m.useImperativeHandle(t,()=>({addItems($){const{controlled:W,instance:ue}=I.current;Jc(W,"addItems"),ue==null?console.error("CodeView.addItems: no valid instance to append items with",$):ue.addItems($)},getItem($){const{instance:W}=I.current;if(W==null){console.error("CodeView.getItem: no valid instance exists",$);return}else return W.getItem($)},removeItem($){const{controlled:W,instance:ue}=I.current;return Jc(W,"removeItem"),ue==null?(console.error("CodeView.removeItem: no valid instance to remove item from",$),!1):ue.removeItem($)},updateItem($){const{controlled:W,instance:ue}=I.current;return Jc(W,"updateItem"),ue==null?(console.error("CodeView.updateItem: no valid instance to update item with",$),!1):ue.updateItem($)},updateItemId($,W){const{controlled:ue,instance:Z}=I.current;return Jc(ue,"updateItemId"),Z==null?(console.error("CodeView.updateItemId: no valid instance to update item id with",$,W),!1):Z.updateItemId($,W)},scrollTo($){const{instance:W}=I.current;W==null?console.error("CodeView.scrollTo: no valid instance to scroll with",$):W.scrollTo($)},setSelectedLines($){const{instance:W}=I.current;W==null?console.error("CodeView.setSelectedLines: no valid instance to update selection with",$):(W.setSelectedLines($,{notify:!1}),X($))},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}),X(null))},getEditor($){const{instance:W}=I.current;if(W==null){console.error("CodeView.getEditor: no valid instance exists",$);return}return W.getEditor($)},getInstance(){return I.current.instance}}),[X]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:ke,className:n,style:N}),(O||L||V)&&i.jsx(K9,{managedContentStore:ne,renderCustomHeader:v,renderHeaderPrefix:C,renderHeaderFilenameSuffix:b,renderHeaderMetadata:w,renderAnnotation:f,renderGutterUtility:y,renderCodeViewHeader:x,renderCodeViewFooter:g})]})}const dD=m.forwardRef(B9);function V9(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 $9(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 Jc(e,t){if(e)throw new Error(`CodeView.${t} cannot be used when CodeView is controlled. Use initialItems for imperative item updates.`)}function W9(){let e;const t=new Set;return{getSnapshot(){return e},publish(n){if(!oD(e,n)){e=n;for(const s of t)s()}},subscribe(n){return t.add(n),()=>{t.delete(n)}}}}function U9({options:e,hasCustomHeader:t,hasGutterRenderer:n,hasCodeViewHeader:s,hasCodeViewFooter:o,onSelectedLinesChange:r,controlledSelection:a,createEditor:l,onItemEditChange:c,onItemEditComplete:d}){const u={...e,controlledSelection:a,onSelectedLinesChange:r,createEditor:l};return c!=null&&(u.onItemEditChange=c),d!=null&&(u.onItemEditComplete=d),t&&(u.renderCustomHeader=Zc),n&&(u.renderGutterUtility=Zc),s&&(u.renderCodeViewHeader=Zc),o&&(u.renderCodeViewFooter=Zc),u}const K9=m.memo(function({managedContentStore:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderCodeViewHeader:c,renderCodeViewFooter:d}){"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=>Us.createPortal(q9({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(()=>c!=null&&p?.header!=null?Us.createPortal(c(),p.header):null,[c,p?.header]),m.useMemo(()=>d!=null&&p?.footer!=null?Us.createPortal(d(),p.footer):null,[d,p?.footer])]})});function q9({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderFilenameSuffix:s,renderHeaderMetadata:o,renderAnnotation:r,renderGutterUtility:a}){if(e.type==="diff"){const{item:l,instance:c}=e;return cD({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?d=>r(d,l):void 0,lineAnnotations:l.annotations,renderGutterUtility:a!=null?d=>a(d,l):void 0,getHoveredLine:c.getHoveredLine})}else{const{item:l,instance:c}=e;return TM({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?d=>r(d,l):void 0,lineAnnotations:l.annotations,renderGutterUtility:a!=null?d=>a(d,l):void 0,getHoveredLine:c.getHoveredLine})}}function Zc(){}const Wy=typeof window>"u"?m.useEffect:m.useLayoutEffect;function Y9({fileDiff:e,options:t,editorOptions:n,lineAnnotations:s,selectedLines:o,prerenderedHTML:r,metrics:a,hasGutterRenderUtility:l,hasCustomHeader:c,disableWorkerPool:d,edit:u}){const h=DM(),p=o!==void 0,f=m.useContext(aj),g=rj(),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 iD($p({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),h,a,d?void 0:f,!0):x.current=new sD($p({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),d?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 Wy(()=>{const{current:y}=x;if(y==null)return;const b=$p({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),w=b!==void 0&&!Ku(y.options,b);y.setOptions(b),y.render({forceRender:w,fileDiff:e,lineAnnotations:s}),o!==void 0&&y.setSelectedLines(o)}),Wy(()=>{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 $p({options:e,controlledSelection:t,hasCustomHeader:n,hasGutterRenderUtility:s}){return t||s||n?{...e,controlledSelection:t,renderCustomHeader:n?g0:e?.renderCustomHeader,renderGutterUtility:s?g0:e?.renderGutterUtility}:e}function X9({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:o,selectedLines:r,className:a,style:l,prerenderedHTML:c,renderAnnotation:d,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderGutterUtility:g,disableWorkerPool:x=!1,edit:v=!1}){const{ref:y,getHoveredLine:b}=Y9({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:o,selectedLines:r,prerenderedHTML:c,hasGutterRenderUtility:g!=null,hasCustomHeader:u!=null,disableWorkerPool:x,edit:v});return i.jsx(oj,{ref:y,className:a,style:l,children:IM(cD({fileDiff:e,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderAnnotation:d,renderGutterUtility:g,lineAnnotations:o,getHoveredLine:b}),c)})}function J9(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 Z9(e,t){const n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(s=>e[s]===t[s])}function uD(e,t){let n=e;for(let s=t.length-1;s>=0;s--){const{oldText:o,newText:r}=t[s];if(r===""&&n!=="")return null;const a=n.indexOf(r);if(a===-1)return null;n=n.slice(0,a)+o+n.slice(a+r.length)}return n}function Q9(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],c=a.flatMap(b=>b.edits??[]),d=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:d[0]?.oldText??null;const y=typeof l=="string"?l:f;v==null&&(c.length>0&&typeof l=="string"?v=uD(l,c):u!=null&&c.length===0&&(v="")),y==null&&p?.fileChange?.truncated===!0&&s.add(r),!(v==null||y==null)&&(v===y&&d.length===0||(o[r]=v,n.push({path:r,oldText:v,newText:y})))}return{files:n,snapshots:o,...s.size>0?{incompletePaths:[...s]}:{}}}const dv=m.createContext(null),eK={theme:wa,diffStyle:"split",lineDiffType:"word",disableFileHeader:!0,preferredHighlighter:"shiki-js",overflow:"wrap"};function Uy({path:e,blocks:t,snapshot:n}){const{t:s}=se(),o=e.split("/").pop()||"file",[r,a]=m.useState({kind:"loading"}),l=m.useContext(dv),c=m.useContext(qu),d=l??c,u=d?.conversationId,h=d?.projectId,p=d?Pg(e,d.cwd):null,f=d&&p===null&&lj(e)?e:null;return m.useEffect(()=>{let g=!0;if(n)return a({kind:"loading"}),la().then(()=>{g&&a({kind:"full",oldText:n.oldText,newText:n.newText})}).catch(()=>{g&&a({kind:"blocks"})}),()=>{g=!1};const x=u&&h&&p?window.electronAPI.files.read({conversationId:u,projectId:h,rel:p}):u&&h&&f?window.electronAPI.files.read({conversationId:u,projectId:h,path:f}):Promise.resolve(null);return Promise.all([la(),x]).then(([,v])=>{if(!g)return;const y=typeof v=="string"?uD(v,t):null;a(y!=null&&typeof v=="string"?{kind:"full",oldText:y,newText:v}:{kind:"blocks"})}).catch(()=>{g&&a({kind:"blocks"})}),()=>{g=!1}},[t,u,f,h,p,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(Ky,{name:o,oldText:r.oldText,newText:r.newText}):t.map((g,x)=>i.jsx(Ky,{name:o,oldText:g.oldText,newText:g.newText},x))})}function Ky({name:e,oldText:t,newText:n}){const s=rc(eK),o=m.useMemo(()=>{const r=vo({name:e,contents:t},{name:e,contents:n});return r.cacheKey=rv(e,t,n),r},[e,t,n]);return i.jsx(X9,{fileDiff:o,options:s})}function $m({hits:e,defaultOpen:t=!1}){const{t:n}=se();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(nK,{hit:s,defaultOpen:t},s.id))})}function tK({view:e}){const{t}=se(),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($m,{hits:[e.memory],defaultOpen:!0}):i.jsx($m,{hits:e.candidates})]})}function nK({hit:e,defaultOpen:t}){const{t:n}=se(),[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:U("min-w-0 flex-1 font-medium text-foreground text-xs",s?"break-words":"truncate"),children:e.title}),e.unitType&&i.jsx(ca,{variant:"secondary",size:"sm",children:e.unitType}),e.space&&i.jsx(ca,{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:U("mt-0.5 whitespace-pre-wrap break-words text-muted-foreground text-xs leading-relaxed",s?"block":"line-clamp-2"),children:e.content})]})})}const sK={"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 uv(e){return U("inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",sK[e])}function iK({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 oK({recipient:e,onRemove:t}){const{t:n}=se();return i.jsxs("span",{className:U(uv("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(iK,{label:n("Remove Agent recipient"),onRemove:t}),i.jsx("span",{className:"sr-only",children:e.typeKey})]})}const hv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function hD(e){if(!e)return null;try{const t=JSON.parse(e);return hv(t)?t:null}catch{return null}}function Wm(e,t){if(!Array.isArray(e))return null;const n=[];for(const s of e){if(!hv(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 rK(e){const t=hD(e);return t?Wm(t.results,"relevance"):null}function aK(e,t){const n=hD(e);if(n?.status==="candidates_found"){const o=Wm(n.candidates,"similarity");return o?{written:!1,candidates:o}:null}if(n?.status!=="inserted"||!hv(n.memory)||!t)return null;const s=Wm([{...n.memory,content:t}],"relevance")?.[0];return s?{written:!0,deduplicated:n.deduplicated===!0,memory:s}:null}const pD=m.createContext(void 0);function Nc(e){const t=m.useContext(pD);if(t===void 0&&!e)throw new Error(ac(50));return t}const lK=600,fD=300,cK={...PM,instantType:e=>e.instantType,adaptiveOrigin:e=>e.adaptiveOrigin,closeDelay:e=>e.closeDelay};class dK extends EM{constructor(t,n,s){const o=new LM;super(uK(t,o,n,s),hK(o),cK)}setOpen=(t,n)=>{const{inlineRectCoordsRef:s}=this.context;AM(this,t,n,{onBeforeDispatch(){const o=n.event;t&&n.reason===OM&&n.trigger&&"clientX"in o&&"clientY"in o&&s.current?.element!==n.trigger&&nT(s,n.trigger,o.clientX,o.clientY)}})}}function uK(e,t,n,s=!1){const o={...MM(),instantType:void 0,adaptiveOrigin:void 0,closeDelay:fD,...e};return o.floatingRootContext=RM(t,n,s),o}function hK(e){return{popupRef:m.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e,inlineRectCoordsRef:{current:void 0}}}function qy(e){const{open:t,defaultOpen:n=!1,onOpenChange:s,onOpenChangeComplete:o,actionsRef:r,handle:a,triggerId:l,defaultTriggerId:c=null,children:d}=e,u=FM((y,b)=>new dK({open:n,openProp:t,activeTriggerId:c,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");HM(u,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:x}=BM(h,u,()=>{u.context.inlineRectCoordsRef.current=void 0});Ag(()=>{h&&p==null&&u.set("payload",void 0)},[u,p,h]),m.useImperativeHandle(r,()=>({unmount:x,close:()=>u.setOpen(!1,VM($M))}),[x,u]);const v=h||f;return i.jsxs(pD.Provider,{value:u,children:[a&&i.jsx(WM,{handle:a,store:u}),v&&i.jsx(pK,{store:u}),typeof d=="function"?d({payload:g}):d]})}function pK({store:e}){const t=e.useState("floatingRootContext"),n=UM(t);return KM(e,{activeTriggerProps:n.reference,inactiveTriggerProps:n.trigger,popupProps:n.floating}),null}const fK=zM(function(t){return Nc(!0)?i.jsx(qy,{...t}):i.jsx(GM,{children:i.jsx(qy,{...t})})}),mD=m.createContext(void 0);function mK(){const e=m.useContext(mD);if(e===void 0)throw new Error(ac(48));return e}const gK=m.forwardRef(function(t,n){const{keepMounted:s=!1,...o}=t;return Nc().useState("mounted")||s?i.jsx(mD.Provider,{value:s,children:i.jsx(qM,{ref:n,...o})}):null}),xK=YM(function(t,n){const{render:s,className:o,delay:r,closeDelay:a,id:l,payload:c,handle:d,style:u,...h}=t,p=Nc(!0),g=XM(d)??p;if(!g)throw new Error(ac(89));const x=cj(l),v=g.useState("isTriggerActive",x),y=g.useState("isOpenedByTrigger",x),b=g.useState("floatingRootContext"),w=g.context.inlineRectCoordsRef,C=m.useRef(null),_=r??lK,N=a??fD,{registerTrigger:S,isMountedByThisTrigger:k}=JM(x,C,g,{payload:c,closeDelay:N}),A=ZM(b,{mouseOnly:!0,move:!1,handleClose:QM(),delay:()=>({open:_,close:N}),triggerElementRef:C,isActiveTrigger:v,isClosing:()=>g.select("transitionStatus")==="ending"}),I=eR(b,{delay:_}),D={open:y},P=g.useState("triggerProps",k),T=eW(w,y);return lc("a",t,{state:D,ref:[n,S,C],props:[A,I.reference,P,T,{id:x},h],stateAttributesMapping:tR})}),gD=m.createContext(void 0);function vK(){const e=m.useContext(gD);if(e===void 0)throw new Error(ac(49));return e}const bK=m.forwardRef(function(t,n){const{render:s,className:o,anchor:r,positionMethod:a="absolute",side:l="bottom",align:c="center",sideOffset:d=0,alignOffset:u=0,collisionBoundary:h="clipping-ancestors",collisionPadding:p=5,arrowPadding:f=5,sticky:g=!1,disableAnchorTracking:x=!1,collisionAvoidance:v=nR,style:y,...b}=t,w=Nc(),C=mK(),_=sR(),N=w.useState("open"),S=w.useState("mounted"),k=w.useState("floatingRootContext"),A=w.useState("instantType"),I=w.useState("transitionStatus"),D=w.useState("adaptiveOrigin"),P=w.context.inlineRectCoordsRef,T=iR({anchor:r,floatingRootContext:k,positionMethod:a,mounted:S,side:l,sideOffset:d,align:c,alignOffset:u,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:g,disableAnchorTracking:x,keepMounted:C,nodeId:_,collisionAvoidance:v,adaptiveOrigin:D,inline:tW(P)}),z=T.update;Ag(()=>{N&&S&&z()},[N,S,z]);const O={open:N,side:T.side,align:T.align,anchorHidden:T.anchorHidden,instant:A},L=oR(t,O,{styles:T.positionerStyles,transitionStatus:I,props:b,refs:[n,w.useStateSetter("positionerElement")],hidden:!S,inert:!N});return i.jsx(gD.Provider,{value:T,children:i.jsx(rR,{id:_,children:L})})}),wK=m.forwardRef(function(t,n){const{className:s,render:o,style:r,...a}=t,l=Nc(),{side:c,align:d}=vK(),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 aR({open:u,ref:l.context.popupRef,onComplete(){u&&l.context.onOpenChangeComplete?.(!0)}}),lR(g,{closeDelay:x}),lc("div",t,{state:{open:u,side:c,align:d,instant:h,transitionStatus:p},ref:[n,l.context.popupRef,l.useStateSetter("popupElement")],props:[cR,f,uR(p),a],stateAttributesMapping:dR})}),pv=fK;function fv({...e}){return i.jsx(xK,{"data-slot":"preview-card-trigger",...e})}function xD({className:e,children:t,align:n="center",sideOffset:s=4,...o}){return i.jsx(gK,{children:i.jsx(bK,{align:n,className:"z-50","data-slot":"preview-card-positioner",sideOffset:s,children:i.jsx(wK,{className:U("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 Yy={mask:"text-sky-600 dark:text-sky-400",warn:"text-amber-600 dark:text-amber-400",block:"text-red-600 dark:text-red-400"},yK={mask:Yu,warn:oa,block:dj},SK={mask:"Mask",warn:"Warn only",block:"Block"},CK={system:"System prompt",user:"Your message",tool_result:"Tool output",tool_args:"Tool arguments",assistant:"Earlier replies",tools:"Tool descriptions"};function kK({report:e}){const{t}=se(),n=hR(e);if(!n)return null;const s=yK[n],o=new Set(e.hits.map(r=>r.token)).size;return i.jsxs(pv,{children:[i.jsxs(fv,{render:i.jsx("span",{className:U("inline-flex shrink-0 items-center gap-0.5 text-[11px]",Yy[n]),"data-privacy-mask":n}),children:[i.jsx(s,{className:"size-3.5"}),i.jsx("span",{className:"tabular-nums",children:o})]}),i.jsxs(xD,{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:pR(e.hits).map(r=>i.jsxs("li",{className:"flex flex-wrap gap-x-2",children:[i.jsx("span",{className:Yy[r.action],children:t(SK[r.action])}),i.jsx("span",{children:r.kind}),i.jsx("span",{className:"text-muted-foreground",children:t(CK[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 jK=/^\[.+#[0-9A-Fa-f]{4}\]$/;function _K(e){const t=e.indexOf(`
|
|
58
|
-
`),n=t===-1?e:e.slice(0,t);return jK.test(n)?t===-1?"":e.slice(t+1).split(`
|
|
59
|
-
`).map(s=>s.replace(/^\d+:/,"")).join(`
|
|
60
|
-
`):e}const NK={theme:wa,disableFileHeader:!0,overflow:"wrap",preferredHighlighter:"shiki-js"};function Vd({path:e,contents:t}){const{t:n}=se(),[s,o]=m.useState(!1),r=rc(NK);m.useEffect(()=>{let l=!0;return la().then(()=>{l&&o(!0)}),()=>{l=!1}},[]);const a=m.useMemo(()=>({name:e.split("/").pop()||"file",contents:_K(t)}),[e,t]);return s?i.jsx(uj,{file:a,disableWorkerPool:!0,options:r}):i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("Loading...")})}function TK(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 DK={compressed:"Compressed",unchanged:"Unchanged",pending:"Background task started",bypassed:"Bypassed",unavailable:"Unavailable"};function IK({value:e}){const t=D4(e),{t:n}=se();if(!t)return null;const s=TK(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(DK[t.status])}),s&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:n("~{{count}} tokens saved",{count:Zn(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:Zn(t.inputTokens)})}),i.jsx("dt",{children:n("Output estimate")}),i.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:Zn(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 EK(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 PK(e,t,n=I4){const s=t-e;return s>=n?s:null}const AK={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"},MK={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."},vD=600;function RK(e){return e?.kind==="deadline"?["background","timeout"]:[]}function LK(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:vD,command:s})}function OK(e,t,n){return t(e)?(n(),!0):!1}let vl=null,bl=null,wl=null,yl=null,Sl=null,Cl=null;function zK(e){return vl=e,()=>{vl===e&&(vl=null)}}function GK(e){return wl=e,()=>{wl===e&&(wl=null)}}function FK(e){return bl=e,()=>{bl===e&&(bl=null)}}function Co(){return wl?(wl(),!0):!1}function HK(e){return Cl=e,()=>{Cl===e&&(Cl=null)}}function BK(e){return Cl?Cl(e):!1}function Zl(e){return vl?(vl(e),!0):!1}function Eh(e){return bl?(bl(e),!0):!1}function VK(e){return yl=e,()=>{yl===e&&(yl=null)}}function mv(e,t){return yl?(yl(e,t),!0):!1}function $K(e){return Sl=e,()=>{Sl===e&&(Sl=null)}}function WK(e){return Sl?(Sl(e),!0):!1}function UK(){const[e,t]=m.useState(()=>Date.now());return m.useEffect(()=>{const n=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(n)},[]),e}const Um=5,Xy=2*Math.PI*Um;function KK({startedAt:e,deadlineAt:t,output:n}){const{t:s}=se(),o=UK(),r=m.useRef({output:n,at:e??Date.now()});r.current.output!==n&&(r.current={output:n,at:Date.now()});const a=EK(e,t,o),l=PK(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:Um,fill:"none",stroke:"currentColor",opacity:"0.25"}),i.jsx("circle",{cx:"6",cy:"6",r:Um,fill:"none",stroke:"currentColor",strokeDasharray:Xy,strokeDashoffset:Xy*(1-a.fraction),transform:"rotate(-90 6 6)"})]}),Math.ceil(a.remainingMs/1e3),"s"]})]})}function bD(e,t){return e.kind==="exit_nonzero"&&e.exitCode===void 0?t("Failed"):t(AK[e.kind],{code:e.exitCode??""})}function qK({failure:e}){const{t}=se();return i.jsx("span",{"data-shell-failure":e.kind,className:U("shrink-0 rounded px-1 text-[10px]",e.retryable?"bg-muted text-muted-foreground":"bg-destructive/10 text-destructive"),children:bD(e,t)})}function YK({failure:e,command:t}){const{t:n}=se(),[s,o]=m.useState(!1);if(!e)return null;const r=MK[e.kind],a=RK(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:bD(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:()=>{OK(LK(l,t,n),Eh,Co)},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:vD})},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(Xu,{className:"h-3 w-3"}),n("Copy command")]})]})}function XK(e){return e.startsWith("/skill:")?"skill":e==="/goal"?"goal":"command"}function JK(e){return e.startsWith("/skill:")?e.slice(7):e.replace(/^\//,"")}function Du(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 ZK={skill:ti,goal:Ia,command:UN},QK={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 wD(e,t=!1){return U("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",QK[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 Iu({name:e,className:t,interactive:n=!1,trailing:s}){const o=XK(e),r=ZK[o];return i.jsxs("span",{className:U(wD(o,n),t),children:[i.jsx(r,{className:"h-3 w-3"}),JK(e),s]})}function eq({icon:e,state:t}){const n=t==="running"||t==="reviewing";return i.jsxs("span",{className:U("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 yD({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 tq={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 nq({view:e,titles:t}){const{t:n}=se();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(sq,{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 sq({run:e,title:t}){const{t:n}=se(),[s,o]=tq[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:U("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 gv=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Jy=e=>typeof e=="string"&&e.trim()?e:null;function Km(e){if(!gv(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 iq=new Set(["closed","parked","creating"]);function oq(e){if(!gv(e))return null;const{agentId:t,status:n,latestRun:s}=e;return typeof t!="string"||typeof n!="string"?null:(iq.has(n)?null:Km(s))??{agentId:t,runId:"",status:n,durationMs:null}}function rq(e,t){const n=fR(t);if(!n)return null;const{head:s,value:o}=n;if(e==="report"){const l=Km(o.run);if(!l)return null;const{text:c,value:d,error:u,...h}=o;return{kind:"report",head:s,runs:[l],text:Jy(c),value:d==null?null:JSON.stringify(d,null,2),error:Jy(u),info:JSON.stringify(h,null,2)}}if(e==="list"){if(!Array.isArray(o.agents))return null;const l=o.agents.flatMap(c=>oq(c)??[]);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(!gv(r)||!Array.isArray(r.runs))return e===void 0&&o.report===void 0&&typeof o.agentId=="string"&&typeof o.runId=="string"?{kind:"receipt",head:s,runs:[],info:JSON.stringify(o,null,2)}:null;const a=r.runs.flatMap(l=>Km(l)??[]);return a.length!==r.runs.length?null:{kind:"wait",head:s,runs:a,timedOut:r.timedOut===!0,interrupted:r.interrupted===!0,info:JSON.stringify(o,null,2)}}function aq({command:e,output:t,failure:n}){const s=ye(a=>a.terminalTheme),o=ye(a=>a.terminalFontFamily),r=Ju(s)??mR;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(YK,{failure:n,command:e})]})}function lq(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 SD({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(R$,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):i.jsx(zx,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/50"}),i.jsx("span",{className:U(t.status==="completed"?"text-muted-foreground line-through":t.status==="in_progress"?"font-medium":"text-muted-foreground"),children:t.content})]},t.content))})}function CD({done:e,total:t,className:n}){return i.jsx("div",{className:U("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 cq({conversationId:e}){const{t}=se(),n=ye(u=>u.pinUnfinishedTodos),s=oe(u=>u.conversations[e]?.messages),o=m.useMemo(()=>n&&s?lq(s):null,[n,s]),[r,a]=m.useState(!1),[,l]=m.useState(0);if(!o||Zy.has(o.id))return null;const c=o.todos.filter(u=>u.status==="completed").length,d=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(hj,{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:[c,"/",o.todos.length]}),!r&&d&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",title:d.content,children:d.content}),r?i.jsx(Vn,{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(CD,{done:c,total:o.todos.length,className:"mb-2"}),i.jsx(SD,{todos:o.todos})]})]})}const dq=1e3,uq=new Set(["ask_user"]);function kD(e,t){let n=t;for(;n>0&&e[n-1]?.role!=="user";)n--;const s=[];for(let c=n;c<=t&&c<e.length;c++){const d=e[c];if(d.role==="assistant"&&d.timing){const u=d.timing.stepStartMs,h=d.timing.completedMs??(typeof d.duration=="number"?u+d.duration:void 0);if(h!==void 0&&h>u){const p=x=>x!==void 0&&x>u&&x<h?x:void 0,f=p(d.timing.firstTokenMs),g=p(d.timing.thinkingEndMs);s.push({key:`m${c}`,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(d.role==="toolResult"&&typeof d.toolDurationMs=="number"&&typeof d.timestamp=="number"){const u=d.toolName??"tool";s.push({key:`t${c}`,kind:uq.has(u)?"wait":"tool",label:u,start:d.timestamp-d.toolDurationMs,end:d.timestamp})}}if(s.length===0||s.length===1&&!s[0].phases)return null;s.sort((c,d)=>c.start-d.start);const o=[];let r=s[0].start;for(const c of s)c.start-r>dq&&o.push({key:`w${c.key}`,kind:"wait",label:"",start:r,end:c.start}),o.push(c),r=Math.max(r,c.end);let a;const l=o.filter(c=>c.kind!=="wait");for(const c of l.length>1?l:[])(!a||c.end-c.start>a.end-a.start)&&(a=c);return{start:o[0].start,end:r,bars:o,...a?{slowest:a.key}:{}}}function hq(e,t){return oe(n=>{const s=e?n.conversations[e]:void 0;if(!s)return!1;const o=t-(s.historyBaseIndex??0);return s.messages[o]?.timing?kD(s.messages,o)!==null:!1})}const Wp={ttft:"bg-brand/30",thinking:"bg-brand/60",output:"bg-brand"};function pq(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 Qy=e=>e<1e3?`${Math.round(e)}ms`:Un(e),eS={ttft:"Waiting for first token",thinking:"Think time",output:"Output"},fq={model:"bg-brand",tool:"bg-info",wait:"bg-muted-foreground/30"};function mq({conversationId:e,messageIndex:t}){const{t:n}=se(),s=oe(c=>c.conversations[e]?.messages),o=oe(c=>c.conversations[e]?.historyBaseIndex??0),r=m.useMemo(()=>s?kD(s,t-o):null,[s,t,o]);if(!r)return null;const a=Math.max(1,r.end-r.start),l=r.bars.some(c=>c.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(c=>{const d=c.key===r.slowest,u=c.kind==="model"?n("Model"):c.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:U("truncate text-muted-foreground",c.kind==="tool"&&"font-mono",d&&"font-medium text-warning"),title:u,children:u}),i.jsx("span",{className:"relative h-2.5",children:i.jsx("span",{className:U("absolute top-0.5 flex h-1.5 min-w-px overflow-hidden rounded-sm",c.phases?d&&"ring-1 ring-warning ring-offset-1 ring-offset-background":d?"bg-warning":fq[c.kind]),style:{left:`${(c.start-r.start)/a*100}%`,width:`${(c.end-c.start)/a*100}%`},children:c.phases&&pq(c).map(h=>i.jsx("span",{className:U("h-full",Wp[h.phase]),style:{width:`${h.width}%`},title:`${n(eS[h.phase])} ${Qy(h.to-h.from)}`},h.phase))})}),i.jsx("span",{className:U("text-right tabular-nums text-muted-foreground",d&&"font-medium text-warning"),children:Qy(c.end-c.start)})]},c.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(Wp).map(c=>i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx("span",{className:U("h-1.5 w-2.5 rounded-sm",Wp[c])}),n(eS[c])]},c))})]})}const gq={report:()=>{},scroller:{current:null}},jD=m.createContext(gq),xq=jD.Provider;function vq(){return m.useContext(jD)}async function bq(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 wq(e){const t=await bq(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 _D({src:e,className:t,frameClassName:n,onError:s}){const{t:o}=se(),[r,a]=m.useState(!1);Ig(r),m.useEffect(()=>{if(!r)return;const c=d=>{d.key==="Escape"&&a(!1)};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[r]);const l=()=>{wq(e).then(()=>ze({type:"success",title:o("Image copied")}),c=>ze({type:"error",title:o("Could not copy image"),description:c instanceof Error?c.message:String(c)}))};return i.jsxs(i.Fragment,{children:[i.jsxs(po,{children:[i.jsx(fo,{render:i.jsx("button",{type:"button",onClick:()=>a(!0),className:U("cursor-zoom-in",n),children:i.jsx("img",{src:e,alt:"",className:t,onError:s})}),onContextMenu:c=>c.stopPropagation()}),i.jsx(mo,{className:"min-w-36",children:i.jsx(Vt,{closeOnClick:!0,onClick:l,children:o("Copy image")})})]}),r&&i.jsx("button",{type:"button",onClick:()=>a(!1),className:U("fixed inset-0 flex cursor-zoom-out items-center justify-center bg-black/75"),style:{zIndex:Cn.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 yq=(e,t)=>e===t||!!e&&!!t&&e.runMs===t.runMs&&e.turnMs===t.turnMs&&e.ttftMs===t.ttftMs&&e.tps===t.tps;function Sq(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"&&yq(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])&&n.tools.length===s.tools.length}}const Cq=/^<(agent-notification|goal-continuation|coworker-hired|coworker-dismissed|background-task-update)>\n?([\s\S]*?)\n?<\/\1>\s*$/,ND=/^<role>\n?([\s\S]*?)\n?<\/role>\s*/,kq=/^<workspace-migrated>\n?([\s\S]*?)\n?<\/workspace-migrated>\s*/;function jq({note:e}){const{t}=se(),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(Ri,{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 TD({note:e}){const{t}=se();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(va,{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}=se(),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(zR,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):i.jsx(_4,{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 _q({tag:e,body:t}){const n=e==="agent-notification"?EU(t):null;return n?i.jsx(Nq,{notices:n}):i.jsx(Tq,{tag:e,body:t})}function Nq({notices:e}){const{t}=se(),[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:U("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:Zn(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 Tq({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:$o;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(c=>!c),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:U("min-w-0 flex-1",a?"truncate":"whitespace-pre-wrap"),children:a?o.slice(0,r):o}),a&&i.jsx(un,{className:U("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 ID=/^<message-from-main-agent>\n?([\s\S]*?)\n?<\/message-from-main-agent>\s*$/;function Dq(e){const t=ND.exec(e);return ID.test(t?e.slice(t[0].length):e)}function Iq({name:e,content:t}){const{t:n}=se();return i.jsxs(vn,{children:[i.jsxs(VR,{className:wD("skill",!0),children:[i.jsx(ti,{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 qm({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:[i.jsx("div",{className:"flex flex-wrap items-center gap-1",children:e}),t?i.jsx("div",{className:"mt-1.5 whitespace-pre-wrap break-words leading-relaxed",children:t}):null]})}function Eq({blocks:e}){const t=HR(e.rest),n=i.jsx(qm,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:e.skills.map(s=>i.jsx(Iq,{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(TD,{note:t.plan}),t.unattended&&i.jsx(DD,{note:t.unattended}),n]})}function Pq({text:e}){const t=vj(e);if(t.names.length>1)return i.jsx(qm,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:t.names.map(s=>i.jsx(Iu,{name:`/skill:${s}`},s))}),extra:t.rest});const n=Du(e);return n.slash?i.jsx(qm,{chip:i.jsx(Iu,{name:n.slash}),extra:n.rest.trim()}):null}function Aq({preset:e}){const{t}=se();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(Mg,{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"?So:e==="chat"?Ko:d4;return i.jsxs("span",{className:U(uv(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 Oa({text:e,searchQuery:t="",activeNth:n=-1}){const s=G4(GR(e)),o={n:0};return i.jsx("span",{className:"whitespace-pre-wrap",children:s.map((r,a)=>r.type==="file"?i.jsx(xj,{path:r.path,children:i.jsx(kl,{kind:"file",label:kh(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()?FR(r.text,t,n,o):r.text},a))})}function Mq({files:e,chats:t}){return i.jsxs("span",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[e.map(n=>i.jsx(xj,{path:n,children:i.jsx(kl,{kind:"file",label:kh(n),title:n})},`f:${n}`)),t.map(n=>i.jsx(kl,{kind:"chat",label:n.label,title:n.sessionFile},`c:${n.sessionFile}`))]})}const tl="max-w-[82%] rounded-[10px] bg-muted px-3.5 py-[9px] text-(length:--chat-body-size) leading-[1.6]";function nl({text:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=se(),o=Wi(),r=!!(o?.speaker||o?.botSession),a=r?_R(e):null;if(a)return i.jsx(mU,{message:a});const l=r?NR(e):e;if(l!==e)return i.jsx(nl,{text:l,searchQuery:t,activeNth:n});const c=r?TR(e):null;if(c?.refs.length)return i.jsxs("div",{className:"flex w-full flex-col items-end gap-1.5",children:[c.body&&i.jsx(nl,{text:c.body,searchQuery:t,activeNth:n}),i.jsx("div",{className:"flex flex-wrap justify-end gap-1.5",children:c.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(pa,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:N.title})]},N.id))})]});const d=DR(e);if(d.note){const N=d.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(TD,{note:d.note}),N&&i.jsx(nl,{text:N,searchQuery:t,activeNth:n})]})}const u=IR(e);if(u.note){const N=u.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(DD,{note:u.note}),N&&i.jsx(nl,{text:N,searchQuery:t,activeNth:n})]})}const h=ER(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(FN,{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:U(tl,"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(va,{className:"h-3 w-3"}),s("Plan feedback")]}),i.jsx(Oa,{text:h.feedback,searchQuery:t,activeNth:n})]});const p=PR(e);if(p)return i.jsx(Aq,{preset:p});const f=W4(e);if(f.files.length>0||f.chats.length>0){const N=Du(f.body);return i.jsxs("div",{className:tl,children:[N.slash?i.jsxs(i.Fragment,{children:[i.jsx(Iu,{name:N.slash}),N.rest.trim()?i.jsx("span",{className:"ml-1.5 align-middle",children:i.jsx(Oa,{text:N.rest.trim(),searchQuery:t,activeNth:n})}):null]}):i.jsx(Oa,{text:f.body,searchQuery:t,activeNth:n}),i.jsx(Mq,{files:f.files,chats:f.chats})]})}const x=AR(e);if(x)return i.jsx(Eq,{blocks:x});if(Du(e).slash)return i.jsx(Pq,{text:e});const v=kq.exec(e);if(v){const N=e.slice(v[0].length).trim();return i.jsxs(i.Fragment,{children:[i.jsx(jq,{note:v[1]}),N&&i.jsx("div",{className:U(tl,"whitespace-pre-wrap"),children:i.jsx(Oa,{text:N,searchQuery:t,activeNth:n})})]})}const y=Cq.exec(e);if(y)return i.jsx(_q,{tag:y[1],body:y[2]});const b=ND.exec(e),w=b?e.slice(b[0].length):e,C=ID.exec(w),_=C?C[1]:w;return i.jsxs("div",{className:U(C?"max-w-[80%] rounded-2xl rounded-bl-md border border-blue-500/20 bg-blue-500/8 px-4 py-2.5 text-sm":U(tl,"whitespace-pre-wrap")),children:[C&&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]&&!pU(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]]}),C?i.jsx(_s,{text:_,searchQuery:t,activeNth:n}):i.jsx(Oa,{text:_,searchQuery:t,activeNth:n})]})}function tS(e){return e.kind==="tool-group"||e.kind==="thinking"||e.kind==="tool"&&fj(e)}const ma="text-[color:var(--subtle-foreground,var(--muted-foreground))]",ta="animate-pulse motion-reduce:animate-none";function Rq({model:e,at:t,privacyMask:n}){const s=Wi()?.speaker,o=[e,typeof t=="number"?Ph(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:U("min-w-0 truncate text-[11.5px]",ma),children:o}),n&&i.jsx(kK,{report:n})]})}const Lq=m.memo(function({item:t,onToggleGroup:n,onToggleTurn:s}){const o=gR(),r=o.query,a=o.activeKey===t.key?o.activeNth:-1;switch(t.kind){case"user":{const l=t.text?Dq(t.text):!1,c=t.collapsed===!0;return i.jsxs("div",{"data-enso":"message-user",className:U("group/user flex flex-col gap-1.5",l?"items-start":"items-end"),children:[t.images.map((d,u)=>i.jsx(_D,{src:`data:${d.mimeType};base64,${d.data}`,className:"max-h-48 max-w-full rounded-lg border object-contain"},u)),t.text&&i.jsx(nl,{text:t.text,searchQuery:r,activeNth:a}),c?i.jsx(Wq,{turnKey:t.key,timestamp:t.timestamp,turnDurationMs:t.turnDurationMs,onToggle:s}):i.jsx(Uq,{turnKey:t.key,messageIndex:Number(t.key),timestamp:t.timestamp,deliveryState:t.deliveryState,canCollapse:t.canCollapse,onToggleTurn:s})]})}case"text":return i.jsx(Kq,{item:t,searchQuery:r,activeNth:a});case"thinking":return i.jsx(Xq,{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(xR,{name:t.name,output:t.output,state:t.state}),i.jsx(sY,{item:t}),t.pluginArtifacts?i.jsx(vR,{artifacts:t.pluginArtifacts}):null]});case"tool-group":return i.jsx(eY,{item:t,onToggle:n});case"error":return i.jsxs("div",{className:"flex items-start gap-2 text-sm text-destructive",children:[i.jsx(br,{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(PD,{})]});case"task-note":return i.jsx(Jq,{item:t});case"compaction":case"compaction-notice":return i.jsx(Qq,{item:t});case"compaction-progress":return i.jsx(Zq,{state:t.state});case"session-custom":return i.jsx(Fq,{entry:t.entry});case"plugin-message":return i.jsx(zq,{item:t});case"discarded-turn":return i.jsx(Gq,{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"})]})}},Sq),nS=e=>{if(typeof e=="string")return e;if(e===void 0)return"—";try{return JSON.stringify(e)}catch{return String(e)}};function Oq({entry:e}){const{t}=se(),n=xU(),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(Wo,{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 zq({item:e}){const{t}=se();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(Zu,{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 Gq({item:e,onToggle:t}){const{t:n}=se();return i.jsxs("div",{"data-discarded-turn":e.pluginId,children:[i.jsxs("button",{type:"button",onClick:()=>t?.(e.key),"data-enso":"tool-row",className:U("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",ma),children:[i.jsx(pj,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"shrink-0 text-muted-foreground group-hover/step:text-foreground",children:Fo("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:U("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(Zu,{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)),e.tools.map((s,o)=>i.jsxs("p",{className:U("truncate",ma),children:[Fo(s.name,n)," ",s.summary]},o))]})]})}function Fq({entry:e}){const{t}=se();if(e.kind==="oauth-account-selected")return i.jsx(Oq,{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(br,{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:U("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(br,{className:U("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:[nS(o.previous)," → ",nS(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 ED=()=>()=>{};function PD(){const{t:e}=se(),t=Wi(),n=t?.botControls,s=oe(l=>{if(t&&(!t.canRetry||t.botControls))return!1;const c=Ps(l);return!!(c?.started&&!c.spawning&&c.status!=="running")}),o=()=>{if(!n||!t?.canRetry)return!1;const l=n.projection();return!!(l&&l.status!=="running")},r=m.useSyncExternalStore(n?.subscribe??ED,o,o);return(n?r:s)?i.jsxs("button",{type:"button",title:e("Retry"),onClick:()=>{if(n)return n.retry();const l=Ps(oe.getState());l&&oe.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(Wo,{className:"h-3 w-3"}),e("Retry")]}):null}function Hq(e,t){return BR(Ps(e),t)}const xv="flex items-center gap-1 text-[11px] text-muted-foreground transition-opacity hover:text-foreground";function Bq({messageIndex:e}){const{t}=se(),n=Wi();return oe(o=>LR(Ps(o),n))?i.jsxs("button",{type:"button",className:xv,title:t("Keep this session and start a parallel one from here"),onClick:()=>{const o=oe.getState(),r=Ps(o);if(!r)return;const a=OR(r,e);a!==null&&o.forkFromMessage(r.id,a)},children:[i.jsx(Ri,{className:"h-3 w-3"}),t("Conversation branch")]}):null}function Vq({messageIndex:e}){const{t}=se(),n=Wi(),s=oe(r=>Ps(r)?.id),o=oe(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 MR(l)||a.status==="running"&&RR(l)?l?.deliveryId:void 0});return!s||!o?null:i.jsxs("button",{type:"button",title:t("Withdraw message"),onClick:()=>oe.getState().withdrawMessage(s,{kind:"delivery",id:o}),className:"inline-flex items-center gap-1 hover:text-foreground",children:[i.jsx(fa,{className:"h-3 w-3"}),t("Withdraw message")]})}function $q({messageIndex:e}){const{t}=se(),[n,s]=m.useState(!1),[o,r]=m.useState(null),a=Wi(),l=a?.botControls,c=oe(x=>{if(a?.botControls)return!1;const v=Ps(x);return Hq(x,a)&&!!(v&&Pc(v.id,v.id,v,e))}),d=()=>{if(!l||!a?.canRewind||!a.sessionId)return null;const x=l.projection();return!x||x.status==="running"?null:Pc(a.sessionId,a.sessionId,x,e)?.entryId??null},u=m.useSyncExternalStore(l?.subscribe??ED,d,d);if(!(l?u!==null:c))return null;const p=x=>{if(l&&a?.sessionId&&u){r({restoreFiles:x,conversationId:a.sessionId,entryId:u});return}const v=Ps(oe.getState());if(!v)return;const y=Pc(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=oe.getState(),w=Ps(b),C=Pc(v,w?.id,b.conversations[v],e,y);C&&b.rewind(C.conversationId,C.entryId,x)},g=[{icon:fa,label:t("Conversation only"),desc:t("Rewind to this message"),restoreFiles:!1,action:()=>p(!1)},{icon:Ko,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:xv,title:t("Rewind to this message"),children:[i.jsx(fa,{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 Wq({turnKey:e,timestamp:t,turnDurationMs:n,onToggle:s}){const{t:o}=se();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:Ph(t)}),n!==void 0&&i.jsxs("span",{children:["· ",o("took {{duration}}",{duration:Un(n)})]})]})}function Uq({turnKey:e,messageIndex:t,timestamp:n,canCollapse:s,deliveryState:o,onToggleTurn:r}){const{t:a}=se(),l=ye(c=>c.autoCollapseTurns);return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/75 select-none",children:[i.jsx($q,{messageIndex:t}),i.jsx(Vq,{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:U(xv,"cursor-pointer opacity-0 group-hover/user:opacity-100"),title:a("Collapse"),children:[i.jsx(Vn,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{children:a("Collapse")})]}),typeof n=="number"&&i.jsx("span",{children:Ph(n)})]})}function Kq({item:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=se(),o=Wi(),r=e.perf?Yq(e.perf,s,e.turnDurationMs!==void 0):"",a=oe(p=>Ps(p)?.id??null),l=Number(e.key.split("-")[0]),c={text:e.text,messageIndex:l,sessionId:o?o.sessionId:a},d=hq(!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:c.messageIndex,sessionId:c.sessionId}}),e.turnEnd&&!e.streaming&&o?.turnFooter?.(Number(e.key.split("-")[0])),!e.streaming&&i.jsxs("div",{className:U("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(x0,{position:"left",...c}),i.jsx(qq,{text:e.text}),i.jsx(x0,{position:"right",...c}),e.turnEnd&&i.jsx(Bq,{messageIndex:Number(e.key.split("-")[0])}),e.timestamp&&!e.turnEnd&&i.jsx("span",{children:Ph(e.timestamp)}),e.turnDurationMs!==void 0&&(d?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:U("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&&d&&a&&i.jsx(mq,{conversationId:a,messageIndex:l})]})}function qq({text:e}){const{t}=se(),[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(Xu,{className:"h-3 w-3"})})}const sS=e=>String(e).padStart(2,"0"),Ph=e=>{const t=new Date(e);return`${sS(t.getHours())}:${sS(t.getMinutes())}`},iS=e=>{const t=e/1e3;return t<10?String(Math.round(t*10)/10):String(Math.round(t))};function Yq(e,t,n=!1){const s=[];return(!n||e.turnMs!==void 0)&&s.push(`${iS(e.runMs)}s`),e.ttftMs!==void 0&&s.push(`TTFT ${iS(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 Xq({itemKey:e,text:t,streaming:n,durationMs:s,startedAt:o}){const{t:r}=se(),a=ye(u=>u.expandLiveReasoning),[l,c]=m.useState(null),d=jR(l,n,a);return i.jsxs("div",{"data-enso":"thinking","data-live":n||void 0,children:[i.jsxs("button",{type:"button",onClick:()=>c(!d),className:U("flex min-h-6 items-center gap-2 text-[13px] transition-colors hover:text-foreground",ma),children:[i.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:i.jsx(bR,{className:U("size-3",n&&"animate-pulse text-brand")})}),n?i.jsx("span",{className:U("text-foreground",ta),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(AD,{itemKey:e,since:o}),i.jsx(un,{className:U("h-3 w-3 transition-transform",d&&"rotate-90")})]}),d&&i.jsx(wR,{text:t,streaming:n,itemKey:e})]})}function Jq({item:e}){const{t}=se(),[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,c=/(?:read ((?:\/|[A-Za-z]:[\\/]).+?\.log) for the complete log|Full log: ((?:\/|[A-Za-z]:[\\/])\S+?\.log))/.exec(e.detail)?.slice(1).find(Boolean)??null;return m.useEffect(()=>{!n||!c||o!==void 0||window.electronAPI.files.read(c).then(d=>{r(typeof d=="string"?d:null)}).catch(()=>r(null))},[n,c,o]),i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>s(d=>!d),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:U("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:c?o===void 0?t("Loading…"):Si(o??t("(log unavailable)")):t("(no log available)")})]})]})}function Zq({state:e}){const{t}=se();return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx(Yt,{className:"h-3 w-3 animate-spin"}),i.jsx("span",{children:t(e==="queued"?"Compacts after this turn":"Compacting…")})]})}function Qq({item:e}){const{t}=se(),[n,s]=m.useState(!1),o=e.kind==="compaction",r=e.tokensBefore===null?null:Zn(e.tokensBefore),a=MU(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:Zn(e.tokensBefore),after:Zn(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(c=>!c),className:U("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(Y6,{className:"h-3 w-3"}),l,i.jsx(un,{className:U("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 eY({item:e,onToggle:t}){const{t:n}=se(),s=ye(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 c=e.explore,d=e.exploring||!!(a&&e.live),u=c?Fo("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=c?[c.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:()=>{c?.steps&&t?.(v0(e.key)),t?.(e.key)},title:c?.goal,"data-explore-head":c?"":void 0,"data-enso":"tool-row",className:U("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",ma),children:[i.jsx(yD,{state:e.exploring?"running":"ok"}),i.jsx("span",{className:U("shrink-0 text-muted-foreground group-hover/step:text-foreground",d&&U(ta,"text-foreground"),e.exploring&&"font-medium"),children:u}),i.jsx("span",{className:U("min-w-0 flex-1 truncate",d&&ta),children:h.join(" · ")}),i.jsx(un,{className:U("h-3 w-3 shrink-0 transition-transform",e.expanded&&"rotate-90")})]});return!c||!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:[c.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:c.goal})]}),c.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:c.report})]}),i.jsxs("button",{type:"button",onClick:()=>t?.(v0(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:U("h-3 w-3 shrink-0 transition-transform",c.steps&&"rotate-90")}),i.jsx("span",{children:c.steps?n("Hide process"):n("Show process")}),i.jsxs("span",{children:["· ",n("{{count}} tool calls",{count:e.count})]})]})]})]})}function za({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),c=m.useRef(null),d=m.useRef(0);a.current=n;const u=m.useCallback(()=>{r.current=!1,l.current=null,cancelAnimationFrame(d.current)},[]),h=m.useCallback(()=>{!a.current||!r.current||(cancelAnimationFrame(d.current),d.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(d.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(d.current),[]),i.jsx("div",{ref:s,onWheel:p=>{p.deltaY<0&&u()},onPointerDown:p=>{p.target===p.currentTarget&&u()},onTouchStart:p=>{c.current=p.touches[0]?.clientY??null},onTouchMove:p=>{const f=p.touches[0]?.clientY;f!==void 0&&c.current!==null&&f>c.current&&u(),c.current=f??null},onTouchEnd:()=>{c.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:U("max-h-96 overflow-auto [overflow-anchor:none]",t),children:i.jsx("div",{ref:o,children:e})})}function tY(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??""}catch{return String(e)}}function nY({source:e,output:t,view:n}){const s=n?.status==="completed"?tY(n.value):n?.error??t;return i.jsxs("div",{className:"space-y-1 px-3 py-1",children:[e?i.jsx(b0,{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(c=>c.name===o),a=r.find(c=>!c.ok),l=`${o} ×${r.length}`;return i.jsx("span",{className:U("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(c=>c.summary).filter(Boolean).join(`
|
|
72
|
-
`),children:a?`${l} · ${a.error??"error"}`:l},o)})}):null,s?n?.status==="completed"&&typeof n.value!="string"?i.jsx(b0,{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 oS({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(_D,{src:Nf(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 sY({item:e}){const{t}=se(),n=Wi(),s=ye(O=>O.compactReadOnlyTools),o=ye(O=>O.expandLiveEdits),r=s&&e.name!=="bash"&&fj(e),a=!!(e.edits&&e.edits.length>0),l=!!e.writeContent,c=!!(e.fileChanges&&e.fileChanges.length>0),d=e.sandbox??null,u=e.state==="error"?null:e.sentMessage,h=!!e.imagePath&&e.state!=="error",p=hT[e.name],f=mj(e.name),g=e.state!=="error"&&e.todos?.length===0,x=g?t("Todo list cleared"):e.subagentOp?[t(kW[e.subagentOp]),e.summary].filter(Boolean).join(" · "):e.summary,v=e.nestedPending&&e.state==="running"?`${x} · ${e.nestedPending} pending`:d?.calls.length&&e.state!=="error"?yR(d.calls):x,y=!g&&!!(e.output||e.source||u||e.ask),b=e.state==="running"&&e.waiting==="subagent"&&!n,w=a||l||c||y||b||h,C=o&&(a||l||h)&&e.state==="running",[_,N]=m.useState(C),[S,k]=m.useState(!1),A=m.useRef(null),I=vq();m.useEffect(()=>{if(!S)return;const O=A.current;if(!O)return;const L=e.key,V=I.report,X=new IntersectionObserver(([F])=>V(L,F?.isIntersecting===!0),{root:I.scroller.current});return X.observe(O),()=>{X.disconnect(),V(L,!1)}},[S,e.key,I]);const D=_&&e.name==="memory_search"?rK(e.output):null,P=_&&e.name==="memory_capture"?aK(e.output,e.memoryContent):null,T=_&&e.name==="subagent"&&e.state!=="error"?rq(e.subagentOp,e.output):null,z=m.useRef(c);return m.useEffect(()=>{const O=SR(e,z.current);z.current=c,(C||o&&O)&&N(!0)},[C,o,c,e]),e.todos&&e.todos.length>0?i.jsx(rY,{todos:e.todos}):e.name.startsWith("goal_")?i.jsx(iY,{item:e}):e.plan&&e.state!=="error"?i.jsx(oY,{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 O=!_;N(O),k(O),I.report(e.key,O)},className:U("group/step flex min-h-6 min-w-0 flex-1 items-center gap-2 text-left text-[13px]",ma,w&&"cursor-pointer"),children:[i.jsx(yD,{state:e.state}),i.jsx("span",{className:U("shrink-0 text-muted-foreground transition-colors group-hover/step:text-foreground",e.state==="running"&&U(ta,"text-foreground")),children:p?t(p):f?.tool??e.name}),i.jsx("span",{className:U("min-w-0 flex-1 truncate font-mono text-[12px]",e.state==="error"?"text-destructive":"text-muted-foreground",e.state==="running"&&ta),children:e.state==="error"&&e.output?x&&e.name==="apply_patch"&&c?`${v} · ${lS(e.output)}`:lS(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(qK,{failure:e.shellFailure}),e.state==="reviewing"?i.jsx("span",{className:U("shrink-0 text-[11px] text-foreground",ta),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(hY,{callId:e.callId,startedAt:e.startedAt,output:e.output??""}),i.jsx(AD,{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:U("h-3 w-3 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] group-hover/step:opacity-100",_&&"rotate-90 opacity-100")})]}),e.state==="running"&&e.callId&&!n&&i.jsx(aY,{callId:e.callId,waiting:!!e.waiting}),(a||l||c)&&(e.state==="ok"||c)&&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:()=>gj(),children:i.jsx(Gx,{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(O=>i.jsx(oS,{path:O,fallback:i.jsx("p",{className:"break-all px-3 py-2 text-xs text-muted-foreground",children:O})},O))}):null,_&&w&&i.jsxs("div",{"data-slot":"tool-details",className:"t-acc-reveal mt-1 mb-1.5 ml-5 overflow-hidden rounded-lg border border-border/70 bg-card shadow-xs",children:[f&&i.jsxs("div",{className:"truncate border-b border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",children:[f.server,".",f.tool]}),b&&i.jsx(uY,{agentIds:e.subagentTitles?Object.keys(e.subagentTitles):void 0}),a&&e.edits&&i.jsx(za,{follow:e.state==="running",children:i.jsx(Uy,{path:e.summary,blocks:e.edits})}),c&&e.fileChanges&&i.jsx(za,{follow:e.state==="running",children:e.fileChanges.map((O,L)=>i.jsxs("div",{children:[i.jsxs("div",{className:U("flex items-center gap-2 border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",(L>0||a)&&"border-t"),children:[i.jsx("span",{className:"uppercase",children:O.type}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:O.path,children:O.path}),O.truncated&&i.jsx("span",{children:t("Truncated preview")})]}),i.jsx(Uy,{path:O.path,blocks:[O],snapshot:O})]},`${O.type}:${rv(O.path,O.oldText,O.newText)}`))}),CR(e)&&i.jsx(za,{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(za,{follow:e.state==="running",className:U((a||c)&&"border-t border-border/60"),children:i.jsx(Vd,{path:e.summary,contents:e.writeContent})}),!a&&!l&&!c&&(y||h)&&i.jsxs(za,{follow:e.state==="running",children:[kR(e.name)?i.jsx(nY,{source:e.source,output:e.output,view:d}):e.name==="bash"||e.name==="powershell"?i.jsx(aq,{command:e.summary,output:e.output??"",failure:e.shellFailure}):e.name==="read"&&h&&e.imagePath?i.jsx(oS,{path:e.imagePath,fallback:i.jsx(Vd,{path:e.summary,contents:e.output??""})},e.imagePath):e.name==="read"?i.jsx(Vd,{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??""})}):D?i.jsx($m,{hits:D}):P?i.jsx(tK,{view:P}):i.jsxs(i.Fragment,{children:[e.ask&&i.jsx(_U,{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(nq,{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(IK,{value:e.rtk}),i.jsx(jU,{value:e.approvalReview})]})]})]})}function iY({item:e}){const{t}=se(),n=e.name.replace("goal_",""),s=t(n==="complete"?"Goal completed":n==="blocked"?"Goal blocked":"Goal waiting");return i.jsxs("div",{className:U("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(Ia,{className:U("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 oY({plan:e}){const{t}=se(),[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(va,{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:U("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 rY({todos:e}){const{t}=se(),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(hj,{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(CD,{done:n,total:e.length,className:"mt-1.5 mb-2"}),i.jsx(SD,{todos:e})]})}const rS=new Map;function aY({callId:e,waiting:t}){const{t:n}=se(),s=oe(c=>Ps(c)?.id??""),[o,r]=m.useState(!1);if(m.useEffect(()=>{if(!o)return;const c=setTimeout(()=>r(!1),5e3);return()=>clearTimeout(c)},[o]),!s)return null;const a=n(t?o?"Stopping wait…":"Stop waiting":o?"Moving to background…":"Move to background"),l=t?pj:C$;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(c=>{c.ok||r(!1)},()=>r(!1))},children:[i.jsx(l,{className:"h-3 w-3"}),a]})}const lY=5e3,cY=[];function dY(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 uY({agentIds:e}){const{t}=se(),n=oe(l=>Ps(l)?.id??""),s=ay(l=>l.byConversation[n]??cY),[o,r]=m.useState(!1);if(m.useEffect(()=>{if(!n)return;let l=!0;const c=p=>{l&&(ay.getState().replace(n,p),r(!0))},d=()=>window.electronAPI.agent.subagentProgress(n).then(c,()=>{}),u=window.electronAPI.agent.onSubagentProgress(p=>{p.sessionId===n&&c(p.runs)});d();const h=setInterval(d,lY);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:dY(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 AD({itemKey:e,since:t}){const n=Wi(),s=oe(c=>Ps(c)?.id??""),o=n?n.sessionId??"":s,r=m.useRef(null);if(r.current===null){const c=`${o}:${e}`;r.current=t??rS.get(c)??Date.now(),t===void 0&&rS.set(c,r.current)}const a=t??r.current,[,l]=m.useState(0);return m.useEffect(()=>{const c=setInterval(()=>l(d=>d+1),1e3);return()=>clearInterval(c)},[]),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:Un(Date.now()-a)})}function hY({callId:e,startedAt:t,output:n}){const s=Wi(),o=oe(r=>s?void 0:Ps(r)?.toolDeadlineAt?.[e]);return i.jsx(KK,{startedAt:t,deadlineAt:o,output:n})}function aS(e){return e.kind==="tool-group"?!0:e.kind==="tool"&&!e.todos?.length&&!e.name.startsWith("goal_")}const lS=e=>Si(e.split(`
|
|
73
|
-
`,1)[0]??""),pY=100;function fY(e,t,n,s,o=pY){if(s||!n)return{hiddenSince:t,delayMs:null};const r=t??e;return{hiddenSince:r,delayMs:Math.max(0,o-(e-r))}}const mY=1e6;function gY(e,t,n=mY){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 xY(e,t){return t}const vY=new Set(["text","thinking","tool","tool-group"]);function bY(e,t,n,s){const o=m.useRef(w0),[r,a]=m.useState(()=>Date.now()),l=s.compact,c=s.autoCollapseCompletedTurns,d=s.collapseCompletedActivity===!0,u=s.collapseLiveActivity===!0,h=s.turnOverrides,p={compact:l,autoCollapseCompletedTurns:c,turnOverrides:h},f=u?$R(e,t,s,o.current,r):null;o.current=f?.witness??w0;const g=f?.wakeAt??null,x=WR(e,t,n,{...p,collapseCompletedActivity:d,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 wY=[{icon:J$,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:GN,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:bj,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:Ko,title:"Summarize recent changes",hint:"A digest based on git log",prompt:"Summarize the recent changes in this repository based on git log."}];function yY({onPick:e}){const{t}=se();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:wY.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",cS=1e3;function dS({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:U("t-stagger",n&&"is-shown",e),children:t})}const uS=40,SY={index:"LAST",align:"end"},CY={top:600,bottom:600},kY=e=>e?"auto":!1;function jY({style:e,...t}){const n=e?.visibility==="hidden",[s,o]=m.useState(!1),r=m.useRef(null);return m.useEffect(()=>{const a=fY(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 Ah({ref:e,items:t,busy:n,loading:s=!1,running:o,runStartedAt:r,lastOutputAt:a,error:l,emptyTitle:c,emptyDescription:d,onSuggestion:u,onRetryResume:h,onRetrySync:p,virtualize:f=!0,onStartReached:g,historyLoading:x=!1,hasOlder:v,olderCursor:y,searchQuery:b="",activeHit:w=null}){const{t:C}=se(),_=m.useRef(null),[N,S]=m.useState(!0),[k,A]=m.useState(!1),I=m.useRef(!0),D=m.useRef(null),P=m.useRef(0),T=m.useRef(0),z=m.useRef(null),O=m.useRef(!1),L=m.useRef(!1),V=m.useRef(0),[X,F]=m.useState(null),ee=m.useRef(0),H=m.useCallback(we=>{cancelAnimationFrame(ee.current),ee.current=requestAnimationFrame(()=>F(we()))},[]);m.useEffect(()=>()=>cancelAnimationFrame(ee.current),[]);const[Q,q]=m.useState(new Set),ne=m.useRef(new Set),[me,ke]=m.useState(()=>new Set),Me=m.useCallback((we,Qe)=>{const it=ne.current;Qe!==it.has(we)&&(Qe?it.add(we):it.delete(we),ke(new Set(it)))},[]),ge=m.useRef({report:Me,scroller:D});ge.current.report=Me;const $=m.useCallback(we=>{q(Qe=>{const it=new Set(Qe);return it.has(we)?it.delete(we):it.add(we),it})},[]),[W,ue]=m.useState(new Map),Z=ye(we=>we.autoCollapseTurns),J=ye(we=>we.collapseCompletedActivity),ae=ye(we=>we.collapseLiveActivity),te=ye(we=>we.liveActivityFoldDelaySec),pe=ye(we=>we.compactReadOnlyTools),Te=bY(t,o,Q,{compact:pe,autoCollapseCompletedTurns:Z,collapseCompletedActivity:J,collapseLiveActivity:ae,liveActivityFoldDelaySec:te,heldOpenTools:me,turnOverrides:W}),$e=m.useRef({state:oU,collapse:new Map,reveal:new Map}),Ie=m.useMemo(()=>{const we=$e.current,Qe=Xt=>D.current?.querySelector(`[data-nav-key="${CSS.escape(Xt)}"]`),it=rU(we.state,Te,(Xt,E)=>{const R=Qe(Xt)?.getBoundingClientRect().top,M=Qe(E)?.getBoundingClientRect().bottom;return R===void 0||M===void 0?0:M-R}),yt=Date.now();we.state=it.next;for(const{key:Xt,...E}of it.collapses)we.collapse.set(Xt,{at:yt,...E});for(const Xt of it.expands)we.reveal.set(Xt,yt);return it.children},[Te]),Ze=m.useRef(null),Nt=m.useRef(0),Ut=m.useRef(null),Pt=gY(Ze.current,Te.map(we=>we.key));Ze.current=Pt.anchor,Pt.remount&&(Nt.current+=1,Ut.current=null);const _t=Pt.firstItemIndex,B=m.useCallback((we,Qe)=>{ue(it=>it.get(we)===Qe?it:new Map(it).set(we,Qe))},[]),je=m.useMemo(()=>{const we=[];for(let Qe=0;Qe<t.length;Qe++){const it=t[Qe];if(it.kind!=="user")continue;let yt="";for(let Xt=Qe+1;Xt<t.length;Xt++){const E=t[Xt];if(E.kind==="user")break;if(E.kind==="text"){yt=E.text;break}}we.push({key:it.key,question:it.text||"[image]",answer:yt})}return we},[t]),Ye=m.useCallback(()=>{const we=D.current;we&&we.scrollHeight-we.scrollTop-we.clientHeight>2&&(O.current=!0,we.scrollTop=we.scrollHeight)},[]),Tt=m.useCallback(()=>{cancelAnimationFrame(P.current);const we=Date.now()+1200;let Qe=null;const it=()=>{cancelAnimationFrame(P.current),O.current=!1,Qe?.removeEventListener("touchstart",it),Qe?.removeEventListener("wheel",it)},yt=()=>{if(L.current){it();return}!Qe&&D.current&&(Qe=D.current,Qe.addEventListener("touchstart",it,{passive:!0,once:!0}),Qe.addEventListener("wheel",it,{passive:!0,once:!0})),Ye(),I.current=!0,S(!0),Date.now()<we?P.current=requestAnimationFrame(yt):it()};yt(),S(!0),I.current=!0},[Ye]);m.useEffect(()=>()=>{cancelAnimationFrame(P.current),cancelAnimationFrame(T.current),window.clearTimeout(V.current)},[]);const Wt=()=>{L.current=!0,window.clearTimeout(V.current)},le=()=>{window.clearTimeout(V.current),V.current=window.setTimeout(()=>{L.current=!1},400)},ht=()=>{Wt(),le()},Ot=()=>{cancelAnimationFrame(P.current),cancelAnimationFrame(T.current),O.current=!1,I.current=!1,S(!1)},Fe=m.useCallback(we=>{if(z.current?.disconnect(),z.current=null,!we)return;const Qe=new ResizeObserver(()=>{if(!I.current&&!O.current)return;cancelAnimationFrame(T.current);let it=8;const yt=()=>{Ye();const Xt=D.current;(Xt?Xt.scrollHeight-Xt.scrollTop-Xt.clientHeight:0)<=2||(--it>0?T.current=requestAnimationFrame(yt):Tt())};yt()});Qe.observe(we),z.current=Qe,Tt()},[Ye,Tt]);m.useEffect(()=>()=>z.current?.disconnect(),[]);const jt=we=>Te.findIndex(Qe=>Qe.key===we||Qe.kind==="tool-group"&&MD(Qe,we)),Ft=we=>{if(!f){D.current?.querySelector(`[data-nav-key="${CSS.escape(we)}"]`)?.scrollIntoView({block:"center"});return}const Qe=jt(we);Qe>=0&&_.current?.scrollToIndex({index:xY(_t,Qe),align:"center"})},cn=m.useRef(null),re=we=>{if(Ot(),jt(we)>=0){cn.current=null,Ft(we);return}let Qe=null,it=!1;for(const yt of t)if(yt.kind==="user"&&(Qe=yt.key),yt.key===we){it=!0;break}!it||!Qe||(cn.current=we,B(Qe,!1))};m.useLayoutEffect(()=>{const we=cn.current;!we||jt(we)<0||(cn.current=null,Ft(we))},[Te]),m.useImperativeHandle(e,()=>({scrollToBottom:Tt,pinToBottom:Ye,isAtBottom:()=>I.current,getScroller:()=>f?null:D.current,scrollToKey:re}));const Ue=m.useRef(!1),ut=`${y}:${_t}`,xt=m.useRef(ut);xt.current!==ut&&(xt.current=ut,Ue.current=!1);const pt=()=>{!g||Ue.current||(Ue.current=!0,g())};m.useEffect(()=>{f&&!x&&Ut.current===_t&&pt()},[y,x]);const K=m.useMemo(()=>({query:b,activeKey:w?.key??"",activeNth:w?.nth??-1}),[b,w?.key,w?.nth]),fe=(we,Qe)=>{const it=Te[Qe+1];if(it!==void 0&&aS(we)&&aS(it))return"pb-0";if(!pe)return"pb-4";const yt=it!==void 0&&tS(it);return tS(we)?yt?"pb-1":"pb-2":we.kind==="text"&&yt?"pb-1":"pb-4"},De=(we,Qe)=>{const it=Te[Qe-1],yt=it?.kind==="user"&&!it.collapsed&&vY.has(we.kind)?it:void 0,Xt=Date.now(),E=$e.current.collapse.get(we.key),R=E&&Xt-E.at<cS?E:void 0,M=Ie.get(we.key),j=M&&$e.current.reveal.get(M.group),G=M&&j!==void 0&&Xt-j<cS;return i.jsxs("div",{"data-nav-key":we.key,"data-fold-collapse":R?R.pair?"pair":"toggle":void 0,style:R?{"--fold-from":`${R.height}px`}:G?{"--fold-i":M.index}:void 0,className:U(ji,fe(we,Qe),G&&"t-fold-reveal","[overflow-wrap:anywhere]"),children:[yt&&i.jsx(Rq,{model:yt.replyModel,at:yt.replyAt,privacyMask:yt.replyPrivacyMask}),i.jsx(EY,{itemKey:we.key,children:i.jsx(Lq,{item:we,onToggleGroup:$,onToggleTurn:B})})]},we.key)},Pe=m.useRef(!1);v===!0&&(Pe.current=!0);const Ge=UR(t.length>0,x,v,Pe.current,!f&&k);m.useLayoutEffect(()=>{if(f){A(!1);return}const we=D.current;A(!!we&&KR(v===!0,x,we.scrollHeight,we.clientHeight))},[f,v,x,_t,Te.length,t.length]);const st={pageChrome:Ge,onLoadMore:Ge==="more"?pt:void 0,busy:n,loading:!!s,since:aU({loading:!!s,runStartedAt:r}),error:l,onRetryResume:h};return i.jsx(qR.Provider,{value:K,children:i.jsx(xq,{value:ge.current,children:i.jsxs("div",{"data-enso":"timeline",className:"@container relative min-h-0 flex-1",onWheel:ht,onKeyDown:ht,onTouchStart:Wt,onTouchEnd:le,onPointerDown:we=>{we.target===D.current&&(Wt(),window.addEventListener("pointerup",le,{once:!0}))},children:[i.jsx(dU,{items:je,activeKey:X,onJump:re}),t.length===0&&!n?i.jsxs(dS,{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(iU,{className:"size-6"})})}),i.jsx("p",{className:"t-stagger-line t-stagger-line--1 text-[22px] font-semibold tracking-tight",children:c}),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:C(l)}),h&&i.jsx(xe,{size:"sm",variant:"outline",onClick:h,children:C("Retry resume")})]}):i.jsxs(i.Fragment,{children:[p?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"t-stagger-line t-stagger-line--2 max-w-md text-sm text-muted-foreground",children:C("Session is not ready yet — no history to show.")}),i.jsx(xe,{size:"sm",variant:"outline",onClick:p,children:C("Retry sync")})]}):d!==""?i.jsx("p",{className:"t-stagger-line t-stagger-line--2 text-sm text-muted-foreground",children:d??C("Ask the agent…")}):null,u&&i.jsx("div",{className:"t-stagger-line t-stagger-line--3 mt-5 w-full",children:i.jsx(yY,{onPick:u})})]})]}):t.length===0&&l?i.jsxs(dS,{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:C(l)}),h&&i.jsx(xe,{size:"sm",variant:"outline",onClick:h,children:C("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(Yt,{className:"h-5 w-5 animate-spin text-muted-foreground"}),i.jsx("p",{className:"text-sm text-muted-foreground",children:C("Preparing session…")})]}):f?i.jsx(B8,{ref:_,data:Te,defaultItemHeight:80,computeItemKey:(we,Qe)=>Qe.key,firstItemIndex:_t,startReached:pt,followOutput:kY,atBottomThreshold:uS,atBottomStateChange:we=>{if(!we&&I.current&&!L.current){Tt();return}S(we),I.current=we},increaseViewportBy:CY,initialTopMostItemIndex:SY,rangeChanged:({startIndex:we})=>{Ut.current=we,we>_t+4&&(Ue.current=!1),H(()=>{const Qe=Math.max(0,we-_t);let it=null;for(let yt=0;yt<=Math.min(Qe+1,Te.length-1);yt++)Te[yt]?.kind==="user"&&(it=Te[yt].key);return it})},scrollerRef:we=>{D.current=we instanceof HTMLElement?we:null},className:"h-full select-text",context:st,components:NY,itemContent:(we,Qe)=>De(Qe,we-_t)},Nt.current):i.jsx("div",{ref:we=>{D.current=we},onScroll:we=>{const Qe=we.currentTarget;if(O.current){O.current=!1,I.current=!0,S(!0);return}if(!L.current){I.current&&Ye();return}const it=Qe.scrollHeight-Qe.scrollTop-Qe.clientHeight<=uS;it!==I.current&&(I.current=it,S(it)),g&&(Qe.scrollTop<80&&!Ue.current?(Ue.current=!0,g()):Qe.scrollTop>240&&(Ue.current=!1))},className:"h-full select-text overflow-y-auto [overflow-anchor:none]",children:i.jsxs("div",{ref:Fe,children:[i.jsx(RD,{context:st}),Te.map((we,Qe)=>De(we,Qe)),i.jsx(LD,{context:st})]})}),!N&&t.length>0&&i.jsxs("button",{type:"button",onClick:Tt,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(Qu,{className:"h-3 w-3"}),C("Scroll to bottom")]})]})})})}function MD(e,t){return e.children.some(n=>n.key===t||n.kind==="tool-group"&&MD(n,t))}function _Y({chrome:e,onLoadMore:t}){const{t:n}=se();return e==="none"?i.jsx("div",{className:"h-6"}):i.jsx("div",{className:U(ji,"flex items-center justify-center gap-2 py-3"),children:e==="loading"?i.jsxs(i.Fragment,{children:[i.jsx(Yt,{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 RD({context:e}){return i.jsx(_Y,{chrome:e.pageChrome,onLoadMore:e.onLoadMore})}function LD({context:e}){const{t}=se(),{busy:n,loading:s,since:o,error:r,onRetryResume:a}=e;return i.jsxs("div",{className:U(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(TY,{}),i.jsx("span",{className:"animate-pulse text-foreground motion-reduce:animate-none",children:t(s?"Loading…":"Working…")}),o!==void 0&&i.jsx(IY,{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(PD,{}),a&&i.jsx(xe,{size:"sm",variant:"outline",onClick:a,children:t("Retry resume")})]})]})}const NY={List:jY,Header:RD,Footer:LD};function TY(){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 DY=e=>{const t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},IY=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:DY(Date.now()-t)})});class EY 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 na={type:"spring",stiffness:400,damping:30},Eu={type:"tween",duration:.22,ease:[.2,0,0,1]},Up={initial:{height:0,opacity:0},animate:{height:"auto",opacity:1,transition:Eu},exit:{height:0,opacity:0,transition:Eu}};function PY(e){return e.resizing?!0:e.previousConversationId!==void 0&&e.conversationId!==void 0&&e.previousConversationId!==e.conversationId}function OD(e){return e.skip?{duration:0}:e.cover||e.targetW===0?Eu:na}const zD=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))}}},AY={ts:Ma,tsx:Ma,js:Ma,jsx:Ma,mjs:Ma,json:Rg,html:K$,css:y0,scss:y0,md:So,sh:Ef,bash:Ef,yml:hi,yaml:hi,toml:hi},MY={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 Tc(e,t,n=!1){if(t)return n?ni:Cc;const s=e.split(".").pop()?.toLowerCase()??"";return AY[s]??f6}function Dc(e,t){if(t)return"text-amber-500";const n=e.split(".").pop()?.toLowerCase()??"";return MY[n]??"text-muted-foreground"}const RY={artifacts:[],media:[]},Kp=new Map,qp=new Map,LY=new Set(["image","markdown","html","text"]),OY=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`;function zY(e){const t=JSON.stringify(e),[n,s]=m.useState(()=>Kp.get(t)??RY);return m.useEffect(()=>{if(Kp.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)&&Kp.set(t,a),s(a)}).catch(()=>{}),()=>{o=!1}},[t]),n}function GY(e){const{t}=se();return(n,s)=>{window.electronAPI.bots.artifacts.open({...e,rel:n.rel,action:s}).then(o=>{o.ok||ze({type:"error",title:o.error==="not-openable"?t("This file type is only shown in Finder"):t("Could not open the file")})})}}function Pu({target:e}){const{artifacts:t,media:n}=zY(e);return i.jsxs(i.Fragment,{children:[n.length>0&&i.jsx(HY,{target:e,media:n}),t.length>0&&i.jsx($Y,{target:e,artifacts:t})]})}function FY(){const{t:e}=se();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 GD(e,t,n){const s=JSON.stringify(e),o=t&&n==="thumb"?qp.get(t):void 0,[r,a]=m.useState(o?{ok:!0,kind:"image",dataUrl:o}:null);return m.useEffect(()=>{const l=t&&n==="thumb"?qp.get(t):void 0;if(a(l?{ok:!0,kind:"image",dataUrl:l}:null),!t||l)return;let c=!0;return window.electronAPI.bots.artifacts.read({...JSON.parse(s),mediaId:t,variant:n}).then(d=>{n==="thumb"&&d.ok&&d.kind==="image"&&qp.set(t,d.dataUrl),c&&a(d)}).catch(()=>c&&a({ok:!1,error:"unavailable"})),()=>{c=!1}},[s,t,n]),r}function HY({target:e,media:t}){const{t:n}=se(),s=FY(),[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,c)=>l.ok?i.jsx(BY,{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(BN,{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-${c}`))}),a&&i.jsx("p",{className:"mt-1 text-warning text-xs",children:n("Desktop screenshots may capture sensitive content from other windows.")}),i.jsx(VY,{target:e,item:o,label:o?s(o):"",onClose:()=>r(null)})]})}function BY({target:e,item:t,label:n,onOpen:s}){const o=GD(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(BN,{className:"m-auto h-4 w-4 text-muted-foreground"}):i.jsx(Yt,{className:"m-auto h-4 w-4 animate-spin text-muted-foreground"}),n&&i.jsx("span",{className:U("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 VY({target:e,item:t,label:n,onClose:s}){const{t:o}=se(),r=GD(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(FD,{name:a,content:r})]})})}function $Y({target:e,artifacts:t}){const{t:n}=se(),s=GY(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=Tc(a.name,!1),c=LY.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:!c,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:U("h-3.5 w-3.5 shrink-0",Dc(a.name,!1))}),i.jsx("span",{className:"truncate",children:a.name}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:OY(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(wj,{className:"h-3.5 w-3.5"})})]},a.rel)}),i.jsx(WY,{target:e,artifact:o,onOpen:s,onClose:()=>r(null)})]})}function WY({target:e,artifact:t,onOpen:n,onClose:s}){const{t:o}=se(),[r,a]=m.useState(null),l=t?.rel,c=JSON.stringify(e);return m.useEffect(()=>{if(a(null),!l)return;let d=!0;return window.electronAPI.bots.artifacts.read({...JSON.parse(c),rel:l}).then(u=>d&&a(u)).catch(()=>d&&a({ok:!1,error:"unavailable"})),()=>{d=!1}},[c,l]),i.jsx(vn,{open:t!==null,onOpenChange:d=>!d&&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(wj,{className:"h-4 w-4"})})]})]})}),i.jsx(FD,{name:t?.name??"",content:r})]})})}function FD({name:e,content:t}){const{t:n}=se();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(Yt,{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(Vd,{path:e,contents:t.text})})]})}const HD="enso:design-annotations:v1",BD="enso:annotate-prefs:v1",hS=ZR(e=>e.pageKey),pS=[],fS=new WeakMap,Po={annotateHovered:!1,annotateEntered:!1,annotateUseCount:0,annotateSendImmediately:!0};function VD(e){try{return typeof localStorage>"u"?null:localStorage.getItem(e)}catch{return null}}function $D(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(e,t)}catch{}}function UY(){const e=VD(BD);if(!e)return Po;try{const t=JSON.parse(e);return{annotateHovered:typeof t.annotateHovered=="boolean"?t.annotateHovered:Po.annotateHovered,annotateEntered:typeof t.annotateEntered=="boolean"?t.annotateEntered:Po.annotateEntered,annotateUseCount:typeof t.annotateUseCount=="number"&&Number.isFinite(t.annotateUseCount)?t.annotateUseCount:Po.annotateUseCount,annotateSendImmediately:typeof t.annotateSendImmediately=="boolean"?t.annotateSendImmediately:Po.annotateSendImmediately}}catch{return Po}}function Ga(e){$D(BD,JSON.stringify(e))}const mS=YR(VD(HD)),KY=UY();function Qc(e,t){$D(HD,JR({queues:e,pages:t}))}const Wn=Dg((e,t)=>({...KY,queues:mS.queues,pages:mS.pages,sessions:new Map,familiarity:()=>{const n=t();return XR(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};Ga(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};Ga(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};Ga(o),e({annotateSendImmediately:n})},annotationsFor:(n,s)=>{const o=t().queues.get(n);if(!o||o.items.length===0)return pS;if(!s)return o.items;let r=fS.get(o.items);r||(r=new Map,fS.set(o.items,r));const a=r.get(s);if(a)return a;const l=o.items.filter(d=>d.browserId===s),c=l.length===0?pS:l;return r.set(s,c),c},pageKeyOf:n=>t().pages.get(n),setBrowserUrl:(n,s)=>{if(!s)return;const o=yj(s),r=t().pages;if(r.get(n)===o)return;const a=new Map(r);a.delete(n),a.set(n,o),Qc(t().queues,a),e({pages:a})},dispatchQueue:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=hS(r,s);if(a===r)return;const l=new Map(o.queues);l.delete(n),a.items.length>0&&l.set(n,a),Qc(l,o.pages),e({queues:l})},addAnnotation:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=hS(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),Qc(l,o.pages);const c=o.annotateUseCount+1;return Ga({annotateHovered:o.annotateHovered,annotateEntered:o.annotateEntered,annotateUseCount:c,annotateSendImmediately:o.annotateSendImmediately}),e({queues:l,annotateUseCount:c}),a.items.find(d=>d.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(c=>a.has(c)))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:()=>{Ga(Po),Qc(new Map,new Map),e({...Po,queues:new Map,pages:new Map,sessions:new Map})}})),sa=typeof navigator<"u"&&navigator.platform?navigator.platform.startsWith("Mac"):!0,Ym=sa?"⌘⇧D":"Ctrl+Shift+D";function Yp({className:e}){return i.jsx("svg",{viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",className:U("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 qY(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=$r,o.strokeStyle=$r,o.lineWidth=Mf,o.lineCap="round",o.lineJoin="round";for(const l of e.markup)for(const c of Af(l,"complete")){const d=new Path2D(c.d);c.paint==="fill"?o.fill(d):o.stroke(d)}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 YY({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 c=t.current;if(!c)return;const d=()=>{const h=c.getBoundingClientRect();a({width:Math.round(h.width),height:Math.round(h.height)})};d();const u=new ResizeObserver(d);return u.observe(c),()=>u.disconnect()},[]);const l=m.useMemo(()=>r.width>4&&r.height>4?o2(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 XY({drawing:e,pick:t,markupTool:n,editorOpen:s,onMarkupToolChange:o,onExit:r}){const a=n2({drawing:e,pick:t?{region:t.region}:null,markupToolHeld:n!==null,editorOpen:s}),c=m.useMemo(()=>s2(sa),[])[a],d=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(Bs,{className:"h-3.5 w-3.5"});case"circle":return i.jsx(zx,{className:"h-3.5 w-3.5"});case"square":return i.jsx(uc,{className:"h-3.5 w-3.5"});case"arrow-right-up":return i.jsx(j$,{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 (${Ym})`,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:d(c)})]}),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:i2.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:U("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 JY({tabId:e,conversationId:t,active:n,disabled:s,queueOpen:o,onQueueOpenChange:r,onToggleDesignMode:a,onOpenPinFromQueue:l,onSendQueue:c}){const{t:d}=se(),u=Wn(_=>_.familiarity()),h=Wn(_=>_.annotateHovered),p=Wn(_=>_.markHovered),f=Wn(_=>_.annotationsFor(t)),g=Wn(_=>_.annotationsFor(t,e)),x=Wn(_=>_.removeAnnotations),v=Wn(_=>_.clearAnnotations),[y,b]=m.useState(!1),w=n?f:g,C=w.length;return C===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 (${Ym}) — 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:U("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(Yp,{}),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(Yp,{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:[C>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:()=>c(n?void 0:new Set(g.map(_=>_.id))),title:d("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:C})]}),i.jsx("button",{type:"button","aria-label":`Open annotation queue (${C})`,"aria-expanded":o,onClick:()=>r(!o),className:"flex h-full items-center border-l border-white/20 px-1 transition-colors hover:bg-black/10",children:i.jsx(Vn,{className:"h-3 w-3"})})]}):i.jsxs("button",{type:"button",onClick:()=>a(!1),"aria-label":"Annotate","aria-pressed":n,title:`Exit Design Mode (${Ym})`,className:"flex h-6 items-center gap-1 rounded bg-[#3a96dd]/15 px-2 text-xs font-medium text-[#3a96dd]",children:[i.jsx(Yp,{}),u!=="many"&&i.jsx("span",{children:"Annotate"})]}),o&&C>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:C===1?"1 edit":`${C} 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(_=>{const N=_.kind==="region"&&_.images[0]?`data:${_.images[0].mimeType};base64,${_.images[0].data}`:null,S=_.kind==="element"&&_.elements.length>1?_.elements.length-1:0,k=_.comment.trim()||(_.kind==="element"&&_.elements[0]?t2(_.elements[0]):_.kind==="region"?`Screenshot region ${Math.round(_.region.rect.width)} × ${Math.round(_.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(_)},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:_.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,[_.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(Hs,{className:"h-3 w-3"})})]},_.id)})})]})]})}function ZY({stage:e,pinned:t,onTogglePinned:n,onClose:s,onStageChange:o}){const[r,a]=m.useState(""),l=m.useMemo(()=>Cj(e),[e]),c=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]),d=m.useMemo(()=>{const h=r.trim().toLowerCase();return w2.filter(p=>y2(p,{rendersText:e.baseline.rendersText,values:c})&&p.name.includes(h))},[r,e.baseline.rendersText,c]),u=h=>{const p=k2(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(ra,{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:U("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(ci,{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:d.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:U("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 C=S2(v,w.key==="ArrowUp"?1:-1,w.shiftKey,h);C!==null&&(w.preventDefault(),w.stopPropagation(),u({kind:"edit",property:h.name,value:C}))},className:U("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(ra,{className:"h-2.5 w-2.5"})})]},h.name)})})]})}function QY({tabId:e,conversationId:t,stageSize:n,draftPick:s,openPin:o,markupTool:r,warningShown:a,onWarningShownChange:l,onDraftPickChange:c,onMoveSelection:d,onCancelDraft:u,onCloseOpenPin:h,onSendQueue:p,onStrokeStateChange:f,active:g}){const{t:x}=se(),v=Wn(re=>re.annotateSendImmediately),y=Wn(re=>re.setSendImmediately),b=Wn(re=>re.addAnnotation),w=Wn(re=>re.updateAnnotation),C=Wn(re=>re.removeAnnotations),_=Wn(re=>re.annotationsFor(t)),N=m.useMemo(()=>o?_.find(re=>re.id===o.id)??null:null,[_,o]),S=m.useMemo(()=>r2(N?.comment??""),[N?.comment]),[k,A]=m.useState(""),[I,D]=m.useState([]),[P,T]=m.useState(!1),[z,O]=m.useState(!1),[L,V]=m.useState(null),[X,F]=m.useState({x:0,y:0}),[ee,H]=m.useState(!1),[Q,q]=m.useState(null),[ne,me]=m.useState("move"),[ke,Me]=m.useState(null),ge=m.useRef(null),$=m.useRef(null),W=m.useRef(null),ue=m.useRef(null),Z=m.useId(),J=o?`pin:${o.id}`:s?"draft":"none";m.useEffect(()=>{A(S.prose),D(N?N.images.slice(1):[]),T(!1),V(null),F({x:0,y:0}),l(!1),window.setTimeout(()=>W.current?.focus(),10)},[J]),m.useEffect(()=>{const re=a2(_.filter(Ue=>Ue.browserId===e));window.electronAPI.browser.previewDesignCss(e,"queue",re)},[_,e]);const ae=m.useMemo(()=>N?N.kind==="element"?N.elements:[]:s?.description.elements??[],[N,s]),te=ae.length===1?ae[0]:null,pe=m.useCallback(async()=>{if(!te)return;if(P){T(!1);return}const re=await window.electronAPI.browser.readDesignCss(e,te.uniqueId);if(!re){ze({type:"warning",title:x("Could not read CSS for this element")});return}V(l2(re,S.css)),T(!0)},[te,P,e,S.css,x]);m.useEffect(()=>{if(!g||!s?.region)return;const re=Ue=>{if(!(sa?Ue.metaKey:Ue.ctrlKey)||Ue.altKey||Ue.key.toLowerCase()!=="z")return;const xt=document.activeElement===W.current&&k.length>0;if(v2({markCount:s.markup.length+s.redoMarkup.length,toolHeld:r!==null,noteOwnsUndo:xt}))if(Ue.preventDefault(),Ue.stopPropagation(),Ue.shiftKey){const pt=s.redoMarkup.at(-1);if(!pt)return;c({...s,markup:[...s.markup,pt],redoMarkup:s.redoMarkup.slice(0,-1)})}else{const pt=s.markup.at(-1);if(!pt)return;c({...s,markup:s.markup.slice(0,-1),redoMarkup:[...s.redoMarkup,pt]})}};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[g,s,r,k.length,c]),m.useEffect(()=>{if(!Q||!s)return;const re={left:0,top:0,width:n.width,height:n.height},Ue=(pt,K)=>{const fe=pt.key===" "?"Space":pt.key==="Shift"||pt.key==="Alt"||pt.key==="Escape"?pt.key:null;fe&&(fe==="Space"&&pt.preventDefault(),q(De=>De?_0(De,{type:"key",key:fe,down:K},re):null))},ut=pt=>Ue(pt,!0),xt=pt=>Ue(pt,!1);return window.addEventListener("keydown",ut,!0),window.addEventListener("keyup",xt,!0),()=>{window.removeEventListener("keydown",ut,!0),window.removeEventListener("keyup",xt,!0)}},[Q,s,n.width,n.height]);const Te=m.useMemo(()=>L?Cj(L):null,[L]),$e=!!(Te&&Te.changes.size>0),Ie=k.trim().length>0,Ze=N!==null,Nt=Ze?k.trim()!==S.prose.trim()||!!Te?.isDirty:Ie||$e||(s?.markup.length??0)>0,Ut=m.useMemo(()=>Te?S0(k,Te.changes):S.css.size>0?S0(k,S.css):k.trim(),[k,Te,S.css]),Pt=Ze?!0:Ut.length>0||s?.region!==null&&(s?.markup.length??0)>0,_t=b2({sendImmediately:v,isOnStack:Ze}),B=$e&&!Ie?C0[_t].css:C0[_t].note,je=m.useCallback(()=>{const re=ae;if(re.length===0)return;let Ue=!1;re.forEach((ut,xt)=>{const pt=`ui-${Date.now()}-${xt}`,K=Pf(ut),fe=xt===0&&s?.description.image?{data:s.description.image.data,mimeType:s.description.image.mimeType}:void 0;mv({kind:"ui-element",id:pt,label:K,path:ut.path||ut.tagName.toLowerCase(),text:(ut.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||Sj(ut),imageId:`img-${pt}`},fe)&&(Ue=!0)}),Ue?(Co(),u()):ze({type:"warning",title:x("No Composer for this selection")})},[ae,s?.description.image,u,x]),Ye=m.useCallback(async()=>{if(!(ee||!Pt)){H(!0);try{if(Ze&&N){const K=N.images.length>0?[N.images[0],...I]:[...I];w(t,N.id,Ut,K),window.electronAPI.browser.previewDesignCss(e,"draft",{}),h(),v&&p(new Set([N.id]));return}if(!s)return;const re=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ann-${Date.now()}`,Ue=Wn.getState().pageKeyOf(e)??"http://localhost/",ut=s.description.image,xt=[];if(ut){const K=s.region&&s.markup.length>0?await qY({base64:ut.data,markup:s.markup,cropWidth:s.region.width}):ut.data;xt.push({id:`img-${re}`,data:K,mimeType:ut.mimeType,name:ut.name,width:ut.width,height:ut.height})}xt.push(...I);let pt;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"}};pt=b(t,{id:re,kind:"region",comment:Ut,browserId:e,pageKey:Ue,images:xt,region:{rect:s.region,anchor:K,markup:s.markup}})}else pt=b(t,{id:re,kind:"element",comment:Ut,browserId:e,pageKey:Ue,images:xt,elements:s.description.elements});window.electronAPI.browser.previewDesignCss(e,"draft",{}),u(),v&&pt&&p(new Set([pt.id]))}finally{H(!1)}}},[ee,Pt,Ze,N,I,w,t,Ut,e,h,v,p,s,b,u]),Tt=m.useCallback(()=>{if(Nt&&!a){l(!0);return}l(!1),window.electronAPI.browser.previewDesignCss(e,"draft",{}),Ze?h():u()},[Nt,a,l,e,Ze,h,u]),Wt=re=>{for(const Ue of re){if(!Ue.type.startsWith("image/"))continue;const ut=new FileReader;ut.onload=()=>{const xt=ut.result,pt=xt.slice(xt.indexOf(",")+1);D(K=>[...K,{id:`att-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,data:pt,mimeType:Ue.type,name:Ue.name}])},ut.readAsDataURL(Ue)}},le=Q?Q.rect:s?.region??null,ht=Math.min(320,Math.max(240,n.width-16)),Ot=P?360:148,Fe=m.useMemo(()=>{if(o)return c2(o.badge,n,{width:ht,height:Ot});if(le)return k0({x:le.left,y:le.top,width:le.width,height:le.height},n,ht,Ot);if(s&&s.elements.length>0){const re=s.elements.map(fe=>fe.rect.x),Ue=s.elements.map(fe=>fe.rect.y),ut=s.elements.map(fe=>fe.rect.x+fe.rect.width),xt=s.elements.map(fe=>fe.rect.y+fe.rect.height),pt=Math.min(...re),K=Math.min(...Ue);return k0({x:pt,y:K,width:Math.max(...ut)-pt,height:Math.max(...xt)-K},n,ht,Ot)}return{x:16,y:16}},[o,le,s,n,ht,Ot]),jt=z?Math.max(8,n.width-ht-8):Math.max(8,Math.min(Fe.x+X.x,n.width-ht-8)),Ft=z?8:Math.max(8,Math.min(Fe.y+X.y,n.height-120));if(!s&&!o)return null;const cn=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&&Tt()},children:[s&&le&&i.jsxs(i.Fragment,{children:[cn&&i.jsx("img",{src:cn,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%, ${le.left}px 100%, ${le.left}px ${le.top}px, ${le.left+le.width}px ${le.top}px, ${le.left+le.width}px ${le.top+le.height}px, ${le.left}px ${le.top+le.height}px, ${le.left}px 100%, 100% 100%, 100% 0%)`}}),i.jsxs("div",{role:"application","aria-label":"Selected screenshot region",style:{left:le.left,top:le.top,width:le.width,height:le.height,cursor:r!==null?"crosshair":g2(Q?Q.handle:ne,Q!==null)},onPointerMove:re=>{const Ue=re.currentTarget.getBoundingClientRect(),ut={x:re.clientX-Ue.left,y:re.clientY-Ue.top};if(r!==null){if(!ke||!ge.current)return;const xt={x:Math.max(0,Math.min(le.width,ut.x)),y:Math.max(0,Math.min(le.height,ut.y))};if(ke.kind==="pen")Me({kind:"pen",points:f2(ke.points,xt)});else{const pt=re.shiftKey?m2({kind:ke.kind,from:ge.current,to:xt}):xt;Me({kind:ke.kind,from:ge.current,to:pt})}return}if(Q){const xt=re.currentTarget.parentElement?.getBoundingClientRect(),pt={x:re.clientX-(xt?.left??0),y:re.clientY-(xt?.top??0)};q(K=>K?_0(K,{type:"move",point:pt,altKey:re.altKey,shiftKey:re.shiftKey},{left:0,top:0,width:n.width,height:n.height}):null);return}me(j0(ut,le))},onPointerDown:re=>{if(re.button!==0)return;re.preventDefault(),re.stopPropagation(),re.currentTarget.setPointerCapture(re.pointerId);const Ue=re.currentTarget.getBoundingClientRect(),ut={x:Math.max(0,Math.min(le.width,re.clientX-Ue.left)),y:Math.max(0,Math.min(le.height,re.clientY-Ue.top))};if(r!==null){ge.current=ut,f(!0),Me(r==="pen"?{kind:"pen",points:[ut]}:{kind:r,from:ut,to:ut});return}const xt=re.currentTarget.parentElement?.getBoundingClientRect(),pt={x:re.clientX-(xt?.left??0),y:re.clientY-(xt?.top??0)},K=j0(ut,le);q(p2({handle:K,point:pt,rect:le,modifiers:{altKey:re.altKey,shiftKey:re.shiftKey}}))},onPointerUp:async()=>{if(ke){const re=d2(s.markup,ke);Me(null),ge.current=null,f(!1),re.length!==s.markup.length&&c({...s,markup:re,redoMarkup:[]});return}if(Q){const re=u2({rect:Q.rect,viewport:n}),Ue=h2({markup:s.markup,from:s.region??re,to:re,markupScale:1});q(null);const ut=await window.electronAPI.browser.describeSelection(e,{x:re.left,y:re.top,width:re.width,height:re.height});c({...s,region:re,markup:Ue,description:ut.image?ut: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:le.width,height:le.height,className:"pointer-events-none block h-full w-full overflow-visible",children:[s.markup.map((re,Ue)=>Af(re,"complete").map((ut,xt)=>i.jsx("path",{d:ut.d,"data-design-markup-stroke":"",fill:ut.paint==="fill"?$r:"none",stroke:ut.paint==="stroke"?$r:"none",strokeWidth:ut.paint==="stroke"?Mf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`${Ue}-${xt}`))),ke&&Af(ke,"active").map((re,Ue)=>i.jsx("path",{d:re.d,"data-design-markup-stroke":"active",fill:re.paint==="fill"?$r:"none",stroke:re.paint==="stroke"?$r:"none",strokeWidth:re.paint==="stroke"?Mf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`active-${Ue}`))]}),r===null&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"pointer-events-none absolute -top-1.5 -left-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -top-1.5 -right-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -bottom-1.5 -left-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -right-1.5 -bottom-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"})]})]})]}),i.jsxs("div",{style:{left:jt,top:Ft,width:ht},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||z||re.target instanceof Element&&re.target.closest("button, input")||(re.preventDefault(),re.currentTarget.setPointerCapture(re.pointerId),$.current={pointerId:re.pointerId,startX:re.clientX,startY:re.clientY,nudgeX:X.x,nudgeY:X.y})},onPointerMove:re=>{const Ue=$.current;!Ue||Ue.pointerId!==re.pointerId||F({x:Ue.nudgeX+(re.clientX-Ue.startX),y:Ue.nudgeY+(re.clientY-Ue.startY)})},onPointerUp:()=>{$.current=null},className:U("flex items-center justify-between gap-2 px-3 pt-2.5 pb-1",!z&&"cursor-grab active:cursor-grabbing"),children:[i.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:le||N?.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(le?.width??(N?.kind==="region"?N.region.rect.width:0))," ","×"," ",Math.round(le?.height??(N?.kind==="region"?N.region.rect.height:0))]})]}):ae.map((re,Ue)=>{const ut=np[(re.hueIndex??Ue)%np.length]??np[0],xt=sp[(re.hueIndex??Ue)%sp.length]??sp[0];return i.jsxs("span",{style:{backgroundColor:ut.bg,borderColor:xt.stroke,color:ut.border},title:`${x2(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:ut.border}}),i.jsx("span",{className:"truncate",children:Pf(re)})]},re.uniqueId||`${re.tagName}-${Ue}`)})}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 rounded-lg bg-muted/50 p-0.5",children:[!Ze&&!le&&ae.length===1&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:()=>d("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(t6,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",onClick:()=>d("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(cc,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",onClick:()=>d("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(kj,{className:"h-3 w-3"})})]}),ae.length>0&&i.jsx("button",{type:"button",onClick:je,title:`Add element to chat (${sa?"⌘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(Go,{className:"h-3 w-3"})}),te&&i.jsx("button",{type:"button",onClick:()=>{pe()},"aria-label":"Edit CSS properties","aria-pressed":P,title:"Edit CSS properties",className:U("flex h-5 w-5 items-center justify-center rounded-md transition-colors",P||$e?"bg-[#3a96dd]/15 text-[#3a96dd]":"text-muted-foreground hover:bg-background/80 hover:text-foreground"),children:i.jsx(l4,{className:"h-3 w-3"})}),Ze&&N&&i.jsx("button",{type:"button","aria-label":"Delete annotation",title:"Delete annotation",onClick:()=>{C(t,[N.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(Hs,{className:"h-3 w-3"})})]})]}),I.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 px-3 pt-1.5",children:I.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:()=>D(Ue=>Ue.filter(ut=>ut.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:W,rows:2,value:k,onChange:re=>{A(re.target.value),a&&l(!1);const Ue=re.currentTarget;Ue.style.height="auto",Ue.style.height=`${Math.min(144,Math.max(44,Ue.scrollHeight))}px`},onPaste:re=>{const Ue=Array.from(re.clipboardData.files);Ue.length>0&&(re.preventDefault(),Wt(Ue))},onKeyDown:re=>{if(re.nativeEvent.isComposing)return;const Ue=sa?re.metaKey:re.ctrlKey;if(Ue&&re.key.toLowerCase()==="l"){re.preventDefault(),re.stopPropagation(),je();return}if(re.key==="Enter"&&!re.shiftKey){if(Pt||Ue){re.preventDefault(),re.stopPropagation(),Ye();return}if(!Ze&&!le&&ae.length>0){re.preventDefault(),re.stopPropagation(),d("child");return}}if(!Pt&&!Ze&&!le&&ae.length>0){if(re.key==="Enter"&&re.shiftKey||re.key==="\\"){re.preventDefault(),re.stopPropagation(),d("parent");return}if(re.key==="Tab"){re.preventDefault(),re.stopPropagation(),d(re.shiftKey?"previous":"next");return}}Ze&&N&&!Ie&&!$e&&(re.key==="Backspace"||re.key==="Delete")&&!re.altKey&&!re.ctrlKey&&!re.metaKey&&!re.repeat&&(re.preventDefault(),re.stopPropagation(),C(t,[N.id]),h())},placeholder:$e?"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"}),$e&&!P&&Te&&i.jsx("section",{"aria-label":"CSS edits",className:"mt-1.5 flex flex-wrap gap-1 text-[10px] text-[#3a96dd]",children:[...Te.changes].map(([re,Ue])=>i.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-[#3a96dd]/20 bg-[#3a96dd]/10 px-1.5 py-0.5 font-mono",children:[i.jsxs("span",{className:"font-medium",children:[re,":"]}),Ue.to===null?i.jsx("span",{children:"removed"}):i.jsxs(i.Fragment,{children:[i.jsx("del",{className:"opacity-65",children:Ue.from}),i.jsx("span",{className:"opacity-60",children:"→"}),i.jsx("ins",{className:"font-semibold no-underline",children:Ue.to})]})]},re))})]}),P&&L&&te&&i.jsx(ZY,{stage:L,pinned:z,onTogglePinned:()=>O(re=>!re),onClose:()=>T(!1),onStageChange:(re,Ue)=>{V(re),window.electronAPI.browser.previewDesignCss(e,"draft",{[te.uniqueId]:Ue})}}),a&&i.jsxs("div",{"data-design-input-notice":"",className:"flex items-center justify-between gap-2 border-t bg-amber-500/10 px-2.5 py-1.5 text-[11px]",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("span",{className:"font-semibold text-amber-600 dark:text-amber-400",children:"Discard comment?"})," ",i.jsx("span",{className:"text-muted-foreground",children:"This comment isn't saved yet."})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>l(!1),className:"rounded border bg-background px-2 py-0.5 text-[10px] font-medium hover:bg-muted",children:"Keep Editing"}),i.jsx("button",{type:"button",onClick:()=>{l(!1),window.electronAPI.browser.previewDesignCss(e,"draft",{}),Ze?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:ue,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:re=>{Wt(Array.from(re.target.files??[])),re.target.value=""}}),i.jsx("button",{type:"button",onClick:()=>ue.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(Ch,{className:"h-3.5 w-3.5"})}),i.jsxs("label",{htmlFor:Z,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:Z,type:"checkbox",checked:!v,onChange:re=>y(!re.target.checked),className:"sr-only"}),i.jsx("span",{"aria-hidden":"true",className:U("relative inline-flex h-3.5 w-6 shrink-0 items-center rounded-full transition-colors duration-150",v?"bg-muted-foreground/30":"bg-[#3a96dd]"),children:i.jsx("span",{className:U("inline-block h-2.5 w-2.5 rounded-full bg-white shadow-2xs transition-transform duration-150",v?"translate-x-0.5":"translate-x-3")})}),i.jsx("span",{children:"Batch edits"})]})]}),i.jsxs("button",{type:"button",disabled:ee||!Pt,"aria-label":B,title:`${B} (Enter)`,onClick:()=>{Ye()},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:[_t==="add-to-stack"?i.jsx(us,{className:"h-3 w-3"}):_t==="save-note"?i.jsx(Kn,{className:"h-3 w-3"}):i.jsx(dc,{className:"h-3 w-3"}),i.jsx("span",{children:B})]})]})]})]})}function eX({tabId:e,conversationId:t,url:n,designMode:s,onDesignModeState:o,active:r}){const{t:a}=se(),[l,c]=m.useState(!1),[d,u]=m.useState(null),[h,p]=m.useState(null),[f,g]=m.useState(null),[x,v]=m.useState(!1),[y,b]=m.useState(!1),[w,C]=m.useState(!1),_=Wn(O=>O.annotationsFor(t,e)),N=Wn(O=>O.annotationsFor(t)),S=m.useRef(n);m.useEffect(()=>{n&&Wn.getState().setBrowserUrl(e,n),S.current!==n&&(S.current=n,u(null),p(null),b(!1),c(!1),v(!1))},[e,n]);const k=m.useCallback(async O=>{O?Wn.getState().markEntered():(u(null),p(null),g(null),b(!1),c(!1));const L=await window.electronAPI.browser.setDesignMode(e,O);o(L)},[e,o]);m.useEffect(()=>{if(!s||!n)return;const O=yj(n),L=_.filter(V=>V.pageKey===O).map(QR);window.electronAPI.browser.setAnnotationPins(e,O,L)},[s,n,_,e]);const A=m.useCallback(O=>{if(g(O),O!==null&&d&&d.region===null&&d.elements.length>0){const L=d.elements.map(ne=>ne.rect.x),V=d.elements.map(ne=>ne.rect.y),X=d.elements.map(ne=>ne.rect.x+ne.rect.width),F=d.elements.map(ne=>ne.rect.y+ne.rect.height),ee=Math.max(0,Math.min(...L)-12),H=Math.max(0,Math.min(...V)-12),Q=Math.max(24,Math.max(...X)-ee+12),q=Math.max(24,Math.max(...F)-H+12);u({...d,region:{left:ee,top:H,width:Q,height:q}})}},[d]);m.useEffect(()=>window.electronAPI.browser.onDesignMode(O=>{if(O.tabId===e){if(O.type==="cancelled"){u(null),p(null),g(null),c(!1);return}if(O.type==="drawing"){c(O.drawing);return}if(O.type==="pins"){Wn.getState().setPinnedIds(e,O.ids);return}if(O.type==="pin-click"){u(null),b(!1),O.pin&&p({id:O.id,badge:O.pin});return}if(O.type==="select"){if(c(!1),p(null),b(!1),O.addToChat&&O.description.elements.length>0){O.description.elements.forEach((L,V)=>{const X=`ui-${Date.now()}-${V}`,F=Pf(L),ee=V===0&&O.description.image?{data:O.description.image.data,mimeType:O.description.image.mimeType}:void 0;mv({kind:"ui-element",id:X,label:F,path:L.path||L.tagName.toLowerCase(),text:(L.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||Sj(L),imageId:`img-${X}`},ee)}),Co(),window.electronAPI.browser.clearSelection(e);return}u({elements:O.elements,region:O.region?{left:O.region.x,top:O.region.y,width:O.region.width,height:O.region.height}:null,viewportWidth:O.viewportWidth,description:O.description,markup:[],redoMarkup:[]})}}}),[e]);const I=m.useCallback(()=>{u(null),g(null),b(!1),window.electronAPI.browser.clearSelection(e)},[e]),D=m.useCallback(()=>{p(null),b(!1),window.electronAPI.browser.openAnnotationPin(e,null,!1)},[e]),P=m.useCallback(async O=>{const L=await window.electronAPI.browser.moveSelection(e,O);L.elements.length!==0&&u(V=>V?{...V,elements:L.elements,description:L.description}:null)},[e]),T=m.useCallback(async O=>{if(O.browserId!==e){ze({type:"info",title:a("Turn on design mode in this note's browser tab to open it")});return}s||await k(!0);const L=await window.electronAPI.browser.openAnnotationPin(e,O.id,!0);L&&(u(null),p({id:O.id,badge:L}))},[e,s,k,a]),z=m.useCallback(O=>{const L=Wn.getState(),V=L.annotationsFor(t),X=O?V.filter(Q=>O.has(Q.id)):[...V];if(X.length===0)return;const F=e2(X,Q=>Q.pageKey),ee=F.ordered.map(Q=>Q.id);if(L.removeAnnotations(t,ee),!BK({text:F.text,images:F.images,mentions:[]})){L.restoreAnnotations(t,F.ordered),ze({type:"warning",title:a("Note not sent"),description:a("The note stays in the queue.")});return}L.annotationsFor(t).length===0&&s&&k(!1)},[t,s,k,a]);return m.useEffect(()=>{if(!r)return;const O=L=>{if((sa?L.metaKey:L.ctrlKey)&&L.shiftKey&&!L.altKey&&L.key.toLowerCase()==="d"){L.preventDefault(),L.stopPropagation(),k(!s);return}if(!s||L.key!=="Escape")return;const X=L.target instanceof Element?L.target:null,F=X?.closest('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"], [aria-expanded="true"], [data-design-owns-escape]')!==null&&X?.closest("[data-design-owns-escape]")!==null,ee=X?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')!==null;if(w){L.preventDefault(),L.stopPropagation(),C(!1);return}switch(C2({queueOwnsEscape:w,targetOwnsEscape:F,targetIsInput:ee,markupStrokeActive:x,markupToolHeld:f!==null,warningShown:y,draftOpen:d!==null,editorOpen:h!==null})){case"pass-through":return;case"cancel-stroke":L.preventDefault(),L.stopPropagation(),v(!1);return;case"put-down-tool":L.preventDefault(),L.stopPropagation(),g(null);return;case"dismiss-warning":L.preventDefault(),L.stopPropagation(),b(!1);return;case"cancel-draft":L.preventDefault(),L.stopPropagation(),I();return;case"close-editor":L.preventDefault(),L.stopPropagation(),D();return;case"exit":L.preventDefault(),L.stopPropagation(),k(!1);return}};return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[r,s,w,x,f,y,d,h,k,I,D]),{drawing:l,draftPick:d,openPin:h,markupTool:f,warningShown:y,queueOpen:w,allConversationAnnotations:N,setQueueOpen:C,setWarningShown:b,setDraftPick:u,setDesignMode:k,handleMarkupToolChange:A,moveSelection:P,cancelDraft:I,closeOpenPin:D,openPinFromQueue:T,sendQueue:z,setMarkupStrokeActive:v}}const tX=(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,gS=(e,t)=>t.some(n=>tX(e,n)),nX=new Set(["dialog-popup","dialog-viewport","dialog-backdrop","alert-dialog-popup","alert-dialog-viewport","alert-dialog-backdrop"]);function sX(e){if(e.getAttribute("data-enso-float")!==null)return!0;const t=e.getAttribute("data-slot");return t?nX.has(t)||t.endsWith("-popup")||t.endsWith("-positioner"):!1}function xS(e,t){const n=[];for(const s of Array.from(e.querySelectorAll("*"))){if(!sX(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 WD=m.createContext({visible:!0,active:!0});function iX({dockConversationId:e,api:t,children:n}){const s=oe(u=>u.activeId===e),o=fn(u=>!!u.uiByConversation[e]?.open),r=m.useCallback(u=>{const h=t.onDidActiveChange(u),p=t.onDidVisibilityChange(u);return()=>{h.dispose(),p.dispose()}},[t]),a=m.useSyncExternalStore(r,()=>t.isActive),l=m.useSyncExternalStore(r,()=>t.isVisible),c=s&&o&&l,d=m.useMemo(()=>({visible:c,active:c&&a}),[c,a]);return i.jsx(WD.Provider,{value:d,children:n})}function UD(){return m.useContext(WD)}const Au=new Map,Xm=new Set;function vS(){for(const e of Xm)e()}function oX(e){return Xm.add(e),()=>{Xm.delete(e)}}function rX(e){const t=Au.get(e);if(!t?.visible)return!1;let n=0,s;for(const[o,r]of Au)r.kind!==t.kind||!r.visible||(n+=1,r.active&&(s=o));return n<=1||s===e}function KD(e,t=!0){const{visible:n,active:s}=UD(),o=m.useRef(null);o.current===null&&(o.current=Symbol(e));const r=o.current;m.useEffect(()=>{if(t)return Au.set(r,{kind:e,visible:n,active:s}),vS(),()=>{Au.delete(r),vS()}},[s,t,r,e,n]);const a=m.useSyncExternalStore(oX,()=>rX(r));return t&&a}const aX={tabId:null,url:"",title:"",favicon:null,loading:!1,canGoBack:!1,canGoForward:!1,locked:!1,devtoolsOpen:!1,designMode:!1,holder:null},Xp=(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,bS=80,lX=.42;function wS(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=cX(e,t.bottom);return s>0?{...n,radius:s}:n}function cX(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 dX(){const{t:e}=se();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(go,{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 qD(e){return window.electronAPI.remote?i.jsx(dX,{}):i.jsx(uX,{...e})}function uX({conversationId:e,panelApi:t,active:n}){const{t:s}=se(),o=oe(q=>j2(q.conversations,e)),r=fn(q=>q.uiByConversation[o]?.open??!1),a=oe(q=>q.activeId===o),l=n??(r&&a),c=KD("browser",n===void 0),d=n??c,[u,h]=m.useState(aX),[p,f]=m.useState(""),[g,x]=m.useState(!1),[v,y]=m.useState(null),[b,w]=m.useState(lX),[C,_]=m.useState({width:800,height:600}),N=m.useRef(null),S=m.useRef(null),k=m.useRef(null),A=m.useRef(void 0),I=m.useRef(!1),D=m.useRef(void 0),P=m.useRef(!1),T=m.useRef(!1);T.current=u.locked;const z=m.useRef(!1);z.current=u.devtoolsOpen;const O=(u.url.startsWith("http")||u.url.startsWith("file:"))&&!u.loading,L=m.useRef(!1);L.current=O;const V=m.useRef(null),X=t.id,F=eX({tabId:X,conversationId:e,url:u.url,designMode:u.designMode,onDesignModeState:h,active:d});m.useEffect(()=>{const q=N.current;if(!q)return;const ne=()=>{const ke=q.getBoundingClientRect();ke.width>0&&ke.height>0&&_({width:Math.round(ke.width),height:Math.round(ke.height)})};ne();const me=new ResizeObserver(ne);return me.observe(q),()=>me.disconnect()},[]),m.useEffect(()=>window.electronAPI.browser.onState(q=>{q.tabId===X&&h(q.state)}),[X]),m.useEffect(()=>window.electronAPI.browser.onDesignMode(q=>{if(q.tabId!==X||q.type==="cancelled"||q.type==="select"||q.type==="drawing"||q.type==="pin-click"||q.type==="pins")return;let ne=!1;if(q.type==="annotated")ne=q.image?WK(q.image):!1;else{const me=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ui-${Date.now()}`;ne=mv({kind:"ui-element",id:me,label:q.payload.label||q.payload.tag||"element",path:q.payload.path||q.payload.tag||"element",text:q.payload.text||q.payload.label||q.payload.tag||"element",imageId:`img-${me}`},q.image)}ne?Co():ze({type:"warning",title:s("No Composer for this selection")})}),[X,s]),m.useEffect(()=>{g||f(u.url)},[u.url,g]),m.useEffect(()=>{const q=u.title.trim()||s("Browser");t.setTitle(q),t.updateParameters({...t.getParameters(),favicon:u.favicon})},[t,u.title,u.favicon,s]),m.useEffect(()=>{let q=0,ne=!1;document.getElementById("root"),jj();const me=()=>{if(ne)return;const ke=l&&t.isActive&&t.isVisible&&document.visibilityState==="visible",Me=ke?wS(N.current):null,ge=Me!==null&&(T.current||gS(Me,xS(document)));(A.current===void 0||!Xp(A.current,Me)||ge!==I.current)&&(A.current=Me,I.current=ge,window.electronAPI.browser.setViewport(X,e,Me,ge).then(h));const $=L.current?Me:null;Xp(V.current,$)||(V.current=$,fn.getState().setBrowserHole(`${X}:guest`,$));const W=ke&&z.current?wS(S.current):null,ue=W!==null&&gS(W,xS(document));(D.current===void 0||!Xp(D.current,W)||ue!==P.current)&&(fn.getState().setBrowserHole(`${X}:devtools`,W),D.current=W,P.current=ue,window.electronAPI.browser.setDevToolsViewport(X,e,W,ue).then(h)),q=requestAnimationFrame(me)};return q=requestAnimationFrame(me),()=>{ne=!0,cancelAnimationFrame(q);const{setBrowserHole:ke}=fn.getState();ke(`${X}:guest`,null),ke(`${X}:devtools`,null),V.current=null,A.current!==null&&(A.current=null,window.electronAPI.browser.setViewport(X,e,null)),D.current!==null&&(D.current=null,window.electronAPI.browser.setDevToolsViewport(X,e,null))}},[e,X,t,l]);const ee=async()=>{x(!1);const q=p.trim();if(!q)return;const ne=await window.electronAPI.browser.navigate(X,e,q);y(ne.ok?null:ne.error??s("Navigation failed"))},H=q=>{const ne=N.current,me=S.current;if(!ne||!me)return;q.currentTarget.setPointerCapture(q.pointerId);const ke=q.clientY,Me=ne.getBoundingClientRect().height,ge=me.getBoundingClientRect().height,$=Me+ge,W=Z=>{const J=Math.min($-bS,Math.max(bS,ge-(Z.clientY-ke)));w(J/$)},ue=()=>{window.removeEventListener("pointermove",W),window.removeEventListener("pointerup",ue)};window.addEventListener("pointermove",W),window.addEventListener("pointerup",ue)},Q="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:Q,disabled:u.locked||!u.canGoBack,onClick:()=>{window.electronAPI.browser.goBack(X)},"aria-label":s("Back"),children:i.jsx(cc,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:Q,disabled:u.locked||!u.canGoForward,onClick:()=>{window.electronAPI.browser.goForward(X)},"aria-label":s("Forward"),children:i.jsx(kj,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:Q,disabled:u.locked||!u.tabId,onClick:()=>{window.electronAPI.browser.reload(X)},"aria-label":s("Reload"),children:i.jsx(Kk,{className:U("h-3.5 w-3.5",u.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:q=>{q.preventDefault(),ee()},children:[i.jsx(go,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("input",{value:p,onChange:q=>f(q.target.value),onFocus:q=>{x(!0),q.target.select()},onBlur:()=>x(!1),placeholder:s("Enter a URL"),spellCheck:!1,disabled:u.locked,className:"min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground disabled:opacity-60"})]}),i.jsx(JY,{tabId:X,conversationId:e,active:u.designMode,disabled:!u.tabId||u.locked||u.devtoolsOpen,queueOpen:F.queueOpen,onQueueOpenChange:F.setQueueOpen,onToggleDesignMode:q=>{F.setDesignMode(q)},onOpenPinFromQueue:q=>{F.openPinFromQueue(q)},onSendQueue:F.sendQueue}),i.jsx("button",{type:"button",className:U(Q,u.devtoolsOpen&&"bg-muted text-foreground"),disabled:!u.tabId,onClick:()=>{window.electronAPI.browser.setDevTools(X,!u.devtoolsOpen).then(h)},"aria-label":s("Toggle Developer Tools"),"aria-pressed":u.devtoolsOpen,children:i.jsx(GN,{className:"h-3.5 w-3.5"})}),u.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(Sw,{className:"h-3 w-3"}),s("Enso is in control")]})]}),u.designMode&&i.jsx(XY,{drawing:F.drawing,pick:F.draftPick,markupTool:F.markupTool,editorOpen:F.openPin!==null,onMarkupToolChange:F.handleMarkupToolChange,onExit:()=>{F.setDesignMode(!1)}}),v&&i.jsx("div",{className:"border-b bg-destructive/10 px-3 py-1 text-xs text-destructive",children:v}),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col","data-slot":"browser-native-stack",children:[i.jsxs("div",{ref:N,className:U("relative min-h-0",u.devtoolsOpen?"shrink-0":"flex-1",O?"bg-transparent":"bg-background"),style:u.devtoolsOpen?{flex:`${1-b} 1 0`}:void 0,children:[i.jsx(YY,{active:u.designMode}),u.designMode&&i.jsx(QY,{tabId:X,conversationId:e,stageSize:C,draftPick:F.draftPick,openPin:F.openPin,markupTool:F.markupTool,warningShown:F.warningShown,onWarningShownChange:F.setWarningShown,onDraftPickChange:F.setDraftPick,onMoveSelection:q=>{F.moveSelection(q)},onCancelDraft:F.cancelDraft,onCloseOpenPin:F.closeOpenPin,onSendQueue:F.sendQueue,onStrokeStateChange:F.setMarkupStrokeActive,active:d}),!u.url.startsWith("http")&&!u.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(go,{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.")})]}),u.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(Sw,{className:"h-3.5 w-3.5"}),s("Take control")]})]})]}),u.devtoolsOpen&&i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:k,className:"h-1.5 shrink-0 cursor-row-resize bg-border hover:bg-ring",onPointerDown:H}),i.jsx("div",{ref:S,className:"min-h-0 bg-transparent",style:{flex:`${b} 1 0`}})]})]})]})}function hX({chatId:e,visible:t}){const{t:n}=se(),s=de(p=>p.browserTabs[e]),o=de(p=>p.browserTitles),r=de(p=>p.browserHolders),{openBrowserTab:a,selectBrowserTab:l,closeBrowserTab:c,setBrowserTitle:d}=de.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=>d(u,p),getParameters:()=>{},updateParameters:()=>{}}:null,[u,d]);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:U("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(go,{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:()=>{c(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(qD,{conversationId:_2(e),panelApi:h,active:t},h.id)]})}const pX=[[0,59],[0,23],[1,31],[1,12],[0,7]],rr=6e4,fX=60*rr,mX=5e4;function Jp(e,t,n){if(!/^\d+$/u.test(e))return;const s=Number(e);return s>=t&&s<=n?s:void 0}function gX(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 c=a===void 0?1:Jp(a,1,n);if(c===void 0)return;let d,u;if(r==="*")d=t,u=n;else{const[h,p,f]=r.split("-");if(f!==void 0)return;d=Jp(h,t,n),u=p===void 0?a===void 0?d:n:Jp(p,t,n)}if(d===void 0||u===void 0||d>u)return;for(let h=d;h<=u;h+=c)s.add(h)}return[...s].sort((o,r)=>o-r)}function Mh(e){const t=e.trim().split(/\s+/u);if(t.length!==5)return;const n=t.map((c,d)=>gX(c,...pX[d]));if(n.some(c=>c===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(c=>c%7))].sort((c,d)=>c-d),domStar:t[2].startsWith("*"),dowStar:t[4].startsWith("*")}}function xX(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 vX(e,t){let n=Math.floor(t/rr)*rr+rr;for(let s=0;s<mX;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(!xX(e,o))r=new Date(o.getFullYear(),o.getMonth(),o.getDate()+1).getTime();else if(!e.hour.includes(o.getHours()))r=n-o.getMinutes()*rr+fX;else if(!e.minute.includes(o.getMinutes()))r=n+rr;else return n;n=Math.max(r,n+rr)}}const Zp=e=>String(e).padStart(2,"0"),bX=["日","一","二","三","四","五","六"],wX=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function vv(e,t){const n=typeof e=="string"?Mh(e):e;if(!n)return String(e);const[s,o,r,a,l]=n.source.split(" "),c=t==="zh";if(a!=="*")return n.source;const d=/^\*\/(\d+)$/u.exec(s);if(o==="*"&&r==="*"&&l==="*"){if(s==="*")return c?"每分钟":"Every minute";if(d)return c?`每 ${d[1]} 分钟`:`Every ${d[1]} minutes`;if(n.minute.length===1&&/^\d+$/u.test(s)){const h=Zp(n.minute[0]);return c?`每小时 ${h} 分`:`Every hour at :${h}`}return n.source}if(!/^\d+$/u.test(s)||!/^\d+$/u.test(o))return n.source;const u=`${Zp(n.hour[0])}:${Zp(n.minute[0])}`;if(r==="*"&&l==="*")return c?`每天 ${u}`:`Every day at ${u}`;if(r==="*"&&l==="1-5")return c?`工作日 ${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 c?`每周${h.map(p=>bX[p]).join("、")} ${u}`:`Every ${h.map(p=>wX[p]).join(", ")} at ${u}`}if(l==="*"&&/^\d+$/u.test(r)){const h=n.dayOfMonth[0];return c?`每月 ${h} 日 ${u}`:`Monthly on day ${h} at ${u}`}return n.source}const yX=/[A-Za-z0-9._%+-]/,yS=/[A-Za-z0-9_-]/,SX=/```[\s\S]*?(?:```|$)|`[^`\n]*`/g;function YD(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 CX(e,t){if(typeof e!="string")return{ids:[],all:!1};const n=e.normalize("NFC").replace(SX,a=>" ".repeat(a.length)),s=[...t.map(a=>({key:Xd(a.name),id:a.id})),..._j.map(a=>({key:Xd(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&&yX.test(n[a-1]))continue;const l=s.find(({key:c})=>{const d=a+1+c.length;if(n.slice(a+1,d).toLowerCase()!==c)return!1;const u=n[d];return!(u&&yS.test(c.at(-1)??"")&&yS.test(u))});l&&(l.id===null?r=!0:o.includes(l.id)||o.push(l.id))}return{ids:o,all:r}}function kX(e,t){const n=YD(t),{ids:s,all:o}=CX(e,n);return o?{ids:[...new Set(n.map(r=>r.id))],all:o}:{ids:s,all:o}}function jX(e,t){const n=Xd(typeof e=="string"?e.replace(/^@/,""):"");return YD(t).filter(s=>Xd(s.name).startsWith(n))}function Jm(e,t){return/(?:^|\s)\$([^\s$]*)$/.exec(e.slice(0,t))?.[1]??null}function XD(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 _X(e,t,n){const s=n??t;if(s===null)return[];const o=s.toLowerCase();return XD(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 NX=500,TX=72,jl=28;function JD({phase:e,heldMs:t,cancelZone:n}){return e!=="recording"&&e!=="starting"?"none":n?"cancel":e==="starting"||t<NX?"too-short":"finish"}function SS(e,t){return e-t>=TX}function Rh(e,t){const n=[...e,t].slice(-jl);return n.length<jl?[...new Array(jl-n.length).fill(0),...n]:n}const DX=300,IX=12,EX=-50,PX=3;function ZD(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 AX(){let e=Number.POSITIVE_INFINITY;return t=>{const n=t.length/Jd*1e3,s=ZD(t);return e=Math.min(s,e+PX*n/1e3),s>Math.max(e+IX,EX)}}function MX(e){if(e===Jd)return r=>r;const t=e/Jd;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,c=[];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];c.push(h>u?p/(h-u):a[u-s]??0),o++}const d=Math.floor(o*t);return n=a.slice(d-s),s=d,Float32Array.from(c)}}function RX(e){return Math.min(1,Math.max(0,(ZD(e)+55)/45))}const LX=2e3;function OX(e=LX){const t=AX();let n=0,s=0;return o=>{const r=o.length/Jd*1e3;return t(o)?(n+=r,s=0):s+=r,n>=DX&&s>=e}}class QD extends Error{}let li=null;function Zm(){return(!li||li.state==="closed")&&(li=new AudioContext),li.state!=="running"&&li.resume().catch(()=>{}),li}async function zX(){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 CS(){const e=li;li=null,e?.close().catch(()=>{})}const Qp={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};async function GX(e){const t=navigator.mediaDevices;if(!e||e===N2)return t.getUserMedia({audio:Qp});try{return await t.getUserMedia({audio:{...Qp,deviceId:{exact:e}}})}catch(n){const s=n instanceof Error?n.name:"";if(s==="NotAllowedError"||s==="SecurityError")throw n;return t.getUserMedia({audio:Qp})}}const FX=5e3;async function HX(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 GX(t.deviceId),await Promise.race([r,new Promise((w,C)=>setTimeout(()=>C(new Error("audio context stayed suspended")),3e3))])}catch(w){for(const C of l?.getTracks()??[])C.stop();throw a(),w}const c=l.getTracks();if(s.state==="closed"){for(const w of c)w.stop();throw new Error("audio context closed")}const d=s.createMediaStreamSource(l),u=s.createScriptProcessor(4096,1,1),h=MX(s.sampleRate);let p=0,f=()=>{};const g=new Promise(w=>{f=w}),x=setTimeout(f,FX),v=()=>{clearTimeout(x),f()};u.onaudioprocess=w=>{const C=w.inputBuffer.getChannelData(0);for(let N=0;N<C.length;N++)p=Math.max(p,Math.abs(C[N]));p>0&&v(),t.onLevel?.(RX(C));const _=h(new Float32Array(C));_.length>0&&e(_)},d.connect(u),u.connect(s.destination);let y=!1;const b=()=>{if(!y){y=!0,v(),u.onaudioprocess=null,u.disconnect(),d.disconnect();for(const w of c)w.stop();a()}};return{live:g,cancel:b,stop:async()=>{if(b(),p===0)throw new QD("silent recording")}}}const eI="Microphone access denied. Allow it in system settings.",BX={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 tI(e){const t=e?.name;return t==="NotFoundError"||t==="OverconstrainedError"?"No microphone found.":t==="NotAllowedError"||t==="SecurityError"?eI:"Voice input failed."}function nI({startSession:e,requestMicAccess:t,onText:n}){const{t:s}=se(),[o,r]=m.useState("idle"),[a,l]=m.useState(0),[c,d]=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(!c)return;const _=setTimeout(()=>d(null),4e3);return()=>clearTimeout(_)},[c]);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 _=g.current,N=x.current;if(!(!_||!N)){g.current=null,r("transcribing");try{await _.stop();const S=await N.finish();S.ok?S.text?n(S.text):d(s("No speech detected.")):d(s(BX[S.error]))}catch(S){N.cancel(),d(s(S instanceof QD?eI:"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 _=setInterval(()=>l(N=>N+1),1e3);return()=>clearInterval(_)},[o]),m.useEffect(()=>{o==="recording"&&a>=T2&&w()},[a,w,o]),{phase:o,elapsed:a,error:c,setError:d,partial:u,correcting:p,start:async({autoStop:_=!1,...N}={})=>{if(d(null),!navigator.mediaDevices?.getUserMedia){d(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((P,T)=>{x.current===A&&(h(P),f(T))});k=A,x.current=A;const I=_?OX():null,D=await HX(P=>{A.push(P),I?.(P)&&x.current===A&&v.current()},N);if(S!==y.current){D.cancel();return}if(g.current=D,await D.live,S!==y.current)return;r("recording")}catch(A){if(S!==y.current)return;k?.cancel(),x.current=null,r("idle"),d(s(tI(A)))}},finish:w,cancel:b}}const VX=6,kS=8,$X=448;function WX(e,t){const n=Math.min($X,t.width*.8);return{left:Math.max(kS,Math.min(e.left,t.width-kS-n)),bottom:t.height-e.top+VX,maxWidth:n}}const jS=120,sI=12,UX=Array.from({length:sI},(e,t)=>`bar-${t}`),_S=Rh([],0),KX=300;function NS(e){const t=e.getBoundingClientRect();return WX(t,{width:window.innerWidth,height:window.innerHeight})}function iI({anchor:e,status:t,children:n}){const[s,o]=m.useState(()=>NS(e));return m.useLayoutEffect(()=>{let r=0;const a=()=>{const l=NS(e);o(c=>c.left===l.left&&c.bottom===l.bottom&&c.maxWidth===l.maxWidth?c:l),r=requestAnimationFrame(a)};return a(),()=>cancelAnimationFrame(r)},[e]),Us.createPortal(i.jsx("p",{role:t?"status":void 0,"aria-live":"polite","data-testid":t?void 0:"voice-partial",style:{position:"fixed",...s,zIndex:Cn.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 Qm="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 oI({startSession:e,requestMicAccess:t,disabled:n,holdBinding:s,holdScope:o,onText:r}){const{t:a}=se(),{phase:l,elapsed:c,error:d,setError:u,partial:h,correcting:p,start:f,finish:g,cancel:x}=nI({startSession:e,requestMicAccess:t,onText:r}),v=m.useRef(null),[y,b]=m.useState(_S),w=ye(k=>k.voiceInputDevice),C=(k=!1)=>(b(_S),f({autoStop:k,deviceId:w,onLevel:A=>b(I=>Rh(I,A))})),_=m.useRef({phase:l,start:C,finish:g,cancel:x});_.current={phase:l,start:C,finish:g,cancel:x},m.useEffect(()=>{if(!s||n)return;let k=null,A;const I=()=>{clearTimeout(A),A=void 0},D=()=>{A!==void 0&&(I(),s==="space"&&document.execCommand("insertText",!1," "))},P=()=>{if(I(),k===null)return;const O=_.current,L=JD({phase:O.phase,heldMs:performance.now()-k,cancelZone:!1});k=null,L==="finish"?O.finish():L!=="none"&&O.cancel(),L==="too-short"&&u(a("Speech was too short."))},T=O=>{if(O.isComposing||O.keyCode===229)return;if(Al(O,{allowBare:!0})!==s){D();return}const L=o.current;if(!L||!(O.target instanceof Node)||!L.contains(O.target))return;const V=k===null&&A===void 0;V&&(O.repeat||_.current.phase!=="idle")||(O.preventDefault(),k!==null&&O.stopPropagation(),V&&(A=setTimeout(()=>{A=void 0,k=performance.now(),_.current.start()},KX)))},z=O=>{k===null&&!A||!D2(s,O)||(O.preventDefault(),D(),P())};return window.addEventListener("keydown",T,!0),window.addEventListener("keyup",z,!0),window.addEventListener("blur",P),()=>{window.removeEventListener("keydown",T,!0),window.removeEventListener("keyup",z,!0),window.removeEventListener("blur",P),I(),k!==null&&_.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>jS?`…${h.slice(-jS)}`: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:UX.map((k,A)=>i.jsx("span",{className:"w-[2px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:3+y[jl-sI+A]*11}},k))}),i.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(c/60),":",String(c%60).padStart(2,"0")]}),i.jsx(uc,{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:Qm,children:i.jsx(ln,{className:"h-3.5 w-3.5"})})]}):i.jsx("button",{type:"button",disabled:n||l!=="idle",onClick:()=>{C(!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:Qm,children:l==="idle"?i.jsx(Nj,{className:"h-3.5 w-3.5"}):i.jsx(gr,{className:"h-3.5 w-3.5"})}),v.current&&(d||h)?i.jsx(iI,{anchor:v.current,status:!!d,children:d??(p?i.jsxs("span",{className:"flex items-start gap-1.5",children:[i.jsx(gr,{"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 rI=["agents","members","chats"];function qX(e){return[...rI.flatMap(t=>e[t].map(n=>({candidate:n,group:t}))),...e.files.map(t=>({candidate:t,group:"files"}))]}function aI(e,t){const n=rI.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"}))]:qX(e).map(s=>({type:"item",candidate:s.candidate,group:s.group}))}const YX=20;function XX(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,YX).map(s=>({kind:"chat",id:s.id,label:s.title.split(`
|
|
75
|
-
`)[0].trim()||"Untitled chat",sessionFile:s.sessionFile}))}function JX(e){return e.map(t=>({...t,kind:"agent-type",id:t.typeKey,label:t.displayName}))}function ZX(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 QX(e,t,n,s=[]){const o=e.trim().toLocaleLowerCase(),r=o?t.filter(c=>`${c.label}
|
|
76
|
-
${c.description}
|
|
77
|
-
${c.source}
|
|
78
|
-
${c.typeKey}`.toLocaleLowerCase().includes(o)):[...t],a=o?n.filter(c=>`${c.label}
|
|
79
|
-
${c.relativePath}`.toLocaleLowerCase().includes(o)):[...n],l=o?s.filter(c=>c.label.toLocaleLowerCase().includes(o)):[...s];return{agents:r.filter(c=>c.source!=="bot"),members:r.filter(c=>c.source==="bot"),files:a,chats:l}}function lI(e,t,n=[],s={}){const[o,r]=m.useState([]),[a,l]=m.useState([]),c=t!==null,{searchFiles:d,agents:u=!0}=s;return m.useEffect(()=>{if(!c||!u)return;r([]);let h=!1;return window.electronAPI.agentRegistry.list().then(p=>{const f=Tj(p);h||r(f?JX(f.candidates):[])}).catch(()=>{h||r([])}),()=>{h=!0}},[c,u]),m.useEffect(()=>{if(t===null||!e&&!d){l([]);return}let h=!1;const p=window.setTimeout(()=>{(d?d(t):window.electronAPI.files.search(e,t)).then(f=>{h||l(ZX(f))}).catch(()=>{h||l([])})},150);return()=>{h=!0,window.clearTimeout(p)}},[e,t,d]),m.useMemo(()=>t===null?{agents:[],members:[],files:[],chats:[]}:QX(t,o,a,n),[o,a,n,t])}const TS={bot:"Mention a member",all:"Mention a member",chat:"Reference a chat",file:"Files",skill:"Skills"},eJ=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 tJ({chatId:e,placeholder:t,members:n,chatOptions:s=[],skills:o=[],running:r,disabled:a=!1,toolbar:l,hint:c,voice:d,requestMicAccess:u,onSend:h,onStop:p}){const{t:f}=se(),g=m.useRef(null),x=m.useRef(null),v=m.useRef(null),y=m.useRef(!1),[b,w]=m.useState(()=>N0(localStorage,e)),[C,_]=m.useState([]),[N,S]=m.useState(null),[k,A]=m.useState(0),[I,D]=m.useState(!1),P=ye(Z=>Z.keybindings),{"voice-hold":T,"send-message":z}=Oi(P),{text:O}=b,L=Z=>w(J=>({...J,...Z}));m.useEffect(()=>{x.current?.focus()},[]),m.useEffect(()=>{I2(localStorage,e,b)},[e,b]),m.useEffect(()=>E2(Z=>{Z===e&&w(N0(localStorage,Z))}),[e]),m.useLayoutEffect(()=>{const Z=x.current;Z&&(Z.style.height="auto",Z.style.height=`${Math.min(Z.scrollHeight,220)}px`)},[O]);const V=m.useCallback(Z=>window.electronAPI.bots.searchFiles({chatId:e,query:Z}).then(J=>J.ok?J.files:[]),[e]),X=lI(void 0,N?.kind==="at"?N.query:null,[],{searchFiles:V,agents:!1}).files,F=(()=>{if(!N)return[];const Z=N.query.toLowerCase();if(N.kind==="skill")return o.filter(ae=>ae.name.toLowerCase().includes(Z)).slice(0,10).map(ae=>({kind:"skill",skill:ae}));const J=n?jX(N.query,n).map(ae=>({kind:"bot",bot:ae})):[];return n&&_j.some(ae=>ae.startsWith(Z))&&J.push({kind:"all"}),b.chats.length<P2&&J.push(...s.filter(ae=>!b.chats.includes(ae.id)&&ae.title.toLowerCase().includes(Z)).slice(0,6).map(ae=>({kind:"chat",chat:ae}))),J.push(...X.slice(0,8).map(ae=>({kind:"file",path:ae.relativePath,name:ae.label}))),J})(),ee=(Z,J)=>{const ae=o.length?Jm(Z,J):null;if(ae!==null){S({kind:"skill",start:J-ae.length-1,query:ae}),A(0);return}const te=/(^|[^A-Za-z0-9._%+-])@([^\s@]*)$/u.exec(Z.slice(0,J));if(!te)return S(null);S({kind:"at",start:J-te[2].length-1,query:te[2]}),A(0)},H=Z=>{if(!N)return;const J=x.current,ae=J?.selectionStart??O.length,te=O.slice(0,N.start),pe=O.slice(ae);let Te="";const $e={};Z.kind==="bot"||Z.kind==="all"?Te=`@${Z.kind==="all"?f("everyone"):Z.bot.name} `:Z.kind==="file"?(Te=`@${Z.path} `,$e.files=[...new Set([...b.files,Z.path])]):Z.kind==="chat"?$e.chats=[...b.chats,Z.chat.id]:$e.skill=Z.skill.id,L({...$e,text:te+Te+pe}),S(null);const Ie=te.length+Te.length;requestAnimationFrame(()=>{J?.focus(),J?.setSelectionRange(Ie,Ie)})},Q=Z=>{const J=x.current,ae=J?.selectionStart??O.length,te=J?.selectionEnd??O.length;L({text:O.slice(0,ae)+Z+O.slice(te)}),requestAnimationFrame(()=>{J?.focus(),J?.setSelectionRange(ae+Z.length,ae+Z.length)})},q=Z=>{for(const J of Z){if(!J.type.startsWith("image/"))continue;const ae=new FileReader;ae.onload=()=>{const te=ae.result;_(pe=>[...pe,{data:te.slice(te.indexOf(",")+1),mimeType:J.type}])},ae.readAsDataURL(J)}},ne=Z=>{const J=x.current,ae=J?.selectionStart??O.length,te=J?.selectionEnd??O.length;window.electronAPI.bots.savePastedText({chatId:e,text:Z}).catch(()=>({ok:!1,error:"unavailable"})).then(pe=>{const Te=pe.ok?`@${pe.path} `:Z;w($e=>({...$e,text:$e.text.slice(0,ae)+Te+$e.text.slice(te)})),requestAnimationFrame(()=>{J?.focus(),J?.setSelectionRange(ae+Te.length,ae+Te.length)})})},me=new Map(s.map(Z=>[Z.id,Z])),ke=b.skill?o.find(Z=>Z.id===b.skill||Z.name===b.skill):void 0,Me=ke&&n?n.filter(Z=>kX(O,n).ids.includes(Z.id)&&!ke.owners.includes(Z.id)):[],ge=!a&&!I&&(O.trim().length>0||C.length>0||b.chats.length>0||!!b.skill),$=async()=>{if(!ge)return;const Z=b,J=C,ae=Z.text.trim();w(A2),_([]),S(null),D(!0);try{await h({text:ae,images:J,files:Z.files.filter(pe=>ae.includes(`@${pe}`)),chats:Z.chats,...Z.skill?{skill:ke?.id??Z.skill}:{}})||(w(pe=>pe.text||pe.chats.length||pe.skill?pe:Z),_(pe=>pe.length?pe:J))}finally{D(!1)}},W=Z=>{const J=Z.nativeEvent.isComposing||y.current;if(N&&F.length>0&&!J){if(Z.key==="ArrowDown"||Z.key==="ArrowUp"){Z.preventDefault();const ae=Z.key==="ArrowDown"?1:-1;A(te=>(te+ae+F.length)%F.length);return}if(Z.key==="Enter"||Z.key==="Tab"){Z.preventDefault(),H(F[Math.min(k,F.length-1)]);return}if(Z.key==="Escape"){Z.preventDefault(),S(null);return}}!J&&Ij(Z,z)&&(Z.preventDefault(),$())},ue=Z=>(n??[]).filter(J=>Z.includes(J.id)).map(J=>J.name).join(", ");return i.jsxs("div",{ref:g,"data-slot":"composer",className:"relative rounded-2xl border bg-background shadow-float",onDragOver:Z=>Z.preventDefault(),onDrop:Z=>{Z.preventDefault(),q([...Z.dataTransfer.files])},children:[N&&F.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:F.map((Z,J)=>{const ae=TS[Z.kind],te=J===0||TS[F[J-1].kind]!==ae;return i.jsxs("div",{children:[te&&i.jsx("div",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:f(ae)}),i.jsx("button",{type:"button",onMouseDown:pe=>{pe.preventDefault(),H(Z)},onMouseEnter:()=>A(J),className:U("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",J===k&&"bg-muted"),children:i.jsx(nJ,{item:Z,ownerNames:ue,grouped:!!n})})]},eJ(Z))})}),(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(DS,{icon:i.jsx(ti,{className:"h-3 w-3"}),label:ke?.name??b.skill,tone:"skill",onRemove:()=>L({skill:void 0})}),b.chats.map(Z=>i.jsx(DS,{icon:i.jsx(pa,{className:"h-3 w-3"}),label:me.get(Z)?.title??f("Unavailable chat"),onRemove:()=>L({chats:b.chats.filter(J=>J!==Z)})},Z))]}),Me.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:Me.map(Z=>Z.name).join(", ")})}),C.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:C.map((Z,J)=>i.jsxs("div",{className:"group relative h-14 w-14 overflow-hidden rounded-lg border",children:[i.jsx("img",{src:`data:${Z.mimeType};base64,${Z.data}`,alt:"",className:"h-full w-full object-cover"}),i.jsx("button",{type:"button","aria-label":f("Remove"),onClick:()=>_(ae=>ae.filter((te,pe)=>pe!==J)),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"})})]},J))}),i.jsx("textarea",{ref:x,value:O,rows:1,disabled:a,placeholder:t,onChange:Z=>{L({text:Z.target.value}),ee(Z.target.value,Z.target.selectionStart)},onSelect:Z=>ee(Z.currentTarget.value,Z.currentTarget.selectionStart),onBlur:()=>S(null),onKeyDown:W,onCompositionStart:()=>{y.current=!0},onCompositionEnd:()=>{y.current=!1},onPaste:Z=>{const J=[...Z.clipboardData.files].filter(ae=>ae.type.startsWith("image/"));if(J.length===0){const ae=Z.clipboardData.getData("text/plain");if(!Dj(ae))return;Z.preventDefault(),ne(ae);return}Z.preventDefault(),q(J)},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(Ch,{className:"h-4 w-4"})}),i.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:Z=>{q([...Z.target.files??[]]),Z.target.value=""}}),d&&i.jsx(oI,{startSession:d,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:c}),r&&p&&!ge?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(uc,{className:"h-3 w-3 fill-current"})}):i.jsx("button",{type:"button",disabled:!ge,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(dc,{className:"h-4 w-4"})})]})]})}function nJ({item:e,ownerNames:t,grouped:n}){const{t:s}=se();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(pa,{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(So,{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(ti,{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 DS({icon:e,label:t,tone:n,onRemove:s}){const{t:o}=se();return i.jsxs("span",{className:U("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 sJ={thinking:"Thinking",typing:"Writing reply",tool:"Calling tools",retrying:"Retrying"},IS={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"},iJ={running:"Running",done:"Done",error:"Error",denied:"Denied",timeout:"Timed out · denied"},oJ={running:"text-primary",done:"text-success",error:"text-destructive",denied:"text-warning",timeout:"text-warning"},rJ=e=>e<1e4?`${(Math.max(0,e)/1e3).toFixed(1)}s`:xo(e);function cI({conversationId:e,leading:t,trailing:n,className:s}){const{t:o}=se(),r=de(p=>e?p.sessions[e]:void 0),a=de(p=>e?p.queue.find(f=>f.conversationId===e):void 0),l=m.useMemo(()=>M2(r,!!a),[r,a]),c=!!(l&&l.state!=="queued"),[d,u]=m.useState(()=>Date.now());m.useEffect(()=>{if(!c)return;u(Date.now());const p=window.setInterval(()=>u(Date.now()),1e3);return()=>window.clearInterval(p)},[c]);const h=l?l.state!=="queued"?o(sJ[l.state]):o(a?.reason&&Object.hasOwn(IS,a.reason)?IS[a.reason]:"Queued"):null;return i.jsxs("div",{className:U("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}),c&&l?.startedAt!==void 0&&i.jsx("span",{className:"shrink-0 tabular-nums",children:xo(d-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?d-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:Fo(p.name,o)}),p.detail&&i.jsx("span",{className:"truncate font-mono",children:p.detail}),i.jsx("span",{className:U("shrink-0",oJ[p.status]),children:o(p.status==="timeout"&&p.name==="ask_user"?"Timed out · no answer":iJ[p.status])}),f!==void 0&&i.jsx("span",{className:"shrink-0 tabular-nums",children:rJ(f)})]},p.id)})]})]})}const aJ=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),lJ=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),cJ=[],dJ={auto:"Automatic",delegator:"By delegator",human:"Manual"};function Lh({state:e,interrupted:t,autoRetry:n}){const{t:s}=se();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:U("rounded px-1.5 text-[11px]",o),children:r[e]??e})}function dI({check:e,className:t}){const{t:n}=se();return i.jsxs("div",{className:U("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:U("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 Ic(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 uJ(e,t){window.electronAPI.bots.cancelDelegation(e).then(n=>{n.ok||ze({type:"error",title:t("Cancel failed"),description:n.error}),de.getState().refreshDelegations()})}function _l(e,t,n){window.electronAPI.bots.retryDelegation(e,n).then(s=>{s.ok?s.warning&&ze({type:"warning",title:s.warning}):ze({type:"error",title:t("Retry failed"),description:s.error}),de.getState().refreshDelegations()})}function Oh(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 hJ({record:e,delegations:t}){const{t:n}=se(),s=L2(e);if(!s)return null;const o=Aj(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:O2(e)?n("Retrying automatically · attempt {{n}}",{n:o}):n("Retry #{{n}} · {{source}}",{n:o,source:n(dJ[s])})})}function zh({record:e,entry:t,retried:n,append:s,taskSeq:o,fill:r,bots:a,onOpenConversation:l}){const{t:c}=se(),d=de(z=>z.delegations)??cJ,u=e?.state??t?.state??"queued",h=Oh(!s&&Ml(u)),p=a.get(e?.parentBotId??t?.from??""),f=a.get(e?.targetBotId??t?.to??""),g=z2(s?"completed":u),x=R2(e),v=!s&&x&&Ml(u),y=!s&&u==="blocked"?e?.blocked:void 0,b=de(z=>y&&e?.taskId?z.delegations.some(O=>O.taskId===e.taskId&&O.createdAt>e.createdAt):!1),w=de(z=>z.openTask),C=!!t?.taskId&&!s,[_,N]=m.useState(!C),S=e?Ej(e,d):!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:Ic(e,c):t?.summary,I=c("{{from}} → {{to}} · Delegation",{from:p?.name??c("Deleted member"),to:f?.name??c("Deleted member")}),D=i.jsxs(i.Fragment,{children:[C&&i.jsx(un,{"aria-hidden":!0,className:U("size-3.5 shrink-0 transition-transform",_&&"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??c("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??c("Deleted member")}),i.jsxs("span",{children:["· ",c("Delegation")]}),s?i.jsx("span",{className:"rounded bg-info/15 px-1.5 text-[11px] text-info",children:o===void 0?c("Merged into the current run"):c("Merged into the current run of #{{n}}",{n:o})}):v?i.jsx(Pj,{info:x}):i.jsx(Lh,{state:u,interrupted:e?.failure==="interrupted",autoRetry:S}),e&&!s&&i.jsx(hJ,{record:e,delegations:d}),e&&!s&&i.jsx("span",{children:xo((e.finishedAt??h)-e.createdAt)}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:aJ(s?.at??t?.at??e?.createdAt??h)})]}),P="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:U("rounded-xl border bg-card px-3 py-2.5",r?"w-full min-w-0":"max-w-lg"),children:[C?i.jsx("button",{type:"button","aria-expanded":_,"aria-label":c(_?"Collapse delegation result":"Expand delegation result"),className:U(P,"w-full rounded text-left hover:text-foreground"),onClick:()=>N(z=>!z),children:D}):i.jsx("div",{className:P,children:D}),!_&&T&&i.jsx("div",{className:"mt-1 truncate text-muted-foreground text-xs",children:T}),_&&T&&i.jsx("div",{className:"mt-1.5 line-clamp-3 text-sm [overflow-wrap:anywhere]",children:T}),_&&i.jsxs(i.Fragment,{children:[e?.check&&!s&&i.jsx(dI,{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:c("Blocked · needs: {{need}}",{need:y.need})}),i.jsx("div",{className:"text-muted-foreground",children:b?c("Answered; the work continues"):y.waitFor==="parent"?c("Waiting for {{name}} to reply",{name:p?.name??c("Deleted member")}):c("Waiting for your reply")})]}),S&&e?.autoRetryAt!==void 0&&i.jsx("div",{className:"mt-1 text-warning-foreground text-xs dark:text-warning",children:c("Retrying automatically at {{time}} (attempt {{n}})",{time:lJ(e.autoRetryAt),n:Aj(e,d)+1})}),k&&i.jsx("button",{type:"button",onClick:()=>de.getState().focusSeq(k.chatId,k.seq),className:"mt-1.5 text-muted-foreground text-xs underline-offset-2 hover:text-foreground hover:underline",children:c("Result posted to the group · View")}),e&&i.jsxs("div",{className:"mt-2 flex flex-wrap justify-end gap-1.5",children:[i.jsx(xe,{size:"xs",variant:"ghost",onClick:()=>l(e.childConversationId,I),children:c("View process")}),y&&!b&&e.chatId&&e.taskId&&i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>e.chatId&&e.taskId&&w(e.chatId,e.taskId),children:c("Reply")}),g.cancel&&i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>uJ(e.id,c),children:c("Cancel")}),g.retry&&!n&&i.jsx(xe,{size:"xs",variant:"outline",title:S?c("Skip the wait and retry now. The scheduled automatic retry is canceled."):void 0,onClick:()=>_l(e.id,c),children:c(S?"Retry now":"Retry")}),g.resumeOrRestart&&!n&&i.jsxs(i.Fragment,{children:[i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>_l(e.id,c,"resume"),children:c("Continue")}),i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>_l(e.id,c,"restart"),children:c("Start over")})]})]})]})]})}function uI(e){const t=de(d=>d.chats.find(u=>u.id===e)),n=de(d=>d.sessions),s=de(d=>d.queue),o=de(d=>d.silences),r=de(d=>d.delegations),a=de(d=>d.browserHolders),l=de(d=>d.browserTabs[t?.parentId??e]?.tabs),c=de(d=>F2(d.timelines[e]?.entries??[]));return m.useMemo(()=>({chat:t??{id:e,sessions:{}},delegations:r,sessions:n,queue:s,silences:o,clearedAt:c,holders:a,tabIds:l??[]}),[t,e,r,n,s,o,c,a,l])}function pJ(e,t){const n=uI(e);return m.useMemo(()=>G2(t,n),[t,n])}function fJ(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 hI(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 Fa({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 pI({info:e,bot:t}){const{t:n}=se(),s=de(c=>e.delegation?c.bots.find(d=>d.id===e.delegation?.parentBotId):void 0),o=e.delegation,r=fJ(e,n),a=de(c=>e.browserTab?c.browserTitles[e.browserTab]||n("Browser"):void 0),l=e.wait&&"conversationId"in e.wait?e.wait.conversationId:void 0;return i.jsxs(xD,{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(Pj,{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(Fa,{label:n("Task"),children:i.jsx("span",{className:"line-clamp-2",children:o.task})}),i.jsx(Fa,{label:n("From"),children:s?.name??n("Deleted member")}),i.jsx(Fa,{label:n("Time"),children:xo((o.finishedAt??Date.now())-o.createdAt)})]}),r&&i.jsx(Fa,{label:n("Waiting on"),children:r}),a&&i.jsx(Fa,{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:xo(Date.now()-e.quietSince)})}),o&&e.state==="stuck"&&o.state==="failed"&&i.jsx("div",{className:"text-muted-foreground",children:Ic(o,n)}),o&&e.state==="done"&&o.result&&i.jsx("div",{className:"line-clamp-3 text-muted-foreground",children:o.result}),l&&i.jsx(xe,{size:"xs",className:"mt-1 self-start",onClick:()=>hI(l),children:n("Go handle it")})]})]})}function fI({chatId:e,botId:t,bot:n,size:s="sm"}){const{t:o}=se(),r=pJ(e,t);return i.jsxs(pv,{children:[i.jsxs(fv,{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:Rf(r,o)})]}),i.jsx(pI,{info:r,bot:n})]})}function mJ({chatId:e,memberIds:t,bots:n,onOpenLive:s}){const{t:o}=se(),r=uI(e),a=m.useMemo(()=>H2(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:c})=>{const d=n.get(l),u=d?.name??o("Deleted member"),h=B2(c),p=V2(c);return i.jsxs(pv,{children:[i.jsxs(fv,{render:i.jsx("button",{type:"button",onClick:()=>p?.kind==="pending"?hI(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:d,size:"xs",presence:c.state}),h?i.jsx("span",{className:"max-w-56 truncate pr-1.5",children:[u,Rf(c,o),h].join(" · ")}):i.jsx("span",{className:"sr-only",children:`${u} · ${Rf(c,o)}`})]}),i.jsx(pI,{info:c,bot:d})]},l)})})}const mI=[137,80,78,71,13,10,26,10];function ga(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}let ed=null;function gJ(e){if(!ed){ed=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;ed[n]=s>>>0}}let t=4294967295;for(const n of e)t=ed[(t^n)&255]^t>>>8;return(t^4294967295)>>>0}function gI(e){return mI.every((t,n)=>e[n]===t)?"png":e[0]===255&&e[1]===216&&e[2]===255?"jpeg":ga(e.subarray(0,4))==="RIFF"&&ga(e.subarray(8,12))==="WEBP"?"webp":null}function xI(e){if(gI(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=ga(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 vI=e=>{if(e.type!=="tEXt")return null;const t=e.data.indexOf(0);return t>0?ga(e.data.subarray(0,t)):null};function ES(e,t){const n=xI(e)?.find(s=>vI(s)===t);return n?ga(n.data.subarray(t.length+1)):null}function PS(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,gJ(n.subarray(4,8+t.length))),n}function xJ(e,t,n,s=[]){const o=xI(e);if(!o)return null;const r=new Set([t,...s]),a=o.filter(h=>{const p=vI(h);return h.type!=="IEND"&&!(p&&r.has(p))}),l=Uint8Array.from(`${t}\0${n}`,h=>h.charCodeAt(0)&255),c=[Uint8Array.from(mI),...a.map(h=>h.raw),PS("tEXt",l),PS("IEND",new Uint8Array)],d=new Uint8Array(c.reduce((h,p)=>h+p.length,0));let u=0;for(const h of c)d.set(h,u),u+=h.length;return d}function vJ(e){return btoa(ga(new TextEncoder().encode(e)))}function bJ(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 wJ(e){return{budgetCost:e?.dailyCostUsd!==void 0?String(e.dailyCostUsd):"",budgetTokens:e?.dailyTokens!==void 0?String(e.dailyTokens):""}}function bI(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 yJ(e){return{delegationTimeout:e.delegationTimeoutMinutes!==void 0?String(e.delegationTimeoutMinutes):"",maxTurnTokens:e.maxTokensPerTurn!==void 0?String(e.maxTokensPerTurn):""}}function bv(e){const t=e.delegationTimeout.trim()?Number(e.delegationTimeout):null,n=e.maxTurnTokens.trim()?Number(e.maxTurnTokens):null;return t!==null&&!$2(t)||n!==null&&!W2(n)?{ok:!1}:{ok:!0,delegationTimeoutMinutes:t,maxTokensPerTurn:n}}function AS(e){return[...e.normalize("NFC").trim().replace(/\s+/gu,"_").replace(/[^\p{L}\p{N}_-]/gu,"").replace(/_+/gu,"_").replace(/^_+|_+$/gu,"")].slice(0,K2).join("")}const Ao=e=>typeof e=="string"?e.trim():"",ef=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function MS(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 SJ(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 CJ(e){return{...typeof e.title=="string"?{title:e.title.trim()}:{},...Ao(e.scope)?{scope:Ao(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}:{},...U2.includes(e.approvalMode)?{approvalMode:e.approvalMode}:{},...typeof e.memory=="boolean"?{memoryEnabled:e.memory}:{}}}function kJ(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=ef(n.data)?n.data:n,o=Ao(s.name);if(!o)return{ok:!1,error:"not-a-card"};const r=ef(s.extensions)?s.extensions.enso:void 0;if(ef(r)){const d=typeof s.description=="string"?s.description:"";return{ok:!0,draft:{name:AS(o),title:"",scope:MS(d),persona:d,...CJ(r)}}}const a=d=>d.replace(/\{\{char\}\}/giu,o).replace(/\{\{user\}\}/giu,"the user"),l=a(Ao(s.description)),c=[l,Ao(s.personality)&&`Personality: ${a(Ao(s.personality))}`,Ao(s.scenario)&&`Scenario: ${a(Ao(s.scenario))}`].filter(Boolean);return{ok:!0,draft:{name:AS(o),title:"",scope:MS(l),persona:c.join(`
|
|
81
|
-
|
|
82
|
-
`)}}}const Pr=256,RS=4;function wI({hasImage:e,nested:t=!1,disabled:n=!1,onPick:s,onRemove:o}){const{t:r}=se(),a=m.useRef(null),[l,c]=m.useState(null);return i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[i.jsxs(xe,{size:"xs",variant:"outline",disabled:n,onClick:()=>a.current?.click(),children:[i.jsx(Ch,{}),r("Upload avatar")]}),e&&i.jsxs(xe,{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:d=>{const u=d.target.files?.[0];d.target.value="",u&&q2(u).then(c,()=>ze({type:"error",title:r("This image cannot be used as an avatar.")}))}}),i.jsx(jJ,{source:l,nested:t,onCancel:()=>c(null),onDone:d=>{c(null),s(d)}})]})}function jJ({source:e,nested:t=!1,onCancel:n,onDone:s}){const{t:o}=se(),r=m.useRef(null),a=m.useRef(null),[l,c]=m.useState(null),[d,u]=m.useState({zoom:1,x:0,y:0});m.useEffect(()=>{c(null),u({zoom:1,x:0,y:0})},[e]);const h=v=>l?Pr/Math.min(l.w,l.h)*v:1,p=v=>{if(!l)return v;const y=h(v.zoom),b=(l.w*y-Pr)/2,w=(l.h*y-Pr)/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(RS,v))})),g=()=>{const v=r.current;if(!v||!l)return;const y=h(d.zoom),b=Pr/y;s(X2(v,l.w/2-b/2-d.x/y,l.h/2-b/2-d.y/y,b))},x=h(d.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:Pr,height:Pr},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(d.zoom*(v.deltaY<0?1.1:1/1.1)),children:[e&&i.jsx("img",{ref:r,src:e,alt:"",draggable:!1,onLoad:v=>c({w:v.currentTarget.naturalWidth,h:v.currentTarget.naturalHeight}),onError:()=>{ze({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(${d.x}px, ${d.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(Y2,{min:1,max:RS,step:.01,value:d.zoom,"aria-label":o("Zoom"),onValueChange:v=>f(Array.isArray(v)?v[0]:v)})]}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(xe,{size:"sm",disabled:!l,onClick:g,children:o("Use this avatar")})]})]})})}const _J=["tools","approvalMode","skillIds","mcpServerIds","canDelegateTo","acceptFrom"],NJ=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every(n=>t.includes(n)):e===t;function LS(e,t){return _J.flatMap(n=>{const s=t[n];return!s||NJ(e[n],s.value)?[]:[{field:n,from:e[n],to:s.value,reason:s.reason}]})}function TJ(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 yI={tools:"all",approvalMode:"auto-edits",skillIds:[],mcpServerIds:[],canDelegateTo:"any",acceptFrom:"any",memoryEnabled:!0,budgetCost:"",budgetTokens:"",delegationTimeout:"",maxTurnTokens:""};function SI({value:e,onChange:t,profile:n,botId:s,zIndex:o}){const{t:r}=se(),l=de(c=>c.bots).filter(c=>c.id!==s&&!c.archivedAt);return i.jsxs("div",{className:"space-y-4",children:[i.jsx(DJ,{value:e,onApply:t,profile:n,botId:s}),i.jsxs("div",{children:[i.jsx(qt,{children:r("Tools")}),i.jsx(Lg,{value:e.tools,options:[{value:"all",label:r("All tools")},{value:"readonly",label:r("Read-only")}],onChange:c=>t({tools:c})})]}),i.jsxs("div",{children:[i.jsx(qt,{children:r("Approval mode")}),i.jsx(Mj,{value:e.approvalMode,onChange:c=>t({approvalMode:c}),zIndex:o})]}),i.jsx(CI,{value:e,onChange:t}),i.jsx(OS,{label:r("Can delegate to"),value:e.canDelegateTo,bots:l,onChange:c=>t({canDelegateTo:c})}),i.jsx(OS,{label:r("Accepts delegation from"),value:e.acceptFrom,bots:l,onChange:c=>t({acceptFrom:c})}),i.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[i.jsx("span",{children:r("Long-term memory")}),i.jsx(di,{checked:e.memoryEnabled,onCheckedChange:c=>t({memoryEnabled:c})})]}),i.jsxs("div",{children:[i.jsx(qt,{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:c=>t({budgetCost:c.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:c=>t({budgetTokens:c.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(qt,{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:c=>t({maxTurnTokens:c.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(qt,{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:c=>t({delegationTimeout:c.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 Gh(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 DJ({value:e,onApply:t,profile:n,botId:s}){const{t:o,locale:r}=se(),[a,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState([]),p=c?LS(e,c):[],f=async()=>{if(![n.name,n.title,n.scope,n.persona].some(x=>x.trim())){ze({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){ze({type:"error",title:Gh(x,o),...x.detail?{description:x.detail}:{}});return}if(LS(e,x.suggestion).length===0){ze({type:"info",title:o("Current abilities already match the suggestion.")});return}h([]),d(x.suggestion)}finally{l(!1)}},g=()=>{const x=p.map(y=>y.field).filter(y=>!u.includes(y)),v=TJ(e,p,x);t(Object.fromEntries(x.map(y=>[y,v[y]]))),d(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(xe,{size:"xs",variant:"outline",disabled:a,onClick:()=>{f()},children:[a?i.jsx(Yt,{className:"animate-spin"}):i.jsx(ti,{}),o("Auto-configure abilities")]})]}),c&&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(hc,{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:IJ(x.field,o)}),i.jsx(EJ,{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(xe,{size:"xs",variant:"outline",onClick:()=>d(null),children:o("Cancel")}),i.jsx(xe,{size:"xs",disabled:p.every(x=>u.includes(x.field)),onClick:g,children:o("Apply")})]})]})]})}function IJ(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 EJ({change:e}){const{t}=se(),n=ye(p=>p.skills),s=ye(p=>p.mcpServers),o=de(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(Rl[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,c=e.from,d=e.to;if(c==="any"||d==="any"){const p=f=>f==="any"?t("All members"):f.length===0?t("None selected"):f.map(l).join(", ");return r(p(c),p(d))}const u=d.filter(p=>!c.includes(p)),h=c.filter(p=>!d.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 CI({value:e,onChange:t}){const{t:n}=se(),s=ye(a=>a.skills),o=ye(a=>a.mcpServers),r=(a,l)=>a.includes(l)?a.filter(c=>c!==l):[...a,l];return i.jsxs(i.Fragment,{children:[i.jsx(T0,{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:I0(e.skillIds,a,l)}),placeholder:n("Filter skills..."),renderDetail:a=>i.jsx(D0,{rows:[[n("Source"),a.source],[n("Path"),a.path],[n("Description"),a.description]]})}),i.jsx(T0,{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:I0(e.mcpServerIds,a,l)}),placeholder:n("Filter MCP servers..."),renderDetail:a=>i.jsx(D0,{rows:[[n("Source"),a.source],["Transport",a.transport],["URL",a.url]]})})]})}function OS({label:e,value:t,bots:n,onChange:s}){const{t:o}=se();return i.jsxs("div",{children:[i.jsx(qt,{children:e}),i.jsx(Lg,{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(hc,{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 PJ({bot:e}){const{t}=se(),n=de(r=>r.usage?.bots[e.id]);if(m.useEffect(()=>{de.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:ip(a.tokens)}),i.jsx("div",{className:"truncate text-muted-foreground text-xs tabular-nums",children:op(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&&`${ip(n.today.tokens)} / ${ip(o.dailyTokens)} tokens`,o.dailyCostUsd!==void 0&&`${op(n.today.cost??0)} / ${op(o.dailyCostUsd)}`].filter(Boolean).join(" · "),n.exhausted&&` · ${t("Today's budget is used up")}`]})]})}function kI({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(Yt,{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(AJ,{item:r,onDeleted:()=>s(a=>a?.filter(l=>l.id!==r.id)??null)},r.id))})}function AJ({item:e,onDeleted:t}){const{t:n}=se(),[s,o]=m.useState(null),[r,a]=m.useState(!1),l=async()=>{a(!0);const d=await window.electronAPI.memory.detail(e.id);a(!1),d?o({title:d.title,content:d.content}):ze({type:"error",title:n("Memory not found")})},c=async()=>{if(!s)return;a(!0);const d=await window.electronAPI.memory.update(e.id,s);a(!1),d.ok?o(null):ze({type:"error",title:n("Save failed"),description:d.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:d=>o({...s,title:d.target.value})}),i.jsx(Qs,{rows:5,value:s.content,placeholder:n("Memory content"),onChange:d=>o({...s,content:d.target.value})}),i.jsxs("div",{className:"flex justify-end gap-1.5",children:[i.jsx(xe,{size:"xs",variant:"ghost",disabled:r,onClick:()=>o(null),children:n("Cancel")}),i.jsxs(xe,{size:"xs",disabled:r||!s.content.trim(),onClick:()=>{c()},children:[r&&i.jsx(Yt,{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(Yt,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(Bs,{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(d=>{d.ok?t():ze({type:"error",title:d.error??n("Delete failed")})})},className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive",children:i.jsx(Hs,{className:"h-3.5 w-3.5"})})]})]})}function jI({target:e,emptyText:t}){const{t:n}=se(),s="botId"in e?e.botId:void 0,o="chatId"in e?e.chatId:void 0,[r,a]=m.useState(null),[l,c]=m.useState(null),[d,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),c(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),c(null);return}ze({type:"error",title:g.error==="conflict"?n("Notes were updated elsewhere; reloaded the latest version"):n("Save failed")}),g.error==="conflict"&&(c(null),p())};return r?l!==null?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx(Qs,{rows:8,value:l,maxLength:r.maxChars,onChange:g=>c(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(xe,{size:"xs",variant:"ghost",disabled:d,onClick:()=>c(null),children:n("Cancel")}),i.jsx(xe,{size:"xs",disabled:d,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(xe,{size:"xs",variant:"outline",onClick:()=>c(r.content),children:n("Edit notes")})]}):i.jsx(Yt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}function _I({value:e,onApply:t}){const{t:n,locale:s}=se(),[o,r]=m.useState(!1),a=async()=>{if(!e.name.trim()||!e.title.trim()){ze({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){ze({type:"error",title:Gh(l,n),...l.detail?{description:l.detail}:{}});return}const{persona:c,scope:d}=l.suggestion,u={persona:e.persona,scope:e.scope};t({persona:c,...d?{scope:d}:{}}),ze({type:"success",title:n(d?"Persona and responsibilities generated":"Persona generated"),timeout:1e4,actions:[{label:n("Undo"),onClick:()=>t(u)}]})}finally{r(!1)}};return i.jsxs(xe,{size:"xs",variant:"ghost",className:"-my-1 h-6 text-muted-foreground",disabled:o,onClick:()=>{a()},children:[o?i.jsx(Yt,{className:"animate-spin"}):i.jsx(ti,{}),n("Generate with AI")]})}function zS(e){const t=Mh(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(d=>d%7))].sort((d,u)=>d-u),...l}:void 0}function MJ(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 RJ(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 LJ(e){return e.status==="review"&&!!(e.delegationId&&e.assigneeBotId)}function OJ(e,t){return e.filter(n=>n.chatId===t).sort((n,s)=>n.createdAt-s.createdAt)}const td=e=>e.finishedAt??e.createdAt;function zJ(e,t){const n=e.filter(o=>o.chatId===t),s=o=>Ml(o.state)||Ej(o,e);return{active:n.filter(s).sort((o,r)=>o.createdAt-r.createdAt),completed:n.filter(o=>o.state==="completed").sort((o,r)=>td(r)-td(o)),failed:n.filter(o=>["failed","canceled","blocked"].includes(o.state)&&!s(o)).sort((o,r)=>td(r)-td(o))}}function GJ(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 FJ(e,t){const n=J2(e);if(!n)return;const s=t.find(r=>r.id===e.delegationId);if(n.reason==="failed"){const r=Rj(e);return{reason:"failed",...s?{record:s}:{},since:r?.finishedAt??s?.finishedAt??e.updatedAt}}const o=(e.blockedStreak?.[e.assigneeBotId??""]??0)>=Z2;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 HJ=["0 9 * * *","0 9 * * 1-5","0 9 * * 1","0 * * * *"];function BJ(e,t,n){const s=Mh(e);if(s)return{source:s.source,description:vv(s,t),next:vX(s,n)}}function VJ(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 $J(e){return e.title.trim()?e.prompt.trim()?Mh(e.schedule)?e.chatId?null:"chat":"schedule":"prompt":"title"}function Mu(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 xa("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?xa(n,t):t("This routine is blocked. Fix the problem and enable it again.");default:return e}}function xa(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 NI(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 wv(){const{t:e}=se(),[t,n]=m.useState(!1),s=async(r,a,l)=>{n(!0);try{const c=await a();c.ok?l&&ze({type:"success",title:l}):ze({type:"error",title:r,description:Mu(c.error,e,c.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 TI({routine:e}){const{t,locale:n}=se(),s=de(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:[vv(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 WJ({alert:e}){const{t}=se(),n=de(p=>p.bots),s=de(p=>p.chats),o=de(p=>p.setView),{busy:r,review:a,resume:l,run:c}=wv(),{routine:d}=e,u=n.find(p=>p.id===d.botId),h=s.find(p=>p.id===d.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(yv,{routine:d})]}),i.jsx(TI,{routine:d}),e.kind==="blocked"&&i.jsx("div",{className:"mt-1 text-destructive text-xs",children:xa(d.blockedReason,t)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[h&&i.jsx(xe,{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(xe,{size:"xs",variant:"outline",disabled:r,onClick:()=>c(d,!0),children:t("Dry run")}),i.jsx(xe,{size:"xs",variant:"outline",disabled:r,onClick:()=>a(d,!1),children:t("Reject")}),i.jsx(xe,{size:"xs",disabled:r,onClick:()=>a(d,!0),children:t("Approve")})]}):i.jsx(xe,{size:"xs",disabled:r,onClick:()=>l(d),children:t("Enable again")})]})]})}function yv({routine:e}){const{t}=se(),[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:U("rounded px-1.5 text-[11px]",s),children:n})}function UJ({text:e,target:t}){const{t:n}=se(),s=de(l=>l.routines.find(c=>c.id===t.id&&c.botId===t.botId)),{busy:o,review:r,run:a}=wv();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(yv,{routine:s}):i.jsx("span",{className:"text-[11px]",children:n("Routine removed")})]}),s&&i.jsx(TI,{routine:s}),s?.status==="draft"&&i.jsxs("div",{className:"mt-2 flex justify-end gap-1.5",children:[i.jsx(xe,{size:"xs",variant:"ghost",disabled:o,onClick:()=>a(s,!0),children:n("Dry run")}),i.jsx(xe,{size:"xs",variant:"outline",disabled:o,onClick:()=>r(s,!1),children:n("Reject")}),i.jsx(xe,{size:"xs",disabled:o,onClick:()=>r(s,!0),children:n("Approve")})]})]})}const Sv=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function DI(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 KJ(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 qJ(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 II({botId:e,chatId:t}){const{t:n,locale:s}=se(),o=de(w=>w.chats),r=de(w=>w.bots),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(null),[p,f]=m.useState(null),g=wv(),x=m.useCallback(async()=>{const w=await window.electronAPI.bots.routines.list(e?{botId:e}:{}).catch(()=>null),C=w?.ok?w.routines:[];l(t?OJ(C,t):C)},[e,t]);m.useEffect(()=>(l(null),x(),window.electronAPI.bots.onEvent(w=>{w.kind==="routine"&&x()})),[x]);const v=async(w,C)=>{const{id:_,title:N,prompt:S,schedule:k}=w,A=await window.electronAPI.bots.routines.save({botId:w.botId,id:_,title:N,prompt:S,schedule:k,chatId:w.chatId,enabled:C});A.ok?A.routine.status==="blocked"&&ze({type:"error",title:n("Routine blocked"),description:xa(A.routine.blockedReason,n)}):ze({type:"error",title:n("Routine not saved"),description:Mu(A.error,n)}),x()},y=async w=>{h(null);const C=await window.electronAPI.bots.routines.remove({botId:w.botId,id:w.id});C.ok||ze({type:"error",title:n("Routine not deleted"),description:Mu(C.error,n)}),x()};if(a===null)return i.jsx(Yt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const b=w=>r.find(C=>C.id===w)?.name??n("Deleted member");return i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs(xe,{size:"xs",variant:"outline",onClick:()=>d("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 C=o.find(k=>k.id===w.chatId),_=w.status==="draft",N=Q2(w)&&(w.status==="enabled"||w.status==="paused"),S=C?n("Posts to {{chat}}",{chat:Ss(C,r,n)}):n("Target chat missing");return i.jsxs("div",{"data-slot":"bot-card",className:U("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(yv,{routine:w}),!_&&i.jsx(di,{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):"",vv(w.schedule,s),w.doneBy?n("Done by {{name}}",{name:b(w.doneBy)}):"",t?"":S].filter(Boolean).join(" · ")}),w.proposedBy&&_&&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:xa(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:Sv(w.lastRunAt),result:NI(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:[_?i.jsxs(i.Fragment,{children:[i.jsx(xe,{size:"xs",variant:"ghost",disabled:g.busy,onClick:()=>{g.review(w,!1)},children:n("Reject")}),i.jsx(xe,{size:"xs",disabled:g.busy,onClick:()=>{g.review(w,!0)},children:n("Approve")})]}):i.jsxs(xe,{size:"xs",variant:"ghost",disabled:!N||g.busy,onClick:()=>{g.run(w,!1)},children:[i.jsx(Og,{}),n("Run now")]}),i.jsxs(xe,{size:"xs",variant:"ghost",disabled:g.busy,title:n("Run once without affecting the schedule"),onClick:()=>{g.run(w,!0)},children:[i.jsx(bj,{}),n("Dry run")]}),i.jsxs(xe,{size:"xs",variant:p===w.id?"secondary":"ghost",onClick:()=>f(p===w.id?null:w.id),children:[i.jsx(Ko,{}),n("History")]}),i.jsxs(xe,{size:"xs",variant:"ghost",onClick:()=>d(w),children:[i.jsx(Bs,{}),n("Edit")]}),i.jsxs(xe,{size:"xs",variant:"ghost",onClick:()=>h(w),children:[i.jsx(Hs,{}),n("Delete")]})]}),p===w.id&&i.jsx(YJ,{routine:w})]},w.id)}),c&&i.jsx(ZJ,{botId:e,chatId:t,routine:c==="new"?void 0:c,onClose:w=>{d(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 YJ({routine:e}){const{t}=se(),n=de(l=>l.setView),[s,o]=m.useState(null),{botId:r,id:a}=e;return m.useEffect(()=>{let l=!0;const c=()=>{window.electronAPI.bots.routines.runs({botId:r,id:a}).then(u=>l&&o(u.ok?u.runs:[])).catch(()=>l&&o([]))};c();const d=window.electronAPI.bots.onEvent(u=>{u.kind==="routine"&&c()});return()=>{l=!1,d()}},[r,a]),s===null?i.jsx(Yt,{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:Sv(l.startedAt)}),i.jsx("span",{children:KJ(l.trigger,t)}),i.jsxs("span",{className:U(l.result==="ok"&&"text-success",(l.result==="error"||l.result==="blocked"||l.result==="budget")&&"text-destructive"),children:[NI(l.result,t),qJ(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"?xa(l.error,t):l.error})]},l.runId))})}const XJ=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],GS=e=>String(e).padStart(2,"0");function JJ({value:e,onChange:t}){const{t:n,locale:s}=se(),o=zS(e),[r,a]=m.useState(!o),[l,c]=m.useState(o??{kind:"daily",days:[1],hour:9,minute:0}),d=BJ(e,s,Date.now()),u=f=>{c(f);const g=MJ(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=zS(e);f?c(f):u(l),a(!1)};return i.jsxs("div",{children:[i.jsx(qt,{hint:r?n("cron: minute hour day month weekday, local time"):void 0,action:i.jsx(xe,{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:Cn.DROPDOWN_IN_MODAL,children:h.map(f=>i.jsx(os,{value:f.value,children:f.label},f.value))})]}),l.kind==="weekly"&&XJ.map((f,g)=>{const x=l.days.includes(g);return i.jsx(xe,{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:`${GS(l.hour)}:${GS(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:U("mt-1 text-xs",d?"text-muted-foreground":"text-destructive"),children:d?`${d.description} · ${d.next?n("Next run {{time}}",{time:Sv(d.next)}):n("Never runs")}`:DI("schedule",n)})]})}function ZJ({botId:e,chatId:t,routine:n,onClose:s}){const{t:o}=se(),r=de(V=>V.chats),a=de(V=>V.bots),l=m.useMemo(()=>(r.find(X=>X.id===t)?.members??[]).flatMap(X=>{const F=a.find(ee=>ee.id===X&&ee.archivedAt===void 0);return F?[F]:[]}),[r,a,t]),[c,d]=m.useState(n?.botId??e??l[0]?.id??""),u=m.useMemo(()=>VJ(r,c),[r,c]),[h,p]=m.useState(n?.title??""),[f,g]=m.useState(n?.prompt??""),[x,v]=m.useState(n?.schedule??HJ[0]),[y,b]=m.useState(n?.chatId??t??u[0]?.id??""),[w,C]=m.useState(n?.doneBy??""),[_,N]=m.useState(n?.catchUp??!0),[S,k]=m.useState(null),[A,I]=m.useState(!1),D=V=>{const X=r.find(F=>F.id===V);return X?`${Ss(X,a,o)} · ${X.kind==="group"?o("Group chat"):o("Private chat")}`:o("Target chat missing")},P=u.some(V=>V.id===y)||!y?u.map(V=>V.id):[y,...u.map(V=>V.id)],T=m.useMemo(()=>(r.find(X=>X.id===y)?.members??[]).flatMap(X=>{const F=a.find(ee=>ee.id===X&&ee.archivedAt===void 0);return F&&F.id!==c?[F]:[]}),[r,a,y,c]),z=[{value:"",label:o("The member itself")},...T.map(V=>({value:V.id,label:V.name}))],O=T.some(V=>V.id===w)?w:"",L=async()=>{if(!c)return k(o("Choose a member."));const V=$J({title:h,prompt:f,schedule:x,chatId:y});if(V)return k(DI(V,o));I(!0),k(null);try{const X=await window.electronAPI.bots.routines.save({botId:c,title:h,prompt:f,schedule:x,chatId:y,catchUp:_,doneBy:O||null,...n?{id:n.id,enabled:n.status!=="paused"}:{}});X.ok?s(!0):k(Mu(X.error,o))}finally{I(!1)}};return i.jsx(vn,{open:!0,onOpenChange:V=>!V&&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(qt,{children:o("Routine title")}),i.jsx(Jt,{value:h,onChange:V=>p(V.target.value)})]}),i.jsxs("div",{children:[i.jsx(qt,{hint:o("Sent to the member as the task each time it runs"),children:o("Prompt")}),i.jsx(Qs,{rows:4,value:f,onChange:V=>g(V.target.value)})]}),i.jsx(JJ,{value:x,onChange:v}),t?i.jsxs("div",{children:[i.jsx(qt,{children:o("Member")}),i.jsxs(vs,{items:l.map(V=>({value:V.id,label:V.name})),value:c,disabled:!!n,onValueChange:V=>d(V),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:l.map(V=>i.jsx(os,{value:V.id,children:V.name},V.id))})]})]}):i.jsxs("div",{children:[i.jsx(qt,{children:o("Target chat")}),P.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:P.map(V=>({value:V,label:D(V)})),value:y,onValueChange:V=>b(V),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:P.map(V=>i.jsx(os,{value:V,children:D(V)},V))})]})]}),T.length>0&&i.jsxs("div",{children:[i.jsx(qt,{hint:o("Another member of the target chat runs it, as a delegation"),children:o("Done by")}),i.jsxs(vs,{items:z,value:O,onValueChange:V=>C(V),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:z.map(V=>i.jsx(os,{value:V.value,children:V.label},V.value||"self"))})]})]}),i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx(qt,{hint:o("If the app was closed at the scheduled time, run the latest missed one once on startup"),children:o("Catch up missed runs")}),i.jsx(di,{checked:_,onCheckedChange:N})]}),S&&i.jsx("p",{className:"text-destructive text-sm",children:S})]}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:()=>s(!1),children:o("Cancel")}),i.jsxs(xe,{size:"sm",disabled:A,onClick:()=>{L()},children:[A&&i.jsx(Yt,{className:"animate-spin"}),o("Save")]})]})]})})}function tf(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,...wJ(e.budget),...yJ(e)}}function QJ(e){const t=bI(e),n=bv(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 eZ(e,t){const n=Zd(e),s=n?await fetch(n).then(r=>r.blob()).then(Gj).catch(()=>null):null,o=xJ(eL(s??await tL(e.name,e.avatar.color)),"chara",vJ(JSON.stringify(SJ(e,t))),["ccv3"]);if(!o)throw new Error("png");nL(new Blob([new Uint8Array(o)],{type:"image/png"}),`${e.name}.png`)}function tZ({botId:e,chat:t,onOpenHistory:n}){const{t:s}=se(),o=de(D=>D.bots.find(P=>P.id===e)),r=de(D=>D.bots),[a,l]=m.useState(null),[c,d]=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 D=await window.electronAPI.bots.get(e);D.ok&&(de.getState().upsertBot(D.bot),l(D.persona),d(tf(D.bot,D.persona)),h(!1))},[e]);m.useEffect(()=>{l(null),d(null),b()},[b]);const w=m.useMemo(()=>o&&a!==null?tf(o,a):null,[o,a]),C=u&&!!(c&&w&&JSON.stringify(c)!==JSON.stringify(w));if(m.useEffect(()=>{!u&&w&&d(w)},[o?.version]),!o||!c)return i.jsx("div",{className:"flex flex-1 items-center justify-center",children:i.jsx(Yt,{className:"h-4 w-4 animate-spin text-muted-foreground"})});const _=D=>{d(P=>P&&{...P,...D}),h(!0)},N=zg(c.name,r,s,o.id),S=async D=>{x(!0);try{await zj(o.id,D)||ze({type:"error",title:s("Avatar update failed")})}finally{x(!1)}},k=()=>{eZ(o,a??"").then(()=>ze({type:"success",title:s('Persona embedded in the PNG. Restore it in a new member via "Import character card".')})).catch(()=>ze({type:"error",title:s("Export failed")}))},A=async()=>{const D=QJ(c);if(!D){ze({type:"error",title:bv(c).ok?s("Budget must be a positive number"):s("Check the per-turn token limit and delegation time limit")});return}f(!0);try{const P=await window.electronAPI.bots.update({botId:o.id,expectedVersion:o.version,draft:D});if(P.ok){de.getState().upsertBot(P.bot),l(c.persona),d(tf(P.bot,c.persona)),h(!1);return}ze({type:"error",title:rl(P.reason,P.error,s),...P.reason==="conflict"?{actions:[{label:s("Refresh"),onClick:()=>{b()}}]}:{}})}finally{f(!1)}},I=async()=>{const D=v;if(y(null),D==="archive"){const T=await window.electronAPI.bots.archive(o.id,!0);T.ok?de.getState().upsertBot(T.bot):ze({type:"error",title:rl(T.reason,T.error,s)});return}const P=await window.electronAPI.bots.remove(o.id);if(P.ok){de.getState().setView(null),await Promise.all([de.getState().refreshCatalog(),de.getState().refreshChats()]);return}if(P.reason==="boss"){const T=de.getState().chats,z=(P.chatIds??[]).map(O=>T.find(L=>L.id===O)).filter(O=>!!O).map(O=>Ss(O,r,s));ze({type:"warning",title:s("{{name}} owns group chats",{name:o.name}),description:s("Choose another owner in {{groups}} first.",{groups:z.join("、")})});return}ze({type:"error",title:rl(P.reason,P.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:c.name||o.name,avatar:{...o.avatar,color:c.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(Lf,{children:[i.jsxs(Of,{render:i.jsx(xe,{size:"xs",variant:"outline",onClick:k}),children:[i.jsx(oc,{}),s("Export character card")]}),i.jsx(zf,{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(wI,{hasImage:!!o.avatar.image,disabled:g,onPick:D=>{S(D)},onRemove:()=>{S(null)}})]})]})]}),i.jsxs(eh,{defaultValue:"profile",className:"mt-3 flex min-h-0 flex-1 flex-col",children:[i.jsxs(th,{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(PJ,{bot:o}),i.jsxs("div",{children:[i.jsx(qt,{hint:s("Used for @ in groups; must be unique"),children:s("Name")}),i.jsx(Jt,{value:c.name,onChange:D=>_({name:D.target.value})}),N&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:N})]}),i.jsxs("div",{children:[i.jsx(qt,{children:s("Title")}),i.jsx(Jt,{value:c.title,onChange:D=>_({title:D.target.value})})]}),i.jsxs("div",{children:[i.jsx(qt,{hint:s("Used for routing and the delegation directory"),children:s("Responsibilities")}),i.jsx(Qs,{rows:2,value:c.scope,onChange:D=>_({scope:D.target.value})})]}),i.jsxs("div",{children:[i.jsx(qt,{action:i.jsx(_I,{value:c,onApply:_}),children:s("Persona")}),i.jsx(Qs,{rows:8,value:c.persona,onChange:D=>_({persona:D.target.value})})]}),i.jsxs("div",{children:[i.jsx(qt,{children:s("Avatar color")}),i.jsx(Lj,{value:c.color,onChange:D=>_({color:D})})]}),i.jsxs("div",{className:"flex gap-2 border-t pt-3",children:[i.jsxs(xe,{size:"xs",variant:"outline",onClick:()=>y("archive"),children:[i.jsx(Mi,{}),s("Archive member")]}),i.jsxs(xe,{size:"xs",variant:"destructive-outline",onClick:()=>y("delete"),children:[i.jsx(Hs,{}),s("Delete permanently")]})]})]}),i.jsxs(oo,{value:"abilities",className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(qt,{children:s("Model")}),i.jsx(Oj,{engine:c.engine,onChange:D=>_({engine:D})})]}),i.jsx(SI,{value:c,onChange:_,profile:c,botId:o.id})]}),i.jsxs(oo,{value:"memory",children:[i.jsxs("div",{className:"mb-4",children:[i.jsx(qt,{hint:s("Injected into every new conversation"),children:s("Core notes")}),i.jsx(jI,{target:{botId:o.id},emptyText:s("No notes yet. Key preferences and facts are summarized here automatically after memories are organized.")})]}),i.jsx(kI,{spaceId:`bot:${o.id}`,emptyText:s("No memories yet")})]}),i.jsx(oo,{value:"routines",children:i.jsx(II,{botId:o.id})}),i.jsx(oo,{value:"history",children:i.jsx(nZ,{chat:t,botId:o.id,onOpen:D=>n(D,o.name)})})]})]}),C&&i.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t bg-muted/50 px-4 py-2.5",children:[i.jsx(xe,{size:"sm",variant:"outline",onClick:()=>{w&&d(w),h(!1)},children:s("Discard")}),i.jsxs(xe,{size:"sm",disabled:p||!!N,onClick:()=>{A()},children:[p&&i.jsx(Yt,{className:"animate-spin"}),s("Save")]})]}),i.jsx(ms,{open:v!==null,onOpenChange:D=>!D&&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 nZ({chat:e,botId:t,onOpen:n}){const{t:s}=se(),[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(c=>c.botId===t):[])}),()=>{a=!1}},[e.id,t]),o===null?i.jsx(Yt,{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 Ru(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 EI(e,t,n,s){const o=await window.electronAPI.bots.tasks.reply({chatId:e,id:t,text:n}),r=de.getState();return r.refreshTasks(e),r.refreshDelegations(),r.refreshInbox(),o.ok||ze({type:"error",title:s("Reply not sent"),description:Ru(o.error,s)}),o.ok}function Cv({placeholder:e,onSend:t,className:n}){const{t:s}=se(),[o,r]=m.useState(""),[a,l]=m.useState(!1),c=Oi(ye(u=>u.keybindings))["send-message"],d=async()=>{const u=o.trim();if(!(!u||a)){l(!0);try{await t(u)&&r("")}finally{l(!1)}}};return i.jsxs("div",{className:U("mt-1.5 flex items-end gap-1",n),children:[i.jsx(Qs,{value:o,rows:1,size:"sm",maxLength:Gg,placeholder:e,"aria-label":e,title:c?`${s("Send")} ${mi(c)}`: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&&Ij(u,c)&&(u.preventDefault(),d())}}),i.jsx(xe,{size:"icon-sm",variant:o.trim()?"default":"ghost","aria-label":s("Send reply"),disabled:!o.trim()||a,onClick:()=>{d()},children:a?i.jsx(Yt,{className:"animate-spin"}):i.jsx(Vx,{})})]})}function PI(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 AI=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),MI=(e,t)=>e.ok===void 0?t("Processing"):e.ok?t("Delivered"):t("Not delivered");function sZ({appends:e}){const{t}=se();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:AI(n.at)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",title:n.text,children:n.text}),i.jsx("span",{className:U("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:MI(n,t)})]},n.deliveryId))})}function iZ({runs:e,bots:t,onOpenConversation:n}){const{t:s}=se(),o=de(f=>f.delegations),r=Oh(e.some(f=>Ml(f.state))),[a,l]=m.useState(!1),[c,d]=m.useState(null),u=GJ(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"?Ic(g??f,s):void 0,y=g?.appends??[];return i.jsxs("li",{className:U(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"):PI(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:xo(x.ms)})}):i.jsxs(i.Fragment,{children:[i.jsx(Lh,{state:f.state,interrupted:f.failure==="interrupted"}),i.jsx("span",{children:xo(x.ms)})]}),f.appends&&i.jsx("button",{type:"button","aria-expanded":c===f.id,disabled:!y.length,title:y.map(b=>`${AI(b.at)} ${b.text} · ${MI(b,s)}`).join(`
|
|
83
|
-
`),onClick:()=>d(c===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(xe,{size:"xs",variant:"ghost",onClick:()=>n(g.childConversationId,s("{{from}} → {{to}} · Delegation",{from:p(g.parentBotId),to:p(g.targetBotId)})),children:s("View process")})]}),c===f.id&&y.length>0&&i.jsx(sZ,{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(xe,{size:"xs",variant:"ghost",onClick:()=>l(!0),children:s("Show all ({{n}})",{n:u.length})})]})}const eg=5,oZ=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}=se(),[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(xe,{size:"xs",variant:"ghost",className:"mt-1",onClick:()=>a(!0),children:o("Show all ({{n}})",{n:t})})]})}function rZ({chat:e,onOpenConversation:t}){const{t:n}=se(),s=de(k=>k.tasks[e.id]),o=de(k=>k.bots),r=de(k=>k.delegations),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(null),p=de(k=>k.taskFocus),[f,g]=m.useState(null),x=m.useRef(null),v=Oh(!!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(()=>{de.getState().refreshTasks(e.id)},[e.id]),m.useEffect(()=>{!p||p.chatId!==e.id||!s||(de.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||ze({type:"error",title:A,description:Ru(I.error??"",n)}),de.getState().refreshTasks(e.id)},C=window.electronAPI.bots.tasks,_=k=>({chatId:e.id,id:k.id});if(!s)return i.jsx(Yt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const N=RJ(s),S=k=>i.jsx(aZ,{task:k,bots:y,members:b,onOpenConversation:t,block:FJ(k,r),now:v,highlighted:f===k.id,onEdit:()=>l(k),onAssign:A=>{w(()=>C.assign({..._(k),botId:A}),n("Task not assigned"))},onComplete:()=>{w(()=>C.complete(_(k)),n("Task not updated"))},onAccept:()=>{w(()=>C.review({..._(k),accept:!0}),n("Task not updated"))},onReturn:A=>h({task:k,rework:A}),onCancel:()=>{w(()=>C.cancel(_(k)),n("Task not updated"))},onDelete:()=>d(k),onReply:A=>EI(e.id,k.id,A,n)},k.id);return i.jsxs("div",{ref:x,children:[i.jsxs(xe,{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:eg,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(dZ,{chatId:e.id,task:a==="new"?void 0:a,onClose:k=>{l(null),k&&de.getState().refreshTasks(e.id)}}),u&&i.jsx(cZ,{task:u.task,assignee:y.get(u.task.assigneeBotId??"")?.name??n("Deleted member"),rework:u.rework,onClose:()=>h(null),onReturn:k=>C.review({..._(u.task),accept:!1,reason:k,...u.rework?{rework:!0}:{}}).then(A=>(A.ok&&(h(null),de.getState().refreshTasks(e.id)),A.ok?null:Ru(A.error,n)))}),i.jsx(ms,{open:c!==null,onOpenChange:k=>!k&&d(null),title:n("Delete task #{{n}}?",{n:c?.seq??""}),description:n("The task is removed from the board. This cannot be undone."),confirmLabel:n("Delete"),onConfirm:()=>{const k=c;d(null),k&&w(()=>C.remove(_(k)),n("Task not deleted"))}})]})}function aZ({task:e,bots:t,members:n,onOpenConversation:s,onEdit:o,onAssign:r,onComplete:a,onAccept:l,onReturn:c,onCancel:d,onDelete:u,onReply:h,block:p,now:f,highlighted:g}){const{t:x}=se(),v=e.status==="todo"||e.status==="doing"||e.status==="blocked",y=e.status==="review",b=Rj(e),w=e.assigneeBotId?t.get(e.assigneeBotId):void 0,C=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:U("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(Sh,{className:"h-3.5 w-3.5"})}),i.jsxs(Vi,{align:"end",children:[i.jsxs(mn,{onClick:o,children:[i.jsx(Bs,{}),x("Edit")]}),v&&(!e.delegationId||e.status==="blocked"||b)&&n.length>0&&i.jsxs(Hj,{children:[i.jsxs(Bj,{children:[i.jsx($l,{}),e.assigneeBotId?x("Reassign to"):x("Assign to")]}),i.jsx(Vj,{children:n.map(_=>i.jsxs(mn,{disabled:_.id===e.assigneeBotId,onClick:()=>r(_.id),children:[i.jsx(sn,{bot:_,size:"xs"}),_.name]},_.id))})]}),v&&!b&&i.jsxs(mn,{onClick:a,children:[i.jsx(Kn,{}),x("Mark done")]}),(v||y)&&i.jsxs(mn,{onClick:d,children:[i.jsx(ln,{}),x("Cancel task")]}),i.jsx(ya,{}),i.jsxs(mn,{variant:"destructive",onClick:u,children:[i.jsx(Hs,{}),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:U("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(lZ,{block:p,now:f,assignee:w,bots:t,members:n,assigneeBotId:e.assigneeBotId,onRetry:()=>b&&_l(b.id,x),onAssign:r,onCancel:d,onReply:h}),!p&&(y||e.status==="doing"&&e.delegationId)&&i.jsx(Cv,{placeholder:x(y?"Comment…":"Add to the current run…"),onSend:h}),e.check&&i.jsx(dI,{check:e.check,className:"mt-1"}),y&&i.jsxs("div",{className:"mt-1.5 flex gap-1.5",children:[i.jsxs(xe,{size:"xs",onClick:l,children:[i.jsx(Kn,{}),x("Accept result")]}),i.jsxs(xe,{size:"xs",variant:"outline",onClick:()=>c(!1),children:[i.jsx(fa,{}),x("Return")]}),LJ(e)&&i.jsxs(xe,{size:"xs",variant:"outline",onClick:()=>c(!0),children:[i.jsx(Fg,{}),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:C}),children:oZ(e.updatedAt)})]}),e.runs&&e.runs.length>0&&i.jsx(iZ,{runs:e.runs,bots:t,onOpenConversation:s})]})}function lZ({block:e,now:t,assignee:n,assigneeBotId:s,bots:o,members:r,onRetry:a,onAssign:l,onCancel:c,onReply:d}){const{t:u}=se(),h=n?.name??u("Deleted member"),p=u("Stuck for {{time}}",{time:xo(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(Cv,{placeholder:u("Answer {{name}}; they continue after your reply…",{name:h}),onSend:d})]})}const f=e.record?.state==="failed"&&Ic(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(xe,{size:"xs",variant:"outline",onClick:a,children:[i.jsx(ra,{}),u("Retry")]}),r.length>0&&i.jsxs(Hi,{children:[i.jsxs(Bi,{render:i.jsx(xe,{size:"xs",variant:"outline"}),children:[i.jsx($l,{}),u("Reassign")]}),i.jsx(Vi,{align:"start",children:r.map(g=>i.jsxs(mn,{disabled:g.id===s,onClick:()=>l(g.id),children:[i.jsx(sn,{bot:g,size:"xs"}),g.name]},g.id))})]}),i.jsxs(xe,{size:"xs",variant:"outline",onClick:c,children:[i.jsx(ln,{}),u("Cancel task")]})]})]})}function cZ({task:e,assignee:t,rework:n,onClose:s,onReturn:o}){const{t:r}=se(),[a,l]=m.useState(""),[c,d]=m.useState(null),[u,h]=m.useState(!1),p=async()=>{if(!a.trim())return d(r("Enter a reason."));h(!0);try{d(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(qt,{children:r("Reason for returning")}),i.jsx(Qs,{rows:4,autoFocus:!0,value:a,maxLength:Gg,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.")}),c&&i.jsx("p",{className:"text-destructive text-sm",children:c})]}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:s,children:r("Cancel")}),i.jsxs(xe,{size:"sm",disabled:u,onClick:()=>{p()},children:[u&&i.jsx(Yt,{className:"animate-spin"}),r(n?"Return for rework":"Return")]})]})]})})}function dZ({chatId:e,task:t,onClose:n}){const{t:s}=se(),[o,r]=m.useState(t?.title??""),[a,l]=m.useState(t?.detail??""),[c,d]=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:c.trim(),...t?{id:t.id}:{}});x.ok?n(!0):h(Ru(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(qt,{children:s("Task title")}),i.jsx(Jt,{value:o,maxLength:sL,onChange:x=>r(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(qt,{children:s("Details")}),i.jsx(Qs,{rows:4,value:a,maxLength:Gg,onChange:x=>l(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(qt,{children:s("Acceptance check (optional)")}),i.jsx(Jt,{value:c,maxLength:iL,onChange:x=>d(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(xe,{variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsxs(xe,{size:"sm",disabled:p,onClick:()=>{g()},children:[p&&i.jsx(Yt,{className:"animate-spin"}),s("Save")]})]})]})})}function uZ({chat:e,onOpenConversation:t}){const{t:n}=se(),s=de(c=>c.delegations),o=de(c=>c.bots),r=m.useMemo(()=>new Map(o.map(c=>[c.id,c])),[o]),a=m.useMemo(()=>zJ(s,e.id),[s,e.id]),l=c=>i.jsx(zh,{record:c,retried:Fj(c,s),bots:r,onOpenConversation:t},c.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:eg,children:c=>a.completed.slice(0,c).map(l)}),a.failed.length>0&&i.jsx(io,{title:n("Failed · interrupted · canceled"),count:a.failed.length,limit:eg,children:c=>a.failed.slice(0,c).map(l)})]})}const hZ=(e,t)=>e.workspace.kind===t.kind&&(t.kind!=="project"||e.workspace.kind==="project"&&e.workspace.projectId===t.projectId);function RI({chat:e,className:t}){const{t:n}=se(),s=ye(f=>f.projects),o=de(f=>f.bots),r=de(f=>f.upsertChat),[a,l]=m.useState(!1),[c,d]=m.useState(null),u=$j(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")},...nh(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):ze({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:U("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(Cc,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:u}),i.jsx(Vn,{className:"h-3 w-3 shrink-0 opacity-60"})]}),i.jsxs(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||ze({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=hZ(e,f.input);return i.jsxs("button",{type:"button",onClick:()=>{l(!1),g||d(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:c!==null,onOpenChange:f=>!f&&d(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=c;d(null),f&&p(f)}})]})}function tr({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 nf({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 LI(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 lL(e,t,n,new Date().toISOString())}async function pZ(e,t){const n=await LI(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 fZ(e,t){const n=await LI(e,t),s=n&&oL(rL(n.team));return s?aL(o=>({...o,teams:cL(o.teams,s,crypto.randomUUID())})):!1}function mZ({chat:e,thread:t=e,onOpenConversation:n}){const{t:s}=se(),o=de(T=>T.bots),r=de(T=>T.runtime[t.id]),a=de(T=>T.upsertChat),l=de(T=>T.openDirect),c=ye(T=>T.projects),d=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"),C=de(T=>T.taskFocus);m.useEffect(()=>{C?.chatId===e.id&&w("board")},[C,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 _=async T=>{const z=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,...T});z.ok?a(z.chat):(ze({type:"error",title:Ns(z.error,s)}),de.getState().refreshChats())},N=e.members.map(T=>({id:T,bot:d.get(T)})),S=e.routing.muted??[],k=o.filter(T=>!T.archivedAt&&!e.members.includes(T.id)),A=T=>T?d.get(T)?.name??"?":"—",I=e.workspace.kind==="project"?c.find(T=>e.workspace.kind==="project"&&T.id===e.workspace.projectId):void 0,D=p!==String(e.routing.maxHops)||g!==String(e.routing.maxTurnsPerBot),P=[{value:"boss",label:s("Group owner replies")},{value:"smart",label:s("Smart pick")}];return i.jsxs(eh,{value:b,onValueChange:T=>w(String(T)),className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs(th,{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(rZ,{chat:e,onOpenConversation:n})}),i.jsx(oo,{value:"delegations",children:i.jsx(uZ,{chat:t,onOpenConversation:n})}),i.jsx(oo,{value:"routines",children:i.jsx(II,{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 _({title:u.trim()}),onKeyDown:T=>T.key==="Enter"&&T.currentTarget.blur()}),i.jsxs(tr,{title:s("Members"),children:[N.map(({id:T,bot:z})=>i.jsxs("div",{className:"group flex items-center gap-2 rounded-lg py-1.5",children:[i.jsxs("button",{type:"button",onClick:()=>{l(T)},className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(fI,{chatId:t.id,botId:T,bot:z}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[i.jsx("span",{className:"truncate",children:z?.name??s("Deleted member")}),e.bossBotId===T&&i.jsx("span",{className:"shrink-0 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:s("Owner")}),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(yw,{className:"h-2.5 w-2.5"}),s("Muted")]})]}),i.jsx("div",{className:"truncate text-muted-foreground text-xs",children:z?.scope||z?.title})]})]}),i.jsxs(Hi,{children:[i.jsx(Bi,{className:"rounded p-1 text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 data-popup-open:opacity-100",children:i.jsx(Sh,{className:"h-3.5 w-3.5"})}),i.jsxs(Vi,{align:"end",children:[i.jsxs(mn,{disabled:e.bossBotId===T,onClick:()=>{_({bossBotId:T})},children:[i.jsx(Wj,{}),s("Make owner")]}),i.jsxs(mn,{disabled:e.bossBotId===T,onClick:()=>{_({routing:{muted:S.includes(T)?S.filter(O=>O!==T):[...S,T]}})},children:[i.jsx(yw,{}),S.includes(T)?s("Unmute"):s("Mute")]}),i.jsxs(mn,{disabled:e.bossBotId===T||e.members.length<=2,onClick:()=>{_({members:e.members.filter(O=>O!==T)})},children:[i.jsx(C4,{}),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),_({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(tr,{title:s("Reply queue"),children:[i.jsx(nf,{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(nf,{label:s("Waiting"),value:r?.queue.length?r.queue.map(T=>A(T)).join("、"):"—"}),i.jsx(nf,{label:s("Per-member limit"),value:s("{{n}} replies",{n:e.routing.maxTurnsPerBot})})]}),i.jsx(tr,{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(RI,{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(tr,{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:P,value:e.routing.mode,onValueChange:T=>{T!==e.routing.mode&&_({routing:{mode:T}})},children:[i.jsx(bs,{size:"sm",className:"w-40",children:i.jsx(ws,{})}),i.jsx(ys,{children:P.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)})]})]}),D&&i.jsx(xe,{size:"xs",className:"mt-2",onClick:()=>{_({routing:{maxHops:Math.round(Number(p))||e.routing.maxHops,maxTurnsPerBot:Math.round(Number(g))||e.routing.maxTurnsPerBot}})},children:s("Save")})]}),i.jsx(tr,{title:s("Group notes"),children:i.jsx(jI,{target:{chatId:e.id},emptyText:s("No group notes yet. Group conventions and decisions are summarized here automatically after memories are organized.")})}),i.jsx(tr,{title:s("Group memory"),children:i.jsx(kI,{spaceId:`chat:${e.id}`,emptyText:s("No group memories yet")})}),i.jsxs(tr,{title:s("Team"),children:[i.jsxs(xe,{size:"xs",variant:"outline",onClick:()=>{pZ(e,o).then(T=>T||ze({type:"error",title:s("Export failed")}))},children:[i.jsx(oc,{}),s("Export team")]}),i.jsxs(xe,{size:"xs",variant:"outline",className:"ml-1.5",onClick:()=>{fZ(e,o).then(T=>ze(T?{type:"success",title:s("Saved as team template")}:{type:"error",title:s("Could not save as team template")}))},children:[i.jsx(I$,{}),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 gZ(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 xZ(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 vZ(e,t){const n=String(t),s=`${n}-`;return e.find(o=>o.key===n||o.key.startsWith(s))?.key}function bZ(e){return e.earliest===void 0?"wait":e.target>=e.earliest?"scroll":e.loading?"wait":e.hasOlder?"load":"give-up"}function wZ(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 yZ(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 SZ({chatId:e,bots:t}){const{t:n}=se(),s=de(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(xe,{size:"sm",variant:"ghost",disabled:o!==null,onClick:async()=>{if(a.deliveryId){r(a.deliveryId);try{const c=await window.electronAPI.bots.interjectQueued(e,a.deliveryId);c.ok||ze({type:"error",title:c.error})}catch{ze({type:"error",title:n("Failed to send")})}finally{r(null)}}},children:n("Insert into {{name}}’s current task",{name:l})})]},a.deliveryId)})}const CZ=(e,t)=>t?e.find(n=>n.conversationId===t):void 0,kZ=(e,t)=>Math.max(0,Math.floor((t-e)/1e3));function OI({since:e}){const{t}=se(),[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:kZ(e,n)})})}function zI({conversationId:e,className:t}){const n=de(s=>CZ(s.silences,e)?.since);return n===void 0?null:i.jsx("span",{className:t??"shrink-0 text-warning",children:i.jsx(OI,{since:n})})}const $d=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),jZ={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 _Z({chat:e,bots:t,timeline:n,runtime:s,delegations:o,focus:r,onFocusDone:a,onLoadOlder:l,onLoadNewer:c,onLoadAround:d,onJumpLatest:u,onOpenConversation:h,onOpenLive:p}){const{t:f}=se(),g=m.useRef(null),x=m.useRef(!0),v=m.useRef(h);v.current=h;const y=m.useCallback((te,pe)=>v.current(te,pe),[]),b=m.useRef(null),w=m.useRef(!1),C=n?.entries??[],_=m.useRef({chatId:e.id,loaded:C,delegations:o});_.current={chatId:e.id,loaded:C,delegations:o};const N=m.useCallback(te=>{const{chatId:pe,loaded:Te,delegations:$e}=_.current,Ie=pL(Te,te);if(Ie!==void 0)return de.getState().focusSeq(pe,Ie);const Ze=$e.find(Nt=>Nt.id===te);ze({type:"info",title:Ze&&Ze.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=gZ(C,e.epochSeq??0),k=n?.history,A=e.epochSeq??0,[I,D]=m.useState(!1);m.useEffect(()=>D(!1),[e.id,A]);const P=A>0&&!I&&!k,T=m.useMemo(()=>P?C.filter(te=>te.seq>=A):C,[C,P,A]),z=m.useMemo(()=>fL(T),[T]),O=()=>{P&&n?.hasOlder&&!n.loading&&!C.some(te=>te.seq<A)&&(ke(),l()),D(P)},L=m.useMemo(()=>{const te=new Map;if(!k)for(const pe of z)pe.kind==="entry"&&pe.entry.kind==="bot"&&!pe.continued&&te.set(pe.entry.botId,pe.entry.id);return new Set(te.values())},[z,k]),V=m.useMemo(()=>new Map(o.map(te=>[te.id,{record:te,retried:Fj(te,o)}])),[o]),X=m.useMemo(()=>Kj(o,e.id),[o,e.id]),F=m.useMemo(()=>mL(T,gL(X)),[T,X]),ee=de(te=>te.tasks[e.id]),H=X.some(te=>te.appends?.length);m.useEffect(()=>{H&&!ee&&de.getState().refreshTasks(e.id)},[H,ee,e.id]);const Q=({key:te,record:pe,append:Te})=>i.jsx(zh,{record:pe,append:Te,taskSeq:Te&&ee?.find($e=>$e.id===pe.taskId)?.seq,fill:!0,bots:t,onOpenConversation:h},te),q=s?.current?t.get(s.current):void 0,ne=s?.current?e.sessions[s.current]?.conversationId:void 0,me=de(te=>ne?te.sessions[ne]?.messages.length:void 0);m.useLayoutEffect(()=>{const te=g.current;te&&(te.scrollTop=te.scrollHeight),x.current=!0},[e.id]);const ke=()=>{const te=g.current;if(!te)return;const pe=te.getBoundingClientRect().top;for(const Te of te.querySelectorAll("[data-seq]")){const $e=Te.getBoundingClientRect();if(!($e.bottom<=pe)){b.current={seq:Number(Te.dataset.seq),top:$e.top-pe};return}}};m.useLayoutEffect(()=>{const te=g.current;if(!te)return;const pe=b.current;!n?.loading&&!n?.loadingNewer&&(b.current=null);const $e=w.current&&!k;w.current=!!k;const Ie=pe&&te.querySelector(`[data-seq="${pe.seq}"]`);if(pe&&Ie){te.scrollTop+=Ie.getBoundingClientRect().top-te.getBoundingClientRect().top-pe.top;return}$e&&(x.current=!0),x.current&&!k&&(te.scrollTop=te.scrollHeight)},[T,k,n?.loading,n?.loadingNewer,X.length,q?.id,me,s?.routing]);const Me=()=>{const te=g.current;if(!te||!n)return;const pe=te.scrollHeight-te.scrollTop-te.clientHeight;x.current=pe<40,b.current&&ke(),!(T.length===0||P&&(C[0]?.seq??0)<=A)&&(te.scrollTop<80&&n.hasOlder&&!n.loading&&(ke(),l()),pe<80&&k&&!n.loadingNewer&&(ke(),c()))},[ge,$]=m.useState(null),W=m.useRef(null),[ue,Z]=m.useState(null);m.useLayoutEffect(()=>{if(!r||W.current===r.nonce)return;if(P&&r.seq<A){D(!0);return}const te=T[0]?.seq,pe=T.at(-1)?.seq,Te=ue?.nonce===r.nonce?ue:null,$e=wZ({target:r.seq,range:n?te===void 0||pe===void 0?null:[te,pe]:void 0,loading:!!(Te&&!Te.done),jumped:!!Te?.done});if($e!=="wait"){if($e==="jump"){const Ie=r.nonce;x.current=!1,b.current=null,Z({nonce:Ie,done:!1}),d(r.seq).finally(()=>Z(Ze=>Ze?.nonce===Ie?{nonce:Ie,done:!0}:Ze));return}W.current=r.nonce,a?.(r.nonce),$e==="scroll"&&(x.current=!1,b.current=null,$(r.seq),g.current?.querySelector(`[data-seq="${r.seq}"]`)?.scrollIntoView({block:"center"}))}},[r,T,n===void 0,ue,P]),m.useEffect(()=>{if(ge===null)return;const te=window.setTimeout(()=>$(null),2500);return()=>window.clearTimeout(te)},[ge]);const J=()=>{x.current=!0,b.current=null,u()},ae=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:Me,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:U(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(Yt,{className:"h-4 w-4 animate-spin"})}),n&&!n.hasOlder&&!P&&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(Yt,{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.")}),F.head.map(Q),z.map(te=>te.kind==="day"?i.jsx("div",{className:"py-1 text-center text-[11px] text-muted-foreground",children:new Date(te.at).toLocaleDateString()},te.key):i.jsxs(m.Fragment,{children:[A>0&&!k&&te.entry.seq===A&&i.jsxs("button",{type:"button",onClick:O,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:[P?i.jsx(un,{className:"h-3.5 w-3.5"}):i.jsx(Vn,{className:"h-3.5 w-3.5"}),P?f("Earlier conversation · {{n}} messages",{n:A-1}):f("Collapse earlier conversation")]}),i.jsx("div",{"data-seq":te.entry.seq,className:U("-mx-2 flex flex-col rounded-lg px-2 transition-colors duration-500",ge===te.entry.seq&&"bg-brand/10"),children:i.jsx(NZ,{chatId:e.id,entry:te.entry,continued:te.continued,latest:L.has(te.entry.id),retryable:S.has(te.entry.id)&&e.archivedAt===void 0,retryBusy:!!(s?.current||s?.routing),bots:t,records:V,onOpenConversation:y,onLocateDelegation:N})}),F.after.get(te.entry.id)?.map(Q)]},te.key)),n?.loadingNewer&&i.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:i.jsx(Yt,{className:"h-4 w-4 animate-spin"})}),!k&&!q&&s?.routing&&i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(FS,{}),f("Choosing who replies…")]}),!k&&i.jsx(SZ,{chatId:e.id,bots:t}),!k&&q&&i.jsxs("button",{type:"button",disabled:!ne,title:f("View live"),onClick:()=>ne&&p(ne,q.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:q,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:q.name}),f("Replying")]}),i.jsx(cI,{conversationId:ne,leading:i.jsx(FS,{}),trailing:i.jsxs(i.Fragment,{children:[i.jsx(zI,{conversationId:ne}),ne&&i.jsx("span",{className:"shrink-0 underline-offset-2 hover:underline",children:f("View live")})]})})]})]})]})})}),k&&i.jsxs("button",{type:"button",onClick:J,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(Qu,{className:"h-3 w-3"}),ae>0?f("Back to latest · {{n}} new",{n:ae}):f("Back to latest")]})]})}function FS(){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 NZ=m.memo(function({chatId:t,entry:n,continued:s,latest:o,bots:r,records:a,onOpenConversation:l,onLocateDelegation:c,retryable:d,retryBusy:u}){const{t:h}=se(),[p,f]=m.useState(!1),g=async()=>{if(!p){f(!0);try{const x=await window.electronAPI.bots.retry(t,n.id);x.ok||ze({type:"error",title:h("Retry failed"),description:Ns(x.error,h)})}catch{ze({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")," · ",$d(n.at),i.jsx("div",{className:"h-px flex-1 bg-border"})]}):n.routine?i.jsx(UJ,{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,d&&i.jsx(xe,{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:U(tl,"whitespace-pre-wrap break-words"),children:i.jsx(Wd,{text:n.text,bots:r})}),n.images?.length?i.jsx(Pu,{target:{chatId:t,entryId:n.id}}):null,(n.refs?.skill||n.refs?.chats?.length)&&i.jsx(EZ,{refs:n.refs}),!s&&i.jsx("span",{className:"mt-0.5 text-[11px] text-muted-foreground",children:$d(n.at)})]});case"progress":return i.jsx(DZ,{chatId:t,entry:n,bots:r,failed:a.get(n.delegationId)?.record.state==="failed"});case"delegation":return i.jsx(zh,{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:U("flex w-full gap-2.5",s&&"-mt-1.5"),children:[s?i.jsx("span",{className:"w-6 shrink-0"}):o?i.jsx(fI,{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} · `:"",$d(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&&c(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(jZ[n.routedBy])})]}),i.jsx("div",{className:"text-sm",children:i.jsx(_s,{text:n.text})}),i.jsx(Pu,{target:{chatId:t,entryId:n.id}}),i.jsx(IZ,{entry:n,onOpen:()=>l(n.conversationId,x?.name??"")})]})]})}}}),TZ={started:{icon:O$,className:"border-brand/50 text-brand"},blocked:{icon:br,className:"border-warning/60 text-warning"},failed:{icon:dL,className:"border-destructive/60 text-destructive"},delivered:{icon:Eg,className:"border-success/60 text-success"}};function DZ({chatId:e,entry:t,bots:n,failed:s}){const{t:o}=se(),r=de(u=>u.openTask),a=n.get(t.botId),l=TZ[t.phase==="blocked"&&s?"failed":t.phase],c=l.icon,d=xZ(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:U("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(c,{"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")})," ",d?i.jsxs(i.Fragment,{children:[i.jsx(Wd,{text:d[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:d[1]}),i.jsx(Wd,{text:d[2],bots:n})]}):i.jsx(Wd,{text:t.text,bots:n})]}),i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:$d(t.at)})]})]})}function Wd({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 Wk(e).flatMap(a=>a.type==="file"?[a]:(r?a.text.split(r):[a.text]).map((l,c)=>l.startsWith("@")&&c%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:U(uv("file"),"mx-0.5 leading-4"),title:s.path,children:[i.jsx(So,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:Uj})]},o):i.jsx("span",{className:"font-medium underline underline-offset-2",children:s.part},o))})}function IZ({entry:e,onOpen:t}){const{t:n}=se(),[s,o]=m.useState(!1),[r,a]=m.useState(null);m.useEffect(()=>{if(!s||r)return;let c=!0;const d=h=>{const p=uL(h,e.text);if(c){if(!p)return a({error:n("No process recorded.")});a({steps:hL(h.slice(p.start,p.end)),exact:p.exact})}},u=de.getState().sessions[e.conversationId]?.messages;return u?.some(h=>h.role==="assistant")?d(u):window.electronAPI.bots.sessionHistory({conversationId:e.conversationId}).then(h=>h.ok?d(h.messages):c&&a({error:h.error})),()=>{c=!1}},[s,r,e.conversationId,e.text,n]);const l=s?Vn:un;return i.jsxs("div",{className:"mt-1",children:[i.jsxs("button",{type:"button",onClick:()=>o(c=>!c),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(Yt,{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(c=>i.jsxs("div",{className:U("truncate",c.error&&"text-destructive"),children:[c.error?"✗":"·"," ",Fo(c.name,n),c.detail&&i.jsxs("span",{className:"text-foreground/80",children:[" ",c.detail]})]},c.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 EZ({refs:e}){const{t}=se(),n=de(a=>a.chats),s=de(a=>a.bots),o=ye(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:U(r,"bg-info/15 text-info"),children:[i.jsx(ti,{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(c=>c.id===a);return i.jsxs("span",{className:U(r,"bg-muted"),title:t("Referenced chat"),children:[i.jsx(pa,{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 Fh({retry:e,onCancel:t}){const{t:n}=se(),[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(Wo,{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 HS(e,t){return t.projectId?t.projectId:e.workspace.kind==="member-home"?void 0:e.workspace.projectId}function PZ(e,t,n){for(const s of e??[])for(const o of Object.values(s.sessions))if(o.conversationId===n)return HS(s,o);for(const s of t??[]){if(s.childConversationId!==n||!s.chatId)continue;const o=e?.find(a=>a.id===s.chatId),r=o?.sessions[s.targetBotId];if(o&&r)return HS(o,r)}}function GI(e,t){const n=de(o=>e?PZ(o.chats,o.delegations,e):void 0),s=t??n;return!e||!s?null:{conversationId:e,projectId:s}}function FI(e){const{t}=se(),n=de(r=>r.delegations),s=e?xL(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:PI(r.trigger,t)})})),[o,t])}const AZ=2500;function HI({focus:e,timelineRef:t,items:n,baseIndex:s,hasMessages:o,loading:r,loadOlder:a,onDone:l}){const[c,d]=m.useState(null),u=m.useRef(null);return m.useEffect(()=>{if(!e||u.current===e.nonce)return;const h=bZ({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"?vZ(n,e.messageIndex):void 0;p&&(window.setTimeout(()=>t.current?.scrollToKey(p),60),d({key:p,query:e.query}))},[e,n,s,o,r,a,l,t]),m.useEffect(()=>{if(!c)return;const h=window.setTimeout(()=>d(null),AZ);return()=>window.clearTimeout(h)},[c]),{searchQuery:c?.query??"",activeHit:c?{key:c.key,nth:0}:null}}function BI({conversationId:e,speaker:t,emptyTitle:n,emptyDescription:s,className:o,focus:r,onFocusDone:a,turnFooter:l,controls:c,runDividers:d,dataSlot:u}){const h=de(k=>k.sessions[e]),p=de(k=>!!k.sessionHistoryLoading[e]),f=m.useRef(null),g=h?.status==="running",x=m.useMemo(()=>h?wr(h.messages,g,h.customEntries,void 0,{historyBaseIndex:h.historyBaseIndex,toolOutputs:h.toolOutputs,pendingApprovals:h.pendingApprovals,toolStartedAt:h.toolStartedAt,runDividers:d}):[],[h,g,d]);m.useEffect(()=>{f.current?.isAtBottom()&&f.current.pinToBottom()},[x]);const v=m.useMemo(()=>()=>{de.getState().loadOlderSession(e)},[e]),y=HI({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:C}=t,_=m.useMemo(()=>({sessionId:e,canRewind:!!c,canRetry:!!c,canFork:!1,speaker:{name:b,color:w,image:C},turnFooter:l,...c?{botControls:c}:{}}),[e,b,w,C,l,c]),N=(h?.historyBaseIndex??0)>0,S=GI(e);return i.jsx(dv.Provider,{value:S,children:i.jsx(Ih.Provider,{value:_,children:i.jsxs("div",{"data-slot":u,className:U("@container flex min-h-0 flex-1 flex-col",o),children:[i.jsx(Ah,{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?()=>{de.getState().loadOlderSession(e)}:void 0,searchQuery:y.searchQuery,activeHit:y.activeHit},e),h?.retry&&i.jsx("div",{className:ji,children:i.jsx(Fh,{retry:h.retry})})]})})})}function MZ({conversationId:e,title:t,speaker:n,emptyTitle:s,emptyDescription:o,footer:r,onClose:a}){const l=FI(e);return i.jsx(vn,{open:e!==null,onOpenChange:c=>!c&&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(BI,{className:"border-t",conversationId:e,speaker:n,emptyTitle:s??t,emptyDescription:o,runDividers:l}),r&&i.jsx("div",{className:ji,children:r})]})})}function kv({conversationId:e,title:t,speaker:n,focus:s,turnFooter:o,read:r,botSession:a=!0,onClose:l}){const{t:c}=se(),[d,u]=m.useState(null),[h,p]=m.useState(),[f,g]=m.useState(),[x,v]=m.useState(!1),y=m.useRef(!1),b=m.useRef(null),w=m.useCallback(z=>r?r(z):window.electronAPI.bots.sessionHistory({conversationId:e??"",...z!==void 0?{beforeIndex:z}:{}}),[e,r]);m.useEffect(()=>{if(u(null),g(void 0),p(void 0),!e)return;let z=!0;return w().then(O=>{z&&(O.ok?(u({messages:O.messages,baseIndex:O.baseIndex}),p(O.projectId)):g(O.code==="not-found"?c("This conversation has no history yet."):O.error))}),()=>{z=!1}},[e,w,c]);const C=m.useCallback(async()=>{if(!(!e||!d||d.baseIndex<=0||y.current)){y.current=!0,v(!0);try{const z=await w(d.baseIndex);z.ok&&z.baseIndex+z.messages.length===d.baseIndex&&u({messages:[...z.messages,...d.messages],baseIndex:z.baseIndex})}finally{y.current=!1,v(!1)}}},[e,w,d]),_=FI(e),N=m.useMemo(()=>d?wr(d.messages,!1,[],void 0,{historyBaseIndex:d.baseIndex,runDividers:_}):[],[d,_]),S=m.useCallback(()=>{C()},[C]),k=HI({focus:s,timelineRef:b,items:N,baseIndex:d?.baseIndex??0,hasMessages:!!d?.messages.length,loading:x||d===null,loadOlder:S}),A=n?.name,I=n?.color,D=n?.image,P=m.useMemo(()=>({sessionId:e,canRewind:!1,canRetry:!1,botSession:a,speaker:A&&I?{name:A,color:I,image:D}:void 0,turnFooter:o}),[a,e,A,I,D,o]),T=GI(a?e:null,h);return i.jsx(dv.Provider,{value:T,children:i.jsx(vn,{open:e!==null,onOpenChange:z=>!z&&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(Ih.Provider,{value:P,children:i.jsx("div",{className:"@container flex min-h-0 flex-1 flex-col border-t",children:f?i.jsx("p",{className:"p-6 text-muted-foreground text-sm",children:f}):i.jsx(Ah,{ref:b,items:N,busy:d===null,loading:d===null,running:!1,emptyTitle:t,hasOlder:!!(d&&d.baseIndex>0),historyLoading:x,olderCursor:d?.baseIndex,onStartReached:d&&d.baseIndex>0?()=>{C()}:void 0,searchQuery:k.searchQuery,activeHit:k.activeHit})})})]})})})}function Bo(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 tg="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 RZ({group:e,thread:t}){const{t:n}=se(),s=de(k=>k.chats),o=de(k=>k.sessions),r=de(k=>k.timelines),a=de(k=>k.queue),l=de(k=>k.reads),c=de(k=>k.bots),[d,u]=m.useState(!1),[h,p]=m.useState(null),[f,g]=m.useState(null),x=e.archivedAt!==void 0,v=m.useMemo(()=>Object.fromEntries(c.map(k=>[k.id,k.name])),[c]),y=k=>k.threadTitle??(k.parentId?n("New topic"):n("Main topic")),b=wW(s,e).map(k=>{const A=Hg(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&&Qa(A.marker,l[A.key]),running:A.running,canRename:!x,canDelete:!!k.parentId}}),w=dT(b,{currentId:t.id,rootId:e.id}),C=b.length-w.length,_=k=>de.getState().openThread(e.id,k),N=async()=>{await de.getState().createThread(e.id)||ze({type:"error",title:n("Could not create topic")})},S=async k=>{const A=await window.electronAPI.bots.deleteThread(k);A.ok||ze({type:"error",title:Ns(A.error,n)}),de.getState().refreshChats()};return i.jsxs(i.Fragment,{children:[i.jsxs(Hi,{children:[i.jsxs(Bi,{className:U(tg,"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(Vn,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs(Vi,{align:"end",className:"w-72",children:[i.jsxs(Bg,{children:[i.jsx(Vg,{children:n("Topics")}),w.map(k=>i.jsxs(mn,{onClick:()=>_(k.id),children:[i.jsx(Kn,{className:U(k.id!==t.id&&"invisible")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:k.title}),i.jsx(jv,{entry:k})]},k.id))]}),i.jsx(ya,{}),C>0&&i.jsxs(mn,{onClick:()=>u(!0),children:[i.jsx(Hx,{}),n("All topics ({{n}})",{n:b.length})]}),i.jsxs(mn,{disabled:x,onClick:()=>{N()},children:[i.jsx(Go,{}),n("New topic")]}),i.jsxs(mn,{disabled:x,onClick:()=>p({id:t.id,title:y(t)}),children:[i.jsx(Bs,{}),n("Rename topic")]}),t.parentId&&i.jsxs(mn,{variant:"destructive",onClick:()=>g(t.id),children:[i.jsx(Hs,{}),n("Delete topic")]})]})]}),i.jsxs("button",{type:"button",disabled:x,onClick:()=>{N()},className:U(tg,"shrink-0"),title:n("New topic"),"aria-label":n("New topic"),children:[i.jsx(Go,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New topic")})]}),d&&i.jsx(VI,{heading:n("Topics"),placeholder:n("Search topics..."),empty:n("No matching topics"),filters:!0,entries:b,currentId:t.id,onClose:()=>u(!1),onOpen:k=>{_(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:d?"nested":"base"}),h!==null&&i.jsx(LZ,{initial:h.title,nested:d,onClose:()=>p(null),onSave:async k=>{const A=await window.electronAPI.bots.renameThread(h.id,k);if(!A.ok){ze({type:"error",title:Ns(A.error,n)});return}de.getState().upsertChat(A.chat),p(null)}})]})}function jv({entry:e}){const{locale:t}=se();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:Bo(e.activityAt,t)})]})}function VI({heading:e,placeholder:t,empty:n,filters:s=!1,entries:o,currentId:r,onClose:a,onOpen:l,onRename:c,onDelete:d}){const{t:u}=se(),[h,p]=m.useState(""),[f,g]=m.useState("all"),x=Lw(o,h,f),v=b=>Lw(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(sh,{"data-size":"sm",className:"mt-1",children:[i.jsx(ih,{children:i.jsx(ei,{})}),i.jsx(oh,{autoFocus:!0,value:h,placeholder:t,onChange:b=>p(b.target.value)})]}),s&&i.jsx(eh,{value:f,onValueChange:b=>g(b),children:i.jsxs(th,{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:U("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(jv,{entry:b})]}),c&&b.canRename&&i.jsx("button",{type:"button",className:y,onClick:()=>c(b),title:u("Rename topic"),"aria-label":u("Rename topic"),children:i.jsx(Bs,{className:"h-3.5 w-3.5"})}),d&&b.canDelete?i.jsx("button",{type:"button",className:U(y,"hover:text-destructive"),onClick:()=>d(b),title:u("Delete topic"),"aria-label":u("Delete topic"),children:i.jsx(Hs,{className:"h-3.5 w-3.5"})}):d?i.jsx("span",{className:"w-5.5 shrink-0","aria-hidden":!0}):null]},b.id))]})]})})}function LZ({initial:e,nested:t,onClose:n,onSave:s}){const{t:o}=se(),[r,a]=m.useState(e),l=()=>{r.trim()&&s(r.trim())};return i.jsx(vn,{open:!0,onOpenChange:c=>!c&&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:c=>a(c.target.value),onKeyDown:c=>{c.nativeEvent.isComposing||c.key==="Enter"&&l()}})}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(xe,{size:"sm",disabled:!r.trim(),onClick:l,children:o("Save")})]})]})})}function OZ({chat:e,botId:t,running:n,onView:s}){const{t:o}=se(),[r,a]=m.useState([]),[l,c]=m.useState(!1),[d,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(C=>C.botId===t))})},[e.id,t]);m.useEffect(p,[p,h,n]);const f=r.map(w=>{const C=w.conversationId===h;return{id:w.conversationId,title:w.title??o(C?"New conversation":"Untitled conversation"),preview:C||w.resumable?"":o("Workspace changed; view only"),activityAt:w.activityAt??(C?Date.now():0),unread:!1,running:C&&n,resumable:w.resumable}}),g=dT(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 C=await window.electronAPI.bots.switchSession(e.id,w);C.ok||ze({type:"error",title:Ns(C.error,o)}),await de.getState().refreshChats(),p()},b=w=>{const C=f.find(_=>_.id===w);!C||w===h||(C.resumable?n?u(w):y(w):s(w,C.title))};return f.length<2?null:i.jsxs(i.Fragment,{children:[i.jsxs(Hi,{onOpenChange:w=>w&&p(),children:[i.jsxs(Bi,{className:U(tg,"max-w-56"),children:[i.jsx("span",{className:"truncate",children:v}),i.jsx(Vn,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs(Vi,{align:"end",className:"w-72",children:[i.jsxs(Bg,{children:[i.jsx(Vg,{children:o("Conversations")}),g.map(w=>i.jsxs(mn,{onClick:()=>b(w.id),children:[i.jsx(Kn,{className:U(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(jv,{entry:w})]},w.id))]}),x>0&&i.jsxs(i.Fragment,{children:[i.jsx(ya,{}),i.jsxs(mn,{onClick:()=>c(!0),children:[i.jsx(Hx,{}),o("All conversations ({{n}})",{n:f.length})]})]})]})]}),l&&i.jsx(VI,{heading:o("Conversations"),placeholder:o("Search conversations..."),empty:o("No matching conversations"),entries:f,currentId:h??"",onClose:()=>c(!1),onOpen:w=>{c(!1),b(w)}}),i.jsx(ms,{open:d!==null,onOpenChange:w=>!w&&u(null),title:o("Switch conversation?"),description:o("The reply in progress will be stopped."),confirmLabel:o("Switch"),onConfirm:()=>d&&void y(d)})]})}function $I(e){const{t}=se(),n=Ca(),s=ye(c=>c.virtualModels);if(!e?.engine)return t("Default model");const{providerId:o,modelId:r}=e.engine,a=Qj(s,e.engine);return a?a.name:n.find(c=>c.id===o)?.models.find(c=>c.id===r)?.label??r}function zZ({chat:e,group:t=e}){const{t:n}=se(),s=de(le=>le.bots),o=de(le=>le.chats),r=de(le=>le.sessions),a=de(le=>le.queue),l=de(le=>le.delegations),c=de(le=>le.timelines[e.id]),d=de(le=>le.runtime[e.id]),u=de(le=>le.markRead),h=de(le=>le.panelOpen),p=de(le=>le.panelTab),f=de(le=>le.browserTabs[t.id]?.tabs.length??0),g=de(le=>le.panelWidth),x=ye(le=>le.skills),v=ye(le=>le.voiceInputEnabled),y=ye(le=>le.voiceModel),{status:b}=qj(v),w=v&&b?.state!=="unsupported"&&b?.models.find(le=>le.id===y)?.state==="ready",[C,_]=m.useState(!1),[N,S]=m.useState(0),k=Sa(),A=m.useRef(null);m.useEffect(()=>{const le=A.current?.parentElement;if(!le)return;const ht=()=>S(le.clientWidth);ht();const Ot=new ResizeObserver(ht);return Ot.observe(le),()=>Ot.disconnect()},[]);const I=k?N:Zj(g,N),D=h?I:0,P=m.useCallback(le=>{const ht=A.current?.parentElement;ht&&de.getState().nudgePanelWidth(-le,ht.clientWidth)},[]),[T,z]=m.useState(null),[O,L]=m.useState(),[V,X]=m.useState(null),F=de(le=>le.focus?.chatId===e.id?le.focus:null),ee=de(le=>le.clearFocus),H=m.useMemo(()=>new Map(s.map(le=>[le.id,le])),[s]),Q=m.useMemo(()=>Object.fromEntries(s.map(le=>[le.id,le.name])),[s]),q=e.members.map(le=>H.get(le)).filter(le=>!!le),ne=q.map(le=>`${le.id}:${le.skillIds.join(",")}`).join("|"),me=m.useMemo(()=>x.flatMap(le=>{const ht=q.filter(Ot=>Ot.skillIds.includes(le.id)).map(Ot=>Ot.id);return ht.length?[{id:le.id,name:le.name,description:le.description,owners:ht}]:[]}),[x,ne]),ke=m.useMemo(()=>o.filter(le=>le.id!==t.id&&!le.parentId&&le.archivedAt===void 0).map(le=>({id:le.id,title:Ss(le,s,n),kind:le.kind})),[o,t.id,s,n]),Me=Hg(e,{sessions:r,timeline:c,queue:a,names:Q}),ge=de(le=>le.reads[Me.key]),$=e.kind==="group"?vL(c,ge):Me.marker,W=m.useMemo(()=>l.filter(le=>le.chatId===e.id),[l,e.id]),ue=m.useMemo(()=>Yj(r,Xj(o,l),e.id),[r,o,l,e.id]),J=T?(le=>{const ht=W.find(jt=>jt.childConversationId===le);if(ht)return H.get(ht.targetBotId);const Ot=Object.entries(e.sessions).find(([,jt])=>jt.conversationId===le)?.[0],Fe=c?.entries.find(jt=>jt.kind==="bot"&&jt.conversationId===le);return H.get(Ot??(Fe?.kind==="bot"?Fe.botId:e.kind==="direct"?e.members[0]:""))})(T.id):void 0,ae=V?H.get(V.botId):void 0,te=V?ue.filter(le=>le.conversationId===V.id):[],pe=V?.title??ae?.name??n("Deleted member"),Te=V&&l.find(le=>le.childConversationId===V.id)?.state==="queued",$e=m.useCallback((le,ht)=>{const Ot=bL(de.getState().delegations,le);Ot?(de.getState().sessions[le]||de.getState().trackSession(le),X({id:le,botId:Ot.botId,title:ht})):z({id:le,title:ht})},[]);m.useEffect(()=>{u(Me.key,$)},[u,Me.key,$]),m.useEffect(()=>{if(e.kind==="group"){const le=de.getState();le.timelines[e.id]?.history&&le.focus?.chatId!==e.id?le.jumpLatest(e.id):le.loadLatest(e.id),de.getState().refreshRuntime(e.id)}},[e.id,e.kind]);const Ie=e.kind==="direct"?q[0]:void 0,Ze=Ie?e.sessions[Ie.id]?.conversationId:void 0,Nt=F?.locator,Ut=F&&Nt?.kind==="session"&&Nt.conversationId===Ze?{messageIndex:Nt.messageIndex,query:F.query,nonce:F.nonce}:void 0,Pt=F&&Nt?.kind==="timeline"?{seq:Nt.seq,query:F.query,nonce:F.nonce}:void 0;m.useEffect(()=>{F?.locator.kind==="session"&&F.locator.conversationId!==Ze&&(z({id:F.locator.conversationId,title:n("History")}),L({messageIndex:F.locator.messageIndex,query:F.query,nonce:F.nonce}),ee(F.nonce))},[F,Ze,ee,n]);const _t=T?.id,B=m.useCallback(le=>e.kind==="direct"&&_t?i.jsx(Pu,{target:{chatId:e.id,conversationId:_t,messageIndex:le}}):null,[e.id,e.kind,_t]),je=e.archivedAt!==void 0,Ye=d?.current?H.get(d.current):void 0,Tt=(()=>{if(je)return n("This chat is archived. Restore it before sending.");if(e.kind==="group"){const le=e.routing.mode==="smart"?n("Without @, the best-fit member is picked to reply"):n("Without @, the group owner replies");return Ye?`${le} · ${n("{{name}} is replying; new messages are routed after they finish",{name:Ye.name})}`:le}return Me.running&&Ie?n("{{name}} is working; your message joins the current turn",{name:Ie.name}):null})(),Wt=async({text:le,images:ht,...Ot})=>{const Fe=await de.getState().send(e.id,le,ht,Ot);return Fe.ok?(Fe.queued&&ze({type:"info",title:n("Queued until a session slot frees up")}),de.getState().timelines[e.id]?.history&&de.getState().jumpLatest(e.id),!0):(ze({type:"error",title:n("Message not sent"),description:Ns(Fe.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:[Ie?i.jsx(sn,{bot:Ie,busy:Me.running}):i.jsx(al,{bots:q,busy:Me.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:Ie?i.jsx(FZ,{bot:Ie,running:Me.running,queued:Me.queued,conversationId:e.sessions[Ie.id]?.conversationId}):n("{{n}} members · Owner {{name}}",{n:q.length,name:H.get(e.bossBotId??"")?.name??"—"})})]}),i.jsx("div",{className:"flex-1"}),i.jsx(RI,{chat:t}),Ie?i.jsxs(i.Fragment,{children:[i.jsx(OZ,{chat:e,botId:Ie.id,running:Me.running,onView:(le,ht)=>z({id:le,title:ht})}),i.jsxs("button",{type:"button",disabled:je,onClick:()=>{window.electronAPI.bots.newSession(e.id).then(le=>{le.ok?de.getState().refreshChats():ze({type:"error",title:Ns(le.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(Go,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New conversation")})]})]}):i.jsx(RZ,{group:t,thread:e})]}),Ie?i.jsxs(i.Fragment,{children:[i.jsx(GZ,{items:Kj(W,e.id),bots:H,onOpenConversation:$e}),i.jsx(BZ,{chat:e,bot:Ie,focus:Ut,onFocusDone:ee})]}):i.jsx(_Z,{chat:e,bots:H,timeline:c,runtime:d,delegations:W,focus:Pt,onFocusDone:ee,onLoadOlder:()=>{de.getState().loadOlder(e.id)},onLoadNewer:()=>{de.getState().loadNewer(e.id)},onLoadAround:le=>de.getState().loadAround(e.id,le),onJumpLatest:()=>{de.getState().jumpLatest(e.id)},onOpenConversation:$e,onOpenLive:(le,ht)=>X({id:le,botId:ht,title:H.get(ht)?.name??n("Deleted member")})}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:U(ji,"pb-4"),children:[Ie&&(Me.running||Me.queued)&&i.jsx(cI,{conversationId:e.sessions[Ie.id]?.conversationId,className:"mb-2 rounded-lg border bg-muted/30 px-3 py-2"}),i.jsx(BS,{items:ue,bots:H,showNames:e.kind==="group"}),e.kind==="group"&&i.jsx(mJ,{chatId:e.id,memberIds:e.members,bots:H,onOpenLive:(le,ht)=>X({id:le,botId:ht,title:H.get(ht)?.name??n("Deleted member")})}),i.jsx(tJ,{chatId:e.id,placeholder:Ie?n("Message {{name}}…",{name:Ie.name}):n("@ a member, or just say it…"),members:e.kind==="group"?q:void 0,chatOptions:ke,skills:me,voice:w?zD:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,running:Me.running||!!(d?.current||d?.routing),disabled:je,hint:Tt,toolbar:Ie?i.jsx(HZ,{bot:Ie}):null,onSend:Wt,onStop:()=>{de.getState().stop(e.id)}},e.id)]})})]}),h&&!k&&i.jsx(ku,{onResize:P,onResizingChange:_}),i.jsx(Rs.aside,{ref:A,initial:!1,animate:{width:D},style:k?void 0:{maxWidth:`max(0px, calc(100% - ${Jj+$g}px))`},transition:OD({skip:C,cover:k,targetW:D}),className:U("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:U("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(le=>i.jsxs("button",{type:"button",onClick:()=>de.getState().setPanelTab(le),className:U("flex h-7 items-center gap-1.5 rounded-md px-2.5 text-xs transition-colors",p===le?"bg-brand/10 font-medium text-foreground dark:bg-brand/15":"text-muted-foreground hover:text-foreground"),children:[le==="info"?i.jsx(rh,{className:"h-3.5 w-3.5"}):i.jsx(go,{className:"h-3.5 w-3.5"}),n(le==="info"?Ie?"Member":"Group info":"Browser"),le==="browser"&&f>0&&i.jsx("span",{className:"text-muted-foreground tabular-nums",children:f})]},le))}),p==="browser"?i.jsx(hX,{chatId:t.id,visible:h}):Ie?i.jsx(tZ,{botId:Ie.id,chat:e,onOpenHistory:$e}):i.jsx(mZ,{chat:t,thread:e,onOpenConversation:$e})]})}),i.jsx(kv,{conversationId:T?.id??null,title:T?.title??"",speaker:J?{name:J.name,color:J.avatar.color,image:Zd(J)}:void 0,focus:O,turnFooter:B,onClose:()=>{z(null),L(void 0)}}),i.jsx(MZ,{conversationId:V?.id??null,title:pe,speaker:{name:ae?.name??pe,color:ae?.avatar.color??"#64748b",image:ae?Zd(ae):void 0},emptyTitle:Te?n("Queued and has not started yet"):void 0,emptyDescription:Te?"":void 0,footer:ae&&te.length>0?i.jsx(BS,{items:te,bots:H,showNames:!1}):void 0,onClose:()=>X(null)})]})}function GZ({items:e,bots:t,onOpenConversation:n}){const{t:s}=se();return e.length===0?null:i.jsx("div",{className:"shrink-0 border-b bg-muted/30",children:i.jsxs("div",{className:U(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(zh,{record:o,bots:t,onOpenConversation:n},o.id))})]})})}function FZ({bot:e,running:t,queued:n,conversationId:s}){const{t:o}=se(),r=$I(e),a=o(t?"Working":n?"Queued":"Idle");return i.jsxs(i.Fragment,{children:[[e.title,r,a].filter(Boolean).join(" · "),t&&i.jsx(zI,{conversationId:s,className:"ml-1.5 text-warning"})]})}function HZ({bot:e}){const{t}=se(),n=$I(e),s=Rl[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(ti,{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(Yu,{className:"h-3 w-3"}),t(s.labelKey)]})]})}function BZ({chat:e,bot:t,focus:n,onFocusDone:s}){const{t:o}=se(),r=e.sessions[t.id]?.conversationId,a=e.archivedAt!==void 0,l=m.useMemo(()=>{if(a||!r)return;const d=u=>{u.ok||ze({type:"error",title:Ns(u.error??"unavailable",o)})};return{subscribe:de.subscribe,projection:()=>de.getState().sessions[r],rewind:(u,h)=>{de.getState().rewind(e.id,u,h).then(d)},retry:()=>{de.getState().retry(e.id).then(d)}}},[e.id,r,a,o]),c=m.useCallback(d=>r?i.jsx(Pu,{target:{chatId:e.id,conversationId:r,messageIndex:d}}):null,[e.id,r]);return r?i.jsx(BI,{conversationId:r,speaker:{name:t.name,color:t.avatar.color,image:Zd(t)},emptyTitle:o("Say hi to {{name}}",{name:t.name}),focus:n,onFocusDone:s,turnFooter:c,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 BS({items:e,bots:t,showNames:n}){const{t:s}=se(),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),c=a[0].delegation,d=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||c)&&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"}),c?s("{{name}} (on behalf of {{owner}}) needs you",{name:d,owner:t.get(c.parentBotId)?.name??s("Deleted member")}):s("{{name}} needs you",{name:d})]}),i.jsx(jh,{approvals:u,onRespond:(p,f)=>{window.electronAPI.agent.respondApproval(r,p,f)}}),i.jsx(_h,{asks:h,onAnswer:(p,f)=>{window.electronAPI.agent.respondAsk(r,p,f)}})]},r)})})}function VZ(e,t){const n={pending:[],budgets:[],routines:[],silences:[],interrupted:[],blocked:[],count:0};for(const s of wL(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 $Z({write:e,bot:t,chatName:n}){const{t:s}=se(),o=yL(u=>u.review),[r,a]=m.useState(!1),[l,c]=m.useState(null),d=u=>{a(!0),c(null),o(e.id,u).then(h=>{h.ok||c(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(xe,{size:"xs",variant:"outline",disabled:r,onClick:()=>d("reject"),children:s("Reject")}),i.jsx(xe,{size:"xs",disabled:r,onClick:()=>d("approve"),children:s("Approve")})]})]})}function WZ(){const{t:e}=se(),t=de(p=>p.inbox),n=de(p=>p.chats),s=de(p=>p.bots),o=de(p=>p.delegations),r=de(p=>p.routines),[a,l]=m.useState(null),c=m.useMemo(()=>VZ(t,{routines:r,delegations:o}),[t,r,o]),d=SL(),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:[c.count===0&&d.length===0&&i.jsxs("div",{className:"flex flex-col items-center gap-2 py-16 text-muted-foreground",children:[i.jsx(Fx,{className:"h-6 w-6"}),i.jsx("p",{className:"text-sm",children:e("Nothing needs your attention")})]}),c.pending.map(p=>i.jsx(XZ,{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}`)),c.budgets.map(p=>i.jsx(KZ,{item:p,bot:u.get(p.botId??"")},p.key)),d.map(p=>i.jsx($Z,{write:p,bot:p.botId?u.get(p.botId):void 0,chatName:h(p.chatId)},p.id)),c.routines.map(p=>i.jsx(WJ,{alert:p},p.routine.id)),c.silences.map(p=>i.jsx(UZ,{item:p,bot:u.get(p.botId??""),chatName:h(p.chatId)},p.key)),c.blocked.length>0&&i.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Stuck delegated tasks")}),c.blocked.map(({item:p,record:f})=>i.jsx(qZ,{inboxKey:p.key,record:f,bots:u,chatName:h(f.chatId)},p.key)),c.interrupted.length>0&&i.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Interrupted delegations")}),c.interrupted.map(({item:p,record:f})=>i.jsx(YZ,{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(kv,{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 UZ({item:e,bot:t,chatName:n}){const{t:s}=se(),o=de(l=>l.setView),r=de(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(OI,{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(xe,{size:"xs",variant:"ghost",onClick:()=>{r(e.key)},children:s("Dismiss")}),e.chatId&&i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>e.chatId&&o({kind:"chat",chatId:e.chatId}),children:s("Go to chat")})]})]})}function KZ({item:e,bot:t}){const{t:n}=se(),s=de(a=>a.dismissInbox),o=de(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(xe,{size:"xs",variant:"ghost",onClick:()=>{s(e.key)},children:n("Dismiss")}),t&&i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>{o(t.id)},children:n("Go to chat")})]})]})}function qZ({inboxKey:e,record:t,bots:n,chatName:s}){const{t:o}=se(),r=de(g=>g.openTask),a=de(g=>g.dismissInbox),l=Oh(!0),c=n.get(t.targetBotId),d=c?.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:c,size:"xs"}),i.jsx("span",{className:"text-foreground",children:d}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx(Lh,{state:t.state}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:o("Stuck for {{time}}",{time:xo(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(Cv,{placeholder:o("Answer {{name}}; they continue after your reply…",{name:d}),onSend:g=>EI(p,f,g,o)})]}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(xe,{size:"xs",variant:"ghost",onClick:()=>{a(e)},children:o("Dismiss")}),p&&f&&i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>r(p,f),children:o("Open task card")})]})]})}function YZ({inboxKey:e,record:t,bots:n,chatName:s,onOpen:o}){const{t:r}=se(),a=de(p=>p.setView),l=de(p=>p.dismissInbox),c=n.get(t.parentBotId),d=n.get(t.targetBotId),u=c?.name??r("Deleted member"),h=d?.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:c,size:"xs"}),i.jsx("span",{className:"text-foreground",children:u}),i.jsx("span",{children:"→"}),i.jsx(sn,{bot:d,size:"xs"}),i.jsx("span",{className:"text-foreground",children:h}),i.jsxs("span",{children:["· ",r("Delegation")]}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx(Lh,{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:Ic(t,r)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(xe,{size:"xs",variant:"ghost",onClick:()=>{l(e)},children:r("Dismiss")}),t.chatId&&i.jsx(xe,{size:"xs",variant:"ghost",onClick:()=>t.chatId&&a({kind:"chat",chatId:t.chatId}),children:r("Go to chat")}),i.jsx(xe,{size:"xs",variant:"outline",onClick:()=>o(r("{{from}} → {{to}} · Delegation",{from:u,to:h})),children:r("View conversation")}),i.jsx(xe,{size:"xs",onClick:()=>_l(t.id,r),children:r("Retry")})]})]})}function XZ({item:e,bot:t,owner:n,chatName:s}){const{t:o}=se(),r=de(g=>g.setView),[a,l]=m.useState(""),[c,d]=m.useState(!1),u=g=>{d(!0),g.finally(()=>d(!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:uT(e.request.protected,o)})]}),e.kind==="approval"?i.jsxs("div",{className:"mt-2 text-sm",children:[Fo(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(xe,{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(xe,{size:"xs",variant:"outline",disabled:c,onClick:()=>h("deny"),children:o("Deny")}),!e.request.protected&&i.jsx(xe,{size:"xs",variant:"outline",disabled:c,onClick:()=>h("allowSession"),children:o("Always allow in this session")}),i.jsx(xe,{size:"xs",disabled:c,onClick:()=>h("allow"),children:o("Allow")})]}):i.jsxs(i.Fragment,{children:[e.request.options?.map(g=>i.jsx(xe,{size:"xs",variant:"outline",disabled:c,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.nativeEvent.isComposing||c||g.key==="Enter"&&p(a)}}),i.jsx(xe,{size:"xs",disabled:c||!a.trim(),onClick:()=>p(a),children:o("Reply")})]})]})]})}function JZ(e){const{openOnInputClick:t=!1,value:n,defaultValue:s,onValueChange:o,mode:r="list",itemToStringValue:a,...l}=e,c=r==="inline"||r==="both",d=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;c&&f!==""?x=f:u?x=n??"":x=h;const v=CL({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"?d?null:y:y===null?null:(N,S,k)=>y(N,b,k),[y,r,b,d]);function C(N,S){g(""),u||p(N),o?.(N,S)}function _(N,S){e.onItemHighlighted?.(N,S),S.reason!==jL&&g(c&&N!=null?_L(N,a):"")}return i.jsx(kL,{...l,itemToStringLabel:a,openOnInputClick:t,selectionMode:"none",fillInputOnItemPress:!0,filter:w,autoComplete:r,inputValue:x,defaultInputValue:s,onInputValueChange:C,onItemHighlighted:_})}const ZZ=NL,QZ="",eQ=200;function tQ(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 nQ(){const e=TL(),t=m.useRef(null);return m.useEffect(()=>{if(DL)return;const n=t.current;if(n==null)return;const s=tQ(n);if(s==null)return;const o=s.data,r=`${o}${QZ}`;return s.nodeValue=r,e.start(eQ,()=>{s.nodeValue===r&&(s.nodeValue=o)}),()=>{e.clear(),s.nodeValue===r&&(s.nodeValue=o)}},[t,e]),t}const WI=m.createContext(void 0);function sQ(){const e=m.useContext(WI);if(e===void 0)throw new Error(ac(18));return e}const iQ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,items:a,...l}=t,[c,d]=m.useState(),u=m.useMemo(()=>({labelId:c,setLabelId:d,items:a}),[c,d,a]),h=lc("div",t,{ref:n,props:[{role:"group","aria-labelledby":c},l]}),p=i.jsx(WI.Provider,{value:u,children:h});return a?i.jsx(IL,{items:a,children:p}):p}),oQ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,id:a,...l}=t,{setLabelId:c}=sQ(),d=cj(a);return Ag(()=>(c(d),()=>{c(h=>h===d?void 0:h)}),[d,c]),lc("div",t,{ref:n,props:[{id:d},l]})}),rQ=EL,aQ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,children:a,...l}=t,{filteredItems:c}=PL(),d=AL(),u=nQ(),h=c.length===0?a:null;return lc("div",t,{ref:[n,d.state.emptyRef,u],props:[{children:h,role:"status","aria-live":"polite","aria-atomic":!0},l]})});function lQ(e){const t=e.value.length>0,n=t?e.value.replace(/ /g," "):"",s=e.clearing&&t&&n!==e.mirrorText;return{hasValue:t,mirrorText:n,superseded:s}}const _v=JZ,Nl=new WeakMap,Lu=new WeakMap;function cQ(e){const t=Nl.get(e);t!==void 0&&window.clearTimeout(t),Nl.delete(e);for(const n of Lu.get(e)??[])n.cancel();Lu.delete(e),e.classList.remove("is-clearing")}function Ar(e,t){const n=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(e));return Number.isFinite(n)?n:t}function Ud(e){const t=e.querySelector("input"),n=e.querySelector(".t-clear-mirror");if(!t||!n)return;const s=lQ({value:t.value,mirrorText:n.textContent??"",clearing:e.classList.contains("is-clearing")});s.superseded&&cQ(e),e.classList.toggle("has-value",s.hasValue),n.textContent=s.mirrorText}function dQ(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=Nl.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=Ar("--clear-dur",1e3),c=Ar("--clear-out-dur",400),d=Ar("--clear-in-dur",400),u=Ar("--clear-out-fly",12),h=Ar("--clear-in-fly",12),p=Ar("--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:c,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:d,easing:g,fill:"forwards"}),y=window.setTimeout(()=>{x.cancel(),v.cancel(),Lu.delete(t),t.classList.remove("is-clearing"),s.textContent="",Nl.delete(t),Ud(t)},Math.max(l,c,d));Nl.set(t,y),Lu.set(t,[x,v])}function Nv({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&&Ud(l.current);const c=window.requestAnimationFrame(()=>{l.current&&Ud(l.current)});return()=>window.cancelAnimationFrame(c)}),i.jsxs("div",{ref:l,className:"t-clear autocomplete-clear-dissolve relative w-full",onInput:c=>Ud(c.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(ML,{className:U(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:U("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:U("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(fQ,{className:U("-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(e_,{})}),n&&i.jsx(pQ,{className:U("-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 UI({className:e,children:t,sideOffset:n=4,zIndex:s,...o}){return i.jsx(RL,{children:i.jsx(LL,{className:"z-[55] select-none",style:s?{zIndex:s}:void 0,"data-slot":"autocomplete-positioner",sideOffset:n,children:i.jsx("span",{className:U("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(OL,{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 Tv({className:e,children:t,...n}){return i.jsx(rQ,{className:U("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 uQ({className:e,...t}){return i.jsx(iQ,{className:U("[[role=group]+&]:mt-1.5",e),"data-slot":"autocomplete-group",...t})}function hQ({className:e,...t}){return i.jsx(oQ,{className:U("px-2 py-1.5 font-medium text-muted-foreground text-xs",e),"data-slot":"autocomplete-group-label",...t})}function Dv({className:e,...t}){return i.jsx(aQ,{className:U("not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",e),"data-slot":"autocomplete-empty",...t})}function Iv({className:e,...t}){return i.jsx(zL,{scrollbarGutter:!0,scrollFade:!0,children:i.jsx(GL,{className:U("not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3",e),"data-slot":"autocomplete-list",...t})})}function pQ({className:e,onClickCapture:t,onPointerDownCapture:n,...s}){return i.jsx(FL,{className:U("-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||dQ(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 fQ({className:e,...t}){return i.jsx(ZZ,{className:e,"data-slot":"autocomplete-trigger",...t})}const KI=m.createContext({inputRef:null}),qI=HL,mQ=BL;function gQ({className:e,...t}){return i.jsx(WL,{className:U("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 xQ({className:e,...t}){return i.jsx(UL,{className:U("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 YI({className:e,children:t,...n}){const s=m.useRef(null);return i.jsxs(mQ,{children:[i.jsx(VL,{}),i.jsx(gQ,{}),i.jsx(xQ,{children:i.jsx($L,{className:U("-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(KI.Provider,{value:{inputRef:s},children:t})})})]})}function XI({autoHighlight:e="always",keepHighlight:t=!0,open:n=!0,...s}){return i.jsx(_v,{autoHighlight:e,keepHighlight:t,open:n,...s})}function JI({className:e,placeholder:t=void 0,endAddon:n,...s}){const{inputRef:o}=m.useContext(KI);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(Nv,{className:U("border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0",e),placeholder:t,ref:o,size:"lg",startAddon:i.jsx(ei,{}),...s})}),n]})}function ZI({className:e,...t}){return i.jsx(Iv,{className:U("not-empty:scroll-py-2 not-empty:p-2",e),"data-slot":"command-list",...t})}function QI({className:e,...t}){return i.jsx(Dv,{className:U("not-empty:py-6",e),"data-slot":"command-empty",...t})}function eE({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 Mr({className:e,...t}){return i.jsx(uQ,{className:e,"data-slot":"command-group",...t})}function Rr({className:e,...t}){return i.jsx(hQ,{className:e,"data-slot":"command-group-label",...t})}function ar({className:e,...t}){return i.jsx(Tv,{className:U("py-1.5",e),"data-slot":"command-item",...t})}function VS({className:e,...t}){return i.jsx("span",{className:U("ms-auto font-medium text-muted-foreground/72 text-xs tracking-widest",e),"data-slot":"command-shortcut",...t})}function tE({className:e,...t}){return i.jsx("div",{className:U("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 $S=e=>e.locator.kind==="timeline"?`${e.chatId}:${e.locator.seq}`:`${e.chatId}:${e.locator.conversationId}:${e.locator.messageIndex}`;function nE({className:e}){const{t}=se(),n=ye(r=>r.keybindings),s=Oi(n)["search-workspace"],o=t("Search messages");return i.jsx("button",{type:"button",className:e,onClick:()=>de.getState().setSearchOpen(!0),title:s?`${o} (${mi(s)})`:o,children:i.jsx(ei,{className:"h-4 w-4"})})}function vQ(){const{t:e,locale:t}=se(),n=de(v=>v.searchOpen),s=de(v=>v.setSearchOpen),o=de(v=>v.bots),r=de(v=>v.chats),[a,l]=m.useState(""),[c,d]=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=c?.key===u?c:void 0;m.useEffect(()=>{n||(l(""),d(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||d(b.ok?{key:u,hits:b.hits,truncated:b.truncated}:{key:u,hits:[],truncated:!1})}).catch(()=>{v||d({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(qI,{open:n,onOpenChange:s,children:i.jsx(YI,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:g,children:i.jsxs(XI,{children:[i.jsx(JI,{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(),de.getState().focusHit(y,u))}}),i.jsxs(eE,{children:[u&&f&&f.hits.length===0&&i.jsx(QI,{children:e("No matching messages")}),i.jsxs(ZI,{children:[f?.hits.map(v=>{const y=p.get(v.chatId),b=(y?.members??[]).map(_=>h.get(_)).filter(_=>_!==void 0),w=v.speaker.kind==="human"?e("You"):h.get(v.speaker.botId)?.name??e("Deleted member"),C=v.locator.kind==="session"&&!v.locator.current?` · ${e("History")}`:"";return i.jsxs(ar,{value:$S(v),className:"items-start gap-2.5",onClick:()=>de.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(al,{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,C]})]}),i.jsx("p",{className:"line-clamp-2 break-words text-muted-foreground text-xs",children:yZ(v.snippet,v.ranges).map((_,N)=>_.match?i.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:_.text},N):i.jsx("span",{children:_.text},N))})]}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:v.at?Bo(v.at,t,x):""})]},$S(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(tE,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(t_,{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 bQ({chat:e,onOpenChange:t}){const{t:n}=se(),s=de(f=>f.bots),o=de(f=>f.chats),r=ye(f=>f.projects),[a,l]=m.useState(""),[c,d]=m.useState(!1);if(m.useEffect(()=>{if(!e)return;const f=o.filter(g=>g.kind==="group").map(g=>g.title);l(KL(n("{{title}} copy",{title:Ss(e,s,n)}),f)),d(!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){d(!0);try{const g=await window.electronAPI.bots.cloneChat({chatId:e.id,title:f});if(!g.ok){ze({type:"error",title:Ns(g.error,n)});return}const x=de.getState();x.upsertChat(g.chat),x.setView({kind:"chat",chatId:g.chat.id}),x.loadLatest(g.chat.id),ze({type:"success",title:n("Cloned. The chat history is empty.")}),t(!1)}finally{d(!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(qt,{children:n("Group name")}),i.jsx(Jt,{value:a,autoFocus:!0,onChange:f=>l(f.target.value),onKeyDown:f=>{f.nativeEvent.isComposing||c||f.key==="Enter"&&p()}})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(qt,{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:$j(e,r,s,n)}):n("A new empty folder, separate from the original")]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(qt,{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(xe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsx(xe,{size:"sm",disabled:!a.trim()||c,onClick:()=>{p()},children:n("Clone")})]})]})})}const nr="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function wQ({width:e,onCollapse:t,onNewMember:n,onNewGroup:s,onNewTeam:o,onStartFromGoal:r}){const{t:a,locale:l}=se(),c=[{label:a("Start from a goal"),icon:Ia,onClick:r},{label:a("New member"),icon:$l,onClick:n},{label:a("New group chat"),icon:da,onClick:s},{label:a("Create team from template"),icon:Gf,onClick:o}],d=de(B=>B.bots),u=de(B=>B.chats),h=de(B=>B.queue),p=de(B=>B.sessions),f=de(B=>B.delegations),g=de(B=>B.timelines),x=de(B=>B.reads),v=de(B=>B.view),y=de(B=>B.setView),b=de(B=>B.openDirect),w=de(B=>B.upsertChat),C=de(B=>B.upsertBot),[_,N]=m.useState(!1),[S,k]=m.useState(""),[A,I]=m.useState(null),[D,P]=m.useState(null),T=m.useMemo(()=>new Map(d.map(B=>[B.id,B])),[d]),z=m.useMemo(()=>Object.fromEntries(d.map(B=>[B.id,B.name])),[d]),O=m.useMemo(()=>Yj(p,Xj(u,f)),[p,u,f]),L=m.useMemo(()=>{const B=new Set,je=new Set;for(const Ye of f)Ml(Ye.state)&&(Ye.chatId&&B.add(Ye.chatId),je.add(Ye.targetBotId));return{chatIds:B,botIds:je}},[f]),V=m.useMemo(()=>qL(u.map(B=>{const je=Hg(B,{sessions:p,timeline:g[B.id],queue:h,names:z});return{chat:B,summary:{...je,running:je.running||(B.kind==="group"?L.chatIds.has(B.id):L.botIds.has(B.members[0])),pending:O.filter(Ye=>Ye.chatId===B.id).length}}}),x),[u,p,g,h,z,O,L,x]),X=V.filter(B=>!B.chat.archivedAt),F=YL(X.filter(B=>B.chat.kind==="group"&&B.chat.settledAt===void 0)),ee=new Map(X.filter(B=>B.chat.kind==="direct").map(B=>[B.chat.members[0],B])),H=d.filter(B=>B.archivedAt===void 0&&ee.get(B.id)?.chat.settledAt===void 0).map(B=>({bot:B,row:ee.get(B.id)})).sort((B,je)=>{const Ye=Number(je.row?.chat.pinned??!1)-Number(B.row?.chat.pinned??!1),Tt=(B.row?.chat.pinOrder??Number.POSITIVE_INFINITY)-(je.row?.chat.pinOrder??Number.POSITIVE_INFINITY);return Ye||(B.row?.chat.pinned&&Tt?Tt:0)||(je.row?.summary.activityAt??je.bot.updatedAt)-(B.row?.summary.activityAt??B.bot.updatedAt)}),Q=X.filter(B=>B.chat.settledAt!==void 0&&(B.chat.kind==="group"||T.get(B.chat.members[0])?.archivedAt===void 0)).sort((B,je)=>(je.chat.settledAt??0)-(B.chat.settledAt??0)),q=F.filter(B=>B.chat.pinned).map(B=>B.chat.id),ne=H.flatMap(({row:B})=>B?.chat.pinned?[B.chat.id]:[]),[me,ke]=m.useState(null),[Me,ge]=m.useState(!0),$=V.filter(B=>B.chat.archivedAt!==void 0),W=d.filter(B=>B.archivedAt!==void 0),ue=$.length+W.length,Z=S.trim().toLowerCase(),J=(...B)=>!Z||B.some(je=>je.toLowerCase().includes(Z)),ae=$.filter(({chat:B,summary:je})=>J(Ss(B,d,a),je.preview??"")).sort((B,je)=>(je.chat.archivedAt??0)-(B.chat.archivedAt??0)),te=W.filter(B=>J(B.name,B.title,B.scope)).sort((B,je)=>(je.archivedAt??0)-(B.archivedAt??0)),pe=Wg(),Te=v?.kind==="chat"?v.chatId:null,$e=async(B,je)=>{const Ye=await window.electronAPI.bots.updateChat({chatId:B.id,...je});Ye.ok?w(Ye.chat):ze({type:"error",title:Ns(Ye.error,a)})},Ie=B=>$e(B,B.pinned?{pinned:!1}:{pinned:!0,pinOrder:Math.max(-1,...u.filter(je=>je.pinned).map(je=>je.pinOrder??0))+1}),Ze=(B,je,Ye)=>{const Tt=Object.fromEntries(u.map(Wt=>[Wt.id,Wt.pinOrder]));for(const Wt of ZL(B,je,Ye,Tt)){const le=u.find(ht=>ht.id===Wt.chatId);le&&$e(le,{pinOrder:Wt.pinOrder})}},Nt=(B,je)=>{const Ye=je.indexOf(B.id),Tt=V.find(Wt=>Wt.chat.id===B.id)?.summary;return{onSettle:()=>{$e(B,{settled:B.settledAt===void 0})},onSnooze:Wt=>{$e(B,{snoozedUntil:Wt})},onMarkUnread:Tt&&Te!==B.id&&!Qa(Tt.marker,x[Tt.key])&&XL(Tt.marker)!==void 0?()=>de.getState().markUnread(B.id):void 0,onMoveUp:Ye>0?()=>Ze(je,B.id,Ye-1):void 0,onMoveDown:Ye>=0&&Ye<je.length-1?()=>Ze(je,B.id,Ye+1):void 0}},Ut=(B,je)=>B?.pinned?{draggable:!0,onDragStart:Ye=>{Ye.dataTransfer.effectAllowed="move",ke(B.id)},onDragEnd:()=>ke(null),onDragOver:Ye=>{me&&me!==B.id&&je.includes(me)&&Ye.preventDefault()},onDrop:Ye=>{Ye.preventDefault(),me&&je.includes(me)&&Ze(je,me,je.indexOf(B.id)),ke(null)}}:{},Pt=async(B,je)=>{const Ye=await window.electronAPI.bots.archive(B.id,je);Ye.ok?C(Ye.bot):ze({type:"error",title:Ye.error})},_t=B=>B?B.running?a("Working"):B.queued?a("Queued"):B.activityAt?Bo(B.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(sf,{title:a("Group chats"),onAdd:s,addLabel:a("New group chat")}),F.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No group chats yet")}),F.map(({chat:B,summary:je})=>i.jsx(rf,{chat:B,onPin:()=>{Ie(B)},onArchive:()=>{$e(B,{archived:!0})},onDelete:()=>I(B),onClone:()=>P(B),manage:Nt(B,q),children:i.jsx(of,{...Ut(B,q),active:Te===B.id,avatar:i.jsx(al,{bots:B.members.map(Ye=>T.get(Ye)),busy:je.running}),title:Ss(B,d,a),pinned:B.pinned,meta:_t(je),preview:je.preview,unread:Qa(je.marker,x[je.key]),pending:je.pending,onClick:()=>y({kind:"chat",chatId:B.id})})},B.id)),i.jsx(sf,{title:a("Members"),onAdd:n,addLabel:a("New member")}),H.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No members yet")}),H.map(({bot:B,row:je})=>i.jsx(rf,{chat:je?.chat,onPin:je?()=>{Ie(je.chat)}:void 0,onArchive:je?()=>{$e(je.chat,{archived:!0})}:void 0,onArchiveMember:()=>{Pt(B,!0)},manage:je?Nt(je.chat,ne):void 0,children:i.jsx(of,{...Ut(je?.chat,ne),active:!!(je&&Te===je.chat.id),avatar:i.jsx(sn,{bot:B,busy:je?.summary.running||L.botIds.has(B.id)}),title:B.name,pinned:je?.chat.pinned,meta:L.botIds.has(B.id)?a("Working"):_t(je?.summary),preview:je?.summary.preview||B.title||B.scope,unread:!!(je&&Qa(je.summary.marker,x[je.summary.key])&&Te!==je.chat.id),pending:je?.summary.pending??0,onClick:()=>{b(B.id)}})},B.id)),Q.length>0&&i.jsx(sf,{title:`${a("Settled")} · ${Q.length}`,onToggle:()=>ge(B=>!B)}),Me&&Q.map(({chat:B,summary:je})=>{const Ye=B.kind==="direct"?T.get(B.members[0]):void 0;return i.jsx(rf,{chat:B,onPin:()=>{Ie(B)},onArchive:()=>{$e(B,{archived:!0})},onClone:B.kind==="group"?()=>P(B):void 0,manage:Nt(B,[]),children:i.jsx(of,{className:"opacity-75",active:Te===B.id,avatar:Ye?i.jsx(sn,{bot:Ye,busy:je.running}):i.jsx(al,{bots:B.members.map(Tt=>T.get(Tt)),busy:je.running}),title:Ye?Ye.name:Ss(B,d,a),meta:B.snoozedUntil!==void 0?a("Remind {{time}}",{time:Bo(B.snoozedUntil,l)}):_t(je),preview:je.preview,unread:Qa(je.marker,x[je.key])&&(B.kind==="group"||Te!==B.id),pending:je.pending,onClick:()=>Ye?void b(Ye.id):y({kind:"chat",chatId:B.id})})},B.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:nr,title:a("Collapse sidebar"),children:i.jsx(Bx,{className:"h-4 w-4"})}):i.jsx("span",{}),i.jsxs("div",{className:"flex items-center",children:[i.jsx(nE,{className:nr}),c.map(({label:B,icon:je,onClick:Ye})=>i.jsx("button",{type:"button",className:U(nr,"hidden @min-[18.5rem]:flex"),onClick:Ye,title:B,children:i.jsx(je,{className:"h-4 w-4"})},B)),i.jsxs(Hi,{children:[i.jsx(Bi,{className:U(nr,"@min-[18.5rem]:hidden"),title:a("More actions"),children:i.jsx(Sh,{className:"h-4 w-4"})}),i.jsx(Vi,{align:"end",side:"top",children:c.map(({label:B,icon:je,onClick:Ye})=>i.jsxs(mn,{onClick:Ye,children:[i.jsx(je,{}),B]},B))})]}),(pe>0||v?.kind==="inbox")&&i.jsxs("button",{type:"button",className:U(nr,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(Fx,{className:"h-4 w-4"}),pe>0&&i.jsx(Hh,{count:pe,className:"-top-0.5 -right-1 absolute"})]}),ue>0&&i.jsx("button",{type:"button",className:nr,onClick:()=>{k(""),N(!0)},title:`${a("Archived")} (${ue})`,children:i.jsx(Mi,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:nr,onClick:()=>{window.electronAPI.window.openSettings()},title:a("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})})]})]}),i.jsx(vn,{open:_,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:ue})]}),i.jsxs(sh,{"data-size":"sm",className:"mt-1",children:[i.jsx(ih,{children:i.jsx(ei,{})}),i.jsx(oh,{value:S,placeholder:a("Search conversations..."),onChange:B=>k(B.target.value)})]})]}),i.jsxs(Mn,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[ae.length+te.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")}),ae.length>0&&i.jsx(WS,{title:a("Chat threads"),count:ae.length,children:ae.map(({chat:B,summary:je})=>i.jsx(US,{avatar:B.kind==="group"?i.jsx(al,{bots:B.members.map(Ye=>T.get(Ye))}):i.jsx(sn,{bot:T.get(B.members[0])}),title:Ss(B,d,a),preview:je.preview,onOpen:()=>{y({kind:"chat",chatId:B.id}),N(!1)},onRestore:()=>{$e(B,{archived:!1})},onDelete:B.kind==="group"?()=>I(B):void 0},B.id))}),te.length>0&&i.jsx(WS,{title:a("Members"),count:te.length,children:te.map(B=>i.jsx(US,{avatar:i.jsx(sn,{bot:B}),title:B.name,preview:B.title||B.scope,onRestore:()=>{Pt(B,!1)}},B.id))})]})]})}),i.jsx(ms,{open:A!==null,onOpenChange:B=>!B&&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 B=A;I(null),B&&window.electronAPI.bots.deleteChat(B.id).then(je=>{je.ok?(Te===B.id&&y(null),de.getState().refreshChats()):ze({type:"error",title:Ns(je.error,a)})})}}),i.jsx(bQ,{chat:D,onOpenChange:B=>!B&&P(null)})]})}function Hh({count:e,className:t}){return i.jsx("span",{className:U("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 WS({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 US({avatar:e,title:t,preview:n,onOpen:s,onRestore:o,onDelete:r}){const{t:a}=se(),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(Vl,{className:"h-3.5 w-3.5"})}),r&&i.jsx("button",{type:"button",className:U(l,"hover:text-destructive"),onClick:r,title:a("Delete"),children:i.jsx(Hs,{className:"h-3.5 w-3.5"})})]})}function sf({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 of({active:e,avatar:t,title:n,pinned:s,meta:o,preview:r,unread:a,pending:l=0,action:c,className:d,...u}){return i.jsxs("div",{role:"button",tabIndex:0,...u,onKeyDown:h=>{h.key==="Enter"&&u.onClick?.(h)},className:U("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",d),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(ci,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"flex-1"}),l>0?i.jsx(Hh,{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"}),c&&i.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),c.onClick()},className:"shrink-0 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-background hover:text-foreground",children:c.label})]})]})]})}function rf({chat:e,children:t,onPin:n,onArchive:s,onDelete:o,onArchiveMember:r,onClone:a,manage:l}){const{t:c}=se(),d=u=>l?.onSnooze(JL(Date.now())[u]);return i.jsxs(po,{children:[i.jsx(fo,{render:t}),i.jsxs(mo,{className:"min-w-40",children:[n&&i.jsxs(Vt,{onClick:n,children:[e?.pinned?i.jsx(Su,{}):i.jsx(ci,{}),e?.pinned?c("Unpin"):c("Pin")]}),l?.onMoveUp&&i.jsxs(Vt,{onClick:l.onMoveUp,children:[i.jsx(dc,{}),c("Move up")]}),l?.onMoveDown&&i.jsxs(Vt,{onClick:l.onMoveDown,children:[i.jsx(Qu,{}),c("Move down")]}),l&&i.jsxs(Vt,{onClick:l.onSettle,children:[e?.settledAt!==void 0?i.jsx(ra,{}):i.jsx(Eg,{}),e?.settledAt!==void 0?c("Back to in progress"):c("Settle")]}),l&&i.jsxs(n_,{children:[i.jsxs(s_,{children:[i.jsx(b$,{}),c("Remind me later")]}),i.jsxs(i_,{className:"min-w-36",children:[i.jsx(Vt,{onClick:()=>d("hour"),children:c("In 1 hour")}),i.jsx(Vt,{onClick:()=>d("later"),children:c("In 3 hours")}),i.jsx(Vt,{onClick:()=>d("tomorrow"),children:c("Tomorrow 9:00")})]})]}),l?.onMarkUnread&&i.jsxs(Vt,{onClick:l.onMarkUnread,children:[i.jsx(B6,{}),c("Mark as unread")]}),a&&i.jsxs(Vt,{onClick:a,children:[i.jsx(Xu,{}),c("Clone group chat")]}),s&&i.jsxs(Vt,{onClick:s,children:[i.jsx(Mi,{}),c("Archive chat")]}),r&&i.jsxs(Vt,{onClick:r,children:[i.jsx(Vl,{}),c("Archive member")]}),o&&i.jsxs(i.Fragment,{children:[i.jsx(ah,{}),i.jsxs(Vt,{variant:"destructive",onClick:o,children:[i.jsx(Hs,{}),c("Delete group chat")]})]})]})]})}const yQ=30;function KS({onPick:e}){const{t,locale:n}=se(),s=n==="zh"?"zh":"en",o=o_(),r=de(C=>C.bots),[a,l]=m.useState(""),[c,d]=m.useState(!1),[u,h]=m.useState(null),[p,f]=m.useState(null),[g,x]=m.useState(""),v=async()=>{if(!(!a.trim()||c)){d(!0),h(null);try{const C=await window.electronAPI.bots.suggestGoal({goal:a.trim(),language:s,...r.length?{members:r.map(({id:_,name:N,title:S,scope:k})=>({id:_,name:N,title:S,scope:k}))}:{},templates:o.slice(0,yQ).map(({id:_,data:N})=>({id:_,title:N.title,summary:N.summary}))});if(!C.ok){h(Gh(C,t));return}f(C.suggestion),x(C.suggestion.firstMessage)}finally{d(!1)}}},y=async C=>{if(!c){d(!0),h(null);try{await e(C)}catch{h(t("Could not open chat. Try again."))}finally{d(!1)}}};if(!p)return i.jsxs("div",{className:"w-full max-w-lg space-y-2 text-left",children:[i.jsx(Qs,{value:a,autoFocus:!0,rows:3,placeholder:t("e.g. Track competitor news every week and send me a summary"),onChange:C=>l(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.metaKey||C.ctrlKey)&&v()}}),u&&i.jsx("p",{className:"text-destructive text-xs",children:u}),i.jsx("div",{className:"flex justify-end",children:i.jsxs(xe,{size:"sm",disabled:!a.trim()||c,onClick:()=>{v()},children:[c?i.jsx(Yt,{className:"animate-spin"}):i.jsx(ti,{}),t("Recommend")]})})]});const b=p.kind==="team"?o.find(C=>C.id===p.templateId)?.data:void 0,w=p.kind==="existing"?r.find(C=>C.id===p.botId):p.kind==="member"?{...p.member,avatar:{color:ir[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(Ia,{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(C=>i.jsx(sn,{size:"sm",bot:{name:C.name,avatar:{color:C.color}}},C.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(Qs,{value:g,rows:3,onChange:C=>x(C.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(xe,{size:"sm",variant:"ghost",disabled:c,onClick:()=>{f(null),h(null)},children:[i.jsx(cc,{}),t("Back")]}),i.jsxs("div",{className:"flex gap-2",children:[p.kind==="existing"&&i.jsx(xe,{size:"sm",variant:"outline",disabled:c,onClick:()=>{y({firstMessage:g})},children:t("Create new instead")}),i.jsx(xe,{size:"sm",disabled:c||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 nd=e=>({...yI,name:"",title:"",scope:"",persona:"",color:e,engine:null});function SQ({open:e,onOpenChange:t,seed:n,onCreated:s}){const{t:o}=se(),r=de(P=>P.bots),a=QL(),l=m.useRef(null),[c,d]=m.useState({kind:"template",id:"pm"}),[u,h]=m.useState(()=>nd(ir[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=()=>{d({kind:"blank"}),h(nd(ir[r.length%ir.length])),f(null),x(null)},S=P=>{if(!P)return N();const T=e5(P.data);d({kind:"template",id:P.id}),h({...yI,name:T.name??"",title:T.title??"",scope:T.scope??"",persona:T.persona??"",color:T.avatar?.color??ir[0],engine:null,approvalMode:T.approvalMode??"auto-edits",tools:T.tools??"all"}),f(null),x(null)};m.useEffect(()=>{e&&(n?(d({kind:"blank"}),h({...nd(ir[r.length%ir.length]),...n}),f(null),x(null)):S(a[0]),y(!1),w(!1),_(!1))},[e]);const k=P=>{h(T=>({...T,...P})),x(null)},A=async P=>{const T=new Uint8Array(await P.arrayBuffer()),z=gI(T)==="png",O=z?bJ(ES(T,"chara")??ES(T,"ccv3")??""):new TextDecoder().decode(T),L=O?kJ(O):{ok:!1,error:"not-a-card"};if(!L.ok){x(L.error==="invalid-json"&&!z?o("This file is not valid JSON."):o("This file is not a SillyTavern character card."));return}const{color:V,memoryEnabled:X,...F}=L.draft;d({kind:"import"}),h({...nd(V??u.color),...F,...X!==void 0?{memoryEnabled:X}:{}}),f(z?await Gj(P).catch(()=>null):null),y(!0),x(null)},I=zg(u.name,r,o),D=async()=>{if(y(!0),I)return;const P=bI(u);if(!P.ok){x(o("Budget must be a positive number"));return}const T=bv(u);if(!T.ok){x(o("Check the per-turn token limit and delegation time limit"));return}w(!0);try{const z=await window.electronAPI.bots.create({name:u.name.trim(),title:u.title.trim(),scope:u.scope.trim(),...T.delegationTimeoutMinutes?{delegationTimeoutMinutes:T.delegationTimeoutMinutes}:{},...T.maxTokensPerTurn?{maxTokensPerTurn:T.maxTokensPerTurn}:{},persona:u.persona,avatar:{color:u.color},engine:u.engine,approvalMode:u.approvalMode,tools:u.tools,skillIds:u.skillIds,mcpServerIds:u.mcpServerIds,delegation:{canDelegateTo:u.canDelegateTo,acceptFrom:u.acceptFrom},memory:{enabled:u.memoryEnabled},...P.budget?{budget:P.budget}:{}});if(!z.ok){x(rl(z.reason,z.error,o));return}de.getState().upsertBot(z.bot),p&&!await zj(z.bot.id,p)&&ze({type:"error",title:o("Avatar update failed")}),t(!1);const O=await de.getState().openDirect(z.bot.id);O&&s?.(O)}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(xe,{size:"sm",variant:c.kind==="template"?"default":"outline",disabled:a.length===0,onClick:()=>S(a[0]),children:o("From template")}),i.jsx(xe,{size:"sm",variant:c.kind==="blank"?"default":"outline",onClick:N,children:o("Blank")}),i.jsxs(xe,{size:"sm",variant:c.kind==="import"?"default":"outline",onClick:()=>l.current?.click(),children:[i.jsx(Rg,{}),o("Import character card")]}),i.jsx("input",{ref:l,type:"file",accept:".json,.png,application/json,image/png",hidden:!0,onChange:P=>{const T=P.target.files?.[0];P.target.value="",T&&A(T)}})]}),c.kind==="template"&&i.jsxs("div",{className:"grid grid-cols-3 gap-2.5",children:[a.map(P=>i.jsxs("button",{type:"button",onClick:()=>S(P),className:U("flex flex-col items-start gap-1 rounded-xl border bg-card p-3 text-left transition-colors hover:bg-muted",c.id===P.id&&"ring-2 ring-info"),children:[i.jsx(sn,{bot:{name:P.data.title,avatar:{color:P.data.color}}}),i.jsx("span",{className:"font-medium text-sm",children:P.data.title}),i.jsx("span",{className:"text-muted-foreground text-xs",children:P.data.summary})]},P.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(qt,{hint:o("Used for @ in groups; must be unique"),children:o("Name")}),i.jsx(Jt,{value:u.name,onChange:P=>k({name:P.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(qt,{children:o("Title")}),i.jsx(Jt,{value:u.title,onChange:P=>k({title:P.target.value})})]}),i.jsxs("div",{children:[i.jsx(qt,{children:o("Model")}),i.jsx(Oj,{engine:u.engine,onChange:P=>k({engine:P}),zIndex:Cn.DROPDOWN_IN_MODAL})]}),i.jsxs("div",{children:[i.jsx(qt,{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(Lj,{value:u.color,onChange:P=>k({color:P})}),i.jsx(wI,{nested:!0,hasImage:!!p,onPick:f,onRemove:()=>f(null)})]})]})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(qt,{hint:o("Used for routing and the delegation directory"),children:o("Responsibilities")}),i.jsx(Jt,{value:u.scope,onChange:P=>k({scope:P.target.value})})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(qt,{action:i.jsx(_I,{value:u,onApply:k}),children:o("Persona")}),i.jsx(Qs,{rows:4,value:u.persona,onChange:P=>k({persona:P.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":C,onClick:()=>_(P=>!P),children:[i.jsx(un,{className:U("h-4 w-4 transition-transform",C&&"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")})]}),C&&i.jsx("div",{className:"border-t px-3 py-3",children:i.jsx(SI,{value:u,onChange:k,profile:u,zIndex:Cn.DROPDOWN_IN_MODAL})})]})]}),g&&i.jsx("p",{className:"text-destructive text-sm",children:g})]}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),i.jsxs(xe,{size:"sm",disabled:b||v&&!!I,onClick:()=>{D()},children:[b&&i.jsx(Yt,{className:"animate-spin"}),o("Create and start chatting")]})]})]})})}function sE({projectId:e,onChange:t}){const{t:n}=se(),s=ye(p=>p.projects),o=ye(p=>p.addProject),r=m.useMemo(()=>nh(s),[s]),[a,l]=m.useState([]),[c,d]=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&&d(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:r_(f.path),detail:`${f.displayPath} · ${f.sourceName}`}))]},[r,a]),h=async p=>{d(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){ze({type:"error",title:n("Failed to add project"),description:g instanceof Error&&g.message||void 0})}};return i.jsxs(_v,{value:c,onValueChange:(p,f)=>{d(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(Nv,{placeholder:n("Search Code projects or recent folders..."),showClear:!!c,showTrigger:!0})}),i.jsx(xe,{type:"button",variant:"outline",onClick:()=>{window.electronAPI.dialog.selectDirectory().then(p=>{p&&h(p)})},children:n("Browse")})]}),i.jsxs(UI,{zIndex:Cn.DROPDOWN_IN_MODAL,children:[i.jsx(Dv,{children:n("No matching projects found")}),i.jsx(Iv,{children:p=>i.jsxs(Tv,{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 CQ({open:e,onOpenChange:t}){const{t:n}=se(),s=de(D=>D.bots),o=m.useMemo(()=>s.filter(D=>D.archivedAt===void 0),[s]),r=nh(ye(D=>D.projects)),[a,l]=m.useState(""),[c,d]=m.useState([]),[u,h]=m.useState(null),[p,f]=m.useState("project"),[g,x]=m.useState(""),[v,y]=m.useState(String(Ir.maxHops)),[b,w]=m.useState(String(Ir.maxTurnsPerBot)),[C,_]=m.useState(!1),[N,S]=m.useState(null);m.useEffect(()=>{e&&(l(""),d([]),h(null),f(r.length>0?"project":"chat-home"),x(r[0]?.id??""),y(String(Ir.maxHops)),w(String(Ir.maxTurnsPerBot)),_(!1),S(null))},[e]);const k=(D,P)=>{const T=P?[...c,D]:c.filter(z=>z!==D);d(T),T.includes(u??"")?!u&&T.length&&h(T[0]):h(T[0]??null)},A=c.length>=2&&u!==null&&(p==="chat-home"||!!g),I=async()=>{if(A){_(!0);try{const D=await window.electronAPI.bots.createChat({kind:"group",title:a.trim(),members:c,bossBotId:u,workspace:p==="project"?{kind:"project",projectId:g}:{kind:"chat-home"},routing:{maxHops:Math.round(Number(v))||Ir.maxHops,maxTurnsPerBot:Math.round(Number(b))||Ir.maxTurnsPerBot}});if(!D.ok){S(Ns(D.error,n));return}const P=de.getState();P.upsertChat(D.chat),P.setView({kind:"chat",chatId:D.chat.id}),P.loadLatest(D.chat.id),t(!1)}finally{_(!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(qt,{children:n("Group name")}),i.jsx(Jt,{value:a,onChange:D=>l(D.target.value)})]}),i.jsxs("div",{children:[i.jsx(qt,{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(D=>{const P=c.includes(D.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(hc,{checked:P,onCheckedChange:T=>k(D.id,T===!0)}),i.jsx(sn,{bot:D,size:"sm"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-sm",children:[D.name,D.title&&i.jsx("span",{className:"ml-1.5 text-muted-foreground text-xs",children:D.title})]}),P&&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===D.id,onChange:()=>h(D.id),className:"accent-primary"}),n("Owner")]})]},D.id)})})]}),i.jsxs("div",{children:[i.jsx(qt,{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:U("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:U("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(sE,{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(rh,{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(qt,{children:n("@ relay limit (per message of yours)")}),i.jsx(Jt,{type:"number",min:1,max:20,value:v,onChange:D=>y(D.target.value)})]}),i.jsxs("div",{children:[i.jsx(qt,{children:n("Max replies per member")}),i.jsx(Jt,{type:"number",min:1,max:10,value:b,onChange:D=>w(D.target.value)})]})]}),N&&i.jsx("p",{className:"text-destructive text-sm",children:N})]}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsxs(xe,{size:"sm",disabled:!A||C,onClick:()=>{I()},children:[C&&i.jsx(Yt,{className:"animate-spin"}),n("Create")]})]})]})})}const qS={skillIds:[],mcpServerIds:[]};function kQ({open:e,onOpenChange:t,seedTemplateId:n,onCreated:s}){const{t:o,locale:r}=se(),a=de(Q=>Q.bots),l=o_(),c=nh(ye(Q=>Q.projects)),d=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(c[0]?.id??""),y(!1),w(null),_({}),S(null);const Q=l.find(q=>q.id===n);Q&&I({team:E0(Q.data)})},[e]);const I=async Q=>{y(!0),w(null);try{const q=await window.electronAPI.bots.previewTeam(Q);if(!q.ok){w(t5(q.error,o));return}h({team:q.team,renamed:q.renamed,picked:q.team.members.map(ne=>ne.key)}),_({}),S(null),f(q.team.workspace==="project"&&c.length>0?"project":"chat-home")}finally{y(!1)}},D=Q=>h(q=>q&&{...q,team:Q(q.team)}),P=(Q,q)=>D(ne=>({...ne,members:ne.members.map(me=>me.key===Q?{...me,...q}:me)})),T=m.useMemo(()=>u?n5(u.team,u.picked):null,[u]),z=m.useMemo(()=>{const Q=new Map;if(!T)return Q;const q=[...a,...T.members.map(ne=>({id:`team:${ne.key}`,name:ne.name}))];for(const ne of T.members){const me=zg(ne.name,q,o,`team:${ne.key}`);me&&Q.set(ne.key,me)}return Q},[T,a,o]),O=T!==null&&z.size===0&&(p==="chat-home"||!!g)&&!v&&!k,L=Q=>C[Q]??qS,V=(Q,q)=>_(ne=>({...ne,[Q]:{...ne[Q]??qS,...q}})),X=async()=>{if(T){A(!0);try{const Q=r==="zh"?"zh":"en",q=await Promise.all(T.members.map(async $=>{try{const W=await window.electronAPI.bots.suggestAbilities({name:$.name,title:$.title,scope:$.scope,persona:$.persona,language:Q});return{key:$.key,result:W}}catch{return{key:$.key,result:null}}}));let ne=0,me=0,ke;const Me={...C},ge=new Map;for(const{key:$,result:W}of q){if(!W?.ok){me++,W&&!ke&&(ke=Gh(W,o));continue}const{suggestion:ue}=W,Z={};ue.tools&&(Z.tools=ue.tools.value),ue.approvalMode&&(Z.approvalMode=ue.approvalMode.value),Object.keys(Z).length>0&&ge.set($,Z);const J=ue.skillIds?.value??L($).skillIds,ae=ue.mcpServerIds?.value??L($).mcpServerIds;Me[$]={skillIds:[...J],mcpServerIds:[...ae]},(J.length+ae.length>0||ge.has($))&&ne++}_(Me),ge.size>0&&D($=>({...$,members:$.members.map(W=>({...W,...ge.get(W.key)}))})),me>0&&ze({type:"error",title:o("Suggestions failed for {{n}} members",{n:me}),...ke?{description:ke}:{}}),me<q.length&&ze({type:ne>0?"success":"info",title:ne>0?o("Configured abilities for {{n}} members",{n:ne}):o("Current abilities already match the suggestion.")})}finally{A(!1)}}},F=async()=>{if(!(!T||!O)){y(!0),w(null);try{const Q=Object.fromEntries(T.members.map(me=>[me.key,L(me.key)]).filter(([,me])=>me.skillIds.length+me.mcpServerIds.length>0)),q=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(!q.ok){w(rl(q.error,Ns(q.error,o),o));return}const ne=de.getState();for(const me of q.bots)ne.upsertBot(me);ne.upsertChat(q.chat),ne.setView({kind:"chat",chatId:q.chat.id}),ne.loadLatest(q.chat.id),t(!1),s?.(q.chat.id)}finally{y(!1)}}},ee=r==="zh"?"zh":"en",H=Q=>u?.team.members.find(q=>q.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(qt,{children:o("Group name")}),i.jsx(Jt,{value:u.team.title,onChange:Q=>{const q=Q.target.value;D(ne=>({...ne,title:q}))}})]}),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(xe,{size:"xs",variant:"outline",disabled:!T||k||v,onClick:()=>{X()},children:[k?i.jsx(Yt,{className:"animate-spin"}):i.jsx(ti,{}),o("AI auto-configure")]})]}),i.jsx("div",{className:"space-y-1.5",children:u.team.members.map(Q=>{const q=u.picked.includes(Q.key),ne=Q.key===u.team.bossKey,me=u.renamed.find(ue=>ue.key===Q.key),ke=q?z.get(Q.key):void 0,Me=Q.delegation.canDelegateTo,ge=Me==="any"?[]:Me.filter(ue=>u.picked.includes(ue)),$=L(Q.key),W=q&&N===Q.key;return i.jsxs("div",{className:U("flex items-start gap-2.5 rounded-lg border px-2.5 py-2",!q&&"opacity-60"),children:[i.jsx(hc,{className:"mt-1.5",checked:q,disabled:ne,onCheckedChange:ue=>h({...u,picked:ue===!0?[...u.picked,Q.key]:u.picked.filter(Z=>Z!==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:!q,onChange:ue=>{const Z=ue.target.value;D(J=>({...J,members:J.members.map(ae=>ae.key===Q.key?{...ae,name:Z}:ae)}))}}),i.jsx("span",{className:"truncate text-muted-foreground text-xs",children:Q.title}),ne&&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(Wj,{className:"h-3 w-3"}),o("Owner")]})]}),i.jsx("p",{className:"text-muted-foreground text-xs",children:Q.scope}),me&&me.to===Q.name&&i.jsx("p",{className:"text-warning text-xs",children:o('"{{from}}" is taken, renamed to "{{to}}"',me)}),ke&&i.jsx("p",{className:"text-destructive text-xs",children:ke}),i.jsxs("button",{type:"button",disabled:!q,onClick:()=>S(W?null:Q.key),className:"flex items-start gap-1 text-left text-[11px] text-muted-foreground hover:text-foreground disabled:pointer-events-none",children:[W?i.jsx(Vn,{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(Rl[Q.approvalMode].labelKey),ge.length>0&&` · ${o("Delegates to {{names}}",{names:ge.map(H).join(ee==="zh"?"、":", ")})}`," · ",$.skillIds.length+$.mcpServerIds.length===0?o("No skills or MCP"):o("{{n}} skills · {{m}} MCP",{n:$.skillIds.length,m:$.mcpServerIds.length})]})]}),W&&i.jsxs("div",{className:"space-y-3 rounded-lg bg-muted/40 p-2.5",children:[i.jsxs("div",{children:[i.jsx(qt,{children:o("Tools")}),i.jsx(Lg,{value:Q.tools,options:[{value:"all",label:o("All tools")},{value:"readonly",label:o("Read-only")}],onChange:ue=>P(Q.key,{tools:ue})})]}),i.jsxs("div",{children:[i.jsx(qt,{children:o("Approval mode")}),i.jsx(Mj,{value:Q.approvalMode,onChange:ue=>P(Q.key,{approvalMode:ue}),zIndex:Cn.DROPDOWN_IN_MODAL})]}),i.jsx(P0,{label:o("Can delegate to"),value:Q.delegation.canDelegateTo,options:u.picked.filter(ue=>ue!==Q.key),nameOf:H,onChange:ue=>P(Q.key,{delegation:{...Q.delegation,canDelegateTo:ue}})}),i.jsx(P0,{label:o("Accepts delegation from"),value:Q.delegation.acceptFrom,options:u.picked.filter(ue=>ue!==Q.key),nameOf:H,onChange:ue=>P(Q.key,{delegation:{...Q.delegation,acceptFrom:ue}})}),i.jsx(CI,{value:$,onChange:ue=>V(Q.key,ue)})]})]})]},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(qt,{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:U("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:U("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(sE,{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(rh,{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:q})=>i.jsxs("button",{type:"button",disabled:v,onClick:()=>{I({team:E0(q)})},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:q.members.map(ne=>i.jsx(sn,{size:"sm",bot:{name:ne.name,avatar:{color:ne.color}}},ne.key))}),i.jsx("span",{className:"font-medium text-sm",children:q.title}),i.jsx("span",{className:"text-muted-foreground text-xs",children:q.summary})]},Q))}),i.jsxs(xe,{size:"sm",variant:"outline",disabled:v,onClick:()=>d.current?.click(),children:[i.jsx(Rg,{}),o("Import team (JSON)")]}),i.jsx("input",{ref:d,type:"file",accept:".json,application/json",hidden:!0,onChange:Q=>{const q=Q.target.files?.[0];Q.target.value="",q&&q.text().then(ne=>I({text:ne}))}})]}),b&&i.jsx("p",{className:"text-destructive text-sm",children:b})]}),i.jsxs(rs,{children:[u&&i.jsxs(xe,{variant:"ghost",size:"sm",className:"mr-auto",onClick:()=>{h(null),w(null)},children:[i.jsx(cc,{}),o("Back")]}),i.jsx(xe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),u&&i.jsxs(xe,{size:"sm",disabled:!O,onClick:()=>{F()},children:[v&&i.jsx(Yt,{className:"animate-spin"}),o("Create team")]})]})]})})}const To="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function jQ({sidebarWidth:e,collapsed:t,onToggleCollapse:n,onResize:s}){const o=lh()==="mobile",{t:r}=se(),a=de(T=>T.view),l=de(T=>T.chats),c=de(T=>T.bots),d=de(T=>T.loaded),u=de(T=>T.setView),[h,p]=m.useState(!1),[f,g]=m.useState(!1),[x,v]=m.useState(!1),[y,b]=m.useState(!1),[w,C]=m.useState(null),_=m.useRef(""),N=Wg(),S=a?.kind==="chat"?l.find(T=>T.id===a.chatId):void 0,k=S?.kind==="group"?yW(l,S):void 0;m.useEffect(()=>{d&&a?.kind==="chat"&&!S&&u(null)},[d,a,S,u]);const A=async T=>{if(T.botId){const z=de.getState();if(!z.bots.some(L=>L.id===T.botId))throw new Error("Member not found");const O=await z.openDirect(T.botId);if(!O)throw new Error("Could not open chat");A0(O,T.firstMessage.trim()),b(!1);return}b(!1),C(T),_.current=T.firstMessage.trim(),T.templateId?v(!0):p(!0)},I=T=>{_.current&&A0(T,_.current),_.current=""},D=()=>{C(null),_.current="",p(!0)},P=()=>{C(null),_.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(nE,{className:To}),i.jsx("button",{type:"button",className:To,onClick:()=>b(!0),title:r("Start from a goal"),children:i.jsx(Ia,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:To,onClick:D,title:r("New member"),children:i.jsx($l,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:To,onClick:()=>g(!0),title:r("New group chat"),children:i.jsx(da,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:To,onClick:P,title:r("Create team from template"),children:i.jsx(Gf,{className:"h-4 w-4"})}),(N>0||a?.kind==="inbox")&&i.jsxs("button",{type:"button",className:U(To,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(Fx,{className:"h-4 w-4"}),N>0&&i.jsx(Hh,{count:N,className:"-top-0.5 -right-1 absolute"})]}),i.jsx("div",{className:"flex-1"}),i.jsx("button",{type:"button",className:To,onClick:()=>{window.electronAPI.window.openSettings()},title:r("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})}),o&&i.jsx("button",{type:"button",className:To,onClick:n,title:r("Expand sidebar"),children:i.jsx(VN,{className:"h-4 w-4"})})]}):i.jsxs(i.Fragment,{children:[i.jsx(wQ,{width:e,onCollapse:o?n:void 0,onNewMember:D,onNewGroup:()=>g(!0),onNewTeam:P,onStartFromGoal:()=>b(!0)}),i.jsx(ku,{onResize:s})]}),a?.kind==="inbox"?i.jsx(WZ,{}):S?i.jsx(zZ,{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:c.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.")}),c.length===0&&d&&i.jsx(KS,{onPick:A}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(xe,{size:"sm",variant:c.length===0?"outline":"default",onClick:D,children:[i.jsx($l,{}),r("New member")]}),c.length>=2&&i.jsxs(xe,{size:"sm",variant:"outline",onClick:()=>g(!0),children:[i.jsx(da,{}),r("New group chat")]}),i.jsxs(xe,{size:"sm",variant:"outline",onClick:P,children:[i.jsx(Gf,{}),r("Create team from template")]})]})]}),i.jsx(SQ,{open:h,onOpenChange:p,seed:w?.member,onCreated:I}),i.jsx(CQ,{open:f,onOpenChange:g}),i.jsx(vQ,{}),i.jsx(kQ,{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(KS,{onPick:A})})]})})]})}const Ha=[{value:"code",label:"Code",Icon:$o},{value:"bot",label:"Bot",Icon:s5}],_Q={ArrowLeft:-1,ArrowUp:-1,ArrowRight:1,ArrowDown:1},NQ={duration:.26,ease:[.22,1,.36,1]},TQ={duration:.5,ease:[.34,1.36,.64,1]},DQ={duration:.18,ease:[.4,0,.2,1]};function IQ({className:e}){const{t}=se(),n=uo(h=>h.mode),s=uo(h=>h.setMode),o=Wg(),r=Oi(ye(h=>h.keybindings))["toggle-app-mode"],a=r?`${t("Switch between Code and Bot")} (${mi(r)})`:void 0,l=x$()??!1,c=m.useId(),d=m.useRef({}),u=h=>{const p=_Q[h.key];if(!p)return;h.preventDefault();const f=Ha.findIndex(x=>x.value===n),g=Ha[(f+p+Ha.length)%Ha.length].value;s(g),d.current[g]?.focus()};return i.jsx("div",{role:"radiogroup","aria-label":t("Switch mode"),onKeyDown:u,className:U("flex h-7 shrink-0 rounded-lg bg-muted/60 p-0.5 text-xs",e),children:Ha.map(({value:h,label:p,Icon:f})=>{const g=n===h,x=h==="bot"&&n==="code"&&o>0;return i.jsxs("button",{ref:v=>{d.current[h]=v},type:"button",role:"radio","aria-checked":g,tabIndex:g?0:-1,title:a,onClick:()=>s(h),className:U("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:c,"aria-hidden":!0,className:"absolute inset-0 rounded-md bg-background shadow-xs",transition:l?{duration:0}:na}),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:NQ,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:DQ},transition:TQ,children:i.jsx(Hh,{count:o,className:"block"})})})})]},h)})})}const Ql="enso:open-chat-find";let ng;function iE(e){ng=e,window.dispatchEvent(new Event(Ql))}function YS(){const e=ng;return ng=void 0,e}function EQ({query:e,onQueryChange:t,current:n,total:s,onPrev:o,onNext:r,onClose:a}){const{t:l}=se(),c=m.useRef(null);return m.useEffect(()=>{const d=()=>{c.current?.focus(),c.current?.select()};return d(),window.addEventListener(Ql,d),()=>window.removeEventListener(Ql,d)},[]),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(ei,{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:c,value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{if(d.key==="Escape"){d.preventDefault(),a();return}d.key==="Enter"&&(d.preventDefault(),d.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(xe,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:o,"aria-label":l("Previous match"),children:i.jsx(a_,{className:"h-3.5 w-3.5"})}),i.jsx(xe,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:r,"aria-label":l("Next match"),children:i.jsx(Vn,{className:"h-3.5 w-3.5"})}),i.jsx(xe,{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 PQ(e){const{t}=se(),n=e?.startsWith("bot:")?e.slice(4):void 0,s=de(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 c=Tj(l)?.candidates.find(d=>d.typeKey===e);a&&r(c?.displayName)}).catch(()=>{}),()=>{a=!1}},[e,n,s]),!!n)return s??o??t("Member")}function AQ(e,t){return e?null:t?"empty":"hydrating"}function MQ(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 RQ(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,commands:n.commands,compactionError:n.compactionError,agentType:n.agentType,parentHasRunningChild:Ug(t,e.conversations),retry:n.retry,pendingApprovals:n.pendingApprovals,pendingAsks:n.pendingAsks,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,displayedParentId:n.parentId,busy:l_(n)}}function LQ(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt}function OQ(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:LQ(e),messages:[],forkedFromConversationId:e.forkedFromConversationId,unread:e.unread,activeRenewedAt:e.activeRenewedAt,pendingAsks:e.pendingAsks,pendingApprovals:e.pendingApprovals,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 zQ(e){return JSON.stringify(e)}let Xi=null;function Ev(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=OQ(o,Ug({status:o.status??"idle",spawning:o.spawning,subagents:o.subagents,coworkerIds:o.coworkerIds,backgroundTasks:o.backgroundTasks},e));t[s]=r,n.push(`${s}:${zQ(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 Ba=null;function GQ(e){if(Ba?.source===e)return Ba.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=Ba?.print===n?Ba.value:t;return Ba={source:e,print:n,value:s},s}const FQ=[],XS=new WeakMap;function HQ(e,t){const n=e[t];if(!n)return FQ;const s=XS.get(n);if(s?.source===e)return s.value;const o=(n.coworkerIds??[]).flatMap(l=>{const c=e[l];return c?[{id:c.id??l,title:c.title,status:c.status??"idle",spawning:c.spawning===!0,pendingApprovalCount:c.pendingApprovals?.length??0,pendingAskCount:c.pendingAsks?.length??0,coworkerName:c.coworkerName,child:c.child?.agentInstanceName?{agentInstanceName:c.child.agentInstanceName}:void 0,mode:c.child?.mode==="task"?"task":"coworker",reloading:c.reloading===!0}]:[]}),r=JSON.stringify(o),a=s?.print===r?s.value:o;return XS.set(n,{source:e,print:r,value:a}),a}function BQ(){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 VQ(){const e=BQ(),t=e[0];return t?i.jsx($Q,{request:t,total:e.length},t.id):null}function $Q({request:e,total:t}){const{t:n}=se(),[s,o]=m.useState(""),[r,a]=m.useState(!1),l=Wx(e.expiresAt),c=r||l!==void 0&&l<=0,d=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&&!c&&d(s)},children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx(i5,{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(Ux,{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:c,placeholder:n("Login password"),"aria-invalid":e.retry||void 0,onChange:u=>o(u.currentTarget.value),className:U("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:c,onClick:()=>d(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:c||!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:U("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 WQ(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}const UQ={conversationId:void 0,historyBaseIndex:0,seen:null};function KQ(e,t){const{conversationId:n,historyBaseIndex:s}=t;if(!t.authoritative)return{baseline:{conversationId:n,historyBaseIndex:s,seen:null},added:!1};const r=e.conversationId===n&&e.historyBaseIndex===s?e.seen:null,a=WQ(t.timeline),l=r!==null&&[...a].some(c=>!r.has(c));return{baseline:{conversationId:n,historyBaseIndex:s,seen:a},added:l}}function qQ(e,t){const n=ye(a=>a.openChangesOnFileEdit),s=oe(a=>c_((t?a.conversations[t]?.messages:void 0)??[])),o=oe(a=>(t?a.conversations[t]?.historyBaseIndex:void 0)??0),r=m.useRef(UQ);m.useEffect(()=>{const a=KQ(r.current,{conversationId:t,historyBaseIndex:o,authoritative:s,timeline:e});r.current=a.baseline,a.added&&n&&gj()},[s,t,n,o,e])}function Va(e,t){const n=e.trim().toLowerCase();return n?t.some(s=>s?.toLowerCase().includes(n)):!0}function YQ(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 c=r.indexOf(n,a);if(c===-1)break;s.push({key:o.key,nth:l}),l+=1,a=c+n.length}}return s}const XQ=[],JQ=[],ZQ=typeof window<"u"&&!!window.electronAPI?.remote;function oE({conversationId:e,cwd:t,emptyTitle:n,onSuggestion:s,timelineRef:o}){const r=oe(ne=>ne.conversations[e]?.projectId),a=oe(ne=>ne.conversations[e]?.messages??XQ),l=oe(ne=>ne.conversations[e]?.customEntries??JQ),c=oe(ne=>ne.conversations[e]?.status==="running"),d=oe(ne=>ne.conversations[e]?.compaction),u=oe(ne=>ne.conversations[e]?.compactionNoticeAt),h=oe(ne=>ne.conversations[e]?.occupancy?.compactionTokensAfter),p=oe(ne=>ne.conversations[e]?.historyBaseIndex??0),f=oe(ne=>ne.conversations[e]?.toolOutputs),g=oe(ne=>ne.conversations[e]?.toolStartedAt),x=oe(ne=>ne.conversations[e]?.pendingApprovals),v=oe(ne=>ne.conversations[e]?.runStartedAt),y=oe(ne=>ne.conversations[e]?.lastOutputAt),b=oe(ne=>ne.conversations[e]?.error),w=oe(ne=>ne.conversations[e]?.started===!0),C=oe(ne=>ne.conversations[e]?.sessionFile),_=oe(ne=>ne.conversations[e]?.status),N=oe(ne=>ne.conversations[e]?.spawning===!0),S=oe(ne=>ne.conversations[e]?.historyLoadAttempted),k=oe(ne=>!!ne.conversations[e]?.historyLoading),A=oe(ne=>ne.conversations[e]?.syncStalled===!0),I=m.useRef({conversationId:"",items:[]}),D=m.useMemo(()=>{I.current.conversationId!==e&&(I.current={conversationId:e,items:[]});const me=o5(I.current.items,a,c,p)??wr(a,c,l,t,{compaction:d,compactionNoticeAt:u,compactionTokensAfter:h,historyBaseIndex:p,toolOutputs:f,toolStartedAt:g,pendingApprovals:x});return I.current.items=me,me},[d,u,h,e,t,l,p,a,x,c,f,g]);qQ(D,e);const P=r5({started:w,sessionFile:C,messages:a,spawning:N,status:_,historyLoadAttempted:S,historyLoading:k,syncStalled:A}),[T,z]=m.useState(!1),[O,L]=m.useState(""),[V,X]=m.useState(0),F=m.useMemo(()=>T?YQ(D,O):[],[T,O,D]);m.useEffect(()=>{const ne=()=>{const me=YS();z(!0),me&&(L(me),X(0))};return window.addEventListener(Ql,ne),()=>window.removeEventListener(Ql,ne)},[]),m.useEffect(()=>{const ne=YS();if(X(0),ne){L(ne),z(!0);return}e&&(L(""),z(!1))},[e]),m.useEffect(()=>{if(!T||F.length===0)return;const ne=Math.min(V,F.length-1);o.current?.scrollToKey(F[ne].key)},[T,V,F,o]);const ee=m.useCallback(ne=>{F.length!==0&&X(me=>(me+ne+F.length)%F.length)},[F.length]);m.useEffect(()=>{if(!T)return;const ne=me=>{if(me.key==="Escape"){me.preventDefault(),z(!1);return}const ke=Al(me);ke==="mod+g"?(me.preventDefault(),ee(1)):ke==="mod+shift+g"&&(me.preventDefault(),ee(-1))};return window.addEventListener("keydown",ne),()=>window.removeEventListener("keydown",ne)},[T,ee]);const H=m.useMemo(()=>r?{conversationId:e,projectId:r,...t?{cwd:t}:{}}:null,[e,t,r]),Q=m.useRef(null),q=m.useCallback(()=>{const ne=o.current?.getScroller();Q.current=ne?{height:ne.scrollHeight,top:ne.scrollTop}:null,oe.getState().loadOlderHistory(e)},[e,o]);return m.useLayoutEffect(()=>{const ne=o.current?.getScroller(),me=Q.current;!ne||!me||(Q.current=null,ne.scrollTop=me.top+(ne.scrollHeight-me.height))},[p]),i.jsxs(qu.Provider,{value:H,children:[T&&i.jsx(EQ,{query:O,onQueryChange:ne=>{L(ne),X(0)},current:F.length===0?0:Math.min(V,F.length-1)+1,total:F.length,onPrev:()=>ee(-1),onNext:()=>ee(1),onClose:()=>{z(!1),L("")}}),i.jsx(Ah,{virtualize:!ZQ,ref:o,items:D,busy:P!==null,loading:P==="loading",running:c,runStartedAt:v,lastOutputAt:y,error:a5(a,b),emptyTitle:n,onSuggestion:s,onRetryResume:!w&&C&&_==="failed"?()=>{oe.getState().resumeConversation(e)}:void 0,onRetrySync:A&&!c?()=>oe.getState().retrySessionSync(e):void 0,historyLoading:k,hasOlder:p>0,olderCursor:p,onStartReached:p>0?q:void 0,searchQuery:T?O:"",activeHit:T?F[V]??null:null},e)]})}const QQ=/-([0-9a-f]{8})$/i;function JS(e){const t=e.title?.trim();return t||e.name.replace(QQ,"").trim()||e.name}const eee={sm:"size-2",md:"size-2.5"},tee={sm:"h-3 w-3",md:"h-3.5 w-3.5"};function Bh({tone:e,size:t="sm",title:n,className:s,"data-enso":o,"data-status":r}){const{t:a}=se();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:U("flex shrink-0 items-center text-amber-500",s),children:i.jsx(G$,{className:U(tee[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:U("shrink-0 rounded-full",eee[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 nee({parentId:e,coworkerIds:t}){const{t:n,locale:s}=se(),o=ye(y=>y.agentTypes),[r,a]=m.useState([]),[l,c]=m.useState(!1),[d,u]=m.useState(null),h=m.useRef(0),p=t.join("\0"),f=oe(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=d?.childId;return b?window.electronAPI.agent.readChildRun(e,b,y):Promise.resolve({ok:!1,code:"not-found",error:"No child run."})},[e,d?.childId]),v=y=>{if(y.available){if(c(!1),y.live&&t.includes(y.childId)){oe.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&&(oe.setState({pendingChildRun:null}),!!y.available)){if(c(!1),y.live&&t.includes(y.childId)){oe.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=>{c(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(Ko,{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=JS(y);return i.jsx("li",{children:i.jsxs("button",{type:"button",disabled:!y.available,title:b,className:U("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:d_(y.agentType,o)}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Bo(y.startedAt,s)}),y.live&&i.jsx(Bh,{tone:"running",size:"sm",title:n("Running")})]})},y.childId)})})})]}),i.jsx(kv,{conversationId:d?.childId??null,title:d?JS(d):"",read:x,botSession:!1,onClose:()=>u(null)})]})}const see=[{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"}],iee={"/goal":see};function oee(e,t){if(!e)return null;const n=t.trimStart();return n?n.search(/\s/)>=0?null:n:""}function ree(e,t){if(!e)return[];const n=iee[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 aee(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 rE=[];const sg=new Set;function ZS(e){rE=e;for(const t of sg)t()}function lee(e){return sg.add(e),()=>sg.delete(e)}const QS=()=>rE,cee={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 dee({sessionId:e}){const t=m.useSyncExternalStore(lee,QS,QS);return t.length===0?null:i.jsx(i.Fragment,{children:t.map(n=>{const s=n.command?u_().find(a=>a.pluginId===n.pluginId&&a.id===n.command):void 0,o=U("shrink-0 truncate px-1 text-[11px]",cee[n.tone]),r=n.tooltip?`${n.tooltip} · ${n.pluginName}`:n.pluginName;return s?i.jsx("button",{type:"button",title:r,className:U(o,"rounded hover:bg-accent"),onClick:()=>{Kg(s,e).then(a=>{a&&ze({title:a})})},children:n.text},`${n.pluginId}:${n.id}`):i.jsx("span",{title:r,className:o,children:n.text},`${n.pluginId}:${n.id}`)})})}const aE=50,uee=64,hee=120,pee=32*1024,fee=120,sd=[];function eC(e){return/(?:^|\s)#([^\s#]*)$/.exec(e)?.[1]??null}function mee(e,t,n){if(!Array.isArray(n))return[];const s=[];for(const o of n){if(s.length>=aE)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,uee),...typeof l=="string"&&l?{detail:l.slice(0,hee)}:{}}})}return s}function gee(e){const t=typeof e=="string"?e:typeof e=="object"&&e!==null?e.text:null;return typeof t=="string"&&t.length<=pee?t:null}let lE=[];const ig=new Set;function tC(e){lE=e;for(const t of ig)t()}function xee(e){return ig.add(e),()=>ig.delete(e)}const nC=()=>lE;function vee(e,t){const n=m.useSyncExternalStore(xee,nC,nC),[s,o]=m.useState(sd);return m.useEffect(()=>{if(e===null||n.length===0){o(sd);return}let r=!1;const a=setTimeout(()=>{Promise.all(n.map(async({pluginId:l,name:c})=>{const d=await window.electronAPI.extensionPlugins.call({pluginId:l,method:"trigger.candidates",payload:{name:c,query:e},sessionId:t});return d.ok?mee(l,c,d.value):sd})).then(l=>{r||o(l.flat().slice(0,aE))})},fee);return()=>{r=!0,clearTimeout(a)}},[e,n,t]),e===null?sd:s}async function bee(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?gee(n.value):null}const Kd="composer-drop",cE="pinned-drop",Pv="project-group:__ungrouped__",og="project:",rg="project-group:",qd="selector-group:",ag="pinned-chat:",dE=e=>`${og}${e}`,uE=e=>`${rg}${e}`,Av=e=>`${qd}${e}`,wee=e=>`chat:${e}`,hE=e=>`${ag}${e}`,yee=e=>`active-chat:${e}`;function See(e){return e.split(`
|
|
84
|
-
`)[0].trim()||"Untitled chat"}function sC(e){if(e===Pv||e===`${qd}__ungrouped__`)return null;if(e.startsWith(rg)){const t=e.slice(rg.length);return t==="__all__"?void 0:t}if(e.startsWith(qd)){const t=e.slice(qd.length);return t==="__all__"?void 0:t}}function Cee(e,t,n,s){if(!t)return null;if(e.type==="project-group"){const o=sC(t);return!o||o===e.groupId?null:{kind:"reorder-groups",activeId:e.groupId,overId:o}}if(e.type==="project"){if(t===Kd)return{kind:"insert-file-mention",path:e.path,label:e.name};const o=sC(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(og)){const r=t.slice(og.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===Kd?{kind:"insert-file-mention",path:e.relativePath,label:e.name}:null;if(t===Kd)return!e.sessionFile||e.conversationId===n?null:{kind:"insert-chat-mention",conversationId:e.conversationId,label:See(e.title),sessionFile:e.sessionFile};if(t===cE)return e.pinned?null:{kind:"pin-conversation",conversationId:e.conversationId};if(t.startsWith(ag)){const o=t.slice(ag.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 iC=200,kee=Array.from({length:jl},(e,t)=>`bar-${t}`),oC=Rh([],0);function jee({active:e,disabled:t,onChange:n}){const{t:s}=se(),[o,r]=m.useState(!1),[a,l]=m.useState(null),c=m.useRef(null);m.useEffect(()=>{if(!a)return;const h=setTimeout(()=>l(null),4e3);return()=>clearTimeout(h)},[a]);const d=async()=>{if(l(null),!navigator.mediaDevices?.getUserMedia){l(s("Voice input needs a secure (HTTPS) connection."));return}Zm(),r(!0);try{await zX(),n(!0)}catch(h){l(s(tI(h)))}finally{r(!1)}},u=s(e?"Switch to keyboard":"Voice input");return i.jsxs("div",{ref:c,className:"flex shrink-0 items-center",children:[i.jsx("button",{type:"button",disabled:t||o,onClick:()=>e?n(!1):void d(),"aria-label":u,title:u,className:Qm,children:o?i.jsx(gr,{className:"h-3.5 w-3.5"}):e?i.jsx(l5,{className:"h-3.5 w-3.5"}):i.jsx(Nj,{className:"h-3.5 w-3.5"})}),a&&c.current?i.jsx(iI,{anchor:c.current,status:!0,children:a}):null]})}let rC;function _ee({startSession:e,disabled:t,onText:n}){const{t:s}=se(),{phase:o,elapsed:r,error:a,setError:l,partial:c,correcting:d,start:u,finish:h,cancel:p}=nI({startSession:e,onText:n}),[f,g]=m.useState(oC),[x,v]=m.useState(!1),[y,b]=m.useState(!1),w=m.useRef(null);m.useEffect(()=>(clearTimeout(rC),()=>{rC=setTimeout(CS,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 C=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(oC),u({context:Zm(),onLevel:k=>g(A=>Rh(A,k))}))},_=(S,k)=>{const A=w.current;if(!A||A.id!==S.pointerId)return;w.current=null,v(!1),b(!1);const I=JD({phase:o,heldMs:performance.now()-A.at,cancelZone:k||!A.shifted&&SS(A.y,S.clientY)});I==="finish"?h():I!=="none"&&p(),CS(),Zm(),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:C,onPointerMove:S=>{const k=w.current;k?.id===S.pointerId&&(k.shifted&&(k.y=S.clientY,k.shifted=!1),b(SS(k.y,S.clientY)))},onPointerUp:S=>_(S,!1),onPointerCancel:S=>_(S,!0),onContextMenu:S=>S.preventDefault(),className:U("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(Nee,{phase:o,cancelling:y,elapsed:r,levels:f,partial:c,correcting:d}):null]})}function Nee({phase:e,cancelling:t,elapsed:n,levels:s,partial:o,correcting:r}){const{t:a}=se(),l=e==="transcribing",c=o.length>iC?`…${o.slice(-iC)}`:o;return Us.createPortal(i.jsxs("div",{"data-testid":"hold-to-talk",style:{zIndex:Cn.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:U("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:[c?i.jsx("p",{"data-testid":"voice-partial",className:"text-[15px] leading-relaxed",children:c}):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(gr,{"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:kee.map((d,u)=>i.jsx("span",{className:"w-[3px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:4+s[u]*28}},d))})]})}),l?null:i.jsxs("div",{className:"flex flex-col items-center",children:[i.jsx("span",{className:U("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:U("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 aC=e=>e.startsWith("/skill:");function Tee(e,t){return!aC(t)||!e.every(aC)?[t]:e.includes(t)?[...e]:[...e,t]}function Dee(e){const t=vj(e);if(t.names.length>0)return{slashes:t.names.map(s=>`/skill:${s}`),rest:t.rest};const n=Du(e);return{slashes:n.slash?[n.slash]:[],rest:n.rest}}function Iee(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=Dee(t.text??"");return{slashes:o.slashes,segments:o.rest?[{type:"text",text:o.rest}]:[],images:[...n?e.images:[],...t.images??[]]}}const Eee={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>'},Pee='<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>',Aee={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 af(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=U("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",Aee[e.type]);const n=document.createElement("span");n.className="shrink-0 inline-flex",n.innerHTML=e.type==="file"&&/[\\/]$/.test(e.path)?Pee:Eee[e.type],t.appendChild(n);const s=document.createElement("span");return s.className="truncate",s.textContent=e.type==="file"?e.label??kh(e.path):e.label,t.appendChild(s),t}function pE(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 lf(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=pE(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 cf(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 Mee(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 c=document.createRange();return c.setStart(l.node,l.offset),c.collapse(!0),c}function id(e){return e instanceof HTMLElement&&!!e.dataset.mentionKind}function sl(e){return e instanceof Text&&!/[^\s\u00a0]/.test(e.textContent??"")}function Ree(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 c=s.textContent??"";if(t==="before"){if(/[^\s\u00a0]/.test(c.slice(0,o)))return null;let u=s.previousSibling;for(;sl(u);)u=u.previousSibling;return id(u)?u:null}if(/[^\s\u00a0]/.test(c.slice(o)))return null;let d=s.nextSibling;for(;sl(d);)d=d.nextSibling;return id(d)?d:null}const r=s.childNodes;if(t==="before"){let c=o-1;for(;c>=0&&sl(r[c]);)c-=1;const d=c>=0?r[c]:null;return id(d)?d:null}let a=o;for(;a<r.length&&sl(r[a]);)a+=1;const l=r[a];return id(l)?l:null}function Lee(e,t){const n=e.nextSibling;sl(n)&&n.remove();const s=e.previousSibling;if(e.remove(),s){fE(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 fE(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.setStartAfter(e),n.collapse(!0),t.removeAllRanges(),t.addRange(n)}const Oee=m.forwardRef(function({placeholder:t,disabled:n,className:s,onStateChange:o,onKeyDown:r,onPaste:a,onPasteText:l,onCompositionStart:c,onCompositionEnd:d,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 C=window.getSelection();if(!C||C.rangeCount===0||!C.isCollapsed)return;const _=C.anchorNode;if(_&&(_===w||w.contains(_))){const k=Mee(w,C);k?(C.removeAllRanges(),C.addRange(k)):_.nodeType===Node.TEXT_NODE&&(g.current={node:_,offset:C.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)),C.removeAllRanges(),C.addRange(S)};return document.addEventListener("selectionchange",b),()=>document.removeEventListener("selectionchange",b)},[]);const x=m.useCallback(()=>{const b=f.current;if(!b)return;const w=lf(b),C=w.map(D=>D.type==="text"?D.text:"").join(""),_=w.some(D=>D.type!=="text");let N=null,S=null,k=null,A=null;const I=cf(b);if(I){const D=I.node.textContent?.slice(0,I.offset)??"";N=_w(D,D.length),N===null&&(k=Jm(D,D.length)),N===null&&k===null&&(A=eC(D)),N===null&&I.node===b.firstChild&&/^\/[^\s]*$/.test(D)&&(S=D.slice(1))}o({plainText:C,hasMentions:_,segments:w,mentionQuery:N,slashQuery:S,skillQuery:k,pluginQuery:A})},[o]),v=m.useCallback(b=>{const w=f.current;if(!w)return null;const C=cf(w);if(!C)return null;const _=C.node.textContent?.slice(0,C.offset)??"";if(b==="#"){const N=eC(_);return N===null?null:{node:C.node,start:_.length-N.length-1,end:C.offset}}if(b==="@"||b==="$"){const N=b==="@"?_w(_,_.length):Jm(_,_.length);return N===null?null:{node:C.node,start:_.length-N.length-1,end:C.offset}}return C.node!==w.firstChild||!/^\/[^\s]*$/.test(_)?null:{node:C.node,start:0,end:C.offset}},[]),y=m.useCallback((b,w)=>{const C=f.current;if(!C)return;C.focus();const _=document.createRange(),N=w?v("@"):null;if(N)_.setStart(N.node,N.start),_.setEnd(N.node,N.end),_.deleteContents();else{const A=cf(C);A?(_.setStart(A.node,A.offset),_.collapse(!0)):(_.selectNodeContents(C),_.collapse(!1))}const S=b();_.insertNode(S);const k=document.createTextNode(" ");S.parentNode?.insertBefore(k,S.nextSibling),fE(k),x()},[v,x]);return m.useImperativeHandle(p,()=>({focus:()=>f.current?.focus(),isEmpty:()=>{const b=f.current;return b?!lf(b).some(C=>C.type!=="text"||C.text.trim().length>0):!0},getSegments:()=>f.current?lf(f.current):[],setSegments:b=>{const w=f.current;if(w){w.textContent="";for(const C of b)C.type==="text"?w.appendChild(document.createTextNode(C.text)):w.appendChild(af(C));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(()=>af(w),b.kind!=="ui-element")},consumeToken:b=>{const w=v(b);if(!w)return;const C=document.createRange();C.setStart(w.node,w.start),C.setEnd(w.node,w.end),C.deleteContents(),x()},insertFileChip:(b,w)=>{y(()=>af({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,C=w&&Ree(w,b.key==="Backspace"?"before":"after");if(C&&w){b.preventDefault(),Lee(C,w),x();return}}r(b)},onClick:b=>{if(!u)return;const w=b.target;if(!(w instanceof Element))return;const C=w.closest("[data-mention-kind]");if(!(C instanceof HTMLElement)||!f.current?.contains(C))return;const _=pE(C);_&&u(_)},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:c,onCompositionEnd:()=>{d(),x()},className:U("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)})}),zee=/[\\/]/;function Gee(e){return e.split(zee).filter(t=>t.length>0)}function Fee(e){const t=new Map,n=e.map(Gee),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 d=a.slice(l).join("/");if(!s.some(h=>h!==s[o]&&(h===d||h.endsWith(`/${d}`))))break;l--}const c=a.slice(l).join("/");t.set(r,l>0?`…/${c}`:c)}return t}function Hee({groups:e,query:t,activeIndex:n,onActiveIndexChange:s,openFolderId:o,folderIndex:r,onOpenFolderIdChange:a,onFolderIndexChange:l,onSelect:c,id:d="composer-mention-picker",left:u=0,flyoutSide:h="right"}){const{t:p}=se(),f=m.useMemo(()=>aI(e,t),[e,t]),g=m.useMemo(()=>Fee(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:da,chats:Ko},C=o?e[o]:[];let _=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:U("px-2 pb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",k?"pt-2":"pt-1.5"),children:I}),A.map(D=>{const P=_++;return i.jsx(lC,{ref:T=>{T?x.current.set(P,T):x.current.delete(P)},id:`${d}-option-${P}`,candidate:D,active:P===n,pathLabel:D.kind==="file"?g.get(D.relativePath):void 0,onHover:()=>{s(P),y&&a(null)},onSelect:()=>c(D)},`${S}:${D.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:d,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=_++,A=w[S.id];return i.jsxs("button",{ref:I=>{I?x.current.set(k,I):x.current.delete(k)},id:`${d}-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:U("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&&C.length>0&&i.jsx("div",{role:"listbox","aria-label":b[o],"data-slot":"mention-flyout",className:U("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:C.map((S,k)=>i.jsx(lC,{ref:A=>{A?v.current.set(k,A):v.current.delete(k)},id:`${d}-sub-${k}`,candidate:S,active:k===r,onHover:()=>l(k),onSelect:()=>c(S)},`sub:${S.id}`))})]})}function lC({ref:e,id:t,candidate:n,active:s,pathLabel:o,onHover:r,onSelect:a}){const{t:l}=se(),c=Bee(n),d=n.kind==="agent-type"?n.source==="bot"?da:Vs:n.kind==="chat"?Ko:c?Cc:So;return i.jsxs("button",{ref:e,id:t,type:"button",role:"option","aria-selected":s,onClick:a,onMouseMove:r,className:U("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(d,{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(ca,{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(c?"Folder":"File")}),n.kind==="agent-type"&&n.locked&&i.jsx(ca,{variant:"secondary",className:"px-1 py-0 text-[9px]",children:l("Locked")})]}),i.jsx("span",{className:U("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 Bee(e){return e.kind==="file"&&/[\\/]$/.test(e.relativePath)}function Vee(e,t){return e.filter(n=>n!==t)}const cC=new Map,$ee=()=>!!window.electronAPI?.remote&&window.matchMedia?.("(pointer: coarse)").matches===!0;function Mv({cwd:e,commands:t,running:n,busy:s,focusKey:o,pluginPresetId:r=null,autoFocus:a=!window.electronAPI?.remote,enterToSend:l=!$ee(),toolbar:c,locked:d=!1,injectedDraft:u,injectedImages:h,injectedDraftAppend:p,onDraftConsumed:f,chatCandidates:g,onActivate:x,onSend:v,onAbort:y,queuedCount:b=0,onSteerQueued:w,isolated:C=!1,placeholder:_,planMode:N=!1,voice:S,requestMicAccess:k,voiceMode:A="click",savePastedText:I}){const{t:D}=se(),P=Sa(),[T,z]=m.useState(!1),O=A==="hold"?S:void 0,L=ye(ce=>ce.keybindings),V=ye(ce=>ce.privacyMasking),X=Oi(L)["send-message"],F=Oi(L)["voice-hold"],ee=m.useId(),[H,Q]=m.useState([]),[q,ne]=m.useState([]),[me,ke]=m.useState(),Me=m.useRef(o),[ge,$]=m.useState(!1),{setNodeRef:W,isOver:ue}=vc({id:C?`isolated-composer:${o??"side"}`:Kd,disabled:C}),[Z,J]=m.useState(null),[ae,te]=m.useState(null),pe=m.useRef(new Set),Te=m.useRef(v);Te.current=v;const $e=m.useRef(V);$e.current=V,m.useEffect(()=>{if(C)return;const ce=zK(tt=>Ie.current?.insertMention(tt)),Ee=FK(tt=>Ie.current?.insertText(tt)),Oe=GK(()=>Ie.current?.focus()),We=VK((tt,Xe)=>{Xe&&Q(Ce=>[...Ce,{...Xe,id:tt.imageId}]),Ie.current?.insertMention(tt),Ie.current?.focus()}),qe=$K(tt=>{Q(Xe=>[...Xe,{data:tt.data,mimeType:tt.mimeType}]),Ie.current?.focus()}),rt=HK(tt=>{if(Pt.current)return!1;const Xe=$e.current,Ce=Xe.enabled?rp(tt.text,Xe).blocked:[];return Ce.length>0?(ze({type:"error",title:D("Message not sent"),description:D("Privacy masking blocks {{kinds}}. Remove it, or change the action or allow list in Settings → Privacy.",{kinds:Ce.join(", ")})}),!1):Te.current(tt)!==!1});return()=>{ce(),Ee(),Oe(),We(),qe(),rt()}},[C,D]);const Ie=m.useRef(null),Ze=m.useRef(null),Nt=m.useRef(null),Ut=m.useRef(!1),Pt=m.useRef(d);Pt.current=d,m.useEffect(()=>{if(!(C||!o))return c5({key:o,segments:()=>Ie.current?.getSegments()??[],insertText:ce=>Ie.current?.insertText(ce),setText:ce=>Ie.current?.setSegments(ce?[{type:"text",text:ce}]:[]),busy:()=>Ut.current||Pt.current||!Ie.current})},[C,o]);const[_t,B]=m.useState({left:0,flyoutSide:"right"}),[je,Ye]=m.useState(""),[Tt,Wt]=m.useState(!1),[le,ht]=m.useState(null),Ot=lI(e,le,g),Fe=m.useMemo(()=>aI(Ot,le??""),[Ot,le]),[jt,Ft]=m.useState(null),[cn,re]=m.useState(null),[Ue,ut]=m.useState(null),xt=vee(Ue,o??null),[pt,K]=m.useState(0),[fe,De]=m.useState(null),[Pe,Ge]=m.useState(0),st=m.useRef(null),we=m.useCallback(ce=>{(ce.plainText.trim()||ce.hasMentions)&&x?.(),Ye(ce.plainText),Wt(ce.hasMentions);const Ee=new Set(ce.segments.filter(We=>We.type==="ui-element"&&We.imageId).map(We=>We.type==="ui-element"?We.imageId:"")),Oe=[...pe.current].filter(We=>!Ee.has(We));pe.current=Ee,Oe.length>0&&(Q(We=>d5(We,Oe)),J(We=>We&&Oe.includes(We.imageId)?null:We)),ht(We=>(We!==ce.mentionQuery&&(K(0),De(null),Ge(0)),ce.mentionQuery)),Ft(ce.slashQuery),re(ce.skillQuery),ut(ce.pluginQuery)},[x]);m.useEffect(()=>{const ce=Me.current;if(ce!==o){ce&&cC.set(ce,{segments:Ie.current?.getSegments()??[],images:H,slashes:q,recipient:me});const Ee=o?cC.get(o):void 0,Oe=o?u5(o):void 0;Ie.current?.setSegments(Oe?[{type:"text",text:Oe}]:Ee?.segments??[]),pe.current=new Set((Ee?.segments??[]).filter(We=>We.type==="ui-element"&&We.imageId).map(We=>We.type==="ui-element"?We.imageId:"")),Q(Ee?.images??[]),ne(Ee?.slashes??[]),ke(Ee?.recipient),Me.current=o,ht(null),Ft(null),re(null),K(0),De(null),Ge(0)}a&&Ie.current?.focus()},[o]),m.useEffect(()=>{if(!u&&!h?.length)return;const ce=Iee({segments:Ie.current?.getSegments()??[],images:H,slashes:q},{text:u,images:h},p);ne(ce.slashes),Q(ce.images),Ie.current?.setSegments(ce.segments),f?.(),window.setTimeout(()=>Ie.current?.focus(),0)},[u,h,p]);const Qe=q.length===1?q[0]:null,it=oee(Qe,je.replaceAll("","")),yt=_X(t,jt,cn),Xt=jt===null&&cn===null&&it!==null?ree(Qe,it):[];m.useEffect(()=>{K(0)},[jt,cn,it,Ue]),m.useEffect(()=>{st.current?.children[pt]?.scrollIntoView({block:"nearest"})},[pt]);const E=m.useCallback(ce=>{if(ce.kind==="agent-type"){Ie.current?.consumeToken("@"),ke(ce),ht(null);return}Ie.current?.insertMention(ce),ht(null)},[]),R=m.useCallback(ce=>{ut(null),bee(ce,o??null).then(Ee=>{const Oe=Ie.current;Oe&&(Oe.consumeToken("#"),Ee&&Oe.insertText(Ee))})},[o]),M=le!==null&&Fe.length>0?"mention":Ue!==null&&xt.length>0?"plugin":yt.length>0?"slash":Xt.length>0?"slash-sub":null;m.useLayoutEffect(()=>{if(M!=="mention")return;const ce=Ze.current;if(!ce)return;const Ee=()=>{const Oe=ce.getBoundingClientRect(),We=ce.querySelector('[data-slot="mention-picker"]'),qe=We?.querySelector('[role="listbox"]'),rt=We?.querySelector('[data-slot="mention-flyout"]'),tt=Ie.current?.getMentionAnchorRect(),Xe=A4({anchorLeft:tt?tt.left-Oe.left:0,containerWidth:Oe.width,popupWidth:qe instanceof HTMLElement?qe.offsetWidth:280,flyoutWidth:rt instanceof HTMLElement?rt.offsetWidth:252,flyoutGap:4});B(Ce=>Ce.left===Xe.left&&Ce.flyoutSide===Xe.flyoutSide?Ce:Xe)};return Ee(),window.addEventListener("resize",Ee),()=>window.removeEventListener("resize",Ee)},[le,je,fe,M]);const j=M==="mention"?Fe.length:M==="plugin"?xt.length:M==="slash-sub"?Xt.length:yt.length,G=m.useCallback((ce,Ee)=>{const Oe=[{type:"text",text:ce}];if(Ie.current?.setSegments(Oe),!Ee)return;const We=Dw({segments:Oe,slashes:q,images:H,recipient:me});v(We)!==!1&&(Ie.current?.clear(),Q([]),ne([]),ke(void 0),ht(null),Ft(null),re(null))},[H,v,me,q]),he=m.useCallback(ce=>{Ie.current?.consumeToken(cn!==null?"$":"/"),Ft(null),re(null);const Ee=h5(ce);if(!Ee){ne(Oe=>Tee(Oe,ce));return}Kg(Ee,C?null:o??null).then(Oe=>{Oe&&ze({type:"error",title:D("Plugin command failed"),description:Oe})})},[cn,C,o,D]),ve=m.useCallback((ce=!1)=>{if(M==="mention"){if(fe){const Oe=Ot[fe][Pe];Oe&&E(Oe);return}const Ee=Fe[pt];Ee?.type==="item"&&E(Ee.candidate)}else if(M==="plugin"){const Ee=xt[pt];Ee&&R(Ee)}else if(M==="slash"){const Ee=yt[pt];Ee&&he(Ee.name)}else if(M==="slash-sub"){const Ee=Xt[pt];if(!Ee)return;G(Ee.name,ce)}},[pt,Pe,fe,Ot,Fe,E,R,xt,M,yt,he,Xt,G]),Ae=je.replaceAll("","").trim(),Ke=!!(Ae||q.length>0||H.length>0||Tt),ct=me!==void 0,nt=s&&!ct,Qt={sessionId:C?null:o??null,draft:je.replaceAll("",""),busy:d,pluginPresetId:r},dt=n&&b>0&&w!==void 0&&l&&!!X,Dt=dt&&!Ke&&!ct&&!d,Ct=m.useMemo(()=>V.enabled&&Ae?rp(Ae,V):null,[Ae,V]),Et=()=>{if(!Ke)return;const ce=Dw({segments:Ie.current?.getSegments()??[],slashes:q,images:H,recipient:me}),Ee=V.enabled?rp(ce.text,V).blocked:[];if(Ee.length>0){ze({type:"error",title:D("Message not sent"),description:D("Privacy masking blocks {{kinds}}. Remove it, or change the action or allow list in Settings → Privacy.",{kinds:Ee.join(", ")})});return}v(ce)!==!1&&(Ie.current?.clear(),Q([]),ne([]),ke(void 0),ht(null),Ft(null),re(null))},It=m.useCallback(ce=>{for(const Ee of ce){if(Ee.type.startsWith("image/")){const qe=new FileReader;qe.onload=()=>{const rt=qe.result,tt=rt.slice(rt.indexOf(",")+1);Q(Xe=>[...Xe,{data:tt,mimeType:Ee.type}])},qe.readAsDataURL(Ee);continue}const Oe=window.electronAPI.files.pathForFile(Ee),We=window.electronAPI.remote;if(!Oe&&We){We.upload(Ee).then(qe=>{qe&&Ie.current?.insertFileChip(qe)}).catch(()=>{});continue}Oe&&Ie.current?.insertFileChip(Oe)}},[]),bt=ce=>{const Ee=ce.nativeEvent.isComposing||Ut.current;if(M){const We=M==="mention"?Fe[pt]:void 0,qe=M4({key:ce.key,shiftKey:ce.shiftKey,isComposing:Ee,activeIndex:pt,itemCount:j,folderOpen:M==="mention"&&fe!==null,activeIsFolder:M==="mention"&&We?.type==="folder",folderIndex:Pe,folderItemCount:fe?Ot[fe].length:0});if(qe.type==="move"){ce.preventDefault(),K(qe.index),De(null);return}if(qe.type==="move-folder"){ce.preventDefault(),Ge(qe.index);return}if(qe.type==="open-folder"){ce.preventDefault(),We?.type==="folder"&&De(We.id),Ge(0);return}if(qe.type==="close-folder"){ce.preventDefault(),De(null);return}if(qe.type==="pick"){ce.preventDefault(),ve(M==="slash-sub"&&ce.key==="Enter");return}if(qe.type==="close"){ce.preventDefault(),ht(null),Ft(null),re(null),ut(null),De(null);return}}if(Ee)return;const Oe=Al(ce);if(!C&&Oe&&Oe===Oi(ye.getState().keybindings)["switch-model"]){ce.preventDefault(),p5();return}if(ce.key==="Backspace"&&q.length>0&&Ae.length===0&&!Tt){ce.preventDefault(),ne(We=>We.slice(0,-1));return}if(ce.key==="Backspace"&&me&&Ie.current?.isEmpty()&&q.length===0){ce.preventDefault(),ke(void 0);return}l&&!M&&Al(ce,{allowBare:!0})===X&&(ce.preventDefault(),Dt?w?.():Et())};return i.jsxs("div",{ref:Ze,className:"relative",children:[M==="mention"&&i.jsx(Hee,{id:ee,groups:Ot,query:le??"",activeIndex:pt,onActiveIndexChange:K,openFolderId:fe,folderIndex:Pe,onOpenFolderIdChange:De,onFolderIndexChange:Ge,onSelect:E,left:_t.left,flyoutSide:_t.flyoutSide}),M==="plugin"&&i.jsx("div",{ref:st,role:"listbox","aria-label":D("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:xt.map((ce,Ee)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Ee===pt,onMouseDown:Oe=>Oe.preventDefault(),onClick:()=>R(ce),onMouseMove:()=>K(Ee),className:U("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Ee===pt&&"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:ce.item.label}),ce.item.detail&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:ce.item.detail})]},ce.key))}),(M==="slash"||M==="slash-sub")&&i.jsx("div",{ref:st,role:"listbox","aria-label":D("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:(M==="slash"?yt:Xt).map((ce,Ee)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Ee===pt,onClick:()=>{K(Ee),M==="slash"?he(ce.name):G(ce.name,!1)},onMouseMove:()=>K(Ee),className:U("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Ee===pt&&"bg-foreground/10"),children:[i.jsx(UN,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-mono font-medium",children:cn!==null?`$${ce.name.slice(7)}`:ce.name}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:D(ce.description)})]},ce.name))}),i.jsxs("div",{ref:W,"data-slot":"composer","data-enso":"composer",className:U("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)]",(ge||ue)&&"border-brand/50 bg-brand/5",(ct||N)&&"border-primary/35 shadow-primary/5"),onDragOver:ce=>{ce.dataTransfer.types.includes("Files")&&(ce.preventDefault(),$(!0))},onDragLeave:ce=>{ce.currentTarget.contains(ce.relatedTarget)||$(!1)},onDrop:ce=>{const Ee=Array.from(ce.dataTransfer.files);Ee.length!==0&&(ce.preventDefault(),$(!1),It(Ee))},children:[H.filter(ce=>!ce.id).length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:H.filter(ce=>!ce.id).map((ce,Ee)=>i.jsxs("div",{className:"group relative",children:[i.jsx("button",{type:"button",onClick:()=>te(ce),className:"block rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none","aria-label":D("Preview"),children:i.jsx("img",{src:`data:${ce.mimeType};base64,${ce.data}`,alt:"",className:"h-16 w-16 rounded-md border object-cover"})}),i.jsx("button",{type:"button",onClick:()=>Q(Oe=>Vee(Oe,ce)),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"})})]},Ee))}),i.jsxs("div",{className:U("flex items-start gap-1.5 px-4",H.length>0?"pt-1.5":"pt-3.5"),children:[me&&i.jsx(oK,{recipient:me,onRemove:()=>ke(void 0)}),q.map(ce=>i.jsx(Iu,{name:ce,className:"mt-0.5 shrink-0",trailing:i.jsx("button",{type:"button",onClick:()=>ne(Ee=>Ee.filter(Oe=>Oe!==ce)),className:"rounded-sm opacity-70 hover:opacity-100","aria-label":D("Remove"),children:i.jsx(ln,{className:"h-3 w-3"})})},ce)),i.jsx(Oee,{ref:Ie,placeholder:q.length>0?"":d?D("Resolve the pending approval to continue"):ct?D("Message the selected Agent…"):dt?D("Press {{key}} to steer the next queued message into this round…",{key:mi(X)}):_||D(n?"Message will queue until this round finishes…":"Type @ to choose a file or Agent"),disabled:d,onStateChange:we,onChipActivate:ce=>{ce.type==="ui-element"&&J({kind:"ui-element",id:ce.id,label:ce.label,path:ce.path,text:ce.text,imageId:ce.imageId})},onKeyDown:bt,onPasteText:ce=>!I||!Dj(ce)?!1:(I(ce).catch(()=>({ok:!1,error:"unavailable"})).then(Ee=>{const Oe=Ie.current;Ee.ok?Oe?.insertFileChip(Ee.path,`${Uj} · ${D("{{count}} chars",{count:Ee.chars.toLocaleString()})}`):Oe?.insertText(ce)}),!0),onPaste:ce=>{const Ee=Array.from(ce.clipboardData.files);Ee.length!==0&&(ce.preventDefault(),It(Ee))},onCompositionStart:()=>{Ut.current=!0},onCompositionEnd:()=>{Ut.current=!1},ariaProps:{role:"combobox","aria-autocomplete":"list","aria-expanded":M!==null,"aria-controls":M==="mention"?ee:void 0,"aria-activedescendant":M==="mention"?fe?`${ee}-sub-${Pe}`:`${ee}-option-${pt}`:void 0}})]}),ct&&i.jsx("p",{className:"sr-only",children:D("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:U("flex min-w-0 flex-1 items-center gap-1",P?"overflow-x-auto [scrollbar-width:none]":"overflow-hidden"),children:[i.jsx("input",{ref:Nt,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:ce=>{It(Array.from(ce.target.files??[])),ce.target.value=""}}),i.jsx("button",{type:"button",disabled:d,onClick:()=>Nt.current?.click(),"aria-label":D("Attach image"),title:D("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(Ch,{className:"h-3.5 w-3.5"})}),i.jsx(M0,{side:"left",...Qt}),O?i.jsx(jee,{active:T,disabled:d,onChange:ce=>{z(ce),ce?document.activeElement?.blur():Ie.current?.focus()}}):S?i.jsx(oI,{startSession:S,requestMicAccess:k,disabled:d,holdBinding:F||void 0,holdScope:Ze,onText:ce=>{Ie.current?.insertText(ce),Ie.current?.focus()}}):null,c,!C&&i.jsx(dee,{sessionId:Qt.sessionId}),i.jsx(M0,{side:"right",...Qt}),Ct&&(Ct.blocked.length>0||Ct.masked>0)&&i.jsxs("span",{className:U("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(dj,{className:"size-3.5"}):i.jsx(Yu,{className:"size-3.5"}),Ct.blocked.length>0?D("Will be blocked: {{kinds}}",{kinds:Ct.blocked.join(", ")}):D("{{count}} will be masked",{count:Ct.masked})]})]}),nt&&!Ke?i.jsx(xe,{variant:"outline",size:"icon",className:"size-8 shrink-0 rounded-full",onClick:y,"aria-label":D("Stop"),children:i.jsx(H$,{className:"h-4 w-4"})}):i.jsx(xe,{size:"icon",className:"size-8 shrink-0 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-35",onClick:Et,disabled:!Ke||d,"aria-label":D(ct?"Send only to the selected Agent":"Send"),title:ct?D("Send only to the selected Agent"):l&&X?`${D("Send")} ${mi(X)}`:D("Send"),children:i.jsx(dc,{className:"h-4 w-4"})})]})]}),O&&T?i.jsx(_ee,{startSession:O,disabled:d,onText:ce=>{Ie.current?.insertText(ce),document.activeElement?.blur()}}):null,i.jsx(vn,{open:Z!==null,onOpenChange:ce=>!ce&&J(null),children:i.jsxs(bn,{className:"max-w-md",children:[i.jsx(wn,{children:i.jsx(yn,{children:Z?.label??D("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 ce=H.find(Ee=>Ee.id===Z.imageId);return ce?i.jsx("img",{src:`data:${ce.mimeType};base64,${ce.data}`,alt:"",className:"max-h-72 w-full rounded-md border object-contain"}):null})()]})})]})}),i.jsx(vn,{open:ae!==null,onOpenChange:ce=>!ce&&te(null),children:i.jsxs(bn,{className:"max-w-3xl",children:[i.jsx(wn,{children:i.jsx(yn,{children:D("Preview")})}),i.jsx(Mn,{children:ae&&i.jsx("img",{src:`data:${ae.mimeType};base64,${ae.data}`,alt:"",className:"max-h-[80vh] w-full rounded-md object-contain"})})]})})]})}function mE({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:U("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.nativeEvent.isComposing&&(l.key==="Enter"?(l.preventDefault(),a()):l.key==="Escape"&&(l.preventDefault(),s()))}})}async function gE(e,t){const n=await oe.getState().reloadConversation(e);n&&ze({type:"error",title:t("Failed to reload conversation"),description:n})}async function Wee(e,t){const n=await oe.getState().restartConversation(e);n&&ze({type:"error",title:t("Failed to restart conversation"),description:n})}function Uee({parentId:e,displayedId:t,trailing:n}){const{t:s}=se(),o=oe(p=>p.conversations[e]?.title??""),r=oe(p=>p.conversations[e]?.started===!0),a=oe(p=>p.conversations[e]?.reloading===!0),l=oe(p=>!!p.conversations[e]?.spawning),c=oe(p=>HQ(p.conversations,e)),[d,u]=m.useState(!1),h=p=>U("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(h_,{"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(dC,{id:e,label:o||s("New conversation"),className:h(t===e),leading:i.jsx(yr,{className:"h-3 w-3 shrink-0"}),reloadDisabled:a||l,reloading:a,onSelect:()=>oe.getState().selectTab(e,void 0)}),c.map(p=>{const f=f5({status:p.status,spawning:p.spawning,pendingApprovalCount:p.pendingApprovalCount,pendingAskCount:p.pendingAskCount});return i.jsxs("div",{className:"group/tab relative shrink-0",children:[i.jsx(dC,{id:p.id,label:p.title||p.child?.agentInstanceName||p.coworkerName||p.id,className:U(h(t===p.id),t!==p.id&&"group-hover/tab:bg-muted/50"),leading:p.mode==="task"?i.jsx(qg,{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(Bh,{tone:f,size:"sm"})}),reloadDisabled:p.reloading||p.spawning,reloading:p.reloading,onSelect:()=>oe.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."))&&oe.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,d&&i.jsx(Kee,{parentId:e,onClose:()=>u(!1)})]})}function dC({id:e,label:t,className:n,leading:s,trailing:o,reloadDisabled:r,reloading:a,onSelect:l}){const{t:c}=se(),[d,u]=m.useState(!1),h=i.jsxs("button",{type:"button",className:n,onClick:()=>{d||l()},onDoubleClick:p=>{p.preventDefault(),p.stopPropagation(),u(!0)},children:[s,d?i.jsx(mE,{title:t,className:"max-w-48 text-xs",onCommit:p=>{oe.getState().renameConversation(e,p),u(!1)},onCancel:()=>u(!1)}):i.jsx("span",{className:"max-w-48 truncate",children:t}),o]});return i.jsxs(po,{children:[i.jsx(fo,{render:h}),i.jsxs(mo,{className:"min-w-36",children:[i.jsxs(Vt,{onClick:()=>u(!0),children:[i.jsx(Bs,{}),c("Rename")]}),i.jsxs(Vt,{disabled:r,onClick:()=>{gE(e,c)},children:[i.jsx(Wo,{className:a?"animate-spin":void 0}),c("Reload conversation")]})]})]})}function Kee({parentId:e,onClose:t}){const{t:n}=se(),s=ye(x=>x.agentTypes),o=ye(x=>x.disabledBuiltinAgentTypes),[r,a]=m.useState(""),[l,c]=m.useState(""),[d,u]=m.useState(null),h=new Set(s.map(x=>x.name.trim().toLowerCase())),p=[...m5.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 oe.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=>c(x??""),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:f.map(x=>i.jsx(os,{value:x.value,children:x.label},x.value||"general"))})]})]}),d&&i.jsx("p",{className:"text-destructive text-xs",children:d}),i.jsx("div",{className:"h-1"})]}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"ghost",onClick:t,children:n("Cancel")}),i.jsx(xe,{onClick:()=>{g()},disabled:!r.trim(),children:n("Hire")})]})]})})}function qee(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 Yee={active:"bg-green-500 animate-pulse",paused:"bg-amber-500",waiting:"bg-amber-500",blocked:"bg-destructive",completed:"bg-blue-500"};function Xee({conversationId:e,goal:t}){const{t:n}=se(),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(Ia,{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:U("h-1.5 w-1.5 shrink-0 rounded-full",Yee[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:()=>oe.getState().pauseGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(e4,{className:"h-3.5 w-3.5"})}):t.status!=="completed"?i.jsx("button",{type:"button",title:n("Resume goal"),onClick:()=>oe.getState().resumeGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(Og,{className:"h-3.5 w-3.5"})}):null,i.jsx("button",{type:"button",title:n("Clear goal"),onClick:()=>oe.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 Jee(e,t){return e.trim().length>0||t>0}function uC(e,t){return e>0?`${e} ${t}`:null}function xE({conversationId:e,queued:t}){const{t:n}=se(),[s,o]=m.useState(null),[r,a]=m.useState("");if(t.length===0)return null;const l=c=>{Jee(r,c.images?.length??0)&&oe.getState().updateQueuedMessage(e,c.id,r.trim()),o(null)};return i.jsx("div",{className:"mb-1 flex flex-col gap-0.5",children:t.map(c=>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===c.id?i.jsx("input",{value:r,onChange:d=>a(d.target.value),onKeyDown:d=>{d.nativeEvent.isComposing||(d.key==="Enter"&&l(c),d.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:c.text||"[image]"}),uC(c.images?.length??0,n("attachments"))&&i.jsxs("span",{title:uC(c.images?.length??0,n("attachments"))??void 0,className:"flex shrink-0 items-center gap-0.5 text-muted-foreground",children:[i.jsx(L6,{className:"h-3 w-3"}),c.images?.length]}),s===c.id?i.jsx("button",{type:"button",onClick:()=>l(c),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:()=>oe.getState().withdrawMessage(e,{kind:"queue",id:c.id}),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(fa,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Edit"),onClick:()=>{o(c.id),a(c.text)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(Bs,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Send now"),onClick:()=>oe.getState().sendQueuedNow(e,c.id),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(Vx,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Interrupt and send now"),onClick:()=>{oe.getState().interruptAndSendQueued(e,c.id)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(f4,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Remove"),onClick:()=>oe.getState().removeQueuedMessage(e,c.id),className:"rounded p-0.5 text-muted-foreground hover:text-destructive",children:i.jsx(ln,{className:"h-3.5 w-3.5"})})]})]},c.id))})}const vE="mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2 text-xs";function bE({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 Zee({conversationId:e,planState:t,approvalMode:n}){const s=p_(t);return s==="awaiting_review"&&t?.pending?i.jsx(Qee,{conversationId:e,doc:t.pending,approvalMode:n},t.pending.planId):s==="executing"&&t?.executing?i.jsx(ete,{conversationId:e,doc:t.executing},t.executing.planId):null}function Qee({conversationId:e,doc:t,approvalMode:n}){const{t:s}=se(),o=g5(),[r,a]=m.useState(!0),[l,c]=m.useState(!1),[d,u]=m.useState(""),[h,p]=m.useState(!1),[f,g]=m.useState(!1),x=async(v,y)=>{g(!0);const b=oe.getState();y&&y!==n&&b.setApprovalMode(e,y);const w=await b.respondPlan(e,t.planId,v,v==="revise"?d.trim():void 0);w&&(g(!1),ze({type:"error",title:s("Plan response failed"),description:w}))};return i.jsxs("div",{className:vE,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(va,{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:U("h-3 w-3 shrink-0 transition-transform",r&&"rotate-90")})]})]}),r&&i.jsx(bE,{doc:t}),l&&i.jsx("textarea",{autoFocus:!0,value:d,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&d.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||!d.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:()=>c(!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(Rl[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(Vn,{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")}),x5.map(v=>{const y=Rl[v],b=y.icon,w=v==="assistant"&&!o;return i.jsxs("button",{type:"button",disabled:w,onClick:()=>{p(!1),x("approve",v)},className:U("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 ete({conversationId:e,doc:t}){const{t:n}=se(),[s,o]=m.useState(!1);return i.jsxs("div",{className:U(vE,"py-1.5"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(FN,{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:U("h-3 w-3 shrink-0 transition-transform",s&&"rotate-90")})]}),i.jsx("button",{type:"button",title:n("Finish plan"),onClick:()=>{oe.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(bE,{doc:t})]})}function tte({active:e,onToggle:t}){const{t:n}=se();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:U("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(va,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"hidden @min-[28rem]:inline",children:n("Plan")})]})}function nte({presetId:e,onSelect:t,onModel:n,disabled:s}){const{t:o}=se(),r=ye(h=>h.presets),a=v5(),[l,c]=m.useState(!1),d=[{id:b5,name:o("Global")},...r.map(h=>({id:h.id,name:h.name})),...a.map(h=>({id:h.id,name:h.name}))],u=d.find(h=>h.id===e)??{id:e,name:w5(e)?o("Plugin preset unavailable"):d[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(Qd,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:u.name})]}):i.jsxs(gi,{open:l,onOpenChange:c,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(Qd,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:u.name}),i.jsx(Vn,{className:"h-3 w-3 shrink-0"})]}),i.jsx(vi,{side:"top",align:"start",className:"w-52 [&_[data-slot=popover-viewport]]:p-1",children:d.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=y5(f??h.id,a);g&&n?.(g),c(!1)},className:U("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 ste=[];function ite({projectId:e,conversationId:t}){const{t:n}=se(),s=ye(p=>p.projects.find(f=>f.id===e)?.trustedProjectCode??ste),o=ye(p=>p.setProjectTrustedCode),[r,a]=m.useState([]),[l,c]=m.useState(!1),[d,u]=m.useState(!1);m.useEffect(()=>{let p=!1;return c(!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&&!d?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(oa,{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:()=>c(!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(oa,{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(xe,{size:"xs",variant:"outline",onClick:()=>{o(e,r),u(!0)},children:n("Trust and load")}),i.jsx("button",{type:"button",onClick:()=>c(!0),title:n("Dismiss"),children:i.jsx(ln,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}const ote=70,wE=80,yE={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 SE({segments:e,highlight:t,className:n}){return i.jsx("span",{"aria-hidden":!0,className:U("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:U("block h-full transition-opacity",yE[s.kind],t&&t!==s.kind&&"opacity-25"),style:{width:`${s.width}%`}},s.kind))})}function rte({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:U("block h-full rounded-full",t?"bg-destructive":e>=ote?"bg-warning":"bg-muted-foreground/70"),style:{width:`${e}%`}})})}const ate={system:"System prompt",memory:"Enabled instructions",tools:"Tool definitions",skills:"Enabled skills",files:"Files read",results:"Tool results",chat:"Conversation"};function lte({conversationId:e}){const{t}=se(),n=oe(r=>r.conversations[e]?.compaction);if(!oe(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:()=>oe.getState().compact(e),children:o})}function cte({occupancy:e,conversationId:t,cwd:n,onNavigate:s}){const{t:o}=se(),[r,a]=m.useState(),[l,c]=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 d=e.contextWindow,u=XT(e),h=(e.percent??0)>=wE,p=[...u].filter(g=>uy(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:[Zn(e.used),d?` / ${Zn(d)}`:" · ?",e.percent!==void 0&&i.jsx("span",{className:U(h&&"text-warning"),children:` · ${e.percent}%`})]}),i.jsx("span",{className:"text-muted-foreground",children:o("Estimate")})]}),u.length>0&&i.jsx(SE,{segments:u,highlight:r,className:"h-1.5 w-full"}),h&&d!==void 0&&i.jsx("p",{className:"text-[11px] text-warning",children:o("About {{tokens}} left",{tokens:Zn(Math.max(0,d-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:()=>{oe.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=uy(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:()=>c(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:U("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(ate[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:U("block h-full",yE[g]),style:{width:`${v}%`}})})}),i.jsx("span",{className:"w-10 shrink-0 text-right tabular-nums",children:Zn(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 C=AU(w),_=RU(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 C?i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono",title:C.raw,children:C.raw}):i.jsx("span",{className:"min-w-0 flex-1 truncate",children:o(C.key,C.vars)}),_&&(_.type==="settings"||t)?i.jsx("button",{type:"button",onClick:()=>N(_),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(_.type==="file"?"Open":"Settings")}):null,i.jsx("span",{className:U("shrink-0 tabular-nums",_&&"group-hover/item:hidden"),children:Zn(w.tokens)})]},`${w.tag}-${w.name}`)})})]},g)})}),t&&i.jsx(lte,{conversationId:t})]})}function dte(e){return e?e.used:null}const Rv=90;function CE(e,t){const n=dte(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 ute(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 hte(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:`${Zn(a)} · ${l}%`,percent:l,critical:l>=Rv}}else n.context={compact:`${Zn(r)}·?`,full:`${Zn(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:`↑${Zn(t.inputTokens)} ↓${Zn(t.outputTokens)}`,full:e("Input {{input}} tok · Output {{output}} tok",{input:Zn(t.inputTokens),output:Zn(t.outputTokens)})}),t.cacheHitPercent!==void 0&&(n.cache={compact:`${t.cacheHitPercent}%`,full:e("Cache hit {{percent}}%",{percent:t.cacheHitPercent})}),n}function pte(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:df(t.bytes),full:`${df(t.bytes)} / ${df(t.limitBytes)} · ${n}% · ${s}`,critical:t.blocked||n>=Rv}}function df(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 fte({className:e,orientation:t="horizontal",...n}){return i.jsx(C5,{className:U("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 mte={minimal:"Minimal",default:"Default",full:"Full"};function gte({icons:e,values:t}){const{t:n}=se(),s=ye(x=>x.statusLineSegments),o=m.useMemo(()=>kE(s),[s]),r=ye(x=>x.toggleStatusLineSegment),a=ye(x=>x.setStatusLineSegments),[l,c]=m.useState(null),[d,u]=m.useState(null),h=k5(o),p=f_.filter(x=>!o.includes(x)),f=()=>{c(null),u(null)},g=()=>{if(l!==null&&d!==null){const x=d>l?d-1:d,v=T5(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:j5.map(x=>i.jsx(xe,{variant:h===x?"secondary":"ghost",size:"xs",onClick:()=>a([..._5[x]]),children:n(mte[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&&d===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 C=w.currentTarget.getBoundingClientRect(),_=w.clientY<C.top+C.height/2;u(_?v:v+1)},onDrop:w=>{w.preventDefault(),g()},className:U("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),c(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(N5,{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(Ou[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:b?.full||n("No data yet")})]})]}),i.jsx(di,{checked:!0,onCheckedChange:w=>r(x,w)})]})]},x)}),l!==null&&d===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(fte,{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(Ou[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:y?.full||n("No data yet")})]})]}),i.jsx(di,{checked:!1,onCheckedChange:b=>r(x,b)})]},x)})]})]})]})}function kE(e){const t=Array.isArray(e)?e:I5,n=new Set(f_),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 Ou={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"},xte={minimal:"Min",low:"Low",medium:"Med",high:"High",xhigh:"Extra",max:"Max"},vte={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"},bte={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},wte={supervised:M5,"auto-edits":Yu,full:A5,assistant:ti},yte={model:s6,context:L5,requestBody:R5,turns:i4,duration:HN,sessionTime:E6,speed:qg,tokens:Y$,cache:o6,cwd:ni,sessionName:g4,coworkers:da,usage:T4};function Ste(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 Cte(e){return e.split(/[\\/]+/).filter(Boolean).at(-1)??e}function od(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function hC(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 pC(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 kte(e){return{...yte,approval:wte[e.approvalMode??"full"]}}function jte(e,t){const[n,s]=m.useState(()=>{if(!e)return;const o=R0.get(e);return o?{key:e,data:o.data}:void 0});return m.useEffect(()=>{if(!e)return;let o=!1;const r=R0.get(e);if(r&&Date.now()-r.fetchedAt<E5){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 _te(e,t,n,s,o,r,a){const l=SU(n),c={model:void 0,requestBody:pte(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,...hte(e,ute(CU(l),CE(t.occupancy,t.contextWindow)))};if(t.lastModelId){const b=s.find(C=>C.id===t.lastProviderId)?.models.find(C=>C.id===t.lastModelId)?.label??t.lastModelId,w=t.reasoningEnabled?t.thinkingLevel:void 0;c.model={compact:w?`${b} · ${e(xte[w])}`:b,full:w?`${b} · ${e(vte[w])}`:b}}l.steps>0&&(c.turns={compact:`${l.turns}·${l.steps}`,full:e("{{turns}} turns · {{steps}} steps",{turns:l.turns,steps:l.steps})});const d=Ste(t,n,r),u=l.llmMs+d.llm,h=l.toolMs+d.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&&(c.duration={compact:p.join(" · "),full:f.join(" · ")});const g=Math.max(0,r-t.createdAt);c.sessionTime={compact:pC(g),full:pC(g)};const x=o.find(y=>y.id===t.projectId);if(x){const y=Cte(x.path);c.cwd={compact:y,full:x.path}}t.title.trim().length>0&&(c.sessionName={compact:od(t.title,16),full:od(t.title,60)}),c.approval={compact:"",full:e(bte[t.approvalMode??"full"])};const v=t.coworkerIds?.length??0;if(v>0&&(c.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],C=od(w.label,24),_=w.resetsAt!==void 0?hC(w.resetsAt-r):void 0,N=y.length>1?` +${y.length-1}`:"";c.usage={compact:`${C} ${Math.round(w.usedPercent)}%${_?`·${_}`:""}${N}`,full:y.map(S=>{const k=S.resetsAt!==void 0?` · ${e("resets in {{remaining}}",{remaining:hC(S.resetsAt-r)})}`:"";return`${od(S.label,24)} ${Math.round(S.usedPercent)}%${k}`}).join(" · "),critical:b>=Rv}}return c}function jE({conversationId:e,cwd:t}){const{t:n}=se(),s=oe(I=>I.conversations[e]),o=s?.messages??[],r=Ca(),a=ye(I=>I.virtualModels),l=m.useMemo(()=>a.length===0?r:[...r,{id:m_,models:a.map(I=>({id:I.id,label:I.name}))}],[r,a]),c=ye(I=>I.projects),d=ye(I=>I.statusLineSegments),u=m.useMemo(()=>kE(d),[d]),[h,p]=m.useState(null),[f,g]=m.useState(!1),x=m.useMemo(()=>{if(u.includes("usage"))return Yg(r,s)?.accountKey},[u,r,s]),[v,y]=m.useState(()=>Date.now()),b=s?.status==="running"&&u.includes("duration"),w=u.includes("sessionTime"),C=u.includes("usage")&&x!==void 0;m.useEffect(()=>{if(!b&&!w&&!C)return;const I=setInterval(()=>y(Date.now()),1e3);return()=>clearInterval(I)},[b,w,C]);const _=jte(x,v),N=m.useMemo(()=>s?kte(s):null,[s]),S=m.useMemo(()=>s?_te(n,s,o,l,c,v,_):null,[n,s,o,l,c,v,_]);if(!s||!N||!S)return null;const k=s.occupancy?XT(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,D)=>{const P=S[I];if(!P)return null;const T=N[I],z=i.jsxs("span",{title:`${n(Ou[I])} · ${P.full}`,onMouseEnter:()=>p(I),onMouseLeave:()=>p(O=>O===I?null:O),className:U("relative flex items-center gap-1 text-[11px] tabular-nums",P.critical?"text-destructive":I==="context"&&P.percent!==void 0&&P.percent>=wE?"text-warning":"text-subtle-foreground"),children:[I==="context"&&P.percent!==void 0?k.length>0?i.jsx(SE,{segments:k}):i.jsx(rte,{percent:P.percent,critical:!!P.critical}):i.jsx(T,{className:"h-3 w-3 shrink-0 opacity-75"}),P.compact&&i.jsx("span",{className:"truncate",children:P.compact}),h===I&&I!=="context"&&i.jsxs("div",{style:{zIndex:Cn.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(Ou[I])}),i.jsx("span",{className:"ml-1 break-words text-muted-foreground",children:P.full})]})]});return i.jsx("span",{className:U("shrink-0 items-center",f||D5(I,D)?"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:z}),i.jsx(vi,{side:"top",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:i.jsx(cte,{occupancy:s.occupancy,conversationId:s.id,cwd:t,onNavigate:()=>g(!1)})})]}):z},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(g_,{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(gte,{icons:N,values:S})})]})]})}const Nte=["pattern","query","path","file_path"],Tte=["path","file_path","query","pattern"],Dte=["command","cmd","script"],Ite=["path","file_path","pattern","query","command","url","description","summary"],fC=120;function $a(e){const t=e.replace(/\s+/g," ").trim();return t.length>fC?`${t.slice(0,fC-1)}…`:t}function Ete(e){const t=e.toLowerCase();return t.includes("search")||t.includes("grep")||t==="find"?Nte:t==="read"||t.endsWith("_read")?Tte:t==="bash"||t.includes("shell")||t.includes("terminal")?Dte:Ite}function Pte(e,t){const n=t.trim();if(!n)return"";let s;try{s=JSON.parse(n)}catch{return $a(n)}if(s===null)return"";if(typeof s!="object"||Array.isArray(s))return $a(JSON.stringify(s)??String(s));const o=x_(e,s);if(o.summary!==void 0)return $a(o.summary);if(!o.args||typeof o.args!="object")return"";const r=o.args;for(const l of Ete(o.name)){const c=r[l];if(typeof c=="string"&&c.trim())return $a(c)}const a=JSON.stringify(r);return a==="{}"?"":$a(a)}function Ate(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}const _E=new Map,Mte=e=>{const t=_E.get(e);return t?new Set(t):new Set},mC=(e,t)=>(_E.set(e,t),t),lg=new Map,Rte=(e,t)=>{const n=lg.get(e)??new Set;lg.set(e,n);for(const s of t)n.add(s);return n};function Lv({sessionId:e,tasks:t,subagents:n,readOnly:s}){const o=ye(b=>b.virtualModels),{t:r}=se(),[a,l]=m.useState(()=>Mte(e)),[c,d]=m.useState(null),u=oe(b=>b.pendingAgentOpen);m.useEffect(()=>{!u||u.sessionId!==e||(d(u.agentId),oe.setState({pendingAgentOpen:null}))},[u,e]);const h=Rte(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=lg.get(e),w=[...t.filter(_=>_.status!=="running").map(_=>_.taskId),...n.filter(_=>_.status!=="running").map(_=>_.id)].filter(_=>b?.has(_)&&!a.has(_)&&_!==c);if(w.length===0)return;const C=setTimeout(()=>{l(_=>{const N=new Set(_);for(const S of w)N.add(S);return mC(e,N)})},5e3);return()=>clearTimeout(C)},[e,t,n,a,c]),f.length===0&&g.length===0)return null;const x=b=>{l(w=>mC(e,new Set(w).add(b))),c===b&&d(null)},v=f.find(b=>b.taskId===c)??null,y=g.find(b=>b.id===c)??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?` · ${Ff(o,y.modelId)}`:""]}),i.jsx("button",{type:"button",onClick:()=>d(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(Vte,{tail:v.tail}),y&&i.jsx(Lte,{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(gC,{icon:$o,status:b.status,meta:i.jsx(Bte,{task:b}),open:c===b.taskId,onToggle:()=>d(c===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(gC,{icon:Vs,status:b.status,meta:i.jsx(Hte,{agent:b}),open:c===b.id,onToggle:()=>d(c===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:[" ","· ",Ff(o,b.modelId)]}),b.status==="running"&&b.currentActivity&&i.jsxs("span",{className:"text-muted-foreground/60",children:[" · ",b.currentActivity]})]})]},b.id))]})]})}function gC({icon:e,status:t,meta:n,open:s,onToggle:o,stopTitle:r,onStop:a,onDismiss:l,children:c}){const{t:d}=se();return i.jsxs("div",{className:"flex min-h-[30px] min-w-0 items-center gap-2 px-1 text-[13px]",children:[i.jsx(eq,{icon:e,state:t==="running"?"running":t==="failed"?"error":"ok"}),c,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:[d("Output"),i.jsx(Vn,{className:U("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(uc,{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 Lte({agent:e}){const{t}=se(),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=Ate(r.currentTarget)},children:[n.map(r=>i.jsx(Ote,{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:U("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 Ote({activity:e}){const{t}=se(),[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(Fte,{text:e.text,markdown:!0})]});const o=Pte(e.toolName,e.argumentsText),r=x_(e.toolName,e.argumentsText).name,a=mj(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(c=>!c),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(zte,{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(Gte,{status:e.status,label:t(e.status)}),i.jsx(un,{"aria-hidden":"true",className:U("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 zte({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(ei,{"aria-hidden":"true",className:n}):t==="read"||t==="write"||t==="edit"||t==="apply_patch"||t.endsWith("_read")?i.jsx(So,{"aria-hidden":"true",className:n}):t==="bash"||t==="exec"||t==="codemode"||t.includes("shell")||t.includes("terminal")?i.jsx(Ef,{"aria-hidden":"true",className:n}):i.jsx(Fg,{"aria-hidden":"true",className:n})}function Gte({status:e,label:t}){const n="h-3.5 w-3.5";return i.jsx("span",{role:"status","aria-label":t,title:t,className:U("shrink-0",e==="failed"?"text-destructive":"text-muted-foreground"),children:e==="running"?i.jsx(Yt,{"aria-hidden":"true",className:U(n,"animate-spin")}):e==="done"?i.jsx(Kn,{"aria-hidden":"true",className:n}):e==="failed"?i.jsx(br,{"aria-hidden":"true",className:n}):i.jsx(N$,{"aria-hidden":"true",className:n})})}function Fte({text:e,label:t,markdown:n=!1}){const{t:s}=se(),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 Hte({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 Bte({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 Vte({tail:e}){const{t}=se(),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 Ov(e){return e==="darwin"?"Open in Finder":e==="win32"?"Open in File Explorer":"Open in File Manager"}async function zv(e,t){try{const n=await window.electronAPI.projects.reveal(e);n.ok||ze({type:"error",title:t("Could not complete the file action."),description:n.error})}catch(n){ze({type:"error",title:t("Could not complete the file action."),description:String(n)})}}const $te="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 Wte({project:e,conversationId:t,path:n,branch:s,openDisabled:o,children:r}){const{t:a}=se(),[l,c]=m.useState([]),d=e.kind!=="ssh"&&!window.electronAPI.remote,u=e.kind==="scratch",h=u?a("Temporary chats"):e.name,p=m.useCallback(()=>{d&&window.electronAPI.projects.openInApps().then(c).catch(()=>{})},[d]),f=v=>{zv({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(Cc,{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) ${$te}`,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(Ri,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-40 truncate",children:s})]})]})}),i.jsx("span",{className:"ml-1.5 flex shrink-0 items-center",children:r})]}),i.jsxs(Vi,{align:"end",className:"min-w-48",children:[d&&i.jsxs(i.Fragment,{children:[i.jsxs(mn,{disabled:o,onClick:()=>f(),children:[i.jsx(ni,{}),a(Ov(window.electronAPI.env.platform))]}),i.jsx(xC,{label:a("Editors"),apps:g,fallback:i.jsx(bm,{}),disabled:o,onOpen:f}),i.jsx(xC,{label:a("Terminals"),apps:x,fallback:i.jsx($o,{}),disabled:o,onOpen:f}),i.jsx(ya,{})]}),i.jsxs(mn,{onClick:()=>{navigator.clipboard.writeText(n)},children:[i.jsx(Xu,{}),a("Copy Path")]})]})]})}function xC({label:e,apps:t,fallback:n,disabled:s,onOpen:o}){return t.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx(ya,{}),i.jsxs(Bg,{children:[i.jsx(Vg,{children:e}),t.map(r=>i.jsxs(mn,{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 Ute({conversationId:e}){const{t}=se(),n=oe(r=>r.conversations[e]),s=oe(r=>r.rebuildWorktree),o=oe(r=>r.fallbackToMainWorkspace);return!n?.worktreeMissing||!n.worktree?null:i.jsx(v_,{open:!0,children:i.jsxs(b_,{className:"sm:max-w-md",children:[i.jsxs(w_,{children:[i.jsx(y_,{className:"text-base",children:t("Isolated worktree is missing")}),i.jsx(S_,{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(C_,{variant:"bare",children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:()=>{o(e)},children:t("Fall back to main working tree")}),i.jsx(xe,{size:"sm",onClick:()=>{s(e).then(r=>{r&&ze({type:"error",title:t("Failed to rebuild worktree"),description:r})})},children:t("Rebuild worktree")})]})]})})}function zu(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 Kte({initialName:e,data:t,busy:n,disabled:s,error:o,returnFocus:r,onSubmit:a,onClose:l}){const{t:c}=se(),[d,u]=m.useState(e),h=m.useRef(null),p=m.useId(),f=t?.branches.some(v=>v.name===d.trim()),g=n||s||!t?.headCommit||!!t.blockedReason||!d.trim()||f,x=f?c("A branch with this name already exists."):t?.blockedReason?zu(t.blockedReason,c):t&&!t.headCommit?c("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:c("Create branch")}),i.jsx(As,{children:c("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":c("Branch name"),"aria-invalid":!!x,"aria-describedby":x||o?p:void 0,value:d,disabled:n,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.nativeEvent.isComposing&&(v.preventDefault(),g||a(d.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(xe,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:l,children:c("Cancel")}),i.jsxs(xe,{type:"button",size:"sm",disabled:!!g,onClick:()=>{g||a(d.trim())},children:[n&&i.jsx(Yt,{className:"h-3.5 w-3.5 animate-spin"}),c("Create and switch")]})]})]})})}function qte({data:e,loading:t,error:n,disabled:s,query:o,searchRef:r,onQueryChange:a,onSelect:l,onCreate:c,onRetry:d}){const{t:u}=se(),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(ei,{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:zu(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(Yt,{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:d,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:U("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(Go,{className:"h-3.5 w-3.5 shrink-0"}):i.jsx(Ri,{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:c,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 Yd(e){return e.name?.trim()||e.branch}function Yte(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 Xte(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 cg(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[Yd(e),e.branch,e.path,s].join(`
|
|
93
|
-
`)}function Jte({worktree:e,status:t}){const{t:n}=se();return i.jsx("span",{"data-slot":"worktree-label",title:cg(e,t,n),className:"flex shrink-0 items-center",children:i.jsx(Ri,{className:U("size-2.75",t?.exists===!1?"text-destructive":t?.dirty?"text-warning":(t?.ahead??0)>0?"text-info":"text-subtle-foreground")})})}function NE({entity:e,onClose:t}){const{t:n}=se(),s=oe(d=>d.renameWorktree),[o,r]=m.useState(e?.worktree.name??""),[a,l]=m.useState(!1);m.useEffect(()=>{r(e?.worktree.name??""),l(!1)},[e]);const c=async()=>{if(!(!e||a)){l(!0);try{const d=await s(e.conversationId,o.trim());d?ze({type:"error",title:n("Failed to rename worktree"),description:d}):t()}catch(d){ze({type:"error",title:n("Failed to rename worktree"),description:String(d)})}finally{l(!1)}}};return i.jsx(vn,{open:e!==null,onOpenChange:d=>{!d&&!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:d=>r(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.nativeEvent.isComposing&&(d.preventDefault(),c())}})}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",disabled:a,onClick:t,children:n("Cancel")}),i.jsxs(xe,{size:"sm",disabled:a,onClick:()=>{c()},children:[a&&i.jsx(Yt,{className:"h-3.5 w-3.5 animate-spin"}),n("Save")]})]})]})})}function Zte({conversationId:e,onBranchChange:t}){const{t:n}=se(),s=oe(Fe=>Fe.conversations[e]),o=oe(Fe=>Fe.moveConversationToWorktree),r=oe(Fe=>Fe.cleanupWorktree),a=oe(Fe=>Fe.refreshWorktreeStatuses),l=oe(Fe=>Fe.conversations),c=oe(Fe=>Fe.worktreeStatuses),d=oe(Fe=>Fe.attachConversationToWorktree),u=oe(Fe=>Fe.newConversation),h=oe(Fe=>Fe.switchWorkspaceBranch),p=oe(Fe=>Fe.workspaceRevisionByConversation[e]??0),[f,g]=m.useState(null),x=m.useMemo(()=>Yte(l,s?.projectId??"",c),[l,s?.projectId,c]),[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=ye(Fe=>s?Fe.projects.find(jt=>jt.id===s.projectId):void 0),D=!!(s&&!s.parentId&&!s.child&&I?.kind!=="ssh"&&I?.kind!=="scratch"),P=`${e}\0${s?.worktree?.path??I?.path??""}`,T=m.useRef(P);T.current=P;const z=m.useRef(0),O=m.useRef(!1),L=m.useRef(null),V=m.useRef(null),X=m.useRef(null);m.useEffect(()=>{v&&(b?V:X).current?.focus()},[v,b]);const[F,ee]=m.useState(null),H=F?.key===P?F.data:null,Q=H?.currentBranch??void 0;m.useEffect(()=>{t?.(Q)},[t,Q]);const[q,ne]=m.useState(!0),[me,ke]=m.useState(null),[Me,ge]=m.useState(""),[$,W]=m.useState(null),[ue,Z]=m.useState(null),J=$===P;m.useEffect(()=>{y(!1),w(!1),ge(""),W(null),Z(null)},[P]);const ae=m.useCallback(async(Fe=!1)=>{if(!D)return;const jt=++z.current;ne(!0),ke(null);try{const Ft=await window.electronAPI.worktree.branches(e);if(jt!==z.current||T.current!==P)return;if(Ft.ok)ee({key:P,data:Ft.value});else{const cn=zu(Ft.code,n);ke(cn),Fe&&ze({type:"error",title:n("Failed to load branches"),description:cn})}}catch(Ft){if(jt!==z.current||T.current!==P)return;ke(n("Failed to load branches")),Fe&&ze({type:"error",title:n("Failed to load branches"),description:String(Ft)})}finally{jt===z.current&&T.current===P&&ne(!1)}},[e,D,n,P]);if(m.useEffect(()=>{ae();const Fe=()=>{O.current||ae()};return window.addEventListener("focus",Fe),()=>{z.current+=1,window.removeEventListener("focus",Fe)}},[ae,p]),!s||s.parentId||s.child||I?.kind==="ssh")return null;const te=!!s.worktree,pe=C||s.spawning||s.status==="running"||!!(s.workspaceMigrating||s.reloading),Te=s.worktreeMissing||c[e]?.exists===!1,$e=Xte(s),Ie=H?H.currentBranch:s.worktree?.branch,Ze=Ie??(H?.headCommit?n("Detached HEAD"):""),Nt=s.worktree?Yd(s.worktree):n("Local"),Ut=Ze&&Ze!==Nt&&(!H?.defaultBranch||Ie!==H.defaultBranch)?`${Nt} · ${Ze}`:Nt,Pt=pe||Te||q||!!me||!H||!!H.blockedReason,_t=async(Fe,jt=!1,Ft)=>{if(Pt||O.current)return;O.current=!0,z.current+=1,_(!0),Z(null);const cn=n(Ft?"Failed to create conversation":"Failed to switch branch");try{if(Ft){await u(s.projectId,{worktreeFromConversationId:Ft})?T.current===P&&y(!1):ze({type:"error",title:cn});return}const re=await h(e,Fe,jt);if(T.current!==P)return;if(re.ok)ee({key:P,data:re.value}),ke(null),W(null),y(!1);else{const Ue=zu(re.code,n);Z(Ue),ze({type:"error",title:cn,description:re.code==="git-error"?`${Ue}
|
|
94
|
-
${re.error}`:Ue}),ae()}}catch(re){if(T.current!==P)return;Z(String(re)),ze({type:"error",title:cn,description:String(re)})}finally{O.current=!1,_(!1)}},B=Fe=>{Fe.name===H?.currentBranch||Fe.occupied&&!Fe.worktreeConversationId||_t(Fe.name,!1,Fe.occupied?Fe.worktreeConversationId:void 0)},je=async Fe=>{if(pe)return;_(!0);const jt=n(Fe?"Failed to use worktree":"Failed to create conversation");try{if(Fe){const Ft=await d(e,Fe);Ft&&ze({type:"error",title:jt,description:Ft})}else await u(s.projectId,{worktreeFromConversationId:e})||ze({type:"error",title:jt})}catch(Ft){ze({type:"error",title:jt,description:String(Ft)})}finally{_(!1)}},Ye=async()=>{_(!0);try{const Fe=await r(e);Fe?ze({type:"error",title:n("Failed to clean up worktree"),description:Fe}):a()}catch(Fe){ze({type:"error",title:n("Failed to clean up worktree"),description:String(Fe)})}finally{_(!1)}},Tt=async(Fe=!1)=>{_(!0);try{const jt=await o(e,{allowDirtyMainTree:Fe});jt===k_?A(!0):jt?ze({type:"error",title:n("Failed to move to worktree"),description:jt}):a()}catch(jt){ze({type:"error",title:n("Failed to move to worktree"),description:String(jt)})}finally{_(!1)}},Wt=async()=>{_(!0);try{const Fe=await window.electronAPI.worktree.status(e);if(Fe.ok&&Nd(Fe.value)){S(Fe.value);return}await Ye()}catch(Fe){ze({type:"error",title:n("Failed to clean up worktree"),description:String(Fe)})}finally{_(!1)}},le=[{id:"local",selected:!te,icon:i.jsx(Cw,{className:"h-3.5 w-3.5 shrink-0"}),name:n("Local workspace"),hint:n("Work directly in the main working tree"),onSelect:()=>{te&&Wt()}},{id:"worktree",selected:te,icon:i.jsx(Ri,{className:"h-3.5 w-3.5 shrink-0"}),name:s.worktree?Yd(s.worktree):n("New isolated worktree"),hint:te?s.worktree?.branch:n("Run this session on its own git worktree"),onSelect:()=>{te||Tt()}}],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),Tt(!0)}}),Ot=()=>{const Fe=[];return N?.dirty&&Fe.push(n("Uncommitted changes")),N&&N.ahead>0&&Fe.push(n("{{n}} unmerged commits (branch is kept)",{n:N.ahead})),Fe.join("; ")};return i.jsxs(i.Fragment,{children:[i.jsxs(gi,{open:v,onOpenChange:Fe=>{C||(y(Fe),Fe&&(w(!1),ge(""),ae()))},children:[i.jsxs(xi,{ref:L,disabled:pe,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?`${Ut}
|
|
95
|
-
${cg(s.worktree,c[e],n)}`:Ut,children:[C?i.jsx(Yt,{className:"h-3 w-3 shrink-0 animate-spin"}):te?i.jsx(Ri,{className:"h-3 w-3 shrink-0"}):i.jsx(Cw,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:Ut}),i.jsx(Vn,{className:"h-3 w-3 shrink-0"})]}),i.jsx(vi,{side:"top",align:"start",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",initialFocus:X,finalFocus:J||f!==null?!1:L,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(cc,{className:"h-3.5 w-3.5 shrink-0"}),n("Local branches")]}),i.jsx(qte,{data:H,loading:q,error:me,disabled:pe||Te,query:Me,searchRef:V,onQueryChange:ge,onSelect:B,onRetry:()=>{ae(!0)},onCreate:()=>{Pt||!H?.headCommit||(Z(null),W(P),y(!1))}})]}):i.jsxs(i.Fragment,{children:[le.map(Fe=>i.jsxs("button",{ref:Fe.id==="local"?X:void 0,type:"button",disabled:pe,onClick:()=>{Fe.onSelect(),y(!1)},className:U("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",Fe.selected?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[Fe.icon,i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:Fe.name}),Fe.hint&&i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:Fe.hint})]}),Fe.selected&&i.jsx(Kn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},Fe.id)),$e&&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:Fe,worktree:jt})=>i.jsxs("button",{type:"button",disabled:pe,title:cg(jt,c[Fe],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),je(Fe)},children:[i.jsx(Ri,{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:Yd(jt)}),i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:jt.path})]})]},jt.path))})]}),s.worktree&&i.jsxs("div",{className:"mt-1 border-t pt-1",children:[i.jsxs("button",{type:"button",disabled:pe||Te,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),je()},children:[i.jsx(Go,{className:"h-3.5 w-3.5"}),n("New conversation in this worktree")]}),i.jsxs("button",{type:"button",disabled:pe||Te,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(Bs,{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:pe,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(Ri,{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:Fe=>{Fe||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:Ot()}),confirmLabel:n("Clean up"),onConfirm:()=>{S(null),Ye()}}),J&&i.jsx(Kte,{initialName:Me.trim(),data:H,busy:C,disabled:Pt,error:ue,returnFocus:L,onSubmit:Fe=>{_t(Fe,!0)},onClose:()=>W(null)},P),ht,i.jsx(NE,{entity:f,onClose:()=>g(null)})]})}function Qte(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 ene=e=>{Eh(e)&&Co()};function tne(){const{t:e}=se(),t=O5(),n=Ca(),s=ye(B=>B.virtualModels),o=ye(B=>B.agentTypes),r=ye(B=>B.defaultModel),a=ye(B=>B.projects),l=ye(B=>B.projectGroups),c=ye(B=>B.voiceInputEnabled),d=ye(B=>B.voiceModel),u=ye(B=>B.presets),{status:h}=qj(c),p=c&&h?.state!=="unsupported"&&h?.models.find(B=>B.id===d)?.state==="ready",f=m.useSyncExternalStore(B=>oe.persist?.onFinishHydration?.(B)??(()=>{}),()=>oe.persist?.hasHydrated?.()??!0),g=oe(Hf(RQ)),x=oe(B=>B.conversations[g?.parentId??""]?.coworkerIds),v=z5(g?.presetId,B=>u.find(je=>je.id===B)).pluginPresetId??null,y=PQ(g?.displayedParentId?g.agentType:void 0),b=yo(B=>B.snapshot),w=Xg(),C=oe(B=>GQ(B.conversations)),_=g?.parentId,N=g?.parentProjectId,S=m.useMemo(()=>_!==void 0&&N!==void 0?XX(C,N,_):[],[C,_,N]),k=m.useMemo(()=>a.find(B=>B.id===g?.projectId),[g?.projectId,a]),A=m.useMemo(()=>a.find(B=>B.id===g?.parentProjectId),[g?.parentProjectId,a]),I=m.useMemo(()=>eu(k,l),[k,l]),D=m.useMemo(()=>eu(A,l),[A,l]),P=m.useMemo(()=>tu({defaultModel:r,...I,lastProviderId:g?.lastProviderId,lastModelId:g?.lastModelId,providers:n,credentials:Ll(b),virtualModels:s}),[g?.lastModelId,g?.lastProviderId,I,r,b,n,s]),T=m.useMemo(()=>tu({defaultModel:r,...D,lastProviderId:g?.parentLastProviderId,lastModelId:g?.parentLastModelId,providers:n,credentials:Ll(b),virtualModels:s}),[r,b,g?.parentLastModelId,g?.parentLastProviderId,D,n,s]),z=T.source==="none"?null:{providerId:T.providerId,modelId:T.modelId},O=P.source==="none"?void 0:w.find(B=>B.id===P.providerId),L=P.source==="none"?"":P.modelId,V=P.source==="none"?"":Bf(P)?P.providerId:O?.id??"",X=oe(B=>Bf(P)&&g?.id?Qte(B.conversations[g.id]?.messages):void 0),F=oe(Hf(B=>Yg(n,g?.id?B.conversations[g.id]:void 0))),ee=P.source!=="none"?null:P.reason==="oauth-credentials-error"?e("Subscription credentials could not be loaded. Choose an API-key model or retry the credential refresh."):P.reason==="oauth-credentials-loading"||P.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."),H=a.find(B=>B.id===g?.projectId),Q=g?.id,[q,ne]=m.useState(),me=m.useCallback(B=>ne(Q&&B?{id:Q,branch:B}:void 0),[Q]),ke=g?.parentWorktreeBranch??(q?.id===g?.parentId?q?.branch:void 0),Me=ye(B=>B.skills),ge=ye(B=>B.loadLocalSkills),$=ye(B=>G5(B.disabledBuiltinTools,B.projects,g?.projectId,"plan")),[W,ue]=m.useState([]),Z=ge?H?.path??"":"",J=g?.presetId;m.useEffect(()=>{let B=!1;return window.electronAPI.assets.listProjectSkills(Z,J).then(je=>{B||ue(je)}).catch(()=>{B||ue([])}),()=>{B=!0}},[Z,J]);const ae=g?.commands,te=F5(),pe=m.useMemo(()=>{if(!ae)return[];const B={name:"/goal",description:e("Set a session goal (/goal <objective> · pause · resume · clear)")},je={name:"/compact",description:e("Compact the context now (/compact [summary focus])")},Ye={name:"/plan",description:e("Plan mode: research read-only, then approve a plan (/plan [task] · off)")},Tt=Me.filter(le=>le.enabled!==!1).map(le=>({name:`/skill:${le.name}`,description:le.description})),Wt=W.map(le=>({name:`/skill:${le.name}`,description:le.description}));return XD([B,je,...$?[Ye]:[],...Tt,...Wt,...ae,...te])},[e,Me,W,ae,te,$]),Te=m.useRef(null),$e=!g?.displayedParentId&&["planning","awaiting_review"].includes(p_(g?.planState)),Ie=g?.status==="running",Ze=g?.busy===!0,Nt=g?.parentWorktreePath??H?.path,Ut=m.useCallback(()=>{g&&!g.parentStarted&&g.parentSessionFile&&!g.parentWorktreeMissing&&g.parentStatus!=="failed"&&oe.getState().resumeConversation(g.parentId)},[g]);m.useEffect(()=>{const B=g?.compactionError;!B||!g||(ze({type:"error",title:e("Compaction failed"),description:B}),oe.getState().clearCompactionError(g.id))},[g,e]);const Pt=AQ(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(h_,{"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 _t=i.jsx(nne,{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(Ute,{conversationId:g.parentId}),i.jsx(Uee,{parentId:g.parentId,displayedId:g.id,trailing:i.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-1",children:[i.jsx(nee,{parentId:g.parentId,coworkerIds:x??[]}),H?i.jsx(Wte,{project:H,conversationId:g.parentId,path:g.parentWorktreePath??H.path,branch:ke,openDisabled:g.parentWorktreeMissing,children:_t}):i.jsx("div",{className:"flex min-w-0 shrink-0 items-center",children:_t})]})}),i.jsx(oE,{conversationId:g.id,cwd:Nt,emptyTitle:H?.name??"EnsoCode",onSuggestion:H?ene:void 0,timelineRef:Te}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:ji,children:[H&&H.kind!=="ssh"&&H.kind!=="scratch"&&!g.displayedParentId&&i.jsx(ite,{projectId:H.id,conversationId:g.id}),g.retry&&i.jsx(Fh,{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(Yt,{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(qu.Provider,{value:{conversationId:g.id,projectId:g.projectId,...Nt?{cwd:Nt}:{}},children:i.jsx(Lv,{sessionId:g.id,tasks:g.backgroundTasks??[],subagents:g.subagents??[]},g.id)}),i.jsx(jh,{approvals:g.pendingApprovals??[],allowSession:g.childLockedProfileId===void 0,onRespond:(B,je)=>{window.electronAPI.agent.respondApproval(g.id,B,je)}}),i.jsx(VQ,{}),i.jsx(_h,{asks:g.pendingAsks??[],onAnswer:(B,je)=>{window.electronAPI.agent.respondAsk(g.id,B,je)}}),!g.displayedParentId&&i.jsx(Zee,{conversationId:g.id,planState:g.planState,approvalMode:g.approvalMode??"full"}),i.jsx(xE,{conversationId:g.id,queued:g.queuedMessages??[]}),g.goal&&i.jsx(Xee,{conversationId:g.id,goal:g.goal}),i.jsx(cq,{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(Mv,{cwd:H?.path,chatCandidates:S,commands:pe,running:Ie,busy:Ze,locked:(g.pendingApprovals??[]).length>0||!!(g.rewinding||g.restoringFiles),focusKey:g.id,pluginPresetId:v,planMode:$e,savePastedText:H?.kind==="ssh"?void 0:B=>window.electronAPI.files.savePastedText({conversationId:g.id,text:B}),voice:p?zD:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,placeholder:$e?e("Describe the task — a plan comes first"):void 0,injectedDraft:g.draftText,injectedImages:g.draftImages,injectedDraftAppend:g.draftAppend,onDraftConsumed:()=>oe.getState().clearDraft(g.id),queuedCount:g.queuedMessages?.length??0,onSteerQueued:()=>oe.getState().steerQueued(g.id),toolbar:i.jsxs(i.Fragment,{children:[!g.displayedParentId&&i.jsxs(i.Fragment,{children:[i.jsx(nte,{presetId:g.presetId??"default",disabled:g.started,onSelect:B=>oe.getState().setPreset(g.id,B),onModel:B=>oe.getState().setModel(g.id,B.providerId,B.modelId)}),i.jsx(Zte,{conversationId:g.id,onBranchChange:me}),($||g.planState?.active)&&i.jsx(tte,{active:g.planState?.active??!1,onToggle:B=>oe.getState().setPlanMode(g.id,B)}),i.jsx(H5,{mode:g.approvalMode??"full",autoReject:g.autoRejectApprovals===!0,onSelect:B=>oe.getState().setApprovalMode(g.id,B),onToggleAutoReject:B=>oe.getState().setAutoRejectApprovals(g.id,B)}),i.jsx(ch,{listenHotkey:!0,refreshAllModels:!0,providers:w,virtualModels:s,routedModelLabel:X,activeAccount:F,providerId:V,modelId:L,reasoningEnabled:g.reasoningEnabled??!1,thinkingLevel:g.thinkingLevel??"medium",onSelect:(B,je)=>oe.getState().setModel(g.id,B,je),onReasoningChange:B=>oe.getState().setReasoning(g.id,B),onThinkingChange:B=>oe.getState().setThinking(g.id,B)})]}),g.displayedParentId&&i.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[y??(g.agentType?d_(g.agentType,o):"coworker"),g.lastModelId?` · ${Ff(s,g.lastModelId)}`:""]})]}),onActivate:Ut,onSend:B=>!B.recipient&&!H||!B.recipient&&!g.displayedParentId&&(!V||!L)?!1:(qee(B,{dispatchAgent:(je,Ye)=>{oe.getState().dispatchAgent(je,Ye,z)},sendCoding:(je,Ye)=>{H&&(Te.current?.scrollToBottom(),oe.getState().send(je,{providerId:V,modelId:L,cwd:H.path},Ye))}}),!0),onAbort:()=>{oe.getState().abort()}}),i.jsx(jE,{conversationId:g.id,cwd:Nt})]})})]})}function nne({status:e,pendingAskCount:t=0,hasRunningChild:n=!1}){const s=Jg({status:e,pendingAskCount:t,hasRunningChild:n});return i.jsx(Bh,{tone:s,title:e})}function TE(e,t,n){const s=e.slice();return s.splice(n<0?s.length+n:n,0,s.splice(t,1)[0]),s}function sne(e,t){return e.reduce((n,s,o)=>{const r=t.get(s);return r&&(n[o]=r),n},Array(e.length))}function rd(e){return e!==null&&e>=0}function ine(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 one(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const ad={scaleX:1,scaleY:1},rne=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 c=ane(n,a,o);if(a===o){const d=n[r];return d?{x:o<r?d.left+d.width-(l.left+l.width):d.left-l.left,y:0,...ad}:null}return a>o&&a<=r?{x:-l.width-c,y:0,...ad}:a<o&&a>=r?{x:l.width+c,y:0,...ad}:{x:0,y:0,...ad}};function ane(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 DE=e=>{let{rects:t,activeIndex:n,overIndex:s,index:o}=e;const r=TE(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}},ld={scaleX:1,scaleY:1},vC=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 d=r[a];return d?{x:0,y:n<a?d.top+d.height-(l.top+l.height):d.top-l.top,...ld}:null}const c=lne(r,o,n);return o>n&&o<=a?{x:0,y:-l.height-c,...ld}:o<n&&o>=a?{x:0,y:l.height+c,...ld}:{x:0,y:0,...ld}};function lne(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 IE="Sortable",EE=Ne.createContext({activeIndex:-1,containerId:IE,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:DE,disabled:{draggable:!1,droppable:!1}});function dg(e){let{children:t,id:n,items:s,strategy:o=DE,disabled:r=!1}=e;const{active:a,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=xc(),h=mc(IE,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=d?f.indexOf(d.id):-1,y=m.useRef(f),b=!ine(f,y.current),w=v!==-1&&x===-1||b,C=one(r);bi(()=>{b&&g&&u(f)},[b,f,g,u]),m.useEffect(()=>{y.current=f},[f]);const _=m.useMemo(()=>({activeIndex:x,containerId:h,disabled:C,disableTransforms:w,items:f,overIndex:v,useDragOverlay:p,sortedRects:sne(f,c),strategy:o}),[x,h,C.draggable,C.droppable,w,f,v,c,p,o]);return Ne.createElement(EE.Provider,{value:_},t)}const cne=e=>{let{id:t,items:n,activeIndex:s,overIndex:o}=e;return TE(n,s,o).indexOf(t)},dne=e=>{let{containerId:t,isSorting:n,wasDragging:s,index:o,items:r,newIndex:a,previousItems:l,previousContainerId:c,transition:d}=e;return!d||!s||l!==r&&o===a?!1:n?!0:a!==o&&t===c},une={duration:200,easing:"ease"},PE="transform",hne=Gi.Transition.toString({property:PE,duration:0,easing:"linear"}),pne={roleDescription:"sortable"};function fne(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 c=o.current;if(c){const d=_a(s.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.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 Vh(e){let{animateLayoutChanges:t=dne,attributes:n,disabled:s,data:o,getNewIndex:r=cne,id:a,strategy:l,resizeObserverConfig:c,transition:d=une}=e;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:g,sortedRects:x,overIndex:v,useDragOverlay:y,strategy:b}=m.useContext(EE),w=mne(s,f),C=u.indexOf(a),_=m.useMemo(()=>({sortable:{containerId:h,index:C,items:u},...o}),[h,o,C,u]),N=m.useMemo(()=>u.slice(u.indexOf(a)),[u,a]),{rect:S,node:k,isOver:A,setNodeRef:I}=vc({id:a,data:_,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...c}}),{active:D,activatorEvent:P,activeNodeRect:T,attributes:z,setNodeRef:O,listeners:L,isDragging:V,over:X,setActivatorNodeRef:F,transform:ee}=lx({id:a,data:_,attributes:{...pne,...n},disabled:w.draggable}),H=Bz(I,O),Q=!!D,q=Q&&!g&&rd(p)&&rd(v),ne=!y&&V,me=ne&&q?ee:null,Me=q?me??(l??b)({rects:x,activeNodeRect:T,activeIndex:p,overIndex:v,index:C}):null,ge=rd(p)&&rd(v)?r({id:a,items:u,activeIndex:p,overIndex:v}):C,$=D?.id,W=m.useRef({activeId:$,items:u,newIndex:ge,containerId:h}),ue=u!==W.current.items,Z=t({active:D,containerId:h,isDragging:V,isSorting:Q,id:a,index:C,items:u,newIndex:W.current.newIndex,previousItems:W.current.items,previousContainerId:W.current.containerId,transition:d,wasDragging:W.current.activeId!=null}),J=fne({disabled:!Z,index:C,node:k,rect:S});return m.useEffect(()=>{Q&&W.current.newIndex!==ge&&(W.current.newIndex=ge),h!==W.current.containerId&&(W.current.containerId=h),u!==W.current.items&&(W.current.items=u)},[Q,ge,h,u]),m.useEffect(()=>{if($===W.current.activeId)return;if($!=null&&W.current.activeId==null){W.current.activeId=$;return}const te=setTimeout(()=>{W.current.activeId=$},50);return()=>clearTimeout(te)},[$]),{active:D,activeIndex:p,attributes:z,data:_,rect:S,index:C,newIndex:ge,items:u,isOver:A,isSorting:Q,isDragging:V,listeners:L,node:k,overIndex:v,over:X,setNodeRef:H,setActivatorNodeRef:F,setDroppableNodeRef:I,setDraggableNodeRef:O,transform:J??Me,transition:ae()};function ae(){if(J||ue&&W.current.newIndex===C)return hne;if(!(ne&&!ph(P)||!d)&&(Q||Z))return Gi.Transition.toString({...d,property:PE})}}function mne(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 bC=["idle","running","waiting","error"];function AE(e,t){return e?Gv({...e,hasRunningChild:Ug({...e,status:e.status??"idle"},t)}):"idle"}function Gv(e){const t=Jg({status:e.status??"idle",spawning:e.spawning,pendingAskCount:(e.pendingAsks?.length??0)+(e.pendingApprovals?.length??0),hasRunningChild:e.hasRunningChild});return t==="failed"?"error":t==="unread"?"idle":t}function gne(e){let t=0;for(const n of Object.values(e))!n||n.parentId||n.btwParentId||(t=Math.max(t,bC.indexOf(AE(n,e))));return bC[t]}const xne=e=>e==="/"?null:e.replace(/\/[^/]+$/,"")||"/";function vne(e,t){const n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}function ug({list:e,create:t,initialPath:n,reloadKey:s=0,onSelect:o,onClose:r}){const{t:a}=se(),[l,c]=m.useState(null),[d,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 C=m.useCallback((I,D=!1)=>{const P=++y.current;u(!0),p(""),w.current(I,D).then(T=>{if(!(P!==y.current||!T)){if("error"in T){p(T.error);return}c(T),b.current=T.path}}).catch(()=>{P===y.current&&p(a("Failed to list remote directory."))}).finally(()=>{P===y.current&&u(!1)})},[a]),_=m.useRef(n);m.useEffect(()=>{C(_.current)},[C]),m.useEffect(()=>{s&&C(b.current??_.current,!0)},[s,C]);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(D=>{if(I===y.current){if("error"in D){v(a(D.error));return}g(null),p(""),c(D),b.current=D.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(xe,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!k||d,onClick:()=>k&&C(k),children:a("Up")}),t&&i.jsx(xe,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!N||d||f!==null,onClick:()=>{g(""),v("")},children:a("New Folder")}),i.jsx(xe,{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:d,onChange:I=>g(I.target.value),onKeyDown:I=>{if(I.key==="Enter"){if(I.nativeEvent.isComposing)return;I.preventDefault(),A()}else I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),g(null))}}),i.jsx(xe,{type:"button",size:"sm",className:"h-7 px-2 text-xs",disabled:d||!f.trim(),onClick:A,children:a("Create")}),i.jsx(xe,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",disabled:d,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&&!d?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:a("No subdirectories")}):i.jsx("div",{className:d?"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:d,onClick:()=>N&&C(vne(N,I)),children:[I,"/"]},I))}),d&&i.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60",children:[i.jsx(Yt,{className:"h-4 w-4 animate-spin text-muted-foreground"}),i.jsx("span",{className:"sr-only",children:a("Loading...")})]})]}),i.jsx(xe,{type:"button",variant:"outline",size:"sm",className:"h-7 w-full text-xs",disabled:!N||d,onClick:()=>N&&o(N),children:a("Use this directory")})]})}function bne({open:e,onOpenChange:t,onAdd:n,groups:s=[],defaultGroupId:o}){const{t:r}=se(),a=ye(J=>J.projects),[l,c]=m.useState("local"),[d,u]=m.useState(""),[h,p]=m.useState(""),[f,g]=m.useState(""),[x,v]=m.useState([]),[y,b]=m.useState(o),[w,C]=m.useState(!1),[_,N]=m.useState([]),[S,k]=m.useState(""),[A,I]=m.useState(null),[D,P]=m.useState(null),[T,z]=m.useState(0),[O,L]=m.useState(!1),[V,X]=m.useState(!1),F=m.useRef(0),ee=m.useMemo(()=>[{value:"",label:r("Ungrouped")},...s.map(J=>({value:J.id,label:J.name}))],[s,r]);m.useEffect(()=>{F.current+=1,X(!1),e&&(c("local"),u(""),p(""),g(""),b(o),C(!1),k(""),I(null),P(null),z(0),window.electronAPI.sshConnections.list().then(v).catch(()=>v([])),window.electronAPI.projects.getRecent().then(N).catch(()=>N([])))},[e,o]);const H=m.useMemo(()=>new Set(a.map(J=>J.path)),[a]),Q=m.useMemo(()=>_.filter(J=>!H.has(J.path)),[_,H]),q=m.useCallback((J,ae)=>{if(!ae)return!0;const te=ae.toLowerCase();return J.path.toLowerCase().includes(te)||J.displayPath.toLowerCase().includes(te)||J.sourceName.toLowerCase().includes(te)},[]),ne=!!window.electronAPI.remote,me=async()=>{if(ne){C(ae=>!ae);return}const J=await window.electronAPI.dialog.selectDirectory();J&&u(J)},ke=m.useCallback(J=>window.electronAPI.projects.listHostDirs(J).then(ae=>ae.ok?ae:{error:ae.error}),[]),Me=m.useCallback((J,ae)=>window.electronAPI.projects.createHostDir(J,ae).then(te=>te.ok?te:{error:te.error}),[]),ge=m.useCallback(async(J,ae)=>{const te=await window.electronAPI.sshConnections.listDirs(h,J);if(te.ok)return{path:te.path,parent:xne(te.path),dirs:te.dirs};const pe=L0(te,x.find(Te=>Te.id===h));return!pe||ae?{error:te.error}:(P("browse"),I(pe),null)},[h,x]),$=l==="local"?d.trim().length>0:h.length>0&&f.trim().startsWith("/"),W=()=>{const J=x.find(ae=>ae.id===h);n({path:f.trim(),sshConnectionId:h,sshHost:J?.name,...y?{groupId:y}:{}}),t(!1)},ue=J=>{if(J.preventDefault(),!$)return;if(l!=="ssh"){n({path:d.trim(),...y?{groupId:y}:{}}),t(!1);return}if(V)return;X(!0),k("");const ae=++F.current,te=x.find(pe=>pe.id===h);window.electronAPI.sshConnections.test(h).then(pe=>{if(ae===F.current){if(!pe.ok){const Te=L0(pe,te);if(Te){P("submit"),I(Te);return}k(pe.error);return}W()}}).finally(()=>{ae===F.current&&X(!1)})},Z=async()=>{if(!A)return;L(!0);const J=await window.electronAPI.sshConnections.trustHost(h);if(L(!1),!J.ok){k(J.error||r("Could not save host key.")),I(null),P(null);return}const ae=D;if(I(null),P(null),ae==="browse"){z(te=>te+1);return}ae==="submit"&&W()};return i.jsxs(vn,{open:e,onOpenChange:t,children:[i.jsx(bn,{className:"max-w-lg",children:i.jsxs("form",{onSubmit:ue,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(eh,{value:l,onValueChange:J=>{c(J),C(!1)},children:i.jsxs(th,{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(J=>({value:J.id,label:`${J.name} (${J.user?`${J.user}@`:""}${J.host})`}))],value:h,onValueChange:J=>p(J??""),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsxs(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:[i.jsx(os,{value:"",children:r("Select an SSH connection")}),x.map(J=>i.jsxs(os,{value:J.id,children:[J.name," (",J.user?`${J.user}@`:"",J.host,")"]},J.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:J=>g(J.target.value),placeholder:"/home/user/project",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,className:"min-w-0 flex-1"}),i.jsx(xe,{type:"button",variant:"outline",disabled:!h,onClick:()=>C(J=>!J),children:r("Browse")})]})]}),w&&h&&i.jsx(ug,{list:ge,initialPath:f.trim().startsWith("/")?f.trim():void 0,reloadKey:T,onSelect:J=>{g(J),C(!1)},onClose:()=>C(!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(_v,{value:d,onValueChange:J=>u(J??""),items:Q,filter:q,itemToStringValue:J=>J.path,children:[i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(Nv,{placeholder:r("Type a path or select from recent projects..."),showClear:!!d,showTrigger:!0})}),i.jsx(xe,{type:"button",variant:"outline",onClick:()=>{me()},children:r("Browse")})]}),i.jsxs(UI,{zIndex:Cn.DROPDOWN_IN_MODAL,children:[i.jsx(Dv,{children:r("No matching projects found")}),i.jsx(Iv,{children:J=>i.jsxs(Tv,{value:J,className:"gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",title:J.path,children:J.displayPath}),i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:J.sourceName})]},J.path)})]})]}),w&&ne&&i.jsx(ug,{list:ke,create:Me,initialPath:d.trim()||void 0,onSelect:J=>{u(J),C(!1)},onClose:()=>C(!1)})]}),s.length>0&&i.jsxs(Os,{children:[i.jsx(zs,{children:r("Project group")}),i.jsxs(vs,{items:ee,value:y??"",onValueChange:J=>b(J||void 0),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:ee.map(J=>i.jsx(os,{value:J.value,children:J.label},J.value||"ungrouped"))})]})]})]}),i.jsxs(rs,{children:[i.jsx(xe,{type:"button",variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(xe,{type:"submit",size:"sm",disabled:!$||V,children:r("Add")})]})]})}),i.jsx(B5,{challenge:A,nested:!0,busy:O,onTrust:()=>{Z()},onDismiss:()=>{O||(I(null),P(null))}})]})}function wne(e,t){return{x:e.left-t,width:Math.max(0,e.width)}}const ME="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",RE="flex size-4.5 shrink-0 items-center justify-center rounded-[5px] text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",yne=24,Wa=20;function Sne({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,query:a,onQueryChange:l,searchOpen:c,onSearchOpenChange:d,onSelect:u,onAddGroup:h,onEditGroup:p}){const{t:f}=se(),g=e.slice().sort((X,F)=>X.order-F.order),x=g.length>0,v=c||a.length>0,y=m.useRef(null),b=m.useRef(null),w=m.useRef(null),C=m.useRef(null),_=m.useRef(null),[N,S]=m.useState({left:!1,right:!1,overflow:!1}),{active:k}=xc(),A=g.find(X=>X.id===t),I=t===hs?f("Ungrouped"):A?.name??null,D=I?f("Search in {{group}}...",{group:I}):f("Search conversations..."),P=m.useCallback(()=>{const X=w.current,F=b.current,ee=C.current,H=_.current,Q=F?.querySelector("[data-selected]");if(!X||!F||!ee||!H||!Q||X.offsetParent===null){H&&(H.style.width="0px");return}const q=F.getBoundingClientRect(),ne=X.getBoundingClientRect(),me=Q.getBoundingClientRect(),ke=wne(me,q.left);ee.style.left=`${q.left-ne.left}px`,ee.style.width=`${q.width}px`,H.style.transform=`translateX(${ke.x}px)`,H.style.width=`${ke.width}px`},[]),T=m.useCallback(()=>{const X=b.current;P(),!(!X||X.clientWidth===0)&&S(F=>{const ee=F.overflow?yne:0,H={left:X.scrollLeft>1,right:X.scrollLeft+X.clientWidth<X.scrollWidth-1,overflow:X.scrollWidth>X.clientWidth+ee+1};return F.left===H.left&&F.right===H.right&&F.overflow===H.overflow?F:H})},[P]);m.useLayoutEffect(()=>{const X=b.current;if(!X)return;T();const F=new ResizeObserver(T);return F.observe(X),X.firstElementChild&&F.observe(X.firstElementChild),()=>F.disconnect()},[T]),m.useLayoutEffect(()=>{P()},[P,k,t,v,g.length]),m.useEffect(()=>{const X=b.current;if(!X)return;const F=ee=>{Math.abs(ee.deltaY)<=Math.abs(ee.deltaX)||X.scrollWidth<=X.clientWidth||(X.scrollLeft+=ee.deltaY,ee.preventDefault())};return X.addEventListener("wheel",F,{passive:!1}),()=>X.removeEventListener("wheel",F)},[]);const z=m.useRef(!1);m.useLayoutEffect(()=>{const X=b.current,F=X?.querySelector("[data-selected]");if(!X||!F||X.clientWidth===0)return;const ee=z.current?"smooth":"auto";z.current=!0;const H=F.offsetLeft,Q=H+F.offsetWidth;H<X.scrollLeft+Wa?X.scrollTo({left:H-Wa,behavior:ee}):Q>X.scrollLeft+X.clientWidth-Wa&&X.scrollTo({left:Q-X.clientWidth+Wa,behavior:ee})},[t,x,c]),m.useEffect(()=>{c&&y.current?.focus()},[c]);const O=()=>{l(""),d(!1)},L=X=>X?`${Wa}px`:"0px",V=N.left||N.right?`linear-gradient(to right, transparent, #000 ${L(N.left)}, #000 calc(100% - ${L(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(KN,{className:"size-3.5 shrink-0"}),i.jsx("input",{ref:y,value:a,onChange:X=>l(X.target.value),onKeyDown:X=>{X.key==="Escape"&&(X.stopPropagation(),O())},onBlur:()=>{!a&&document.hasFocus()&&d(!1)},placeholder:D,className:"h-full min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground"}),i.jsx("button",{type:"button",onClick:O,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:U("relative flex min-w-0 flex-1 items-center gap-1.5",v&&"hidden"),children:[i.jsx("div",{ref:b,onScroll:T,style:{maskImage:V},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:Gu(t===In,!1),children:i.jsx(Fu,{label:f("All"),count:s})}),i.jsx("button",{type:"button","data-enso":"group-chip","data-selected":t===Mo||void 0,"data-active":t===Mo||void 0,onClick:()=>u(Mo),className:Gu(t===Mo,!1),children:i.jsx(Fu,{label:f("Recent"),count:o})}),i.jsx(dg,{items:g.map(X=>Av(X.id)),strategy:rne,children:g.map(X=>i.jsx(Cne,{group:X,count:n[X.id]??0,selected:t===X.id,onSelect:()=>u(X.id)},X.id))}),x&&i.jsx(kne,{label:f("Ungrouped"),count:r,selected:t===hs,onSelect:()=>u(hs)})]})}),i.jsx("span",{ref:C,"aria-hidden":!0,className:"pointer-events-none absolute -bottom-px z-10 h-[1.5px] overflow-hidden",children:i.jsx("span",{ref:_,className:"absolute top-0 left-0 h-full rounded-full bg-foreground"})}),i.jsx("button",{type:"button",onClick:h,className:U(RE,"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(jne,{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 Gu(e,t){return U("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 Fu({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 LE=e=>e?.type==="project";function Cne({group:e,count:t,selected:n,onSelect:s}){const{attributes:o,listeners:r,setNodeRef:a,transform:l,transition:c,isDragging:d,isOver:u,active:h}=Vh({id:Av(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:c},className:U(Gu(n,u&&LE(h?.data.current)),d&&"z-10 cursor-grabbing text-foreground"),...o,...r,children:i.jsx(Fu,{label:e.name,count:t,emoji:e.emoji,color:e.color})})}function kne({label:e,count:t,selected:n,onSelect:s}){const{active:o}=xc(),{setNodeRef:r,isOver:a}=vc({id:Av(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:Gu(n,a&&LE(o?.data.current)),children:i.jsx(Fu,{label:e,count:t})})}function jne({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,onSelect:a,onAddGroup:l,onEditGroup:c}){const{t:d}=se(),[u,h]=m.useState(!1),p=f=>()=>{h(!1),f()};return i.jsxs(gi,{open:u,onOpenChange:h,children:[i.jsx(xi,{className:U(RE,"ml-auto data-popup-open:bg-foreground/5 data-popup-open:text-foreground"),title:d("All groups"),"aria-label":d("All groups"),children:i.jsx(Vn,{className:"size-3"})}),i.jsxs(vi,{side:"bottom",align:"end",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsx(cd,{label:d("All"),count:s,selected:t===In,onSelect:p(()=>a(In))}),i.jsx(cd,{label:d("Recent"),count:o,selected:t===Mo,onSelect:p(()=>a(Mo))}),e.map(f=>i.jsx(cd,{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(()=>c(f.id))},f.id)),e.length>0&&i.jsx(cd,{label:d("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:U(ME,"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:d("New group")})]})]})]})}function cd({label:e,count:t,emoji:n,color:s,selected:o,onSelect:r,onEdit:a}){const{t:l}=se();return i.jsxs("div",{className:"group/row relative",children:[i.jsxs("button",{type:"button",onClick:r,className:U(ME,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:U("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(Bs,{className:"size-3.5"})})]})}function OE({value:e,reasoningEnabled:t,thinkingLevel:n,onChange:s,onReasoningChange:o,onThinkingChange:r,description:a,inheritLabel:l}){const{t:c}=se(),d=ye(g=>g.virtualModels),u=Xg(),h=e?u.find(g=>g.id===e.providerId):void 0,p=h?.models.find(g=>g.id===e?.modelId),f=Qj(d,e);return i.jsxs(Os,{className:"w-full items-stretch",children:[i.jsx(zs,{children:c("Default model")}),i.jsx(j_,{children:a}),u.length>0&&i.jsx("div",{className:"w-full min-w-0",children:i.jsx(ch,{providers:u,virtualModels:d,providerId:f?e?.providerId??"":h?.id??"",modelId:f?f.id:p?.id??"",reasoningEnabled:t,thinkingLevel:n,emptyLabel:l,side:"bottom",triggerClassName:V5,zIndex:Cn.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:c("Selected model is unavailable — falls back to the default model.")}),e&&i.jsx(xe,{type:"button",variant:"ghost",size:"sm",className:"self-start",onClick:()=>s(null),children:c("Follow default model")})]})}const _ne=["#3b82f6","#22c55e","#eab308","#f97316","#ef4444","#a855f7","#06b6d4","#64748b"];function Nne({open:e,group:t,projects:n,onOpenChange:s,onSave:o,onDelete:r}){const{t:a}=se(),l=ye(P=>P.defaultReasoningEnabled),c=ye(P=>P.defaultThinkingLevel),[d,u]=m.useState(""),[h,p]=m.useState(),[f,g]=m.useState(null),[x,v]=m.useState(!0),[y,b]=m.useState("medium"),[w,C]=m.useState(new Set),[_,N]=m.useState(""),S=t===null,k=S?n??[]:[],A=_.trim().toLowerCase(),I=A?k.filter(P=>P.name.toLowerCase().includes(A)):k;m.useEffect(()=>{if(!e)return;u(t?.name??""),p(t?.color),g(t?.defaultModel??null);const P=nu({defaultReasoningEnabled:l,defaultThinkingLevel:c});v(t?.defaultReasoningEnabled??P.reasoningEnabled),b(t?.defaultThinkingLevel??P.thinkingLevel),C(new Set),N("")},[e,t,l,c]);const D=P=>{C(T=>{const z=new Set(T);return z.has(P)?z.delete(P):z.add(P),z})};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:P=>{P.preventDefault();const T=d.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:d,onChange:P=>u(P.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"})}),_ne.map(P=>i.jsx("button",{type:"button",className:"h-6 w-6 rounded-full border border-border",style:{backgroundColor:P,outline:h===P?"2px solid var(--color-ring)":void 0,outlineOffset:2},onClick:()=>p(h===P?void 0:P),"aria-label":P},P))]}),i.jsx(OE,{value:f,reasoningEnabled:x,thinkingLevel:y,onChange:P=>{if(g(P),P)return;const T=nu({defaultReasoningEnabled:l,defaultThinkingLevel:c});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:_,onChange:P=>N(P.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(P=>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(hc,{checked:w.has(P.id),onCheckedChange:()=>D(P.id)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:P.name})]},P.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(xe,{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(xe,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),children:a("Cancel")}),i.jsx(xe,{type:"submit",size:"sm",disabled:!d.trim(),children:a("Save")})]})]})]})})})}function Tne({project:e,onClose:t}){const{t:n}=se(),[s,o]=m.useState(null),[r,a]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1);m.useEffect(()=>{if(!e)return;let p=!0;return o(null),a(null),c(null),window.electronAPI.sessionImport.scan(e.path).then(f=>{p&&o(f)}).catch(()=>{p&&o([])}),()=>{p=!1}},[e]),m.useEffect(()=>{if(!r){c(null);return}let p=!0;return c(null),window.electronAPI.sessionImport.read(r.sourceId,r.path).then(f=>{p&&c(f)}).catch(()=>{p&&c([])}),()=>{p=!1}},[r]);const h=async()=>{if(!(!e||!r)){u(!0);try{const p=await window.electronAPI.sessionImport.import(r.sourceId,r.path,e.path);p&&(oe.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(gr,{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:U("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(gr,{className:"size-4"})}):i.jsx("div",{className:"flex flex-col gap-2.5",children:l.map((p,f)=>i.jsx("div",{className:U("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(xe,{variant:"outline",onClick:t,children:n("Cancel")}),i.jsxs(xe,{onClick:()=>{h()},disabled:!r||d,children:[d?i.jsx(gr,{className:"mr-1.5 size-3.5"}):i.jsx(oc,{className:"mr-1.5 h-3.5 w-3.5"}),n("Import")]})]})]})})}function Dne({open:e,project:t,onOpenChange:n}){const{t:s}=se(),o=ye(H=>H.projectGroups),r=ye(H=>H.defaultReasoningEnabled),a=ye(H=>H.defaultThinkingLevel),l=ye(H=>H.setProjectDefaultModel),c=ye(H=>H.setProjectGroupId),d=ye(H=>H.setProjectAlias),u=ye(H=>H.setProjectDisabledBuiltinTools),h=ye(H=>H.setProjectSubagentAllowedModes),p=ye(H=>H.setProjectTrustedCode),f=ye(H=>H.disabledBuiltinTools),g=ye(H=>H.subagentAllowedModes),[x,v]=m.useState(""),[y,b]=m.useState(null),[w,C]=m.useState(!0),[_,N]=m.useState("medium"),[S,k]=m.useState(""),[A,I]=m.useState(!0),[D,P]=m.useState([]),[T,z]=m.useState(!0),[O,L]=m.useState([]),[V,X]=m.useState(!1);m.useEffect(()=>{if(!e)return;X(!1),b(t?.defaultModel??null),k(t?.groupId??""),v(t?.alias??"");const H=t?.groupId?o.find(me=>me.id===t.groupId):void 0,Q=nu({groupReasoningEnabled:H?.defaultReasoningEnabled,groupThinkingLevel:H?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});C(t?.defaultReasoningEnabled??Q.reasoningEnabled),N(t?.defaultThinkingLevel??Q.thinkingLevel);const q=t?.disabledBuiltinTools===void 0;I(q),P(q?[...f]:[...t?.disabledBuiltinTools??[]]);const ne=t?.subagentAllowedModes===void 0;z(ne),L(ne?[...g]:[...t?.subagentAllowedModes??[]])},[e,t,o,r,a,f,g]);const F=m.useMemo(()=>[{value:"",label:s("Ungrouped")},...o.slice().sort((H,Q)=>H.order-Q.order).map(H=>({value:H.id,label:H.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:H=>{H.preventDefault(),t&&(l(t.id,y,y?{reasoningEnabled:w,thinkingLevel:_}:null),c(t.id,S||null),d(t.id,x),u(t.id,A?null:D),h(t.id,T?null:O),V&&p(t.id,null),n(!1))},children:[i.jsxs(wn,{children:[i.jsx(yn,{children:s("Project settings")}),i.jsx(As,{children:t?Lo(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:H=>v(H.target.value),placeholder:t?Lo({...t,alias:void 0}):""}),i.jsx(j_,{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(Yk,{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:F,value:S,onValueChange:H=>k(H??""),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:F.map(H=>i.jsx(os,{value:H.value,children:H.label},H.value||"ungrouped"))})]})]}),i.jsx(OE,{value:y,reasoningEnabled:w,thinkingLevel:_,onChange:H=>{if(b(H),H)return;const Q=S?o.find(ne=>ne.id===S):void 0,q=nu({groupReasoningEnabled:Q?.defaultReasoningEnabled,groupThinkingLevel:Q?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});C(q.reasoningEnabled),N(q.thinkingLevel)},onReasoningChange:C,onThinkingChange:N,description:s("Used for new conversations in this project."),inheritLabel:s("Follows group, then global default")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("Session choice overrides the project default.")}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Follow global built-in tools")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("When off, configure built-in tools for this project. They override the global setting on the next session.")})]}),i.jsx(di,{checked:A,onCheckedChange:I})]}),!A&&i.jsx("div",{className:"space-y-2",children:$5.map(H=>i.jsxs("div",{className:"flex items-center gap-3 rounded-md border px-3 py-2.5",children:[i.jsx(Fg,{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(H.name)}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s(H.description)})]}),i.jsx(di,{checked:!D.includes(H.id),onCheckedChange:Q=>P(q=>Q?q.filter(ne=>ne!==H.id):[...new Set([...q,H.id])])})]},H.id))}),i.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Follow global unified agent modes")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("When off, this project uses its own explicit Agent mode permission mask.")})]}),i.jsx(di,{checked:T,onCheckedChange:H=>{z(H),H||L([...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(([H,Q])=>i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsx("span",{className:"text-sm",children:s(Q)}),i.jsx(di,{checked:O.includes(H),disabled:(A?f:D).includes("subagent"),onCheckedChange:q=>L(ne=>q?[...new Set([...ne,H])]:ne.filter(me=>me!==H))})]},H)),(A?f:D).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(oa,{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(", ")}),V&&i.jsx("p",{className:"text-muted-foreground text-xs",children:s("No longer loaded after saving, starting with the next session.")})]}),i.jsx(xe,{type:"button",size:"xs",variant:"outline",disabled:V,onClick:()=>X(!0),children:s("Revoke trust")})]}):null]}),i.jsxs(rs,{children:[i.jsx(xe,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsx(xe,{type:"submit",size:"sm",disabled:!t,children:s("Save")})]})]})})})}const Ine={connecting:"Connecting…","host-offline":"Desktop is offline",unauthorized:"Pairing expired",replaced:"Open in another page",offline:"Reconnecting…"};function Ene(e,t){if(e.state!=="online")return t(Ine[e.state]);const n=e.transport==="direct"?t("Direct link"):t("Via relay"),s=W5(e.rttMs);return s?`${t("Connected")} · ${n} · ${s}`:`${t("Connected")} · ${n}`}function Pne(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}function Ane(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 Mne(e){return e==="AbortError"?"service-unreachable":e==="NotAllowedError"?"permission-denied":"subscribe-failed"}async function Rne(e){if(!Pne())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:Ane(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:Mne(o)}}}const Lne="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 One(){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 zne(e,t){return e.pushError?t(zE[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 zE={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 wC(){const{t:e}=se(),t=One();if(!t)return null;const n=Ene(t,e),s=zne(t,e),o=t.pushBusy||t.pushAvailability!=="ok"||!t.pushReady||t.state!=="online"&&!t.pushEnabled;return i.jsxs(gi,{children:[i.jsx(xi,{className:Lne,title:n,"aria-label":n,children:i.jsx(rh,{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(U5,{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(di,{checked:t.pushEnabled,disabled:o,title:s,"aria-label":s,onCheckedChange:()=>{Gne(t)}})]}),t.pushError&&i.jsx("p",{className:"mt-2 text-destructive text-xs",children:e(zE[t.pushError])})]})]})}async function Gne(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 Rne(n);if(!s.ok){t.setPushPending({busy:!1,enabled:!1,error:s.reason});return}t.setPushSubscription(s.subscription)}const $h=5,GE=15,yC=9;function Wh(e,t){return e<=0?0:Math.min(e,$h+Math.max(0,t))}function Fne(e,t){return Wh(e,t)>=e?0:Math.min(Math.max(0,e-$h),t+GE)}function Hne(e){return Math.max(0,e-GE)}function Bne(e){const{order:t,conversations:n,pinnedOrderIds:s=[],projectIds:o,archivedProjectIds:r=[],collapsedProjects:a={},revealedExtras:l={},searching:c=!1,matches:d=()=>!0,projectMatches:u=()=>!1,leadingIds:h=[]}=e,p=[],f=new Set,g=v=>{f.has(v)||p.length>=yC||(f.add(v),p.push(v))};for(const v of h)g(v);const x=__(t,n,s,r);for(const v of c?x.filter(d):x)g(v);for(const v of o){if(p.length>=yC)break;if(c?!1:a[v]===!0)continue;const b=Xr(t,n,v),w=!c||u(v)?b:b.filter(d),C=c?w:w.slice(0,Wh(w.length,l[v]??0));for(const _ of C)g(_)}return p}function Fv(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 dd(e,t,n,s){const o=Fv(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 Vne(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 $ne(e,t){return e.includes(t)?e.filter(n=>n!==t):[t,...e]}function Wne(e,t,n){const s=n.includes(e),o=n.includes(t);return s&&o?"pinned":!s&&!o?"order":null}function uf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function SC(e){return e==="browser"||typeof e=="string"&&e.startsWith("browser:")}function Une(e){if(typeof e.contentComponent=="string")return e.contentComponent;if(typeof e.component=="string")return e.component}function CC(e){if(!uf(e)||!uf(e.panels))return{browsers:0,terminals:0};let t=0,n=0;for(const[s,o]of Object.entries(e.panels)){if(!uf(o))continue;const r=Une(o);r==="browser"||SC(o.id)||SC(s)?t+=1:r==="terminal"&&(n+=1)}return{browsers:t,terminals:n}}function Kne({conversationId:e}){const{t}=se(),n=fn(o=>CC(o.layouts[e]).browsers),s=fn(o=>CC(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(go,{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($o,{className:"h-3 w-3","aria-hidden":!0}),s]})]})}const qne=[7,15,30],kC="h-6.5 rounded-lg px-2 text-xs text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",jC="enso-collapsed-scratch",Ji="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",hf="-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 _C({width:e,collapsed:t,onToggleCollapse:n,onOpenSearch:s,onNavigate:o}){const{t:r,locale:a}=se(),l=ye(Y=>Y.projects),d=lh()==="mobile",u=ye(Y=>Y.scratchSessionsEnabled),h=ye(Y=>Y.projectGroups),p=ye(Y=>Y.createProjectGroup),f=ye(Y=>Y.updateProjectGroup),g=ye(Y=>Y.removeProjectGroup),x=ye(Y=>Y.reorderProjectGroups),v=ye(Y=>Y.setProjectGroupId),y=ye(Y=>Y.keybindings),b=ye(Y=>Y.activeRetentionMinutes),w=Oi(y)["search-workspace"],C=w?mi(w):"",_=ye(Y=>Y.addProject),N=ye(Y=>Y.removeProject),S=oe(Y=>Ev(Y.conversations)),k=oe(Y=>Y.order),A=oe(Y=>Y.activeId),I=oe(Y=>Y.newConversation),D=oe(Y=>Y.selectConversation),P=m.useRef(o);P.current=o;const T=m.useCallback(Y=>{P.current?.(),D(Y)},[D]),z=oe(Y=>Y.removeConversation),O=oe(Y=>Y.togglePinConversation),L=oe(Y=>Y.toggleArchiveConversation),V=oe(Y=>Y.moveConversationToWorktree),X=oe(Y=>Y.cleanupWorktree),F=oe(Y=>Y.refreshWorktreeStatuses),ee=oe(Y=>Y.worktreeStatuses),[H,Q]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-projects")??"{}")}catch{return{}}}),q=Y=>{Q(Se=>{const at={...Se,[Y]:!Se[Y]};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(at)),at})},[ne,me]=m.useState(()=>{try{return localStorage.getItem(jC)==="1"}catch{return!1}}),ke=Y=>{try{localStorage.setItem(jC,Y?"1":"0")}catch{}},Me=()=>{me(Y=>{const Se=!Y;return ke(Se),Se})},ge=()=>{me(Y=>Y&&(ke(!1),!1))},[$,W]=m.useState(()=>Ei(zd)),ue=Fv(l.filter(Y=>Y.kind!=="scratch"),$),Z=l.find(Y=>Y.kind==="scratch"),[J,ae]=m.useState(()=>Ei(ro));m.useEffect(()=>aW(()=>Q(km())),[]),m.useEffect(()=>sT(()=>{ae(Ei(ro))}),[]);const[te,pe]=m.useState(()=>Ei(Ew)),Te=Y=>{pe(Y),Io(Ew,Y)},$e=Y=>{if(Te($ne(te,Y)),!te.includes(Y)&&J.includes(Y)){const Se=J.filter(at=>at!==Y);ae(Se),Io(ro,Se)}},Ie=Y=>{const Se=J.includes(Y)?J.filter(at=>at!==Y):[...J,Y];ae(Se),Io(ro,Se),!J.includes(Y)&&te.includes(Y)&&Te(te.filter(at=>at!==Y))},[Ze,Nt]=m.useState(()=>{try{return localStorage.getItem("enso-selected-project-group")??In}catch{return In}}),[Ut,Pt]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-project-groups")??"{}")}catch{return{}}}),_t=Y=>{Nt(Y),localStorage.setItem("enso-selected-project-group",Y)},B=Y=>{Pt(Se=>{const at={...Se,[Y]:!Se[Y]};return localStorage.setItem("enso-collapsed-project-groups",JSON.stringify(at)),at})},je=Ze===In||Ze===Mo||Ze===hs||h.some(Y=>Y.id===Ze)?Ze:In,Ye=je===Mo,Tt=h.find(Y=>Y.id===je)?.id,Wt=Fr(ue,h,J,je),le=K5(Fr(ue,h,J,In),k,S,Date.now()),{pinned:ht,rest:Ot}=Ye?{pinned:[],rest:le}:Vne(Wt,te),Fe=N_(Ot,h,[]),jt=[...ht,...Ot],Ft=jt.map(Y=>Y.id),cn=new Set(Ft),[re,Ue]=m.useState(()=>Ei(ym)),{active:ut}=xc(),xt=ut?.data.current;z_({onDragEnd:Y=>{const Se=Y.active.data.current;if(!Se)return;const at=Y.over?String(Y.over.id):null,wt=Cee(Se,at,A??void 0,{projectGroupId:At=>l.find(ts=>ts.id===At)?.groupId});if(wt)switch(wt.kind){case"move-project-to-group":{if(Ye&&wt.beforeProjectId)break;if(v(wt.projectId,wt.groupId),wt.beforeProjectId){const At=dd(l,$,wt.projectId,wt.beforeProjectId);W(At),Io(zd,At)}break}case"reorder-groups":x(wt.activeId,wt.overId);break;case"reorder-projects":{if(Ye)break;const At=Wne(wt.activeId,wt.overId,te);if(At==="pinned"){const Jo=dd(te.map(jo=>({id:jo})),te,wt.activeId,wt.overId);Te(Jo);break}if(At!=="order")break;const ts=dd(l,$,wt.activeId,wt.overId);W(ts),Io(zd,ts);break}case"insert-file-mention":Zl({kind:"file",id:wt.path,label:wt.label,relativePath:wt.path});break;case"insert-chat-mention":Zl({kind:"chat",id:wt.conversationId,label:wt.label,sessionFile:wt.sessionFile});break;case"pin-conversation":O(wt.conversationId);break;case"reorder-pinned":{const At=dd(Et.map(ts=>({id:ts})),re,wt.activeId,wt.overId);Ue(At),Io(ym,At);break}}}});const[pt,K]=m.useState(null),[fe,De]=m.useState(null),[Pe,Ge]=m.useState(!1),[st,we]=m.useState(!1),[Qe,it]=m.useState(null),yt=Y=>{if(!Y.sshConnectionId){lT(Y.path,{groupId:Y.groupId??Tt,onSelect:T}).catch(at=>{ze({type:"error",title:r("Failed to add project"),description:at instanceof Error?at.message:String(at)})});return}const Se=new Set(l.map(at=>at.id));it({name:r_(Y.path),path:Y.path,sshHost:Y.sshHost}),_(Y.path,{sshConnectionId:Y.sshConnectionId},Y.groupId??Tt).then(at=>{if(at){if(J.includes(at.id)){const wt=J.filter(At=>At!==at.id);ae(wt),Io(ro,wt)}if(Se.has(at.id)){Q(At=>{if(At[at.id]!==!0)return At;const ts={...At,[at.id]:!1};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(ts)),ts});const wt=Xr(k,S,at.id)[0];if(wt){T(wt);return}}I(at.id)}}).catch(at=>{ze({type:"error",title:r("Failed to add project"),description:at instanceof Error?at.message:String(at)})}).finally(()=>it(null))},[Xt,E]=m.useState(null),[R,M]=m.useState(null),j=async Y=>{const Se=S[Y];let at;if(Se?.worktree){const wt=await dn(Y);Nd(wt)&&(at=qn(wt))}M({kind:"conversation",id:Y,worktreeWarning:at})},[G,he]=m.useState({}),[ve,Ae]=m.useState(""),[Ke,ct]=m.useState(!1),[nt,Qt]=m.useState(()=>Date.now());m.useEffect(()=>{const Y=setInterval(()=>Qt(Date.now()),q5);return()=>clearInterval(Y)},[]);const dt={now:nt,ms:b*6e4},Dt=Y5(k,S,J,dt),Ct=Y=>{const Se=IC(l,S[Y].projectId),at=Z5(Y,S,dt);if(at===void 0)return Se;const wt=r("Stays in Active for about {{count}} more min",{count:Math.ceil(at/6e4)});return Se?`${Se}
|
|
97
|
-
${wt}`:wt},Et=__(k,S,re,J),It=X5(k,S,ue.map(Y=>Y.id),J).filter(Y=>u||Y.projectId!==Z?.id),bt=ve.trim().length>0,ce=Y=>Va(ve,[S[Y]?.title||r("New conversation")]),Ee=Z?Xr(k,S,Z.id).filter(Y=>!bt||ce(Y)):[],Oe=bt?!1:ne,We=Y=>{const Se=S[Y]?.projectId;return!Se||cn.has(Se)},qe=(bt?Dt.filter(ce):Dt).filter(We),rt=Bne({order:k,conversations:S,pinnedOrderIds:re,projectIds:Ft,archivedProjectIds:J,collapsedProjects:H,revealedExtras:G,searching:bt,matches:ce,projectMatches:Y=>{const Se=ue.find(at=>at.id===Y);return!!(Se&&Va(ve,[Se.alias??"",Se.name,Se.path]))},leadingIds:qe}),tt=m.useRef(rt);tt.current=rt;const Xe=(bt?Et.filter(ce):Et).filter(We),Ce=new Set(Xe),_e=new Set(qe),He=(Y,Se)=>{if(t||!Ke)return;const at=rt.indexOf(Y);if(!(at<0||(_e.has(Y)?"active":Ce.has(Y)?"pinned":"project")!==Se))return mi(`mod+${at+1}`)},[Le,Re]=m.useState(!1),[Be,kt]=m.useState(""),[Gt,Ht]=m.useState(null),Bt=Be.trim()?It.map(Y=>{const Se=l.find(wt=>wt.id===Y.projectId);return Y.projectArchived===!0&&!!(Se&&Va(Be,[Se.alias??"",Se.name,Se.path]))?Y:{...Y,ids:Y.ids.filter(wt=>Va(Be,[S[wt]?.title||r("New conversation")]))}}).filter(Y=>Y.ids.length>0):It,ie=Y=>{if(je===In)return!0;const Se=l.find(at=>at.id===Y.projectId);return Se?je===hs?!Se.groupId||!h.some(at=>at.id===Se.groupId):Se.groupId===je:je===hs},Kt=Bt.filter(ie),en=It.filter(ie).reduce((Y,Se)=>Y+Se.ids.length,0),on=()=>{kt(""),Re(!0)};m.useEffect(()=>{je!==Ze&&(Nt(In),localStorage.setItem("enso-selected-project-group",In))},[je,Ze]),m.useEffect(()=>{const Y=At=>{const Jo=(Vf?At.metaKey:At.ctrlKey)&&!At.shiftKey&&!At.altKey;if(ct(Jo),!Jo||At.repeat||is.getState().activeNodeId!=="local")return;const jo=Number(At.key);if(jo<1||jo>9)return;const Zo=tt.current[jo-1];Zo&&(At.preventDefault(),T(Zo))},Se=At=>{const ts=Vf?At.metaKey:At.ctrlKey;ct(ts&&!At.shiftKey&&!At.altKey)},at=()=>ct(!1),wt=()=>{document.hidden&&at()};return window.addEventListener("keydown",Y),window.addEventListener("keyup",Se),window.addEventListener("blur",at),document.addEventListener("visibilitychange",wt),()=>{window.removeEventListener("keydown",Y),window.removeEventListener("keyup",Se),window.removeEventListener("blur",at),document.removeEventListener("visibilitychange",wt)}},[T]),m.useEffect(()=>{F();const Y=setInterval(()=>{F()},3e4),Se=()=>{F()};return window.addEventListener("focus",Se),()=>{clearInterval(Y),window.removeEventListener("focus",Se)}},[F]);const[Lt,tn]=m.useState(null),[nn,Dn]=m.useState(null),dn=async Y=>{const Se=await window.electronAPI.worktree.status(Y);return Se.ok?Se.value:void 0},Nn=async(Y,Se)=>{const at=await X(Y);if(at){ze({type:"error",title:r("Failed to clean up worktree"),description:at});return}Se&&L(Y),F()},Sn=async Y=>{const Se=await dn(Y);if(Nd(Se)){tn({kind:"cleanup",id:Y,status:Se});return}await Nn(Y,!1)},xn=async Y=>{const Se=S[Y];if(!Se)return;if(Se.archived||!Se.worktree){L(Y);return}const at=await dn(Y);if(Nd(at)){tn({kind:"archive",id:Y,status:at});return}await Nn(Y,!0)},Hn=async Y=>{for(const Se of Y)!S[Se]||S[Se].archived||await xn(Se)},zn=async(Y,Se=!1)=>{const at=await V(Y,{allowDirtyMainTree:Se});if(at===k_){Dn(Y);return}if(at){ze({type:"error",title:r("Failed to move to worktree"),description:at});return}F()},qn=Y=>{const Se=[];return Y?.dirty&&Se.push(r("Uncommitted changes")),Y&&Y.ahead>0&&Se.push(r("{{n}} unmerged commits (branch is kept)",{n:Y.ahead})),Se.join("; ")};return i.jsxs(Rs.aside,{initial:!1,animate:{width:t?48:e},transition:na,"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:()=>Ge(!0),className:Ji,title:r("Add project"),children:i.jsx(yu,{className:"h-4 w-4"})}),i.jsx("div",{className:"flex-1"}),window.electronAPI.remote?.linkStatus&&i.jsx(wC,{}),en>0&&i.jsx("button",{type:"button",onClick:on,className:Ji,title:`${r("Archived")} (${en})`,children:i.jsx(Mi,{className:"h-4 w-4"})}),window.electronAPI.remote&&i.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:Ji,title:r("Compact view"),children:i.jsx(O0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"settings-button",onClick:()=>window.electronAPI.window.openSettings(),className:Ji,title:r("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})})]}),i.jsxs("div",{className:U("flex h-full min-h-0 flex-col",d&&"pt-3",t&&"hidden"),style:{width:e},children:[i.jsx(Sne,{groups:h,selectedId:je,counts:Object.fromEntries(h.map(Y=>[Y.id,Fr(ue,h,J,Y.id).length])),totalCount:Fr(ue,h,J,In).length,recentCount:le.length,ungroupedCount:Fr(ue,h,J,hs).length,query:ve,onQueryChange:Ae,searchOpen:st,onSearchOpenChange:we,onSelect:_t,onAddGroup:()=>K({mode:"create"}),onEditGroup:Y=>K({mode:"edit",id:Y})}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pt-0.5 pb-2 pl-1.5 [scrollbar-gutter:stable]",children:[ue.length===0&&i.jsx("button",{type:"button",onClick:()=>Ge(!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")}),ue.length===0&&u&&Z&&i.jsx("button",{type:"button",onClick:()=>{ge(),I(Z.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")}),qe.length>0&&i.jsxs("div",{"data-slot":"active-section",children:[i.jsx(Ka,{section:"active",children:r("Active")}),i.jsx("div",{className:"flex flex-col",children:qe.map(Y=>i.jsx(TC,{id:Y,dragId:yee(Y),conversation:S[Y],children:i.jsx(Ua,{id:Y,conversation:S[Y],active:A===Y,switchHint:He(Y,"active"),locale:a,nowTick:nt,hoverTitle:Ct(Y),worktreeStatus:S[Y].worktree?ee[Y]:void 0,isolated:!!S[Y].worktree,onSelect:T,onTogglePin:O,onToggleArchive:Se=>{xn(Se)},onCleanupWorktree:Se=>{Sn(Se)},onMoveToWorktree:Se=>{zn(Se)},onRemove:Se=>{j(Se)}})},Y))})]}),Et.length===0&&xt?.type==="chat"&&!xt.pinned&&i.jsx(DC,{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(ci,{className:"h-3.5 w-3.5"}),r("Drop here to pin")]})}),Xe.length>0&&i.jsxs(DC,{"data-slot":"pinned-section",children:[i.jsx(Ka,{section:"pinned",children:r("Pinned")}),i.jsx("div",{className:"flex flex-col",children:i.jsx(dg,{items:Xe.map(Y=>hE(Y)),strategy:vC,children:Xe.map(Y=>i.jsx(Qne,{id:Y,conversation:S[Y],children:i.jsx(Ua,{id:Y,conversation:S[Y],active:A===Y,switchHint:He(Y,"pinned"),locale:a,nowTick:nt,hoverTitle:IC(l,S[Y].projectId),worktreeStatus:S[Y].worktree?ee[Y]:void 0,isolated:!!S[Y].worktree,onSelect:T,onTogglePin:O,onToggleArchive:Se=>{xn(Se)},onCleanupWorktree:Se=>{Sn(Se)},onMoveToWorktree:Se=>{zn(Se)},onRemove:Se=>{j(Se)}})},Y))})})]}),u&&Z&&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:Me,"aria-expanded":!Oe,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":!Oe||void 0,className:U("size-3 shrink-0 transition-[opacity,transform] duration-150",!Oe&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:"ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",children:Ee.length})]}),i.jsx("button",{type:"button",className:hf,title:r("Start a temporary chat"),"aria-label":r("Start a temporary chat"),onClick:()=>{ge(),I(Z.id)},children:i.jsx(us,{className:"size-3.25"})})]}),i.jsx(fl,{initial:!1,children:!Oe&&i.jsx(Rs.div,{initial:"initial",animate:"animate",exit:"exit",variants:Up,className:"overflow-hidden",children:i.jsx("div",{className:"flex flex-col",children:Ee.map(Y=>i.jsx(Ua,{id:Y,conversation:S[Y],active:A===Y,switchHint:He(Y,"project"),locale:a,nowTick:nt,onSelect:T,onTogglePin:O,onToggleArchive:Se=>{xn(Se)},onCleanupWorktree:Se=>{Sn(Se)},onMoveToWorktree:Se=>{zn(Se)},onRemove:Se=>{j(Se)}},Y))})},"scratch-conversations")})]}),ue.length>0&&i.jsx(Ka,{section:"projects",actions:i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:()=>we(!0),className:U(hf,(st||bt)&&"bg-foreground/5 text-foreground opacity-100"),title:r("Search conversations..."),"aria-label":r("Search conversations..."),children:i.jsx(KN,{className:"size-3.25"})}),i.jsx("button",{type:"button",onClick:()=>Ge(!0),className:hf,title:r("Add project"),"aria-label":r("Add project"),children:i.jsx(us,{className:"size-3.25"})})]}),children:r("Projects")}),Qe&&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(Yt,{className:"size-4 animate-spin"})}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium",title:Qe.path,children:[Qe.name,Qe.sshHost&&i.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal",children:Qe.sshHost})]}),i.jsx("span",{className:"shrink-0 text-xs",children:r("Adding...")})]}),i.jsx(dg,{items:[...je===In?Fe.map(Y=>Y.groupId===hs?Pv:uE(Y.groupId)):[],...Ft.map(Y=>dE(Y))],strategy:vC,children:(()=>{const Y=Se=>{const at=Xr(k,S,Se.id),wt=Va(ve,[Se.alias??"",Se.name,Se.path]),At=!bt||wt?at:at.filter(ce);if(bt&&At.length===0)return null;const ts=bt?!1:H[Se.id]===!0,Jo=G[Se.id]??0,jo=bt?At.length:Wh(At.length,Jo),Zo=At.slice(jo),Tr=te.includes(Se.id),o0=[{kind:"item",key:"pin",label:r(Tr?"Unpin project":"Pin project"),icon:Tr?i.jsx(Su,{}):i.jsx(ci,{}),onSelect:()=>$e(Se.id)},{kind:"item",key:"settings",label:r("Project settings"),icon:i.jsx(hi,{}),onSelect:()=>De(Se.id)},...Se.kind!=="ssh"?[{kind:"item",key:"reveal",label:r(Ov(window.electronAPI.env.platform)),icon:i.jsx(ni,{}),onSelect:()=>zv({projectId:Se.id},r)}]:[],{kind:"item",key:"import",label:r("Import session"),icon:i.jsx(Q5,{}),onSelect:()=>E(Se)},{kind:"separator",key:"sep-group"},{kind:"submenu",key:"move-to-group",label:r("Move to group"),icon:i.jsx(pf,{}),items:[{kind:"item",key:"ungrouped",label:r("Ungrouped"),icon:i.jsx(pf,{}),onSelect:()=>v(Se.id,null)},...h.map(Ki=>({kind:"item",key:`group-${Ki.id}`,label:Ki.name,icon:i.jsx(pf,{emoji:Ki.emoji,color:Ki.color}),onSelect:()=>v(Se.id,Ki.id)}))]},{kind:"item",key:"new-group",label:r("New group"),icon:i.jsx(yu,{}),onSelect:()=>K({mode:"create"})},{kind:"separator",key:"sep-danger"},{kind:"item",key:"archive",label:r("Archive project"),icon:i.jsx(Mi,{}),onSelect:()=>Ie(Se.id)},{kind:"item",key:"remove",label:r("Remove project"),icon:i.jsx(Hs,{}),destructive:!0,onSelect:()=>M({kind:"project",project:Se,conversationIds:at})}];return i.jsx(Zne,{project:Se,activitySorted:Ye,children:Ki=>i.jsxs(po,{children:[i.jsx(fo,{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:()=>q(Se.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",title:Se.path,children:[i.jsx(FE,{folded:ts}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium text-foreground",title:Se.kind==="ssh"?`${Se.sshHost}:${Se.path}`:Se.path,children:[Lo(Se),Se.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:Se.sshConnectionName??Se.sshHost}),Ye&&i.jsx("span",{className:"ml-1.5 font-normal text-[0.7857rem] text-subtle-foreground",children:h.find(ns=>ns.id===Se.groupId)?.name??r("Ungrouped")})]})]}),i.jsx("button",{type:"button",onClick:()=>$e(Se.id),className:"hidden shrink-0 rounded-md p-1 text-muted-foreground group-hover:block hover:bg-muted hover:text-foreground",title:r(Tr?"Unpin project":"Pin project"),children:Tr?i.jsx(Su,{className:"h-3.5 w-3.5"}):i.jsx(ci,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",onClick:()=>{I(Se.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(Go,{className:"h-3.5 w-3.5"})}),i.jsx(tse,{actions:o0}),(Tr||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:[Tr&&i.jsx(ci,{className:"h-3.5 w-3.5"}),ts&&at.length]})]}),i.jsx(fl,{initial:!1,children:!ts&&i.jsx(Rs.div,{initial:"initial",animate:"animate",exit:"exit",variants:Up,className:"overflow-hidden",children:i.jsxs("div",{className:"flex flex-col",children:[At.slice(0,jo).map(ns=>i.jsx(Rs.div,{layout:xt?.type==="project"?!1:"position",transition:na,children:i.jsx(TC,{id:ns,conversation:S[ns],children:i.jsx(Ua,{id:ns,conversation:S[ns],active:A===ns,switchHint:He(ns,"project"),locale:a,nowTick:nt,worktreeStatus:S[ns].worktree?ee[ns]:void 0,isolated:!!S[ns].worktree,onSelect:T,onTogglePin:O,onToggleArchive:Qo=>{xn(Qo)},onCleanupWorktree:Qo=>{Sn(Qo)},onMoveToWorktree:Qo=>{zn(Qo)},onRemove:Qo=>{j(Qo)}})})},ns)),!bt&&at.length>$h&&i.jsxs("div",{className:"flex items-center gap-1 pl-6",children:[Zo.length>0&&i.jsxs(po,{children:[i.jsx(fo,{render:i.jsx("button",{type:"button",onClick:()=>he(ns=>({...ns,[Se.id]:Fne(At.length,ns[Se.id]??0)})),className:kC,children:r("Show {{n}} more",{n:Zo.length})})}),i.jsx(mo,{className:"min-w-36",children:i.jsxs(Vt,{onClick:()=>{Hn(Zo)},children:[i.jsx(Mi,{}),r("Archive {{n}} conversations",{n:Zo.length})]})})]}),Jo>0&&i.jsx("button",{type:"button",onClick:()=>he(ns=>({...ns,[Se.id]:Hne(ns[Se.id]??0)})),className:kC,children:r("Collapse")})]}),At.length===0&&i.jsx("p",{className:"py-1.5 pl-8 text-xs text-subtle-foreground",children:r("No conversations yet")})]})})})]})}),i.jsx(mo,{className:"min-w-40",children:Hu(o0)})]})},Se.id)};return Ye&&!bt&&jt.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:J5})}):!bt&&ue.length>0&&jt.length===0?i.jsx("p",{className:"px-2 py-1.5 text-xs text-subtle-foreground",children:r("No projects in this group yet")}):je===In&&h.length>0?i.jsxs("div",{children:[ht.length>0&&i.jsxs("div",{children:[i.jsx(Ka,{section:"pinned-projects",children:r("Pinned projects")}),i.jsx("div",{children:ht.map(Y)})]}),Fe.map(Se=>{const at=bt?!1:Ut[Se.groupId]===!0;return i.jsxs("div",{children:[i.jsx(Yne,{groupId:Se.groupId,name:Se.group?.name??r("Ungrouped"),emoji:Se.group?.emoji,color:Se.group?.color,count:Se.projects.length,folded:at,sortable:Se.groupId!==hs,onToggle:()=>B(Se.groupId),onEdit:Se.group?()=>K({mode:"edit",id:Se.groupId}):void 0}),i.jsx(fl,{initial:!1,children:!at&&i.jsx(Rs.div,{initial:"initial",animate:"animate",exit:"exit",variants:Up,className:"overflow-hidden",children:i.jsx("div",{children:Se.projects.map(Y)})},`content-${Se.groupId}`)})]},Se.groupId)})]}):ht.length>0&&Ot.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{children:[i.jsx(Ka,{section:"pinned-projects",children:r("Pinned projects")}),i.jsx("div",{children:ht.map(Y)})]}),i.jsx("div",{children:Ot.map(Y)})]}):jt.map(Y)})()})]}),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(wC,{})]}):i.jsx(T_,{}),en>0&&i.jsx("button",{type:"button","data-slot":"archived-button",onClick:on,className:Ji,title:`${r("Archived")} (${en})`,children:i.jsx(Mi,{className:"h-4 w-4"})}),window.electronAPI.remote&&i.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:Ji,title:r("Compact view"),children:i.jsx(O0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"settings-button",onClick:()=>window.electronAPI.window.openSettings(),className:Ji,title:r("Settings"),"aria-label":r("Settings"),children:i.jsx(hi,{className:"h-4 w-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-enso":"search-button",onClick:s,className:Ji,title:C?`${r("Search anything")} (${C})`:r("Search anything"),children:i.jsx(ei,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"sidebar-toggle",onClick:n,className:Ji,title:r("Collapse sidebar"),children:i.jsx(Bx,{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(sh,{"data-size":"sm",children:[i.jsx(ih,{children:i.jsx(ei,{})}),i.jsx(oh,{value:Be,placeholder:r("Search conversations..."),onChange:Y=>kt(Y.target.value)})]}),i.jsx(NC,{open:Gt==="*",onOpenChange:Y=>Ht(Y?"*":null),idsForDays:Y=>z0(k,S,Y,Date.now()),onPick:(Y,Se)=>M({kind:"archived",days:Y,conversationIds:Se}),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:[Kt.length===0&&i.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:Be.trim()?r("No matching conversations"):r("No conversations")}),Kt.map(Y=>{const Se=l.find(wt=>wt.id===Y.projectId),at=Se?Lo(Se):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:[Y.projectArchived&&i.jsx(v6,{className:"size-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate py-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:at}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:Y.ids.length}),Y.projectArchived?i.jsx("button",{type:"button",onClick:()=>Ie(Y.projectId),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",title:r("Unarchive project"),children:i.jsx(Vl,{className:"h-3.5 w-3.5"})}):i.jsx(NC,{open:Gt===Y.projectId,onOpenChange:wt=>Ht(wt?Y.projectId:null),idsForDays:wt=>z0(k,S,wt,Date.now(),Y.projectId),onPick:(wt,At)=>M({kind:"archived",days:wt,conversationIds:At,projectName:at})})]}),i.jsx("div",{className:"flex flex-col",children:Y.ids.map(wt=>i.jsx(Rs.div,{layout:"position",transition:na,children:i.jsx(Ua,{id:wt,conversation:S[wt],active:A===wt,locale:a,nowTick:nt,worktreeStatus:S[wt].worktree?ee[wt]:void 0,isolated:!!S[wt].worktree,menuZIndex:Cn.DROPDOWN_IN_MODAL,onSelect:At=>{T(At),Re(!1)},onTogglePin:O,onToggleArchive:At=>{xn(At)},onCleanupWorktree:At=>{Sn(At)},onMoveToWorktree:At=>{zn(At)},onRemove:At=>{j(At)}})},wt))})]},Y.projectId)})]})]})}),i.jsx(bne,{open:Pe,onOpenChange:Ge,onAdd:yt,groups:h,defaultGroupId:Tt}),i.jsx(Nne,{open:pt!==null,group:pt?.mode==="edit"?h.find(Y=>Y.id===pt.id)??null:null,projects:ue.filter(Y=>!J.includes(Y.id)),onOpenChange:Y=>{Y||K(null)},onSave:Y=>{if(pt?.mode==="edit"){f(pt.id,Y);return}const Se=p(Y);for(const at of Y.projectIds??[])v(at,Se.id)},onDelete:pt?.mode==="edit"?()=>{const Y=pt.id;g(Y),Ze===Y&&_t(In)}:void 0}),i.jsx(Dne,{open:fe!==null,project:l.find(Y=>Y.id===fe)??null,onOpenChange:Y=>{Y||De(null)}}),i.jsx(Tne,{project:Xt,onClose:()=>E(null)}),i.jsx(ms,{open:Lt!==null,onOpenChange:Y=>{Y||tn(null)},title:Lt?.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(Lt?.status)}),confirmLabel:Lt?.kind==="archive"?r("Archive"):r("Clean up"),onConfirm:()=>{Lt&&Nn(Lt.id,Lt.kind==="archive")}}),i.jsx(ms,{open:nn!==null,onOpenChange:Y=>{Y||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 Y=nn;Dn(null),zn(Y,!0)}}),i.jsx(ms,{open:R!==null,onOpenChange:Y=>{Y||M(null)},title:R?.kind==="project"?r("Remove project?"):R?.kind==="archived"?r("Delete archived conversations?"):r("Delete conversation?"),description:R?.kind==="project"?r('"{{name}}" and its {{count}} conversations will be removed from the list.',{name:R.project.name,count:R.conversationIds.length}):R?.kind==="archived"?R.days===0?R.projectName?r('All {{count}} archived conversations in "{{name}}" will be removed from the list.',{count:R.conversationIds.length,name:R.projectName}):r("All {{count}} archived conversations will be removed from the list.",{count:R.conversationIds.length}):R.projectName?r('{{count}} conversations in "{{name}}" archived more than {{days}} days ago will be removed from the list.',{count:R.conversationIds.length,days:R.days,name:R.projectName}):r("{{count}} conversations archived more than {{days}} days ago will be removed from the list.",{count:R.conversationIds.length,days:R.days}):R?.kind==="conversation"&&R.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:R.worktreeWarning}):r("This conversation will be removed from the list."),confirmLabel:r("Remove"),onConfirm:()=>{if(R)if(R.kind==="project"){for(const Y of R.conversationIds)z(Y);N(R.project.id)}else if(R.kind==="archived")for(const Y of R.conversationIds)z(Y);else z(R.id)}}),Us.createPortal(i.jsx(wG,{dropAnimation:null,children:xt?.type==="project"?i.jsx(Jne,{projectId:xt.projectId,name:Xne(l,xt.projectId,xt.name),folded:H[xt.projectId]===!0,revealedExtra:G[xt.projectId]??0,width:e}):(xt?.type==="chat"||xt?.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:[xt.type==="workspace-file"?i.jsx(So,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):i.jsx(ci,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:xt.type==="workspace-file"?xt.name:xt.title.split(`
|
|
98
|
-
`)[0].trim()||r("New conversation")})]})}),document.body)]})}function Yne({groupId:e,name:t,emoji:n,color:s,count:o,folded:r,sortable:a,onToggle:l,onEdit:c}){const d=e===hs?Pv:uE(e),u=vc({id:d}),h=Vh({id:d,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:Gi.Transform.toString(h.transform),transition:h.transition,opacity:h.isDragging?.4:void 0},className:U("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:U("size-3 shrink-0 transition-[opacity,transform] duration-150",!r&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:U("ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",c&&"transition-opacity group-hover:opacity-0"),children:o})]}),c&&i.jsx("button",{type:"button",onClick:f=>{f.stopPropagation(),c()},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(Bs,{className:"size-3.25"})})]})}function Xne(e,t,n){const s=e.find(o=>o.id===t);return s?Lo(s):n}function Jne({projectId:e,name:t,folded:n,revealedExtra:s,width:o}){const{t:r}=se(),a=oe(h=>Ev(h.conversations)),l=oe(h=>h.order),c=Xr(l,a,e),d=n?[]:c.slice(0,Wh(c.length,s)),u=Math.max(0,c.length-d.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(FE,{folded:n}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:t})]}),!n&&i.jsxs("div",{className:"flex flex-col",children:[d.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(HE,{conversation:p}),i.jsx("span",{className:"min-w-0 truncate",children:p.title||r("New conversation")})]},h):null}),c.length>$h&&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")})]}),c.length===0&&i.jsx("p",{className:"py-1.5 pl-8 text-xs text-muted-foreground",children:r("No conversations yet")})]})]})}function Zne({project:e,activitySorted:t=!1,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Vh({id:dE(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:Gi.Transform.toString(o),transition:r,opacity:l?.4:void 0},handleProps:a??{}})}function NC({open:e,onOpenChange:t,idsForDays:n,onPick:s,className:o}){const{t:r}=se();return i.jsxs(Hi,{open:e,onOpenChange:t,children:[i.jsx(Bi,{className:U("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(Zg,{className:"h-3.5 w-3.5"})}),i.jsxs(Vi,{align:"end",className:"min-w-40",zIndex:Cn.DROPDOWN_IN_MODAL,children:[qne.map(a=>{const l=n(a);return i.jsx(mn,{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(mn,{variant:"destructive",disabled:a.length===0,onClick:()=>s(0,a),children:r("Delete all archived")})})()]})]})}function Qne({id:e,conversation:t,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Vh({id:hE(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:Gi.Transform.toString(o),transition:r,opacity:l?.4:void 0},children:n})}function TC({id:e,conversation:t,children:n,dragId:s}){const{setNodeRef:o,listeners:r,isDragging:a}=lx({id:s??wee(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 DC({children:e,...t}){const{setNodeRef:n,isOver:s,active:o}=vc({id:cE}),r=o?.data.current?.type==="chat";return i.jsx("div",{ref:n,className:U("rounded-lg",s&&r&&"bg-brand/8 ring-1 ring-brand/40"),...t,children:e})}function Ua({id:e,conversation:t,active:n,locale:s,nowTick:o,hoverTitle:r,subtitle:a,isolated:l,worktreeStatus:c,switchHint:d,menuZIndex:u,onSelect:h,onTogglePin:p,onToggleArchive:f,onCleanupWorktree:g,onMoveToWorktree:x,onRemove:v}){const{t:y}=se(),b=ye(H=>H.projects.some(Q=>Q.id===t.projectId&&Q.kind!=="ssh")),w=ye(H=>H.projects.some(Q=>Q.id===t.projectId&&Q.kind==="scratch")),[C,_]=m.useState(!1),N=oe(H=>H.conversations[e]?.worktree),S=oe(H=>!!H.conversations[e]?.workspaceMigrating),k=oe(H=>H.conversations[e]?.worktreeMissing),[A,I]=m.useState(!1),[D,P]=m.useState(null),T=A||S||t.spawning||t.status==="running"||t.reloading===!0,z=async()=>{if(!T){I(!0);try{await oe.getState().newConversation(t.projectId,{worktreeFromConversationId:e})||ze({type:"error",title:y("Failed to create conversation")})}catch(H){ze({type:"error",title:y("Failed to create conversation"),description:String(H)})}finally{I(!1)}}},O=t.pinned===!0,L=t.archived===!0,V=O?Su:ci,X=t.title||y("New conversation"),F=t.forkedFromConversationId?oe.getState().conversations[t.forkedFromConversationId]?.title:void 0,ee=i.jsxs("div",{"data-slot":"conversation-row","data-pinned":O?"true":"false","data-enso":"session-row","data-active":n||void 0,"data-status":Gv(t),"data-unread":t.unread||void 0,className:U("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:()=>{C||h(e)},onDoubleClick:H=>{H.preventDefault(),H.stopPropagation(),_(!0)},onKeyDown:H=>{H.key==="Enter"&&!C&&h(e)},role:"button",tabIndex:0,title:r,children:[i.jsx(HE,{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:[F&&i.jsx("span",{className:"max-w-1/3 truncate text-[0.7857rem] text-subtle-foreground",children:y("Branched from {{title}}",{title:F})}),C?i.jsx(mE,{title:X,onCommit:H=>{oe.getState().renameConversation(e,H),_(!1)},onCancel:()=>_(!1)}):i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[X,a&&i.jsx("span",{className:"ml-1.5 text-[0.7857rem] text-subtle-foreground",children:a})]})]}),l&&N&&i.jsx(Jte,{worktree:N,status:c}),i.jsx(Kne,{conversationId:e}),!C&&i.jsx(ese,{pending:t.titleSummaryPending,error:t.titleSummaryError,onRetry:()=>oe.getState().retryTitleSummary(e)}),!C&&(d?i.jsx("span",{className:"shrink-0 text-[0.7857rem] text-subtle-foreground tabular-nums",children:d}):i.jsxs(i.Fragment,{children:[O&&!L&&i.jsx(ci,{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:Bo(t.lastActiveAt??t.createdAt,s,o)}),!L&&i.jsx("button",{type:"button",onClick:H=>{H.stopPropagation(),p(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:y(O?"Unpin":"Pin"),children:i.jsx(V,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",onClick:H=>{H.stopPropagation(),f(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:y(L?"Unarchive":"Archive"),children:L?i.jsx(Vl,{className:"h-3.5 w-3.5"}):i.jsx(Mi,{className:"h-3.5 w-3.5"})}),L&&i.jsx("button",{type:"button",onClick:H=>{H.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(Hs,{className:"h-3.5 w-3.5"})})]}))]})]});return i.jsxs(i.Fragment,{children:[i.jsxs(po,{children:[i.jsx(fo,{render:ee}),i.jsxs(mo,{className:"min-w-36",zIndex:u,children:[i.jsxs(Vt,{onClick:()=>_(!0),children:[i.jsx(Bs,{}),y("Rename")]}),i.jsxs(Vt,{disabled:t.reloading===!0||t.spawning,onClick:()=>{gE(e,y)},children:[i.jsx(Wo,{className:t.reloading?"animate-spin":void 0}),y("Reload conversation")]}),i.jsxs(Vt,{disabled:T,onClick:()=>{Wee(e,y)},children:[i.jsx(ra,{}),y("Restart conversation (reload settings)")]}),b&&i.jsxs(Vt,{disabled:S||k||c?.exists===!1,onClick:()=>{zv({projectId:t.projectId,conversationId:e},y)},children:[i.jsx(ni,{}),y(Ov(window.electronAPI.env.platform))]}),!L&&i.jsxs(Vt,{onClick:()=>p(e),children:[i.jsx(V,{}),y(O?"Unpin":"Pin")]}),i.jsxs(Vt,{onClick:()=>f(e),children:[L?i.jsx(Vl,{}):i.jsx(Mi,{}),y(L?"Unarchive":"Archive")]}),N&&i.jsxs(i.Fragment,{children:[i.jsxs(Vt,{disabled:T||k||c?.exists===!1,onClick:()=>{z()},children:[A?i.jsx(Yt,{className:"animate-spin"}):i.jsx(Go,{}),y("New conversation in this worktree")]}),i.jsxs(Vt,{disabled:T||k||c?.exists===!1,onClick:()=>P({conversationId:e,worktree:N}),children:[i.jsx(Bs,{}),y("Rename worktree")]})]}),!L&&(l?g&&i.jsxs(Vt,{disabled:T,onClick:()=>g(e),children:[i.jsx(Zg,{}),y("Clean up worktree")]}):x&&b&&!w&&i.jsxs(Vt,{disabled:T,onClick:()=>x(e),children:[i.jsx(k6,{}),y("Move to worktree")]})),i.jsx(ah,{}),i.jsxs(Vt,{variant:"destructive",onClick:()=>v(e),children:[i.jsx(Hs,{}),y("Delete")]})]})]}),i.jsx(NE,{entity:D,onClose:()=>P(null)})]})}function ese({pending:e,error:t,onRetry:n}){const{t:s}=se();return e?i.jsxs(Lf,{children:[i.jsx(Of,{render:i.jsx("span",{role:"status",className:"shrink-0 text-muted-foreground/60","aria-label":s("Summarizing title")}),children:i.jsx(Yt,{className:"h-3 w-3 animate-spin"})}),i.jsx(zf,{side:"right",children:s("Summarizing title")})]}):t?i.jsxs(Lf,{children:[i.jsx(Of,{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(br,{className:"h-3 w-3"})}),i.jsxs(zf,{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 IC(e,t){const n=e.find(s=>s.id===t);return n?Lo(n):void 0}function pf({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 Hu(e,t="context"){return e.map(n=>n.kind==="separator"?t==="menu"?i.jsx(ya,{},n.key):i.jsx(ah,{},n.key):n.kind==="submenu"?t==="menu"?i.jsxs(Hj,{children:[i.jsxs(Bj,{children:[n.icon,n.label]}),i.jsx(Vj,{className:"min-w-40",children:Hu(n.items,"menu")})]},n.key):i.jsxs(n_,{children:[i.jsxs(s_,{children:[n.icon,n.label]}),i.jsx(i_,{className:"min-w-40",children:Hu(n.items)})]},n.key):t==="menu"?i.jsxs(mn,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key):i.jsxs(Vt,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key))}function tse({actions:e}){const{t}=se();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(Sh,{className:"h-3.5 w-3.5"})}),i.jsx(Vi,{align:"end",className:"min-w-40",children:Hu(e,"menu")})]})}function Ka({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 FE({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:U("size-3.5 transition-transform duration-150",!e&&"rotate-90")})})}function HE({conversation:e}){const t=(e.pendingApprovals?.length??0)>0?"attention":Jg({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(Bh,{tone:t,size:"sm","data-enso":"session-status","data-status":Gv(e)})})}const nse=15e3,EC={"host-dirs":"host-dirs-result","project-add":"project-add-result"};function ff(e,t){const n=t.type,s=crypto.randomUUID();return new Promise(o=>{const r=(c,d)=>{clearTimeout(l),a(),o(d??{type:EC[n],requestId:s,error:c})},a=window.electronAPI.nodes.onMessage(c=>{if(c.nodeId!==e)return;const d=c.payload;d.type==="command-rejected"&&d.command===n?r(d.error):d.type===EC[n]&&d.requestId===s&&r(void 0,d)}),l=setTimeout(()=>r("timeout"),nse);window.electronAPI.nodes.send(e,{...t,requestId:s}).then(c=>{c.ok||r(c.error??"offline")})})}function sse({nodeId:e,open:t,onOpenChange:n}){const{t:s}=se(),[o,r]=m.useState(""),[a,l]=m.useState(!0),[c,d]=m.useState(!1),[u,h]=m.useState("");m.useEffect(()=>{t&&(r(""),l(!0),d(!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=>ff(e,{type:"host-dirs",...b?{path:b}:{}}).then(f),[e,f]),x=m.useCallback((b,w)=>ff(e,{type:"host-dirs",path:b,create:w}).then(f),[e,f]),v=o.trim(),y=async b=>{if(b.preventDefault(),!v||c)return;d(!0),h("");const w=await ff(e,{type:"project-add",path:v});if(d(!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(xe,{type:"button",variant:"outline",onClick:()=>l(b=>!b),children:s("Browse")})]}),a&&i.jsx(ug,{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(xe,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsx(xe,{type:"submit",size:"sm",disabled:!v||c,children:s("Add")})]})]})})})}function ise(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 mf={exports:{}};const ose={},rse=Object.freeze(Object.defineProperty({__proto__:null,default:ose},Symbol.toStringTag,{value:"Module"})),ase=eO(rse);var PC;function lse(){return PC||(PC=1,(function(e){(function(t){var n=function(E){var R,M=new Float64Array(16);if(E)for(R=0;R<E.length;R++)M[R]=E[R];return M},s=function(){throw new Error("no PRNG")},o=new Uint8Array(16),r=new Uint8Array(32);r[0]=9;var a=n(),l=n([1]),c=n([56129,1]),d=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(E,R,M,j){E[R]=M>>24&255,E[R+1]=M>>16&255,E[R+2]=M>>8&255,E[R+3]=M&255,E[R+4]=j>>24&255,E[R+5]=j>>16&255,E[R+6]=j>>8&255,E[R+7]=j&255}function x(E,R,M,j,G){var he,ve=0;for(he=0;he<G;he++)ve|=E[R+he]^M[j+he];return(1&ve-1>>>8)-1}function v(E,R,M,j){return x(E,R,M,j,16)}function y(E,R,M,j){return x(E,R,M,j,32)}function b(E,R,M,j){for(var G=j[0]&255|(j[1]&255)<<8|(j[2]&255)<<16|(j[3]&255)<<24,he=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,ve=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,Ae=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,Ke=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,ct=j[4]&255|(j[5]&255)<<8|(j[6]&255)<<16|(j[7]&255)<<24,nt=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,Qt=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,dt=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,Dt=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,Ct=j[8]&255|(j[9]&255)<<8|(j[10]&255)<<16|(j[11]&255)<<24,Et=M[16]&255|(M[17]&255)<<8|(M[18]&255)<<16|(M[19]&255)<<24,It=M[20]&255|(M[21]&255)<<8|(M[22]&255)<<16|(M[23]&255)<<24,bt=M[24]&255|(M[25]&255)<<8|(M[26]&255)<<16|(M[27]&255)<<24,ce=M[28]&255|(M[29]&255)<<8|(M[30]&255)<<16|(M[31]&255)<<24,Ee=j[12]&255|(j[13]&255)<<8|(j[14]&255)<<16|(j[15]&255)<<24,Oe=G,We=he,qe=ve,rt=Ae,tt=Ke,Xe=ct,Ce=nt,_e=Qt,He=dt,Le=Dt,Re=Ct,Be=Et,kt=It,Gt=bt,Ht=ce,Bt=Ee,ie,Kt=0;Kt<20;Kt+=2)ie=Oe+kt|0,tt^=ie<<7|ie>>>25,ie=tt+Oe|0,He^=ie<<9|ie>>>23,ie=He+tt|0,kt^=ie<<13|ie>>>19,ie=kt+He|0,Oe^=ie<<18|ie>>>14,ie=Xe+We|0,Le^=ie<<7|ie>>>25,ie=Le+Xe|0,Gt^=ie<<9|ie>>>23,ie=Gt+Le|0,We^=ie<<13|ie>>>19,ie=We+Gt|0,Xe^=ie<<18|ie>>>14,ie=Re+Ce|0,Ht^=ie<<7|ie>>>25,ie=Ht+Re|0,qe^=ie<<9|ie>>>23,ie=qe+Ht|0,Ce^=ie<<13|ie>>>19,ie=Ce+qe|0,Re^=ie<<18|ie>>>14,ie=Bt+Be|0,rt^=ie<<7|ie>>>25,ie=rt+Bt|0,_e^=ie<<9|ie>>>23,ie=_e+rt|0,Be^=ie<<13|ie>>>19,ie=Be+_e|0,Bt^=ie<<18|ie>>>14,ie=Oe+rt|0,We^=ie<<7|ie>>>25,ie=We+Oe|0,qe^=ie<<9|ie>>>23,ie=qe+We|0,rt^=ie<<13|ie>>>19,ie=rt+qe|0,Oe^=ie<<18|ie>>>14,ie=Xe+tt|0,Ce^=ie<<7|ie>>>25,ie=Ce+Xe|0,_e^=ie<<9|ie>>>23,ie=_e+Ce|0,tt^=ie<<13|ie>>>19,ie=tt+_e|0,Xe^=ie<<18|ie>>>14,ie=Re+Le|0,Be^=ie<<7|ie>>>25,ie=Be+Re|0,He^=ie<<9|ie>>>23,ie=He+Be|0,Le^=ie<<13|ie>>>19,ie=Le+He|0,Re^=ie<<18|ie>>>14,ie=Bt+Ht|0,kt^=ie<<7|ie>>>25,ie=kt+Bt|0,Gt^=ie<<9|ie>>>23,ie=Gt+kt|0,Ht^=ie<<13|ie>>>19,ie=Ht+Gt|0,Bt^=ie<<18|ie>>>14;Oe=Oe+G|0,We=We+he|0,qe=qe+ve|0,rt=rt+Ae|0,tt=tt+Ke|0,Xe=Xe+ct|0,Ce=Ce+nt|0,_e=_e+Qt|0,He=He+dt|0,Le=Le+Dt|0,Re=Re+Ct|0,Be=Be+Et|0,kt=kt+It|0,Gt=Gt+bt|0,Ht=Ht+ce|0,Bt=Bt+Ee|0,E[0]=Oe>>>0&255,E[1]=Oe>>>8&255,E[2]=Oe>>>16&255,E[3]=Oe>>>24&255,E[4]=We>>>0&255,E[5]=We>>>8&255,E[6]=We>>>16&255,E[7]=We>>>24&255,E[8]=qe>>>0&255,E[9]=qe>>>8&255,E[10]=qe>>>16&255,E[11]=qe>>>24&255,E[12]=rt>>>0&255,E[13]=rt>>>8&255,E[14]=rt>>>16&255,E[15]=rt>>>24&255,E[16]=tt>>>0&255,E[17]=tt>>>8&255,E[18]=tt>>>16&255,E[19]=tt>>>24&255,E[20]=Xe>>>0&255,E[21]=Xe>>>8&255,E[22]=Xe>>>16&255,E[23]=Xe>>>24&255,E[24]=Ce>>>0&255,E[25]=Ce>>>8&255,E[26]=Ce>>>16&255,E[27]=Ce>>>24&255,E[28]=_e>>>0&255,E[29]=_e>>>8&255,E[30]=_e>>>16&255,E[31]=_e>>>24&255,E[32]=He>>>0&255,E[33]=He>>>8&255,E[34]=He>>>16&255,E[35]=He>>>24&255,E[36]=Le>>>0&255,E[37]=Le>>>8&255,E[38]=Le>>>16&255,E[39]=Le>>>24&255,E[40]=Re>>>0&255,E[41]=Re>>>8&255,E[42]=Re>>>16&255,E[43]=Re>>>24&255,E[44]=Be>>>0&255,E[45]=Be>>>8&255,E[46]=Be>>>16&255,E[47]=Be>>>24&255,E[48]=kt>>>0&255,E[49]=kt>>>8&255,E[50]=kt>>>16&255,E[51]=kt>>>24&255,E[52]=Gt>>>0&255,E[53]=Gt>>>8&255,E[54]=Gt>>>16&255,E[55]=Gt>>>24&255,E[56]=Ht>>>0&255,E[57]=Ht>>>8&255,E[58]=Ht>>>16&255,E[59]=Ht>>>24&255,E[60]=Bt>>>0&255,E[61]=Bt>>>8&255,E[62]=Bt>>>16&255,E[63]=Bt>>>24&255}function w(E,R,M,j){for(var G=j[0]&255|(j[1]&255)<<8|(j[2]&255)<<16|(j[3]&255)<<24,he=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,ve=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,Ae=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,Ke=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,ct=j[4]&255|(j[5]&255)<<8|(j[6]&255)<<16|(j[7]&255)<<24,nt=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,Qt=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,dt=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,Dt=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,Ct=j[8]&255|(j[9]&255)<<8|(j[10]&255)<<16|(j[11]&255)<<24,Et=M[16]&255|(M[17]&255)<<8|(M[18]&255)<<16|(M[19]&255)<<24,It=M[20]&255|(M[21]&255)<<8|(M[22]&255)<<16|(M[23]&255)<<24,bt=M[24]&255|(M[25]&255)<<8|(M[26]&255)<<16|(M[27]&255)<<24,ce=M[28]&255|(M[29]&255)<<8|(M[30]&255)<<16|(M[31]&255)<<24,Ee=j[12]&255|(j[13]&255)<<8|(j[14]&255)<<16|(j[15]&255)<<24,Oe=G,We=he,qe=ve,rt=Ae,tt=Ke,Xe=ct,Ce=nt,_e=Qt,He=dt,Le=Dt,Re=Ct,Be=Et,kt=It,Gt=bt,Ht=ce,Bt=Ee,ie,Kt=0;Kt<20;Kt+=2)ie=Oe+kt|0,tt^=ie<<7|ie>>>25,ie=tt+Oe|0,He^=ie<<9|ie>>>23,ie=He+tt|0,kt^=ie<<13|ie>>>19,ie=kt+He|0,Oe^=ie<<18|ie>>>14,ie=Xe+We|0,Le^=ie<<7|ie>>>25,ie=Le+Xe|0,Gt^=ie<<9|ie>>>23,ie=Gt+Le|0,We^=ie<<13|ie>>>19,ie=We+Gt|0,Xe^=ie<<18|ie>>>14,ie=Re+Ce|0,Ht^=ie<<7|ie>>>25,ie=Ht+Re|0,qe^=ie<<9|ie>>>23,ie=qe+Ht|0,Ce^=ie<<13|ie>>>19,ie=Ce+qe|0,Re^=ie<<18|ie>>>14,ie=Bt+Be|0,rt^=ie<<7|ie>>>25,ie=rt+Bt|0,_e^=ie<<9|ie>>>23,ie=_e+rt|0,Be^=ie<<13|ie>>>19,ie=Be+_e|0,Bt^=ie<<18|ie>>>14,ie=Oe+rt|0,We^=ie<<7|ie>>>25,ie=We+Oe|0,qe^=ie<<9|ie>>>23,ie=qe+We|0,rt^=ie<<13|ie>>>19,ie=rt+qe|0,Oe^=ie<<18|ie>>>14,ie=Xe+tt|0,Ce^=ie<<7|ie>>>25,ie=Ce+Xe|0,_e^=ie<<9|ie>>>23,ie=_e+Ce|0,tt^=ie<<13|ie>>>19,ie=tt+_e|0,Xe^=ie<<18|ie>>>14,ie=Re+Le|0,Be^=ie<<7|ie>>>25,ie=Be+Re|0,He^=ie<<9|ie>>>23,ie=He+Be|0,Le^=ie<<13|ie>>>19,ie=Le+He|0,Re^=ie<<18|ie>>>14,ie=Bt+Ht|0,kt^=ie<<7|ie>>>25,ie=kt+Bt|0,Gt^=ie<<9|ie>>>23,ie=Gt+kt|0,Ht^=ie<<13|ie>>>19,ie=Ht+Gt|0,Bt^=ie<<18|ie>>>14;E[0]=Oe>>>0&255,E[1]=Oe>>>8&255,E[2]=Oe>>>16&255,E[3]=Oe>>>24&255,E[4]=Xe>>>0&255,E[5]=Xe>>>8&255,E[6]=Xe>>>16&255,E[7]=Xe>>>24&255,E[8]=Re>>>0&255,E[9]=Re>>>8&255,E[10]=Re>>>16&255,E[11]=Re>>>24&255,E[12]=Bt>>>0&255,E[13]=Bt>>>8&255,E[14]=Bt>>>16&255,E[15]=Bt>>>24&255,E[16]=Ce>>>0&255,E[17]=Ce>>>8&255,E[18]=Ce>>>16&255,E[19]=Ce>>>24&255,E[20]=_e>>>0&255,E[21]=_e>>>8&255,E[22]=_e>>>16&255,E[23]=_e>>>24&255,E[24]=He>>>0&255,E[25]=He>>>8&255,E[26]=He>>>16&255,E[27]=He>>>24&255,E[28]=Le>>>0&255,E[29]=Le>>>8&255,E[30]=Le>>>16&255,E[31]=Le>>>24&255}function C(E,R,M,j){b(E,R,M,j)}function _(E,R,M,j){w(E,R,M,j)}var N=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function S(E,R,M,j,G,he,ve){var Ae=new Uint8Array(16),Ke=new Uint8Array(64),ct,nt;for(nt=0;nt<16;nt++)Ae[nt]=0;for(nt=0;nt<8;nt++)Ae[nt]=he[nt];for(;G>=64;){for(C(Ke,Ae,ve,N),nt=0;nt<64;nt++)E[R+nt]=M[j+nt]^Ke[nt];for(ct=1,nt=8;nt<16;nt++)ct=ct+(Ae[nt]&255)|0,Ae[nt]=ct&255,ct>>>=8;G-=64,R+=64,j+=64}if(G>0)for(C(Ke,Ae,ve,N),nt=0;nt<G;nt++)E[R+nt]=M[j+nt]^Ke[nt];return 0}function k(E,R,M,j,G){var he=new Uint8Array(16),ve=new Uint8Array(64),Ae,Ke;for(Ke=0;Ke<16;Ke++)he[Ke]=0;for(Ke=0;Ke<8;Ke++)he[Ke]=j[Ke];for(;M>=64;){for(C(ve,he,G,N),Ke=0;Ke<64;Ke++)E[R+Ke]=ve[Ke];for(Ae=1,Ke=8;Ke<16;Ke++)Ae=Ae+(he[Ke]&255)|0,he[Ke]=Ae&255,Ae>>>=8;M-=64,R+=64}if(M>0)for(C(ve,he,G,N),Ke=0;Ke<M;Ke++)E[R+Ke]=ve[Ke];return 0}function A(E,R,M,j,G){var he=new Uint8Array(32);_(he,j,G,N);for(var ve=new Uint8Array(8),Ae=0;Ae<8;Ae++)ve[Ae]=j[Ae+16];return k(E,R,M,ve,he)}function I(E,R,M,j,G,he,ve){var Ae=new Uint8Array(32);_(Ae,he,ve,N);for(var Ke=new Uint8Array(8),ct=0;ct<8;ct++)Ke[ct]=he[ct+16];return S(E,R,M,j,G,Ke,Ae)}var D=function(E){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 R,M,j,G,he,ve,Ae,Ke;R=E[0]&255|(E[1]&255)<<8,this.r[0]=R&8191,M=E[2]&255|(E[3]&255)<<8,this.r[1]=(R>>>13|M<<3)&8191,j=E[4]&255|(E[5]&255)<<8,this.r[2]=(M>>>10|j<<6)&7939,G=E[6]&255|(E[7]&255)<<8,this.r[3]=(j>>>7|G<<9)&8191,he=E[8]&255|(E[9]&255)<<8,this.r[4]=(G>>>4|he<<12)&255,this.r[5]=he>>>1&8190,ve=E[10]&255|(E[11]&255)<<8,this.r[6]=(he>>>14|ve<<2)&8191,Ae=E[12]&255|(E[13]&255)<<8,this.r[7]=(ve>>>11|Ae<<5)&8065,Ke=E[14]&255|(E[15]&255)<<8,this.r[8]=(Ae>>>8|Ke<<8)&8191,this.r[9]=Ke>>>5&127,this.pad[0]=E[16]&255|(E[17]&255)<<8,this.pad[1]=E[18]&255|(E[19]&255)<<8,this.pad[2]=E[20]&255|(E[21]&255)<<8,this.pad[3]=E[22]&255|(E[23]&255)<<8,this.pad[4]=E[24]&255|(E[25]&255)<<8,this.pad[5]=E[26]&255|(E[27]&255)<<8,this.pad[6]=E[28]&255|(E[29]&255)<<8,this.pad[7]=E[30]&255|(E[31]&255)<<8};D.prototype.blocks=function(E,R,M){for(var j=this.fin?0:2048,G,he,ve,Ae,Ke,ct,nt,Qt,dt,Dt,Ct,Et,It,bt,ce,Ee,Oe,We,qe,rt=this.h[0],tt=this.h[1],Xe=this.h[2],Ce=this.h[3],_e=this.h[4],He=this.h[5],Le=this.h[6],Re=this.h[7],Be=this.h[8],kt=this.h[9],Gt=this.r[0],Ht=this.r[1],Bt=this.r[2],ie=this.r[3],Kt=this.r[4],en=this.r[5],on=this.r[6],Lt=this.r[7],tn=this.r[8],nn=this.r[9];M>=16;)G=E[R+0]&255|(E[R+1]&255)<<8,rt+=G&8191,he=E[R+2]&255|(E[R+3]&255)<<8,tt+=(G>>>13|he<<3)&8191,ve=E[R+4]&255|(E[R+5]&255)<<8,Xe+=(he>>>10|ve<<6)&8191,Ae=E[R+6]&255|(E[R+7]&255)<<8,Ce+=(ve>>>7|Ae<<9)&8191,Ke=E[R+8]&255|(E[R+9]&255)<<8,_e+=(Ae>>>4|Ke<<12)&8191,He+=Ke>>>1&8191,ct=E[R+10]&255|(E[R+11]&255)<<8,Le+=(Ke>>>14|ct<<2)&8191,nt=E[R+12]&255|(E[R+13]&255)<<8,Re+=(ct>>>11|nt<<5)&8191,Qt=E[R+14]&255|(E[R+15]&255)<<8,Be+=(nt>>>8|Qt<<8)&8191,kt+=Qt>>>5|j,dt=0,Dt=dt,Dt+=rt*Gt,Dt+=tt*(5*nn),Dt+=Xe*(5*tn),Dt+=Ce*(5*Lt),Dt+=_e*(5*on),dt=Dt>>>13,Dt&=8191,Dt+=He*(5*en),Dt+=Le*(5*Kt),Dt+=Re*(5*ie),Dt+=Be*(5*Bt),Dt+=kt*(5*Ht),dt+=Dt>>>13,Dt&=8191,Ct=dt,Ct+=rt*Ht,Ct+=tt*Gt,Ct+=Xe*(5*nn),Ct+=Ce*(5*tn),Ct+=_e*(5*Lt),dt=Ct>>>13,Ct&=8191,Ct+=He*(5*on),Ct+=Le*(5*en),Ct+=Re*(5*Kt),Ct+=Be*(5*ie),Ct+=kt*(5*Bt),dt+=Ct>>>13,Ct&=8191,Et=dt,Et+=rt*Bt,Et+=tt*Ht,Et+=Xe*Gt,Et+=Ce*(5*nn),Et+=_e*(5*tn),dt=Et>>>13,Et&=8191,Et+=He*(5*Lt),Et+=Le*(5*on),Et+=Re*(5*en),Et+=Be*(5*Kt),Et+=kt*(5*ie),dt+=Et>>>13,Et&=8191,It=dt,It+=rt*ie,It+=tt*Bt,It+=Xe*Ht,It+=Ce*Gt,It+=_e*(5*nn),dt=It>>>13,It&=8191,It+=He*(5*tn),It+=Le*(5*Lt),It+=Re*(5*on),It+=Be*(5*en),It+=kt*(5*Kt),dt+=It>>>13,It&=8191,bt=dt,bt+=rt*Kt,bt+=tt*ie,bt+=Xe*Bt,bt+=Ce*Ht,bt+=_e*Gt,dt=bt>>>13,bt&=8191,bt+=He*(5*nn),bt+=Le*(5*tn),bt+=Re*(5*Lt),bt+=Be*(5*on),bt+=kt*(5*en),dt+=bt>>>13,bt&=8191,ce=dt,ce+=rt*en,ce+=tt*Kt,ce+=Xe*ie,ce+=Ce*Bt,ce+=_e*Ht,dt=ce>>>13,ce&=8191,ce+=He*Gt,ce+=Le*(5*nn),ce+=Re*(5*tn),ce+=Be*(5*Lt),ce+=kt*(5*on),dt+=ce>>>13,ce&=8191,Ee=dt,Ee+=rt*on,Ee+=tt*en,Ee+=Xe*Kt,Ee+=Ce*ie,Ee+=_e*Bt,dt=Ee>>>13,Ee&=8191,Ee+=He*Ht,Ee+=Le*Gt,Ee+=Re*(5*nn),Ee+=Be*(5*tn),Ee+=kt*(5*Lt),dt+=Ee>>>13,Ee&=8191,Oe=dt,Oe+=rt*Lt,Oe+=tt*on,Oe+=Xe*en,Oe+=Ce*Kt,Oe+=_e*ie,dt=Oe>>>13,Oe&=8191,Oe+=He*Bt,Oe+=Le*Ht,Oe+=Re*Gt,Oe+=Be*(5*nn),Oe+=kt*(5*tn),dt+=Oe>>>13,Oe&=8191,We=dt,We+=rt*tn,We+=tt*Lt,We+=Xe*on,We+=Ce*en,We+=_e*Kt,dt=We>>>13,We&=8191,We+=He*ie,We+=Le*Bt,We+=Re*Ht,We+=Be*Gt,We+=kt*(5*nn),dt+=We>>>13,We&=8191,qe=dt,qe+=rt*nn,qe+=tt*tn,qe+=Xe*Lt,qe+=Ce*on,qe+=_e*en,dt=qe>>>13,qe&=8191,qe+=He*Kt,qe+=Le*ie,qe+=Re*Bt,qe+=Be*Ht,qe+=kt*Gt,dt+=qe>>>13,qe&=8191,dt=(dt<<2)+dt|0,dt=dt+Dt|0,Dt=dt&8191,dt=dt>>>13,Ct+=dt,rt=Dt,tt=Ct,Xe=Et,Ce=It,_e=bt,He=ce,Le=Ee,Re=Oe,Be=We,kt=qe,R+=16,M-=16;this.h[0]=rt,this.h[1]=tt,this.h[2]=Xe,this.h[3]=Ce,this.h[4]=_e,this.h[5]=He,this.h[6]=Le,this.h[7]=Re,this.h[8]=Be,this.h[9]=kt},D.prototype.finish=function(E,R){var M=new Uint16Array(10),j,G,he,ve;if(this.leftover){for(ve=this.leftover,this.buffer[ve++]=1;ve<16;ve++)this.buffer[ve]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(j=this.h[1]>>>13,this.h[1]&=8191,ve=2;ve<10;ve++)this.h[ve]+=j,j=this.h[ve]>>>13,this.h[ve]&=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,M[0]=this.h[0]+5,j=M[0]>>>13,M[0]&=8191,ve=1;ve<10;ve++)M[ve]=this.h[ve]+j,j=M[ve]>>>13,M[ve]&=8191;for(M[9]-=8192,G=(j^1)-1,ve=0;ve<10;ve++)M[ve]&=G;for(G=~G,ve=0;ve<10;ve++)this.h[ve]=this.h[ve]&G|M[ve];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,he=this.h[0]+this.pad[0],this.h[0]=he&65535,ve=1;ve<8;ve++)he=(this.h[ve]+this.pad[ve]|0)+(he>>>16)|0,this.h[ve]=he&65535;E[R+0]=this.h[0]>>>0&255,E[R+1]=this.h[0]>>>8&255,E[R+2]=this.h[1]>>>0&255,E[R+3]=this.h[1]>>>8&255,E[R+4]=this.h[2]>>>0&255,E[R+5]=this.h[2]>>>8&255,E[R+6]=this.h[3]>>>0&255,E[R+7]=this.h[3]>>>8&255,E[R+8]=this.h[4]>>>0&255,E[R+9]=this.h[4]>>>8&255,E[R+10]=this.h[5]>>>0&255,E[R+11]=this.h[5]>>>8&255,E[R+12]=this.h[6]>>>0&255,E[R+13]=this.h[6]>>>8&255,E[R+14]=this.h[7]>>>0&255,E[R+15]=this.h[7]>>>8&255},D.prototype.update=function(E,R,M){var j,G;if(this.leftover){for(G=16-this.leftover,G>M&&(G=M),j=0;j<G;j++)this.buffer[this.leftover+j]=E[R+j];if(M-=G,R+=G,this.leftover+=G,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(M>=16&&(G=M-M%16,this.blocks(E,R,G),R+=G,M-=G),M){for(j=0;j<M;j++)this.buffer[this.leftover+j]=E[R+j];this.leftover+=M}};function P(E,R,M,j,G,he){var ve=new D(he);return ve.update(M,j,G),ve.finish(E,R),0}function T(E,R,M,j,G,he){var ve=new Uint8Array(16);return P(ve,0,M,j,G,he),v(E,R,ve,0)}function z(E,R,M,j,G){var he;if(M<32)return-1;for(I(E,0,R,0,M,j,G),P(E,16,E,32,M-32,E),he=0;he<16;he++)E[he]=0;return 0}function O(E,R,M,j,G){var he,ve=new Uint8Array(32);if(M<32||(A(ve,0,32,j,G),T(R,16,R,32,M-32,ve)!==0))return-1;for(I(E,0,R,0,M,j,G),he=0;he<32;he++)E[he]=0;return 0}function L(E,R){var M;for(M=0;M<16;M++)E[M]=R[M]|0}function V(E){var R,M,j=1;for(R=0;R<16;R++)M=E[R]+j+65535,j=Math.floor(M/65536),E[R]=M-j*65536;E[0]+=j-1+37*(j-1)}function X(E,R,M){for(var j,G=~(M-1),he=0;he<16;he++)j=G&(E[he]^R[he]),E[he]^=j,R[he]^=j}function F(E,R){var M,j,G,he=n(),ve=n();for(M=0;M<16;M++)ve[M]=R[M];for(V(ve),V(ve),V(ve),j=0;j<2;j++){for(he[0]=ve[0]-65517,M=1;M<15;M++)he[M]=ve[M]-65535-(he[M-1]>>16&1),he[M-1]&=65535;he[15]=ve[15]-32767-(he[14]>>16&1),G=he[15]>>16&1,he[14]&=65535,X(ve,he,1-G)}for(M=0;M<16;M++)E[2*M]=ve[M]&255,E[2*M+1]=ve[M]>>8}function ee(E,R){var M=new Uint8Array(32),j=new Uint8Array(32);return F(M,E),F(j,R),y(M,0,j,0)}function H(E){var R=new Uint8Array(32);return F(R,E),R[0]&1}function Q(E,R){var M;for(M=0;M<16;M++)E[M]=R[2*M]+(R[2*M+1]<<8);E[15]&=32767}function q(E,R,M){for(var j=0;j<16;j++)E[j]=R[j]+M[j]}function ne(E,R,M){for(var j=0;j<16;j++)E[j]=R[j]-M[j]}function me(E,R,M){var j,G,he=0,ve=0,Ae=0,Ke=0,ct=0,nt=0,Qt=0,dt=0,Dt=0,Ct=0,Et=0,It=0,bt=0,ce=0,Ee=0,Oe=0,We=0,qe=0,rt=0,tt=0,Xe=0,Ce=0,_e=0,He=0,Le=0,Re=0,Be=0,kt=0,Gt=0,Ht=0,Bt=0,ie=M[0],Kt=M[1],en=M[2],on=M[3],Lt=M[4],tn=M[5],nn=M[6],Dn=M[7],dn=M[8],Nn=M[9],Sn=M[10],xn=M[11],Hn=M[12],zn=M[13],qn=M[14],Y=M[15];j=R[0],he+=j*ie,ve+=j*Kt,Ae+=j*en,Ke+=j*on,ct+=j*Lt,nt+=j*tn,Qt+=j*nn,dt+=j*Dn,Dt+=j*dn,Ct+=j*Nn,Et+=j*Sn,It+=j*xn,bt+=j*Hn,ce+=j*zn,Ee+=j*qn,Oe+=j*Y,j=R[1],ve+=j*ie,Ae+=j*Kt,Ke+=j*en,ct+=j*on,nt+=j*Lt,Qt+=j*tn,dt+=j*nn,Dt+=j*Dn,Ct+=j*dn,Et+=j*Nn,It+=j*Sn,bt+=j*xn,ce+=j*Hn,Ee+=j*zn,Oe+=j*qn,We+=j*Y,j=R[2],Ae+=j*ie,Ke+=j*Kt,ct+=j*en,nt+=j*on,Qt+=j*Lt,dt+=j*tn,Dt+=j*nn,Ct+=j*Dn,Et+=j*dn,It+=j*Nn,bt+=j*Sn,ce+=j*xn,Ee+=j*Hn,Oe+=j*zn,We+=j*qn,qe+=j*Y,j=R[3],Ke+=j*ie,ct+=j*Kt,nt+=j*en,Qt+=j*on,dt+=j*Lt,Dt+=j*tn,Ct+=j*nn,Et+=j*Dn,It+=j*dn,bt+=j*Nn,ce+=j*Sn,Ee+=j*xn,Oe+=j*Hn,We+=j*zn,qe+=j*qn,rt+=j*Y,j=R[4],ct+=j*ie,nt+=j*Kt,Qt+=j*en,dt+=j*on,Dt+=j*Lt,Ct+=j*tn,Et+=j*nn,It+=j*Dn,bt+=j*dn,ce+=j*Nn,Ee+=j*Sn,Oe+=j*xn,We+=j*Hn,qe+=j*zn,rt+=j*qn,tt+=j*Y,j=R[5],nt+=j*ie,Qt+=j*Kt,dt+=j*en,Dt+=j*on,Ct+=j*Lt,Et+=j*tn,It+=j*nn,bt+=j*Dn,ce+=j*dn,Ee+=j*Nn,Oe+=j*Sn,We+=j*xn,qe+=j*Hn,rt+=j*zn,tt+=j*qn,Xe+=j*Y,j=R[6],Qt+=j*ie,dt+=j*Kt,Dt+=j*en,Ct+=j*on,Et+=j*Lt,It+=j*tn,bt+=j*nn,ce+=j*Dn,Ee+=j*dn,Oe+=j*Nn,We+=j*Sn,qe+=j*xn,rt+=j*Hn,tt+=j*zn,Xe+=j*qn,Ce+=j*Y,j=R[7],dt+=j*ie,Dt+=j*Kt,Ct+=j*en,Et+=j*on,It+=j*Lt,bt+=j*tn,ce+=j*nn,Ee+=j*Dn,Oe+=j*dn,We+=j*Nn,qe+=j*Sn,rt+=j*xn,tt+=j*Hn,Xe+=j*zn,Ce+=j*qn,_e+=j*Y,j=R[8],Dt+=j*ie,Ct+=j*Kt,Et+=j*en,It+=j*on,bt+=j*Lt,ce+=j*tn,Ee+=j*nn,Oe+=j*Dn,We+=j*dn,qe+=j*Nn,rt+=j*Sn,tt+=j*xn,Xe+=j*Hn,Ce+=j*zn,_e+=j*qn,He+=j*Y,j=R[9],Ct+=j*ie,Et+=j*Kt,It+=j*en,bt+=j*on,ce+=j*Lt,Ee+=j*tn,Oe+=j*nn,We+=j*Dn,qe+=j*dn,rt+=j*Nn,tt+=j*Sn,Xe+=j*xn,Ce+=j*Hn,_e+=j*zn,He+=j*qn,Le+=j*Y,j=R[10],Et+=j*ie,It+=j*Kt,bt+=j*en,ce+=j*on,Ee+=j*Lt,Oe+=j*tn,We+=j*nn,qe+=j*Dn,rt+=j*dn,tt+=j*Nn,Xe+=j*Sn,Ce+=j*xn,_e+=j*Hn,He+=j*zn,Le+=j*qn,Re+=j*Y,j=R[11],It+=j*ie,bt+=j*Kt,ce+=j*en,Ee+=j*on,Oe+=j*Lt,We+=j*tn,qe+=j*nn,rt+=j*Dn,tt+=j*dn,Xe+=j*Nn,Ce+=j*Sn,_e+=j*xn,He+=j*Hn,Le+=j*zn,Re+=j*qn,Be+=j*Y,j=R[12],bt+=j*ie,ce+=j*Kt,Ee+=j*en,Oe+=j*on,We+=j*Lt,qe+=j*tn,rt+=j*nn,tt+=j*Dn,Xe+=j*dn,Ce+=j*Nn,_e+=j*Sn,He+=j*xn,Le+=j*Hn,Re+=j*zn,Be+=j*qn,kt+=j*Y,j=R[13],ce+=j*ie,Ee+=j*Kt,Oe+=j*en,We+=j*on,qe+=j*Lt,rt+=j*tn,tt+=j*nn,Xe+=j*Dn,Ce+=j*dn,_e+=j*Nn,He+=j*Sn,Le+=j*xn,Re+=j*Hn,Be+=j*zn,kt+=j*qn,Gt+=j*Y,j=R[14],Ee+=j*ie,Oe+=j*Kt,We+=j*en,qe+=j*on,rt+=j*Lt,tt+=j*tn,Xe+=j*nn,Ce+=j*Dn,_e+=j*dn,He+=j*Nn,Le+=j*Sn,Re+=j*xn,Be+=j*Hn,kt+=j*zn,Gt+=j*qn,Ht+=j*Y,j=R[15],Oe+=j*ie,We+=j*Kt,qe+=j*en,rt+=j*on,tt+=j*Lt,Xe+=j*tn,Ce+=j*nn,_e+=j*Dn,He+=j*dn,Le+=j*Nn,Re+=j*Sn,Be+=j*xn,kt+=j*Hn,Gt+=j*zn,Ht+=j*qn,Bt+=j*Y,he+=38*We,ve+=38*qe,Ae+=38*rt,Ke+=38*tt,ct+=38*Xe,nt+=38*Ce,Qt+=38*_e,dt+=38*He,Dt+=38*Le,Ct+=38*Re,Et+=38*Be,It+=38*kt,bt+=38*Gt,ce+=38*Ht,Ee+=38*Bt,G=1,j=he+G+65535,G=Math.floor(j/65536),he=j-G*65536,j=ve+G+65535,G=Math.floor(j/65536),ve=j-G*65536,j=Ae+G+65535,G=Math.floor(j/65536),Ae=j-G*65536,j=Ke+G+65535,G=Math.floor(j/65536),Ke=j-G*65536,j=ct+G+65535,G=Math.floor(j/65536),ct=j-G*65536,j=nt+G+65535,G=Math.floor(j/65536),nt=j-G*65536,j=Qt+G+65535,G=Math.floor(j/65536),Qt=j-G*65536,j=dt+G+65535,G=Math.floor(j/65536),dt=j-G*65536,j=Dt+G+65535,G=Math.floor(j/65536),Dt=j-G*65536,j=Ct+G+65535,G=Math.floor(j/65536),Ct=j-G*65536,j=Et+G+65535,G=Math.floor(j/65536),Et=j-G*65536,j=It+G+65535,G=Math.floor(j/65536),It=j-G*65536,j=bt+G+65535,G=Math.floor(j/65536),bt=j-G*65536,j=ce+G+65535,G=Math.floor(j/65536),ce=j-G*65536,j=Ee+G+65535,G=Math.floor(j/65536),Ee=j-G*65536,j=Oe+G+65535,G=Math.floor(j/65536),Oe=j-G*65536,he+=G-1+37*(G-1),G=1,j=he+G+65535,G=Math.floor(j/65536),he=j-G*65536,j=ve+G+65535,G=Math.floor(j/65536),ve=j-G*65536,j=Ae+G+65535,G=Math.floor(j/65536),Ae=j-G*65536,j=Ke+G+65535,G=Math.floor(j/65536),Ke=j-G*65536,j=ct+G+65535,G=Math.floor(j/65536),ct=j-G*65536,j=nt+G+65535,G=Math.floor(j/65536),nt=j-G*65536,j=Qt+G+65535,G=Math.floor(j/65536),Qt=j-G*65536,j=dt+G+65535,G=Math.floor(j/65536),dt=j-G*65536,j=Dt+G+65535,G=Math.floor(j/65536),Dt=j-G*65536,j=Ct+G+65535,G=Math.floor(j/65536),Ct=j-G*65536,j=Et+G+65535,G=Math.floor(j/65536),Et=j-G*65536,j=It+G+65535,G=Math.floor(j/65536),It=j-G*65536,j=bt+G+65535,G=Math.floor(j/65536),bt=j-G*65536,j=ce+G+65535,G=Math.floor(j/65536),ce=j-G*65536,j=Ee+G+65535,G=Math.floor(j/65536),Ee=j-G*65536,j=Oe+G+65535,G=Math.floor(j/65536),Oe=j-G*65536,he+=G-1+37*(G-1),E[0]=he,E[1]=ve,E[2]=Ae,E[3]=Ke,E[4]=ct,E[5]=nt,E[6]=Qt,E[7]=dt,E[8]=Dt,E[9]=Ct,E[10]=Et,E[11]=It,E[12]=bt,E[13]=ce,E[14]=Ee,E[15]=Oe}function ke(E,R){me(E,R,R)}function Me(E,R){var M=n(),j;for(j=0;j<16;j++)M[j]=R[j];for(j=253;j>=0;j--)ke(M,M),j!==2&&j!==4&&me(M,M,R);for(j=0;j<16;j++)E[j]=M[j]}function ge(E,R){var M=n(),j;for(j=0;j<16;j++)M[j]=R[j];for(j=250;j>=0;j--)ke(M,M),j!==1&&me(M,M,R);for(j=0;j<16;j++)E[j]=M[j]}function $(E,R,M){var j=new Uint8Array(32),G=new Float64Array(80),he,ve,Ae=n(),Ke=n(),ct=n(),nt=n(),Qt=n(),dt=n();for(ve=0;ve<31;ve++)j[ve]=R[ve];for(j[31]=R[31]&127|64,j[0]&=248,Q(G,M),ve=0;ve<16;ve++)Ke[ve]=G[ve],nt[ve]=Ae[ve]=ct[ve]=0;for(Ae[0]=nt[0]=1,ve=254;ve>=0;--ve)he=j[ve>>>3]>>>(ve&7)&1,X(Ae,Ke,he),X(ct,nt,he),q(Qt,Ae,ct),ne(Ae,Ae,ct),q(ct,Ke,nt),ne(Ke,Ke,nt),ke(nt,Qt),ke(dt,Ae),me(Ae,ct,Ae),me(ct,Ke,Qt),q(Qt,Ae,ct),ne(Ae,Ae,ct),ke(Ke,Ae),ne(ct,nt,dt),me(Ae,ct,c),q(Ae,Ae,nt),me(ct,ct,Ae),me(Ae,nt,dt),me(nt,Ke,G),ke(Ke,Qt),X(Ae,Ke,he),X(ct,nt,he);for(ve=0;ve<16;ve++)G[ve+16]=Ae[ve],G[ve+32]=ct[ve],G[ve+48]=Ke[ve],G[ve+64]=nt[ve];var Dt=G.subarray(32),Ct=G.subarray(16);return Me(Dt,Dt),me(Ct,Ct,Dt),F(E,Ct),0}function W(E,R){return $(E,R,r)}function ue(E,R){return s(R,32),W(E,R)}function Z(E,R,M){var j=new Uint8Array(32);return $(j,M,R),_(E,o,j,N)}var J=z,ae=O;function te(E,R,M,j,G,he){var ve=new Uint8Array(32);return Z(ve,G,he),J(E,R,M,j,ve)}function pe(E,R,M,j,G,he){var ve=new Uint8Array(32);return Z(ve,G,he),ae(E,R,M,j,ve)}var Te=[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 $e(E,R,M,j){for(var G=new Int32Array(16),he=new Int32Array(16),ve,Ae,Ke,ct,nt,Qt,dt,Dt,Ct,Et,It,bt,ce,Ee,Oe,We,qe,rt,tt,Xe,Ce,_e,He,Le,Re,Be,kt=E[0],Gt=E[1],Ht=E[2],Bt=E[3],ie=E[4],Kt=E[5],en=E[6],on=E[7],Lt=R[0],tn=R[1],nn=R[2],Dn=R[3],dn=R[4],Nn=R[5],Sn=R[6],xn=R[7],Hn=0;j>=128;){for(tt=0;tt<16;tt++)Xe=8*tt+Hn,G[tt]=M[Xe+0]<<24|M[Xe+1]<<16|M[Xe+2]<<8|M[Xe+3],he[tt]=M[Xe+4]<<24|M[Xe+5]<<16|M[Xe+6]<<8|M[Xe+7];for(tt=0;tt<80;tt++)if(ve=kt,Ae=Gt,Ke=Ht,ct=Bt,nt=ie,Qt=Kt,dt=en,Dt=on,Ct=Lt,Et=tn,It=nn,bt=Dn,ce=dn,Ee=Nn,Oe=Sn,We=xn,Ce=on,_e=xn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=(ie>>>14|dn<<18)^(ie>>>18|dn<<14)^(dn>>>9|ie<<23),_e=(dn>>>14|ie<<18)^(dn>>>18|ie<<14)^(ie>>>9|dn<<23),He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Ce=ie&Kt^~ie&en,_e=dn&Nn^~dn&Sn,He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Ce=Te[tt*2],_e=Te[tt*2+1],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Ce=G[tt%16],_e=he[tt%16],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,qe=Re&65535|Be<<16,rt=He&65535|Le<<16,Ce=qe,_e=rt,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=(kt>>>28|Lt<<4)^(Lt>>>2|kt<<30)^(Lt>>>7|kt<<25),_e=(Lt>>>28|kt<<4)^(kt>>>2|Lt<<30)^(kt>>>7|Lt<<25),He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Ce=kt&Gt^kt&Ht^Gt&Ht,_e=Lt&tn^Lt&nn^tn&nn,He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,Dt=Re&65535|Be<<16,We=He&65535|Le<<16,Ce=ct,_e=bt,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=qe,_e=rt,He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,ct=Re&65535|Be<<16,bt=He&65535|Le<<16,Gt=ve,Ht=Ae,Bt=Ke,ie=ct,Kt=nt,en=Qt,on=dt,kt=Dt,tn=Ct,nn=Et,Dn=It,dn=bt,Nn=ce,Sn=Ee,xn=Oe,Lt=We,tt%16===15)for(Xe=0;Xe<16;Xe++)Ce=G[Xe],_e=he[Xe],He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=G[(Xe+9)%16],_e=he[(Xe+9)%16],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,qe=G[(Xe+1)%16],rt=he[(Xe+1)%16],Ce=(qe>>>1|rt<<31)^(qe>>>8|rt<<24)^qe>>>7,_e=(rt>>>1|qe<<31)^(rt>>>8|qe<<24)^(rt>>>7|qe<<25),He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,qe=G[(Xe+14)%16],rt=he[(Xe+14)%16],Ce=(qe>>>19|rt<<13)^(rt>>>29|qe<<3)^qe>>>6,_e=(rt>>>19|qe<<13)^(qe>>>29|rt<<3)^(rt>>>6|qe<<26),He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,G[Xe]=Re&65535|Be<<16,he[Xe]=He&65535|Le<<16;Ce=kt,_e=Lt,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[0],_e=R[0],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[0]=kt=Re&65535|Be<<16,R[0]=Lt=He&65535|Le<<16,Ce=Gt,_e=tn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[1],_e=R[1],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[1]=Gt=Re&65535|Be<<16,R[1]=tn=He&65535|Le<<16,Ce=Ht,_e=nn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[2],_e=R[2],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[2]=Ht=Re&65535|Be<<16,R[2]=nn=He&65535|Le<<16,Ce=Bt,_e=Dn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[3],_e=R[3],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[3]=Bt=Re&65535|Be<<16,R[3]=Dn=He&65535|Le<<16,Ce=ie,_e=dn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[4],_e=R[4],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[4]=ie=Re&65535|Be<<16,R[4]=dn=He&65535|Le<<16,Ce=Kt,_e=Nn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[5],_e=R[5],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[5]=Kt=Re&65535|Be<<16,R[5]=Nn=He&65535|Le<<16,Ce=en,_e=Sn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[6],_e=R[6],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[6]=en=Re&65535|Be<<16,R[6]=Sn=He&65535|Le<<16,Ce=on,_e=xn,He=_e&65535,Le=_e>>>16,Re=Ce&65535,Be=Ce>>>16,Ce=E[7],_e=R[7],He+=_e&65535,Le+=_e>>>16,Re+=Ce&65535,Be+=Ce>>>16,Le+=He>>>16,Re+=Le>>>16,Be+=Re>>>16,E[7]=on=Re&65535|Be<<16,R[7]=xn=He&65535|Le<<16,Hn+=128,j-=128}return j}function Ie(E,R,M){var j=new Int32Array(8),G=new Int32Array(8),he=new Uint8Array(256),ve,Ae=M;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,$e(j,G,R,M),M%=128,ve=0;ve<M;ve++)he[ve]=R[Ae-M+ve];for(he[M]=128,M=256-128*(M<112?1:0),he[M-9]=0,g(he,M-8,Ae/536870912|0,Ae<<3),$e(j,G,he,M),ve=0;ve<8;ve++)g(E,8*ve,j[ve],G[ve]);return 0}function Ze(E,R){var M=n(),j=n(),G=n(),he=n(),ve=n(),Ae=n(),Ke=n(),ct=n(),nt=n();ne(M,E[1],E[0]),ne(nt,R[1],R[0]),me(M,M,nt),q(j,E[0],E[1]),q(nt,R[0],R[1]),me(j,j,nt),me(G,E[3],R[3]),me(G,G,u),me(he,E[2],R[2]),q(he,he,he),ne(ve,j,M),ne(Ae,he,G),q(Ke,he,G),q(ct,j,M),me(E[0],ve,Ae),me(E[1],ct,Ke),me(E[2],Ke,Ae),me(E[3],ve,ct)}function Nt(E,R,M){var j;for(j=0;j<4;j++)X(E[j],R[j],M)}function Ut(E,R){var M=n(),j=n(),G=n();Me(G,R[2]),me(M,R[0],G),me(j,R[1],G),F(E,j),E[31]^=H(M)<<7}function Pt(E,R,M){var j,G;for(L(E[0],a),L(E[1],l),L(E[2],l),L(E[3],a),G=255;G>=0;--G)j=M[G/8|0]>>(G&7)&1,Nt(E,R,j),Ze(R,E),Ze(E,E),Nt(E,R,j)}function _t(E,R){var M=[n(),n(),n(),n()];L(M[0],h),L(M[1],p),L(M[2],l),me(M[3],h,p),Pt(E,M,R)}function B(E,R,M){var j=new Uint8Array(64),G=[n(),n(),n(),n()],he;for(M||s(R,32),Ie(j,R,32),j[0]&=248,j[31]&=127,j[31]|=64,_t(G,j),Ut(E,G),he=0;he<32;he++)R[he+32]=E[he];return 0}var je=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 Ye(E,R){var M,j,G,he;for(j=63;j>=32;--j){for(M=0,G=j-32,he=j-12;G<he;++G)R[G]+=M-16*R[j]*je[G-(j-32)],M=Math.floor((R[G]+128)/256),R[G]-=M*256;R[G]+=M,R[j]=0}for(M=0,G=0;G<32;G++)R[G]+=M-(R[31]>>4)*je[G],M=R[G]>>8,R[G]&=255;for(G=0;G<32;G++)R[G]-=M*je[G];for(j=0;j<32;j++)R[j+1]+=R[j]>>8,E[j]=R[j]&255}function Tt(E){var R=new Float64Array(64),M;for(M=0;M<64;M++)R[M]=E[M];for(M=0;M<64;M++)E[M]=0;Ye(E,R)}function Wt(E,R,M,j){var G=new Uint8Array(64),he=new Uint8Array(64),ve=new Uint8Array(64),Ae,Ke,ct=new Float64Array(64),nt=[n(),n(),n(),n()];Ie(G,j,32),G[0]&=248,G[31]&=127,G[31]|=64;var Qt=M+64;for(Ae=0;Ae<M;Ae++)E[64+Ae]=R[Ae];for(Ae=0;Ae<32;Ae++)E[32+Ae]=G[32+Ae];for(Ie(ve,E.subarray(32),M+32),Tt(ve),_t(nt,ve),Ut(E,nt),Ae=32;Ae<64;Ae++)E[Ae]=j[Ae];for(Ie(he,E,M+64),Tt(he),Ae=0;Ae<64;Ae++)ct[Ae]=0;for(Ae=0;Ae<32;Ae++)ct[Ae]=ve[Ae];for(Ae=0;Ae<32;Ae++)for(Ke=0;Ke<32;Ke++)ct[Ae+Ke]+=he[Ae]*G[Ke];return Ye(E.subarray(32),ct),Qt}function le(E,R){var M=n(),j=n(),G=n(),he=n(),ve=n(),Ae=n(),Ke=n();return L(E[2],l),Q(E[1],R),ke(G,E[1]),me(he,G,d),ne(G,G,E[2]),q(he,E[2],he),ke(ve,he),ke(Ae,ve),me(Ke,Ae,ve),me(M,Ke,G),me(M,M,he),ge(M,M),me(M,M,G),me(M,M,he),me(M,M,he),me(E[0],M,he),ke(j,E[0]),me(j,j,he),ee(j,G)&&me(E[0],E[0],f),ke(j,E[0]),me(j,j,he),ee(j,G)?-1:(H(E[0])===R[31]>>7&&ne(E[0],a,E[0]),me(E[3],E[0],E[1]),0)}function ht(E,R,M,j){var G,he=new Uint8Array(32),ve=new Uint8Array(64),Ae=[n(),n(),n(),n()],Ke=[n(),n(),n(),n()];if(M<64||le(Ke,j))return-1;for(G=0;G<M;G++)E[G]=R[G];for(G=0;G<32;G++)E[G+32]=j[G];if(Ie(ve,E,M),Tt(ve),Pt(Ae,Ke,ve),_t(Ke,R.subarray(32)),Ze(Ae,Ke),Ut(he,Ae),M-=64,y(R,0,he,0)){for(G=0;G<M;G++)E[G]=0;return-1}for(G=0;G<M;G++)E[G]=R[G+64];return M}var Ot=32,Fe=24,jt=32,Ft=16,cn=32,re=32,Ue=32,ut=32,xt=32,pt=Fe,K=jt,fe=Ft,De=64,Pe=32,Ge=64,st=32,we=64;t.lowlevel={crypto_core_hsalsa20:_,crypto_stream_xor:I,crypto_stream:A,crypto_stream_salsa20_xor:S,crypto_stream_salsa20:k,crypto_onetimeauth:P,crypto_onetimeauth_verify:T,crypto_verify_16:v,crypto_verify_32:y,crypto_secretbox:z,crypto_secretbox_open:O,crypto_scalarmult:$,crypto_scalarmult_base:W,crypto_box_beforenm:Z,crypto_box_afternm:J,crypto_box:te,crypto_box_open:pe,crypto_box_keypair:ue,crypto_hash:Ie,crypto_sign:Wt,crypto_sign_keypair:B,crypto_sign_open:ht,crypto_secretbox_KEYBYTES:Ot,crypto_secretbox_NONCEBYTES:Fe,crypto_secretbox_ZEROBYTES:jt,crypto_secretbox_BOXZEROBYTES:Ft,crypto_scalarmult_BYTES:cn,crypto_scalarmult_SCALARBYTES:re,crypto_box_PUBLICKEYBYTES:Ue,crypto_box_SECRETKEYBYTES:ut,crypto_box_BEFORENMBYTES:xt,crypto_box_NONCEBYTES:pt,crypto_box_ZEROBYTES:K,crypto_box_BOXZEROBYTES:fe,crypto_sign_BYTES:De,crypto_sign_PUBLICKEYBYTES:Pe,crypto_sign_SECRETKEYBYTES:Ge,crypto_sign_SEEDBYTES:st,crypto_hash_BYTES:we,gf:n,D:d,L:je,pack25519:F,unpack25519:Q,M:me,A:q,S:ke,Z:ne,pow2523:ge,add:Ze,set25519:L,modL:Ye,scalarmult:Pt,scalarbase:_t};function Qe(E,R){if(E.length!==Ot)throw new Error("bad key size");if(R.length!==Fe)throw new Error("bad nonce size")}function it(E,R){if(E.length!==Ue)throw new Error("bad public key size");if(R.length!==ut)throw new Error("bad secret key size")}function yt(){for(var E=0;E<arguments.length;E++)if(!(arguments[E]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Xt(E){for(var R=0;R<E.length;R++)E[R]=0}t.randomBytes=function(E){var R=new Uint8Array(E);return s(R,E),R},t.secretbox=function(E,R,M){yt(E,R,M),Qe(M,R);for(var j=new Uint8Array(jt+E.length),G=new Uint8Array(j.length),he=0;he<E.length;he++)j[he+jt]=E[he];return z(G,j,j.length,R,M),G.subarray(Ft)},t.secretbox.open=function(E,R,M){yt(E,R,M),Qe(M,R);for(var j=new Uint8Array(Ft+E.length),G=new Uint8Array(j.length),he=0;he<E.length;he++)j[he+Ft]=E[he];return j.length<32||O(G,j,j.length,R,M)!==0?null:G.subarray(jt)},t.secretbox.keyLength=Ot,t.secretbox.nonceLength=Fe,t.secretbox.overheadLength=Ft,t.scalarMult=function(E,R){if(yt(E,R),E.length!==re)throw new Error("bad n size");if(R.length!==cn)throw new Error("bad p size");var M=new Uint8Array(cn);return $(M,E,R),M},t.scalarMult.base=function(E){if(yt(E),E.length!==re)throw new Error("bad n size");var R=new Uint8Array(cn);return W(R,E),R},t.scalarMult.scalarLength=re,t.scalarMult.groupElementLength=cn,t.box=function(E,R,M,j){var G=t.box.before(M,j);return t.secretbox(E,R,G)},t.box.before=function(E,R){yt(E,R),it(E,R);var M=new Uint8Array(xt);return Z(M,E,R),M},t.box.after=t.secretbox,t.box.open=function(E,R,M,j){var G=t.box.before(M,j);return t.secretbox.open(E,R,G)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var E=new Uint8Array(Ue),R=new Uint8Array(ut);return ue(E,R),{publicKey:E,secretKey:R}},t.box.keyPair.fromSecretKey=function(E){if(yt(E),E.length!==ut)throw new Error("bad secret key size");var R=new Uint8Array(Ue);return W(R,E),{publicKey:R,secretKey:new Uint8Array(E)}},t.box.publicKeyLength=Ue,t.box.secretKeyLength=ut,t.box.sharedKeyLength=xt,t.box.nonceLength=pt,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(E,R){if(yt(E,R),R.length!==Ge)throw new Error("bad secret key size");var M=new Uint8Array(De+E.length);return Wt(M,E,E.length,R),M},t.sign.open=function(E,R){if(yt(E,R),R.length!==Pe)throw new Error("bad public key size");var M=new Uint8Array(E.length),j=ht(M,E,E.length,R);if(j<0)return null;for(var G=new Uint8Array(j),he=0;he<G.length;he++)G[he]=M[he];return G},t.sign.detached=function(E,R){for(var M=t.sign(E,R),j=new Uint8Array(De),G=0;G<j.length;G++)j[G]=M[G];return j},t.sign.detached.verify=function(E,R,M){if(yt(E,R,M),R.length!==De)throw new Error("bad signature size");if(M.length!==Pe)throw new Error("bad public key size");var j=new Uint8Array(De+E.length),G=new Uint8Array(De+E.length),he;for(he=0;he<De;he++)j[he]=R[he];for(he=0;he<E.length;he++)j[he+De]=E[he];return ht(G,j,j.length,M)>=0},t.sign.keyPair=function(){var E=new Uint8Array(Pe),R=new Uint8Array(Ge);return B(E,R),{publicKey:E,secretKey:R}},t.sign.keyPair.fromSecretKey=function(E){if(yt(E),E.length!==Ge)throw new Error("bad secret key size");for(var R=new Uint8Array(Pe),M=0;M<R.length;M++)R[M]=E[32+M];return{publicKey:R,secretKey:new Uint8Array(E)}},t.sign.keyPair.fromSeed=function(E){if(yt(E),E.length!==st)throw new Error("bad seed size");for(var R=new Uint8Array(Pe),M=new Uint8Array(Ge),j=0;j<32;j++)M[j]=E[j];return B(R,M,!0),{publicKey:R,secretKey:M}},t.sign.publicKeyLength=Pe,t.sign.secretKeyLength=Ge,t.sign.seedLength=st,t.sign.signatureLength=De,t.hash=function(E){yt(E);var R=new Uint8Array(we);return Ie(R,E,E.length),R},t.hash.hashLength=we,t.verify=function(E,R){return yt(E,R),E.length===0||R.length===0||E.length!==R.length?!1:x(E,0,R,0,E.length)===0},t.setPRNG=function(E){s=E},(function(){var E=typeof self<"u"?self.crypto||self.msCrypto:null;if(E&&E.getRandomValues){var R=65536;t.setPRNG(function(M,j){var G,he=new Uint8Array(j);for(G=0;G<j;G+=R)E.getRandomValues(he.subarray(G,G+Math.min(j-G,R)));for(G=0;G<j;G++)M[G]=he[G];Xt(he)})}else typeof ise<"u"&&(E=ase,E&&E.randomBytes&&t.setPRNG(function(M,j){var G,he=E.randomBytes(j);for(G=0;G<j;G++)M[G]=he[G];Xt(he)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})(mf)),mf.exports}lse();new TextEncoder;new TextDecoder;function cse(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 dse(e){return e.kind!=="ssh"?void 0:e.sshConnectionName?.trim()||e.sshHost}function BE(e){return e.alias?.trim()||e.name}function AC(e){const t=BE(e),n=dse(e);return n?`${t} (${n})`:t}const ud={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},MC={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"};function use({open:e,onOpenChange:t,projects:n,providers:s,onCreate:o}){const{t:r}=se(),a=ye(P=>P.approvalReviewer),l=ye(P=>P.lastApprovalMode),c=Ca(),d=yo(P=>P.snapshot),u=m.useMemo(()=>tO(a,c,Ll(d),l),[a,l,c,d]),[h,p]=m.useState(null),[f,g]=m.useState(null),[x,v]=m.useState(null),[y,b]=m.useState(u),[w,C]=m.useState(!1),[_,N]=m.useState("medium");m.useEffect(()=>{e&&(p(null),g(null),v(null),b(u))},[e,u]);const S=n.find(P=>P.id===h)?.id??n[0]?.id??"",k=s.find(P=>P.id===f)??s[0]??{id:"",models:[]},A=k.models.find(P=>P.id===x)?.id??k.models[0]?.id??"",I=!!(S&&k.id&&A),D=()=>{I&&(ye.getState().setLastApprovalMode(y),o({projectId:S,providerId:k.id,modelId:A,approvalMode:y,...w?{reasoningEnabled:!0,thinkingLevel:_}:{}}),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(qa,{label:r("Project"),children:i.jsxs(vs,{items:n.map(P=>({value:P.id,label:AC(P)})),value:S,onValueChange:P=>p(P),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:n.map(P=>i.jsx(os,{value:P.id,children:AC(P)},P.id))})]})}),i.jsx(qa,{label:r("Provider"),children:i.jsxs(vs,{items:s.map(P=>({value:P.id,label:P.name})),value:k.id,onValueChange:P=>{g(P),v(null)},children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:s.map(P=>i.jsx(os,{value:P.id,children:P.name},P.id))})]})}),i.jsx(qa,{label:r("Model"),children:i.jsxs(vs,{items:k.models.map(P=>({value:P.id,label:P.label??P.id})),value:A,onValueChange:P=>v(P),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:k.models.map(P=>i.jsx(os,{value:P.id,children:P.label??P.id},P.id))})]})}),i.jsx(qa,{label:r("Approval mode"),children:i.jsxs(vs,{items:Object.keys(ud).map(P=>({value:P,label:r(ud[P])})),value:y,onValueChange:P=>b(P),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:Object.keys(ud).map(P=>i.jsx(os,{value:P,children:r(ud[P])},P))})]})}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:r("Reasoning")}),i.jsx(di,{checked:w,onCheckedChange:C})]}),w&&i.jsx(qa,{label:r("Thinking level"),children:i.jsxs(vs,{items:$f.map(P=>({value:P,label:r(MC[P])})),value:_,onValueChange:P=>N(P),children:[i.jsx(bs,{className:"w-full",children:i.jsx(ws,{})}),i.jsx(ys,{zIndex:Cn.DROPDOWN_IN_MODAL,children:$f.map(P=>i.jsx(os,{value:P,children:r(MC[P])},P))})]})})]}),i.jsxs(rs,{children:[i.jsx(xe,{variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(xe,{size:"sm",disabled:!I,onClick:D,children:r("Create")})]})]})})}function qa({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 hse(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 pse(e){return $f.includes(e??"")?e:"medium"}function fse(e){const{t}=se(),{node:n,sessionId:s,entry:o,view:r,syncing:a}=e,l=m.useRef(null),c=r?.status==="running",d=m.useMemo(()=>r?[...r.messages.entries()].sort((v,y)=>v[0]-y[0]):[],[r]),u=m.useMemo(()=>d.map(([,v])=>v),[d]),h=m.useMemo(()=>wr(u,c,[],o?.cwd,{pendingApprovals:r?.approvals,compaction:r?.compaction,compactionNoticeAt:nO(d.map(([v])=>v),r?.compactionNoticeAt)}),[u,d,c,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(()=>hse(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(Ih.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(sO,{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(iO,{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(RC,{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(yr,{className:"h-3 w-3 shrink-0"})}),e.tabGroup.children.map(v=>i.jsx(RC,{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(Ah,{ref:l,items:h,busy:c||r===null,loading:!c&&r===null,running:c,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(Fh,{retry:r.retry}),i.jsx(Lv,{sessionId:s,tasks:r?.tasks??[],subagents:r?.subagents??[]},s),i.jsx(jh,{approvals:r?.approvals??[],onRespond:e.onApproval}),i.jsx(_h,{asks:r?.asks??[],onAnswer:e.onAsk}),i.jsx(Mv,{commands:[],running:c,busy:c,locked:(r?.approvals??[]).length>0,focusKey:`${n.nodeId}:${s}`,toolbar:g&&o?i.jsx(ch,{providers:f,providerId:o.providerId??"",modelId:o.modelId??"",reasoningEnabled:o.reasoningEnabled??!1,thinkingLevel:pse(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 RC({active:e,icon:t,label:n,status:s,onClick:o}){return i.jsxs("button",{type:"button",onClick:o,className:U("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:U("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 Bu(e){return[...e].sort((t,n)=>(n.updatedAt??0)-(t.updatedAt??0))}function VE(e){const t=n=>(n.pendingAskCount??0)>0||(n.pendingApprovalCount??0)>0;return[...e.filter(t),...e.filter(n=>!t(n))]}function mse(e,t){const n=Bu(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,...VE([...s.values()])]}function LC(e){return VE([...Bu(e.filter(t=>t.pinned)),...Bu(e.filter(t=>!t.pinned))])}const gf="flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function gse({width:e,node:t,catalog:n,pinnedOrder:s,projects:o,groups:r=[],activeId:a,canCreate:l,onSelect:c,onNewConversation:d,onAddProject:u}){const{t:h,locale:p}=se(),[f,g]=m.useState(In),[x,v]=m.useState(""),[y,b]=m.useState({}),[w,C]=m.useState(!1),[_,N]=m.useState(()=>Date.now());m.useEffect(()=>{const F=setInterval(()=>N(Date.now()),6e4);return()=>clearInterval(F)},[]);const S=f===In||f===hs||r.some(F=>F.id===f)?f:In,k=o.filter(F=>F.archived).map(F=>F.id),A=Fr(o,r,k,S),I=new Set(A.map(F=>F.id)),D=x.trim().toLowerCase(),P=m.useMemo(()=>n.filter(F=>!F.parentId&&(!D||F.title.toLowerCase().includes(D))),[n,D]),T=mse(P.filter(F=>F.pinned&&!F.archived&&(!F.projectId||I.has(F.projectId))),s),z=Bu(P.filter(F=>F.archived?S===In?!0:!!(F.projectId&&I.has(F.projectId)):!1)),O=P.filter(F=>!F.archived),L=new Set(o.map(F=>F.id)),V=LC(O.filter(F=>!L.has(F.projectId))),X=(F,ee)=>i.jsxs("button",{type:"button",onClick:()=>c(F.id),className:U("group flex w-full items-center gap-2 rounded-lg py-1.5 pr-2 pl-4 text-left text-sm transition-colors",a===F.id?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted/60"),children:[i.jsx("span",{className:U("h-2 w-2 shrink-0 rounded-full",F.status==="running"&&"animate-pulse bg-brand",F.status==="failed"&&"bg-destructive",F.status==="idle"&&(F.unread?"bg-emerald-500":"bg-muted-foreground/30"))}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[F.title||h("New conversation"),ee&&i.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:ee})]}),F.updatedAt!==void 0&&i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/80 tabular-nums",children:Bo(F.updatedAt,p,_)})]},F.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:U("shrink-0 px-2 py-2",r.length===0&&"border-b"),children:i.jsxs("div",{className:"relative",children:[i.jsx(ei,{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:F=>v(F.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((F,ee)=>F.order-ee.order).map(F=>({value:F.id,label:F.name})),{value:hs,label:h("Ungrouped")}],value:S,onValueChange:F=>{F&&g(F)},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((F,ee)=>F.order-ee.order).map(F=>i.jsx(os,{value:F.id,children:F.name},F.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(ci,{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(F=>X(F,F.projectName))})]}),(S===In&&r.length>0?N_(o,r,k).flatMap(F=>{const ee=y[`g:${F.groupId}`]===!0;return[{kind:"header",section:F,foldedSection:ee},...ee?[]:F.projects.map(H=>({kind:"project",project:H}))]}):A.map(F=>({kind:"project",project:F}))).map(F=>{if(F.kind==="header")return i.jsxs("button",{type:"button",onClick:()=>b(q=>({...q,[`g:${F.section.groupId}`]:!q[`g:${F.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:U("h-3.5 w-3.5 shrink-0 transition-transform duration-150",!F.foldedSection&&"rotate-90")}),F.section.group?.emoji&&i.jsx("span",{className:"shrink-0 text-sm",children:F.section.group.emoji}),F.section.group?.color&&i.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:F.section.group.color}}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:F.section.group?.name??h("Ungrouped")}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/70",children:F.section.projects.length})]},`hdr-${F.section.groupId}`);const{project:ee}=F,H=LC(O.filter(q=>q.projectId===ee.id&&!q.pinned));if(D&&H.length===0)return null;const Q=y[ee.id]===!0;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>b(q=>({...q,[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(Vn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children: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:[H.length===0&&i.jsx("p",{className:"px-4 py-1.5 text-muted-foreground text-xs",children:h("No conversations")}),H.map(q=>X(q))]})]},ee.id)}),V.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:V.map(F=>X(F))})]}),z.length>0&&i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>C(F=>!F),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(Mi,{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:z.length})]}),w&&i.jsx("div",{className:"flex flex-col gap-y-0.5",children:z.map(F=>X(F,F.projectName))})]})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[i.jsx(T_,{}),i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.nodes.openSettings(t.nodeId)},disabled:!t.hostOnline,className:U(gf,!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:U(gf,!t.hostOnline&&"opacity-40"),title:h("Add project"),children:i.jsx(yu,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:d,disabled:!l,className:U(gf,!l&&"opacity-40"),title:h("New remote conversation"),children:i.jsx(WN,{className:"h-4 w-4"})})]})]})}function xse({nodeId:e,sidebarWidth:t}){const n=is(b=>b.nodes.find(w=>w.nodeId===e)),s=is(b=>b.byNode[e])??vse,o=is(b=>b.selectSession),r=is(b=>b.send),a=is(b=>b.requestHistory),l=is(b=>b.spawn),[c,d]=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(C=>C.id===f.parentId):f;if(!b)return;const w=s.catalog.filter(C=>C.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(gse,{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:()=>d(!0),onAddProject:()=>h(!0)}),i.jsx(fse,{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(use,{open:c,onOpenChange:d,projects:s.projects,providers:s.providers,onCreate:b=>l(e,b)}),i.jsx(sse,{nodeId:e,open:u,onOpenChange:h})]})}const vse=oO(),xf=["welcome","provider","skill","mcp","instruction","preset","agentType","done"];function bse(){const{t:e}=se();Ig();const t=ye(N=>N.setOnboarded),n=Ca(),s=ye(N=>N.skills),o=ye(N=>N.mcpServers),r=ye(N=>N.instructions),a=ye(N=>N.presets),[l,c]=m.useState(0),[d,u]=m.useState(null),[h,p]=m.useState(!1),[f,g]=m.useState(!1),[x,v]=m.useState(!1),y=xf[l],b=()=>t(!0),w=()=>c(N=>Math.min(xf.length-1,N+1)),C=()=>c(N=>Math.max(0,N-1)),_={provider:{icon:aO,title:e("Model Providers"),desc:e("Add a provider subscription or API Key, or import providers from local AI apps"),count:n.length,onImport:()=>g(!0),importLabel:e("Add model or provider"),secondary:{label:e("Import from local apps"),onClick:()=>p(!0)}},skill:{icon:ti,title:e("Skills"),desc:e("Import skills from Claude Code, Codex or Cursor"),count:s.length,onImport:()=>u("skill"),importLabel:e("Scan and import")},mcp:{icon:qk,title:e("MCP Servers"),desc:e("Import MCP servers configured in local AI apps"),count:o.length,onImport:()=>u("mcp"),importLabel:e("Scan and import")},instruction:{icon:Qd,title:e("Instruction Files"),desc:e("Import global instruction files configured in local AI tools"),count:r.length,onImport:()=>u("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:b,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:xf.map((N,S)=>i.jsx("span",{className:U("h-1 flex-1 rounded-full transition-colors",S<=l?"bg-primary":"bg-muted")},N))}),y==="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(rO,{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.")})]}),y!=="welcome"&&y!=="done"&&y!=="preset"&&y!=="agentType"&&i.jsx(OC,{..._[y],importedLabel:e("{{count}} imported",{count:_[y].count})}),y==="preset"&&i.jsx(OC,{icon:Qd,title:e("Presets"),desc:e("Bundle skills, MCP servers and an instruction file into a preset (optional)"),count:a.length,onImport:()=>v(!0),importedLabel:e("{{count}} presets",{count:a.length}),importLabel:e("New preset")}),y==="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(lO,{})})]}),y==="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.")})]}),i.jsxs("div",{className:"mt-6 flex items-center justify-between",children:[i.jsx(xe,{variant:"ghost",size:"sm",onClick:C,disabled:l===0,children:e("Back")}),i.jsxs("div",{className:"flex items-center gap-2",children:[y!=="done"&&y!=="welcome"&&i.jsx(xe,{variant:"ghost",size:"sm",onClick:w,children:e("Skip")}),y==="done"?i.jsx(xe,{size:"sm",onClick:b,children:e("Done")}):i.jsx(xe,{size:"sm",onClick:w,children:e(y==="welcome"?"Get started":"Next")})]})]})]}),i.jsx(cO,{open:h,onOpenChange:p}),i.jsx(dO,{open:f,onOpenChange:g}),d&&i.jsx(uO,{kind:d,open:!0,onOpenChange:N=>!N&&u(null)}),x&&i.jsx(hO,{preset:null,onClose:()=>v(!1)})]})}function OC({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(xe,{variant:"outline",size:"sm",onClick:o,children:a}),l&&i.jsx(xe,{variant:"ghost",size:"sm",onClick:l.onClick,children:l.label})]}),s>0&&i.jsx("p",{className:"text-xs text-primary",children:r})]})}const vf=["project","all","all-including-archived"];function zC(e,t=!1){const n=vf.length,s=vf.indexOf(e);return vf[(s+(t?n-1:1))%n]??"all"}const wse=50,bf=160,yse=["title","project","id","body","tool"],Hv=/[\p{Letter}\p{Number}]+/gu,Sse=/[\u3400-\u9fff]/u,Cse=/[^.!?。?!]+[.!?。?!]?/g;function $E(e){return e.toLowerCase().match(Hv)??[]}function Bv(e){return Sse.test(e)}function WE(e){return $E(e)}function UE(e,t){if(t.length===0)return!1;const n=e.toLowerCase(),s=$E(e);return t.every(o=>Bv(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 kse(e,t){const n=e.toLowerCase(),s=WE(t);if(s.length===0||n.length!==e.length)return[{text:e,match:!1}];const o=[];for(const l of s){if(Bv(l)){for(let c=n.indexOf(l);c>=0;c=n.indexOf(l,c+1))o.push([c,c+l.length]);continue}for(const c of n.matchAll(Hv))c.index!==void 0&&c[0].startsWith(l)&&o.push([c.index,c.index+l.length])}if(o.length===0)return[{text:e,match:!1}];o.sort((l,c)=>l[0]-c[0]);const r=[];let a=0;for(const[l,c]of o){if(c<=a)continue;const d=Math.max(l,a);d>a&&r.push({text:e.slice(a,d),match:!1});const u=r.at(-1);u?.match&&d===a?u.text+=e.slice(d,c):r.push({text:e.slice(d,c),match:!0}),a=c}return a<e.length&&r.push({text:e.slice(a),match:!1}),r}function jse(e,t){const n=e.toLowerCase();let s=-1;for(const o of t){if(Bv(o)){const r=n.indexOf(o);r>=0&&(s<0||r<s)&&(s=r);continue}for(const r of e.matchAll(Hv))if(r[0].toLowerCase().startsWith(o)&&r.index!==void 0){(s<0||r.index<s)&&(s=r.index);break}}return s}function _se(e,t){if(e.length<=bf)return e;const n=Math.max(0,jse(e,t)),s=Math.min(n,Math.max(0,e.length-bf));return e.slice(s,s+bf)}function Nse(e){return(e.match(Cse)??[]).map(t=>t.trim()).filter(Boolean)}function Tse(e,t){const n=Nse(e);if(n.length<=1)return;const s=n.findIndex(r=>UE(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 Dse(e,t,n,s){return e.title.trim().toLowerCase()===n.trim().toLowerCase()?0:t==="title"?1:e.projectId===s?2:3}function Ise(e,t,n){const s=n.trim().toLowerCase(),o=e.fields.filter(r=>r.field==="id"?r.text.toLowerCase().startsWith(s):UE(r.text,t));if(o.length!==0)return yse.map(r=>o.find(a=>a.field===r)).find(r=>!!r)}function qE(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:Dse(e,t.field,n,s),lastActiveAt:e.lastActiveAt}}function YE(e,t=wse){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 Ese(e,t,n){const s=WE(t);if(s.length===0)return[];const o=[];for(const r of e){if(!KE(r,n))continue;const a=Ise(r,s,t);if(!a)continue;const l=Tse(a.text,s);o.push(qE(r,{field:a.field,snippet:_se(a.text,s),nearby:l},t,n.currentProjectId))}return YE(o,n.limit)}function Pse(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 c=r.get(l.conversationId);!c||a.has(l.conversationId)||!KE(c,o)||a.set(l.conversationId,qE(c,l,s,o.currentProjectId))}return YE([...a.values()],o.limit)}const Ase=120,Mse=8;function XE(e){return!e.started&&!e.sessionFile&&e.messages.length===0}function Tl(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt??e.createdAt}function Rse(e,t){return e.filter(n=>n.parentId||XE(n)||n.archived&&t.scope!=="all-including-archived"?!1:t.scope!=="project"||n.projectId===t.currentProjectId).sort((n,s)=>Tl(s)-Tl(n)).slice(0,t.limit??Mse)}function Lse(e){return e.content.map(t=>t.type==="text"?t.text:"").join(`
|
|
99
|
-
`).trim()}function Ose(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,Ase);return`${t.join(" ")} ${n}`.trim()}function zse(e){const t=[{field:"title",text:e.title},{field:"project",text:e.projectName},{field:"id",text:e.conversationId},{field:"body",text:e.messages.map(Lse).filter(Boolean).join(`
|
|
100
|
-
`)}],n=e.messages.map(Ose).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 GC=[],Gse={project:"This project",all:"All projects","all-including-archived":"Include archived"},Fse={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 Ya({text:e,query:t}){let n=0;return kse(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 Lr({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 Hse(e){try{return new URL(e).host||e}catch{return e}}function Bse({open:e,onOpenChange:t}){const{t:n,locale:s}=se(),[o,r]=m.useState(""),[a,l]=m.useState("all"),[c,d]=m.useState(),[u,h]=m.useState([]),[p,f]=m.useState([]),g=oe($=>$.conversations),x=oe($=>$.activeId),v=ye($=>$.projects),y=ye($=>$.scratchSessionsEnabled),b=ye($=>$.keybindings),w=(x?g[x]?.projectId:void 0)??v[0]?.id??"",C=o.trim(),_=`${a}
|
|
102
|
-
${w}
|
|
103
|
-
${C}`,N=c?.key===_?c.hits:GC,S=m.useMemo(()=>{if(!e)return[];const W=(x?g[x]:void 0)?.activeTabId,ue=W&&g[W]?W:x;return Object.values(g).map(Z=>{const J=v.find(ae=>ae.id===Z.projectId);return!y&&J?.kind==="scratch"?null:zse({conversationId:Z.id,projectId:Z.projectId,projectName:J?.name??Z.projectId,title:Z.title,lastActiveAt:Tl(Z),archived:Z.archived,isDraftEmpty:XE(Z),isCurrent:Z.id===ue,parentConversationId:Z.parentId,coworkerId:Z.parentId?Z.id:void 0,messages:Z.messages})}).filter(Z=>Z!==null)},[x,g,e,v,y]),k=m.useMemo(()=>C?Ese(S,o,{currentProjectId:w,scope:a}):GC,[w,S,o,a,C]),A=m.useMemo(()=>e?Rse(Object.values(g),{scope:a,currentProjectId:w}):[],[g,w,e,a]),I=pO(p),D=m.useMemo(()=>C?fO(I,o,{translate:$=>n($)}):[],[o,I,n,C]),P=m.useMemo(()=>o.trim()?mO(u,o):[],[u,o]),T=m.useMemo(()=>gO(u),[u]);m.useEffect(()=>{if(!e)return;const $=W=>{W.key==="Escape"&&(W.preventDefault(),W.stopPropagation(),t(!1))};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[t,e]),m.useEffect(()=>{if(!e){r(""),l("all"),d(void 0);return}window.electronAPI.browser.listSearchableTabs().then($=>h($.filter(W=>!D_(W.conversationId)))).catch(()=>{h([])}),window.electronAPI.sshConnections.list().then($=>{f($.map(W=>({id:W.id,name:W.name})))}).catch(()=>{f([])})},[e]),m.useEffect(()=>{if(!e||!C||!w)return;let $=!1;const W=window.setTimeout(()=>{window.electronAPI.workspaceSearch.query({query:C,currentProjectId:w,scope:a}).then(ue=>{$||d({key:_,hits:ue.hits})}).catch(()=>{$||d({key:_,hits:[]})})},80);return()=>{$=!0,window.clearTimeout(W)}},[_,w,e,a,C]);const z=m.useMemo(()=>Pse(S,k,N,o,{currentProjectId:w,scope:a}),[N,w,S,k,o,a]),O=$=>{const W=oe.getState(),ue=W.conversations[$.conversationId],Z=$.parentConversationId??ue?.parentId;if(Z&&W.conversations[Z]?(W.selectConversation(Z),W.selectTab(Z,$.coworkerId??$.conversationId)):W.selectConversation($.conversationId),t(!1),$.field==="body"||$.field==="tool"){const J=o.trim().split(/\s+/).find(Boolean);J&&window.setTimeout(()=>iE(J),0)}},L=$=>{const W=oe.getState(),Z=W.conversations[$.conversationId]?.parentId;Z&&W.conversations[Z]?(W.selectConversation(Z),W.selectTab(Z,$.conversationId)):W.selectConversation($.conversationId),Qg({conversationId:$.conversationId,tabId:$.tabId,title:$.title||n("Browser")}),t(!1)},V=$=>{window.electronAPI.window.openSettings({category:$.category,rowId:$.id}),t(!1)},X=C.length>0&&z.length===0&&P.length===0&&D.length===0,F=$=>{$.key==="Escape"&&($.preventDefault(),$.stopPropagation(),t(!1))},ee=$=>{if($.key!=="Tab"||$.nativeEvent.isComposing){F($);return}$.altKey||$.ctrlKey||$.metaKey||($.preventDefault(),l(W=>zC(W,$.shiftKey)))},H=Oi(b),Q=Date.now(),q=$=>{const W=v.find(ue=>ue.id===$);return W?Lo(W):""},ne=($,W)=>[q($),W?Bo(W,s,Q):""].filter(Boolean).join(" · "),me=($,W)=>i.jsxs(i.Fragment,{children:[$&&i.jsx(ca,{size:"sm",className:"bg-brand/10 text-brand",children:n("Current")}),W&&i.jsx(ca,{variant:"outline",size:"sm",children:n("Archived")})]}),ke=$=>{const W=g[$.conversationId],ue=$.parentConversationId??W?.parentId;let Z=yr;ue&&(Z=W?.child?.mode==="task"?qg:Vs);const J=$.title||W?.child?.agentInstanceName||W?.coworkerName||n("New conversation"),ae=ue?g[ue]?.title||n("New conversation"):void 0,te=$.field==="body"||$.field==="tool"||$.field==="id"?$.snippet.replace(/\s+/g," ").trim():"";return i.jsx(Lr,{icon:Z,title:i.jsxs(i.Fragment,{children:[ae&&i.jsxs("span",{className:"text-muted-foreground",children:[ae," › "]}),i.jsx(Ya,{text:J,query:o})]}),badges:me($.isCurrent,$.archived),detail:te&&i.jsx(Ya,{text:te,query:o}),meta:ne($.projectId,W?Tl(W):void 0)})},Me=($,W)=>i.jsx(ar,{value:W,className:"gap-2.5",onClick:()=>L($),children:i.jsx(Lr,{icon:go,title:i.jsx(Ya,{text:$.title||$.url,query:o}),meta:Hse($.url)})},W),ge=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(W=>zC(W,$.shiftKey))},children:[n(Gse[a]),i.jsx(ai,{className:"h-4 min-w-4 text-[10px]",children:"⇥"})]});return i.jsx(qI,{open:e,onOpenChange:t,children:i.jsx(YI,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:F,children:i.jsxs(XI,{children:[i.jsx(JI,{placeholder:n("Search conversations, browser tabs, settings…"),value:o,onChange:$=>r($.currentTarget.value),onKeyDown:ee,endAddon:ge}),i.jsxs(eE,{children:[X&&i.jsxs(QI,{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(ZI,{children:[!C&&i.jsxs(i.Fragment,{children:[A.length>0&&i.jsxs(Mr,{children:[i.jsx(Rr,{children:n("Recent")}),A.map($=>i.jsx(ar,{value:`recent-${$.id}`,className:"gap-2.5",onClick:()=>O({conversationId:$.id,field:"title",snippet:$.title}),children:i.jsx(Lr,{icon:yr,title:$.title||n("New conversation"),badges:me($.id===x,$.archived),meta:ne($.projectId,Tl($))})},$.id))]}),T.length>0&&i.jsxs(Mr,{children:[i.jsx(Rr,{children:n("Browser")}),T.map($=>Me($,`recent-browser-${$.tabId}`))]}),i.jsxs(Mr,{children:[i.jsx(Rr,{children:n("Actions")}),i.jsxs(ar,{value:"new-conversation",className:"gap-2.5",onClick:()=>{w&&oe.getState().newConversation(w),t(!1)},children:[i.jsx(Lr,{icon:us,title:i.jsxs(i.Fragment,{children:[n("New conversation"),q(w)&&i.jsxs("span",{className:"text-muted-foreground",children:[" · ",q(w)]})]})}),i.jsx(VS,{children:mi(H["new-conversation"])})]}),i.jsxs(ar,{value:"open-settings",className:"gap-2.5",onClick:()=>{window.electronAPI.window.openSettings(),t(!1)},children:[i.jsx(Lr,{icon:hi,title:n("Open settings")}),i.jsx(VS,{children:mi(H["open-settings"])})]})]})]}),C.length>0&&z.length>0&&i.jsxs(Mr,{children:[i.jsx(Rr,{children:n("Conversations")}),z.map($=>i.jsx(ar,{value:`conv-${$.conversationId}-${$.field}`,className:"gap-2.5",onClick:()=>O($),children:ke($)},`${$.conversationId}-${$.field}`))]}),C.length>0&&P.length>0&&i.jsxs(Mr,{children:[i.jsx(Rr,{children:n("Browser")}),P.map($=>Me($,`browser-${$.tabId}`))]}),C.length>0&&D.length>0&&i.jsxs(Mr,{children:[i.jsx(Rr,{children:n("Settings")}),D.map($=>i.jsx(ar,{value:`settings-${$.id}`,className:"gap-2.5",onClick:()=>V($),children:i.jsx(Lr,{icon:hi,title:i.jsx(Ya,{text:n($.title),query:o}),detail:$.description&&i.jsx(Ya,{text:n($.description),query:o}),meta:n(Fse[$.category]??$.category)})},$.id))]})]})]}),i.jsxs(tE,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(t_,{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 JE,ZE=class{constructor(){}},Xs=class extends ZE{constructor(e,t,n,s){super(),this.viewId=e,this.groupId=t,this.panelId=n,this.tabGroupId=s}},Dl=class extends ZE{constructor(e,t){super(),this.viewId=e,this.paneId=t}},bo=class QE{constructor(){}static getInstance(){return QE.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)}};JE=bo;bo.INSTANCE=new JE;function On(){const e=bo.getInstance();if(e.hasData(Xs.prototype))return e.getData(Xs.prototype)[0]}function Xa(){const e=bo.getInstance();if(e.hasData(Dl.prototype))return e.getData(Dl.prototype)[0]}let an;(function(e){e.NONE={dispose:()=>{}};function t(n){return{dispose:()=>{n()}}}e.from=t})(an||(an={}));var ft=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 Zs;(function(e){e.any=(...t)=>n=>{const s=t.map(o=>o(n));return{dispose:()=>{s.forEach(o=>{o.dispose()})}}}})(Zs||(Zs={}));var Vv=class{constructor(){this._defaultPrevented=!1}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}},eP=class{constructor(){this._isAccepted=!1}get isAccepted(){return this._isAccepted}accept(){this._isAccepted=!0}},Vse=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()}},FC=class tP{static create(){var t;return new tP((t=new Error("listener stacktrace").stack)!==null&&t!==void 0?t:"")}constructor(t){this.value=t}print(){console.warn("dockview: stacktrace",this.value)}},$se=class{constructor(e,t){this.callback=e,this.stacktrace=t}},be=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 $se(t,Ni.ENABLE_TRACKING?FC.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,FC.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))}};be.ENABLE_TRACKING=!1;be.MEMORY_LEAK_WATCHER=new Vse;function lt(e,t,n,s){return e.addEventListener(t,n,s),{dispose:()=>{e.removeEventListener(t,n,s)}}}var HC=class{constructor(){this._onFired=new be,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()}},Wse=class extends ft{constructor(e){super(),this._onDidChange=new be,this.onDidChange=this._onDidChange.event,this._value=null,this.addDisposables(this._onDidChange,Nr(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 Nr(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)},et=(e,t,n)=>{const s=e.classList.contains(t);n&&!s&&e.classList.add(t),!n&&s&&e.classList.remove(t)};function hg(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}function nP(e){return new Use(e)}var Use=class extends ft{constructor(e){super(),this._onDidFocus=new be,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new be,this.onDidBlur=this._onDidBlur.event,this.addDisposables(this._onDidFocus,this._onDidBlur);let t=hg(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=()=>{hg(document.activeElement,e)!==t&&(t?o():s())},this.addDisposables(lt(e,"focus",s,!0)),this.addDisposables(lt(e,"blur",o,!0))}refreshState(){this._refreshStateHandler()}};const sP="dv-quasiPreventDefault";function iP(e){e[sP]=!0}function BC(e){return e[sP]}function Kse(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 d=e.createElement("link");d.href=a.href,d.type=a.type,d.rel="stylesheet",e.head.appendChild(d);continue}let l=[];try{a.cssRules&&(l=Array.from(a.cssRules).map(d=>d.cssText))}catch(d){console.warn("dockview: failed to access stylesheet rules due to security restrictions",d)}const c=e.createDocumentFragment();for(const d of l){const u=e.createElement("style");r&&u.setAttribute("nonce",r),u.appendChild(e.createTextNode(d)),c.appendChild(u)}e.head.appendChild(c)}}function pg(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 oP(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 qse(e,t){e.dataset.testid=t}function Yse(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 ec(e=document){const t=Yse(["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 Xse(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 Uh=class{constructor(e){this.element=e,this._classNames=[]}setClassNames(e){for(const t of this._classNames)et(this.element,t,!1);this._classNames=e.split(" ").filter(t=>t.trim().length>0);for(const t of this._classNames)et(this.element,t,!0)}};const rP=100;function wf(e,t){const n=pg(e),s=pg(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 Jse(e){const t=new be;let n=e.screenX,s=e.screenY,o,r=0,a=!1;const l=()=>{if(a||e.closed)return;const d=e.screenX,u=e.screenY;(d!==n||u!==s)&&(clearTimeout(o),o=setTimeout(()=>{t.fire()},rP),n=d,s=u),r=requestAnimationFrame(l)};l();const c=t.dispose.bind(t);return t.dispose=()=>{a||(a=!0,cancelAnimationFrame(r),clearTimeout(o)),c()},t}function Zse(e,t){let n;return new ft(lt(e,"resize",()=>{clearTimeout(n),n=setTimeout(()=>{t()},rP)}))}function Qse(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,c=0;const d=r.left-a.left,u=r.top-a.top,h=r.bottom-a.bottom,p=r.right-a.right;d<o?l=o-d:p>o&&(l=-o-p),u<o?c=o-u:h>o&&(c=-h-o),(l!==0||c!==0)&&(e.style.transform=`translate(${l}px, ${c}px)`)}function eie(e){let t=e;for(;t&&(t.style.zIndex==="auto"||t.style.zIndex==="");)t=t.parentElement;return t}function co(e){if(e.length===0)throw new Error("Invalid tail call");return[e.slice(0,e.length-1),e[e.length-1]]}function aP(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 yf(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))}function hd(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))}function tie(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(t(s))return n}return-1}function lP(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)),$v=()=>{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 nie=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 VC(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 kr=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,et(this.element,"dv-splitview-disabled",e)}get margin(){return this._margin}set margin(e){this._margin=e,et(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 be,this.onDidSashEnd=this._onDidSashEnd.event,this._onDidAddView=new be,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new be,this.onDidRemoveView=this._onDidRemoveView.event,this.resize=(o,r,a=this.viewItems.map(f=>f.size),l,c,d=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(c)for(const I of c)yf(f,I),yf(g,I);if(l)for(const I of l)hd(f,I),hd(g,I);const x=f.reduce((I,D)=>I+this.viewItems[D].minimumSize-a[D],0),v=f.reduce((I,D)=>I+this.viewItems[D].maximumSize-a[D],0),y=g.length===0?Number.POSITIVE_INFINITY:g.reduce((I,D)=>I+a[D]-this.viewItems[D].minimumSize,0),b=g.length===0?Number.NEGATIVE_INFINITY:g.reduce((I,D)=>I+a[D]-this.viewItems[D].maximumSize,0),w=Math.max(x,b),C=Math.min(y,v);let _=!1;if(h){const I=this.viewItems[h.index],D=r>=h.limitDelta;_=D!==I.visible,I.setVisible(D,h.size)}if(!_&&p){const I=this.viewItems[p.index],D=r<p.limitDelta;_=D!==I.visible,I.setVisible(D,p.size)}if(_)return this.resize(o,r,a,l,c,d,u);const N=Pn(r,w,C);let S=0,k=N;for(const I of f){const D=this.viewItems[I],P=a[I],T=Pn(P+k,D.minimumSize,D.maximumSize),z=T-P;S+=z,k-=z,D.size=T}let A=S;for(const I of g){const D=this.viewItems[I],P=a[I],T=Pn(P-A,D.minimumSize,D.maximumSize),z=T-P;A+=z,D.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(c=>this.onDidChange(l,c.size)),l=new nie(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 c=document.createElement("div");c.className="dv-sash";const d=h=>{var p;for(const L of this.viewItems)L.enabled=!1;const f=(p=c.ownerDocument)!==null&&p!==void 0?p:document,g=ec(f),x=this._orientation==="HORIZONTAL"?h.clientX:h.clientY,v=tie(this.sashes,L=>L.container===c),y=this.viewItems.map(L=>L.size);let b,w;const C=ii(v,-1),_=ii(v+1,this.viewItems.length),N=C.reduce((L,V)=>L+(this.viewItems[V].minimumSize-y[V]),0),S=C.reduce((L,V)=>L+(this.viewItems[V].viewMaximumSize-y[V]),0),k=_.length===0?Number.POSITIVE_INFINITY:_.reduce((L,V)=>L+(y[V]-this.viewItems[V].minimumSize),0),A=_.length===0?Number.NEGATIVE_INFINITY:_.reduce((L,V)=>L+(y[V]-this.viewItems[V].viewMaximumSize),0),I=Math.max(N,A),D=Math.min(k,S),P=this.findFirstSnapIndex(C),T=this.findFirstSnapIndex(_);if(typeof P=="number"){const L=this.viewItems[P],V=Math.floor(L.viewMinimumSize/2);b={index:P,limitDelta:L.visible?I-V:I+V,size:L.size}}if(typeof T=="number"){const L=this.viewItems[T],V=Math.floor(L.viewMinimumSize/2);w={index:T,limitDelta:L.visible?D+V:D-V,size:L.size}}const z=L=>{const V=(this._orientation==="HORIZONTAL"?L.clientX:L.clientY)-x;this.resize(v,V,y,void 0,void 0,I,D,b,w),this.distributeEmptySpace(),this.layoutViews()},O=()=>{for(const L of this.viewItems)L.enabled=!0;g.release(),this.saveProportions(),f.removeEventListener("pointermove",z),f.removeEventListener("pointerup",O),f.removeEventListener("pointercancel",O),f.removeEventListener("contextmenu",O),this._onDidSashEnd.fire(void 0)};f.addEventListener("pointermove",z),f.addEventListener("pointerup",O),f.addEventListener("pointercancel",O),f.addEventListener("contextmenu",O)};c.addEventListener("pointerdown",d);const u={container:c,disposable:()=>{c.removeEventListener("pointerdown",d),c.remove()}};this.sashContainer.appendChild(c),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)yf(s,l);for(const l of r)hd(s,l)}typeof e=="number"&&hd(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),c=l-a.size;n-=c,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 c of this.viewItems)e+=c.size,c.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((c,d)=>{o+=this.viewItems[d].size,r.push(o),l+=c.visible?1:0;const u=c.visible?c.size-s:0,h=Math.max(0,l-1),p=d===0||h===0?0:r[d-1]+h/n*s;if(d<this.viewItems.length-1){const f=c.visible?p+u-a/2+this.margin/2:p,g=this.sashes[d];this._orientation==="HORIZONTAL"&&VC(g,`${f}px`,"0px"),this._orientation==="VERTICAL"&&VC(g,"0px",`${f}px`)}this._orientation==="HORIZONTAL"&&(c.setContainerGeometry("width",`${u}px`),c.setContainerGeometry("left",`${p}px`),c.setContainerGeometry("top",""),c.setContainerGeometry("height","")),this._orientation==="VERTICAL"&&(c.setContainerGeometry("height",`${u}px`),c.setContainerGeometry("top",`${p}px`),c.setContainerGeometry("width",""),c.setContainerGeometry("left","")),c.view.layout(c.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 c=this.sashes[l],d=this.viewItems[l];a+=d.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(c,1):y&&t[l]&&(a<this._contentSize||this.endSnappingEnabled)?this.updateSash(c,0):this.updateSash(c,2)}else u&&!h?this.updateSash(c,1):!u&&h?this.updateSash(c,0):this.updateSash(c,3)}}updateSash(e,t){et(e.container,"dv-disabled",t===2),et(e.container,"dv-enabled",t===3),et(e.container,"dv-maximum",t===0),et(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 fg=Object.keys({orientation:void 0,descriptor:void 0,proportionalLayout:void 0,styles:void 0,margin:void 0,disableAutoResizing:void 0,className:void 0});var $C=class extends ft{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 be,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 kr(this.element,{orientation:this._orientation,proportionalLayout:!1,descriptor:t.descriptor}),this.getPanes().forEach(s=>{const o=new ft(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 be,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 mg extends ft{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 mg&&(n.margin=t)})}constructor(t,n,s,o,r,a,l,c){if(super(),this.orientation=t,this.proportionalLayout=n,this.styles=s,this._childrenDisposable=an.NONE,this.children=[],this._onDidChange=new be,this.onDidChange=this._onDidChange.event,this._onDidVisibilityChange=new be,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._orthogonalSize=r,this._size=o,this.element=document.createElement("div"),this.element.className="dv-branch-node",c){const d={views:c.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=c.map(u=>u.node),this.splitview=new kr(this.element,{orientation:this.orientation,descriptor:d,proportionalLayout:n,styles:s,margin:l})}else this.splitview=new kr(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 ft(Zs.any(...this.children.map(t=>t.onDidChange))(t=>{this.invalidateCachedSizes(),this._onDidChange.fire({size:t.orthogonalSize})}),...this.children.map((t,n)=>t instanceof mg?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 gg(e,t){if(e instanceof ls)return e;if(e instanceof Xn)return gg(e.children[t?e.children.length-1:0],t);throw new Error("invalid node")}function cP(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(cP(r,r.size,r.orthogonalSize),r.size,0,!0)}return s}else return new ls(e.view,e.orientation,n)}function xg(e,t,n){if(e instanceof Xn){const s=new Xn(Pi(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 c=e.size===0?0:Math.round(t*l/e.size);o+=c,r===0&&(c+=t-o),s.addChild(xg(a,n,c),c,0,!0)}return s}else return new ls(e.view,Pi(e.orientation),n)}function sie(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=sie(t),s=t.parentElement.parentElement.parentElement;return[...Tn(s),n]}function $s(e,t,n){if(oie(e,t)===iie(n)){const[s,o]=co(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 iie(e){return e==="top"||e==="bottom"?"VERTICAL":"HORIZONTAL"}function oie(e,t){return t.length%2===0?Pi(e):e}const Pi=e=>e==="HORIZONTAL"?"VERTICAL":"HORIZONTAL";function rie(e){return!!e.children}const vg=(e,t)=>{const n=t==="VERTICAL"?e.box.width:e.box.height;if(!rie(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=>vg(o,Pi(t)));return typeof e.cachedVisibleSize=="number"?{type:"branch",data:s,size:e.cachedVisibleSize,visible:!1}:{type:"branch",data:s,size:n}};var dP=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=xg(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(),vg(this.getView(),this.orientation);const r=[];function a(l,c){for(let d=0;d<l.children.length;d++){const u=l.children[d];u instanceof ls?u!==c&&(l.isChildVisible(d)?l.setChildVisible(d,!1):r.push(u)):a(u,c)}}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:vg(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,Pi(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=cP(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(Pi(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(xg(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,Pi(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 gg(r.children[t?a-1:a+1],t)}return gg(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 be,this.onDidChange=this._onDidChange.event,this._onDidViewVisibilityChange=new be,this.onDidViewVisibilityChange=this._onDidViewVisibilityChange.event,this._onDidMaximizedNodeChange=new be,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]=co(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]=co(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]=co(n),[r,a]=this.getNode(s);if(a instanceof Xn){const l=new ls(e,Pi(a.orientation),a.orthogonalSize);a.addChild(l,t,o)}else{const[l,...c]=[...r].reverse(),[d,...u]=[...s].reverse();let h=0;const p=l.getChildCachedVisibleSize(d);typeof p=="number"&&(h=js.Invisible(p)),l.removeChild(d).dispose();const f=new Xn(a.orientation,this.proportionalLayout,this.styles,a.size,a.orthogonalSize,this.locked,this.margin);l.addChild(f,a.size,d);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]=co(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[c,...d]=[...o].reverse(),[u,...h]=[...n].reverse(),p=r.isChildVisible(0);r.removeChild(0,t);const f=c.children.map((g,x)=>c.getChildSize(x));if(c.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];c.addChild(x,x.size,u+g)}for(;l.children.length>0;)l.removeChild(0)}else{const g=new ls(l.view,Pi(l.orientation),l.size),x=p?l.orthogonalSize:js.Invisible(l.orthogonalSize);c.addChild(g,x,u)}l.dispose();for(let g=0;g<f.length;g++)c.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 bg=Object.keys({disableAutoResizing:void 0,proportionalLayout:void 0,orientation:void 0,hideBorders:void 0,className:void 0});var Wv=class extends ft{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(Nr(this._element,n=>{if(this.isDisposed||this.disableResizing||!this._element.offsetParent||!oP(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 aie=$v();function Vu(e){switch(e){case"left":return"left";case"right":return"right";case"above":return"top";case"below":return"bottom";default:return"center"}}var uP=class extends Wv{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=aie.next(),this._groups=new Map,this._onDidRemove=new be,this.onDidRemove=this._onDidRemove.event,this._onDidAdd=new be,this.onDidAdd=this._onDidAdd.event,this._onDidMaximizedChange=new be,this.onDidMaximizedChange=this._onDidMaximizedChange.event,this._onDidActiveChange=new be,this.onDidActiveChange=this._onDidActiveChange.event,this._bufferOnDidLayoutChange=new HC,this.onDidLayoutChange=this._bufferOnDidLayoutChange.onEvent,this._onDidViewVisibilityChangeMicroTaskQueue=new HC,this.onDidViewVisibilityChangeMicroTaskQueue=this._onDidViewVisibilityChangeMicroTaskQueue.onEvent,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new Uh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this.gridview=new dP(!!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()}),Zs.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 tc(e){"@babel/helpers - typeof";return tc=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},tc(e)}function lie(e,t){if(tc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(tc(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function cie(e){var t=lie(e,"string");return tc(t)=="symbol"?t:t+""}function die(e,t,n){return(t=cie(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function WC(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?WC(Object(n),!0).forEach(function(s){die(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):WC(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function uie(e,t){return e==="center"?`Tab into ${t}`:`Split ${e} of ${t}`}function hie(e,t){return e==="center"?`docked into ${t}`:`split ${e} of ${t}`}const $u={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)=>`${uie(e,t)}. Arrows to change, Enter to confirm, Escape to go back.`,moveCommitted:(e,t,n)=>`${e} ${hie(n,t)}.`,moveCancelled:()=>"Move cancelled.",moveNotAllowed:()=>"That move is not allowed.",moveFloated:e=>`${e} floated.`};function hP(e){return e?gt(gt({},$u),e):$u}var pP=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()}},nc=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()}},fP=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()}},Uv=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 hP(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()}},mP=class extends ft{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(lt(this.element,"dragenter",e=>{this.onDragEnter(e)},!0)),this.addDisposables(lt(this.element,"dragover",e=>{this.onDragOver(e)},!0)),this.addDisposables(lt(this.element,"dragleave",e=>{this.onDragLeave(e)})),this.addDisposables(lt(this.element,"dragend",e=>{this.onDragEnd(e)})),this.addDisposables(lt(this.element,"drop",e=>{this.onDrop(e)}))}};const pie={value:50,type:"percentage"},fie=100,mie=100;function wg(){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 gP(e,t,n,s){var o,r,a;const l=(o=s?.smallWidthBoundary)!==null&&o!==void 0?o:fie,c=(r=s?.smallHeightBoundary)!==null&&r!==void 0?r:mie,d=t<l,u=n<c,h=e==="left",p=e==="right",f=e==="top",g=e==="bottom",x=!d&&p,v=!d&&h,y=!u&&f,b=!u&&g;let w=1;const C=(a=s?.size)!==null&&a!==void 0?a:pie;return C.type==="percentage"?w=Pn(C.value,0,100)/100:((x||v)&&(w=Pn(0,C.value,t)/t),(y||b)&&(w=Pn(0,C.value,n)/n)),{isSmallX:d,isSmallY:u,isLeft:h,isRight:p,isTop:f,isBottom:g,rightClass:x,leftClass:v,topClass:y,bottomClass:b,size:w}}function xP(e,t,n,s,o){const r=gP(t,n,s,o),{rightClass:a,leftClass:l,topClass:c,bottomClass:d,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}%`:c?h.height=`${100*u}%`:d&&(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);et(e,"dv-drop-target-small-vertical",r.isSmallY),et(e,"dv-drop-target-small-horizontal",r.isSmallX),et(e,"dv-drop-target-selection-line",p),et(e,"dv-drop-target-left",r.isLeft),et(e,"dv-drop-target-right",r.isRight),et(e,"dv-drop-target-top",r.isTop),et(e,"dv-drop-target-bottom",r.isBottom),et(e,"dv-drop-target-center",t==="center")}function gie(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 xie(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 vP(e){const t=gP(e.quadrant,e.width,e.height,e.overlayModel),{rightClass:n,leftClass:s,topClass:o,bottomClass:r,size:a}=t,l=e.outlineElement.getBoundingClientRect(),c=e.targetModel.getElements(void 0,e.outlineElement),d=c.root,u=c.overlay,h=d.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),gie(u,g)?(xie(u,g),u.className=`dv-drop-target-anchor${e.className?` ${e.className}`:""}`,et(u,"dv-drop-target-left",t.isLeft),et(u,"dv-drop-target-right",t.isRight),et(u,"dv-drop-target-top",t.isTop),et(u,"dv-drop-target-bottom",t.isBottom),et(u,"dv-drop-target-anchor-line",t.isSmallX&&(t.isLeft||t.isRight)||t.isSmallY&&(t.isTop||t.isBottom)),et(u,"dv-drop-target-center",e.quadrant==="center"),c.changed&&(et(u,"dv-drop-target-anchor-container-changed",!0),setTimeout(()=>{et(u,"dv-drop-target-anchor-container-changed",!1)},10)),{boundsChanged:!0,targetChanged:c.changed}):{boundsChanged:!1,targetChanged:c.changed}}var bP=class extends Vv{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 UC(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 vie(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 bie={value:20,type:"percentage"};var Kh=class il extends ft{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 be,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new be,this.onWillShowOverlay=this._onWillShowOverlay.event,this._disabled=!1,this._acceptedTargetZonesSet=new Set(this.options.acceptedTargetZones),this.dnd=new mP(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,c,d,u;if(this._disabled){this.clearOwnOverlay();return}il.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=(c=this.options).getOverlayOutline)===null||l===void 0?void 0:l.call(c))!==null&&a!==void 0?a:this.element,f=p.offsetWidth,g=p.offsetHeight;if(f===0||g===0)return;const x=p.getBoundingClientRect(),v=((d=s.clientX)!==null&&d!==void 0?d: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 C=new bP({nativeEvent:s,position:w,edge:b.edge,edgeGroup:b.edgeGroup});if(this._onWillShowOverlay.fire(C),C.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 _=wg();this.targetElement=_.dropzone,this.overlayElement=_.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&&il.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[il.USED_EVENT_ID]=!0}isAlreadyUsed(t){const n=t[il.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,c,d;vP({outlineElement:(l=(c=(d=this.options).getOverlayOutline)===null||c===void 0?void 0:c.call(d))!==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&&xP(this.overlayElement,t,n,s,this.options.overlayModel)}resolvePosition(t,n,s,o,r){var a,l;const c=(a=(l=this.options).getPositionResolver)===null||a===void 0?void 0:a.call(l);if(c){const u=c.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 d=this.calculateQuadrant(this._acceptedTargetZonesSet,t,n,s,o);return d?{position:d,edge:!1,edgeGroup:!1}:null}calculateQuadrant(t,n,s,o,r){var a,l;const c=(a=(l=this.options.overlayModel)===null||l===void 0?void 0:l.activationSize)!==null&&a!==void 0?a:bie;return c.type==="percentage"?wP(t,n,s,o,r,c.value):yP(t,n,s,o,r,c.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),c=(o=(r=(a=this.options).getOverlayOutline)===null||r===void 0?void 0:r.call(a))!==null&&o!==void 0?o:this.element,d=c.offsetWidth,u=c.offsetHeight;if(!l&&!this.targetElement){const h=wg();this.targetElement=h.dropzone,this.overlayElement=h.selection,c.classList.add("dv-drop-target"),c.append(this.targetElement)}this.toggleClasses(t,d,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}};Kh.USED_EVENT_ID="__dockview_droptarget_event_is_used__";function wP(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 yP(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 wie(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 Wu=class ol extends ft{static getInstance(){var t;return(t=ol._instance)!==null&&t!==void 0||(ol._instance=new ol),ol._instance}constructor(){super(),this._targets=new Set,this._targetByElement=new Map,this._onDragStart=new be,this.onDragStart=this._onDragStart.event,this._onDragMove=new be,this.onDragMove=this._onDragMove.event,this._onDragEnd=new be,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=ec((n=a.ownerDocument)!==null&&n!==void 0?n:document);const c={clientX:r.clientX,clientY:r.clientY,pointerEvent:r};this._onDragStart.fire(c);const d=(s=(o=a.ownerDocument)===null||o===void 0?void 0:o.defaultView)!==null&&s!==void 0?s:globalThis.window;this._moveListener=lt(d,"pointermove",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleMove(u)}),this._upListener=lt(d,"pointerup",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleEnd(u,!0)}),this._cancelListener=lt(d,"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 c=this._targetByElement.get(l);if(c)return c;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 yie={value:20,type:"percentage"};var Sie=class extends ft{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 be,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new be,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,Wu.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,c=l.offsetWidth,d=l.offsetHeight;if(c===0||d===0)return;const u=l.getBoundingClientRect(),h=e.clientX-u.left,p=e.clientY-u.top,f=this._resolvePosition(h,p,c,d,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 bP({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){vP({outlineElement:l,targetModel:a,quadrant:g,width:c,height:d,overlayModel:this.options.overlayModel,className:this.options.className}),this._state=g;return}if(!this._targetElement){const v=wg();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&&xP(this._overlayElement,g,c,d,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 d=l.resolve({x:e,y:t,width:n,height:s,zones:this._acceptedTargetZonesSet,event:o});return d?{position:d.position,edge:!!d.edge}:null}const c=this._calculateQuadrant(e,t,n,s);return c?{position:c,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:yie;return a.type==="percentage"?wP(this._acceptedTargetZonesSet,e,t,n,s,a.value):yP(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 Cie=5,kie=250,jie=8;var _ie=class extends ft{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(lt(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,c=(t=typeof l=="function"?l():l)!==null&&t!==void 0?t:kie;this._armed=!a||c<=0,a&&c>0&&Number.isFinite(c)&&(this._armTimer=setTimeout(()=>{this._armTimer=void 0,this._armed=!0},c));const d=(n=this.options.threshold)!==null&&n!==void 0?n:Cie,u=this.options.pressTolerance,h=(s=typeof u=="function"?u():u)!==null&&s!==void 0?s:jie,p=(o=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&o!==void 0?o:globalThis.window;this._pendingMoveListener=lt(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>=d&&this._beginDrag(f);return}v>h&&this._beginDrag(f)}),this._pendingUpListener=lt(p,"pointerup",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()}),this._pendingCancelListener=lt(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);Wu.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()}},Nie=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())}},Tie=class extends ft{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,lt(this.el,"dragstart",n=>{var s,o,r,a,l,c,d;if(n.defaultPrevented||this._disabled||!((s=(o=this.opts).isCancelled)===null||s===void 0)&&s.call(o,n)){n.preventDefault();return}const u=ec((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(wie(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","")),(c=(d=this.opts).onDragStart)===null||c===void 0||c.call(d,n)}),lt(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(){}},Die=class{constructor(){this.kind="html5"}createDropTarget(e,t){return new Kh(e,t)}createDragSource(e,t){return new Tie(e,t)}},Iie=class{constructor(){this.kind="pointer"}createDropTarget(e,t){return new Sie(e,t)}createDragSource(e,t){const n=t.createGhost?o=>{const r=t.createGhost(o);if(!r)return;const a=new Nie({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),c=r.dispose;a.dispose=()=>{l(),c()}}return a}:void 0,s=new _ie(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 Vo=new Die,wo=new Iie,yg=Object.keys({disableAutoResizing:void 0,disableDnd:void 0,className:void 0});var Eie=class extends eP{constructor(e,t,n,s){super(),this.nativeEvent=e,this.position=t,this.getData=n,this.panel=s}},SP=class extends Vv{constructor(){super()}},CP=class extends ft{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 be,this.onDidDimensionsChange=this._onDidDimensionChange.event,this._onDidChangeFocus=new be,this.onDidFocusChange=this._onDidChangeFocus.event,this._onWillFocus=new be,this.onWillFocus=this._onWillFocus.event,this._onDidVisibilityChange=new be,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._onWillVisibilityChange=new be,this.onWillVisibilityChange=this._onWillVisibilityChange.event,this._onDidActiveChange=new be,this.onDidActiveChange=this._onDidActiveChange.event,this._onActiveChange=new be,this.onActiveChange=this._onActiveChange.event,this._onDidParametersChange=new be,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)}},kP=class extends CP{constructor(e,t){super(e,t),this._onDidConstraintsChangeInternal=new be,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new be({replay:!0}),this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new be,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)}},Pie=class extends kP{set pane(e){this._pane=e}constructor(e,t){super(e,t),this._onDidExpansionChange=new be({replay:!0}),this.onDidExpansionChange=this._onDidExpansionChange.event,this._onMouseEnter=new be({}),this.onMouseEnter=this._onMouseEnter.event,this._onMouseLeave=new be({}),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())}},Kv=class extends ft{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=nP(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 SP;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()}},Aie=class extends Kv{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 Pie(e.id,e.component)),this._onDidChangeExpansionState=new be({replay:!0}),this.onDidChangeExpansionState=this._onDidChangeExpansionState.event,this._onDidChange=new be,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})}),lt(this.element,"mouseenter",t=>{this.api._onMouseEnter.fire(t)}),lt(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()}}}},Mie=class extends Aie{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 be,this.onDidDrop=this._onDidDrop.event,this._onUnhandledDragOver=new be,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:()=>(bo.getInstance().setData([new Dl(t,e)],Dl.prototype),{dispose:()=>{bo.getInstance().clearData(Dl.prototype)}})};this.html5DragSource=Vo.createDragSource(this.header,n),this.pointerDragSource=wo.createDragSource(this.header,n);const o={acceptedTargetZones:["top","bottom"],overlayModel:{activationSize:{type:"percentage",value:50}},canDisplayOverlay:(r,a)=>{const l=Xa();if(l&&l.paneId!==this.id&&l.viewId===this.accessor.id)return!0;const c=new Eie(r,a,Xa,this);return this._onUnhandledDragOver.fire(c),c.isAccepted}};this.target=Vo.createDropTarget(this.element,o),this.pointerTarget=wo.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=Xa();if(t?.viewId!==this.accessor.id){this._onDidDrop.fire(gt(gt({},e),{},{panel:this,api:new nc(this.accessor),getData:Xa}));return}const n=this._params.containerApi,s=t.paneId,o=n.getPanel(s);if(!o){this._onDidDrop.fire(gt(gt({},e),{},{panel:this,getData:Xa,api:new nc(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 Rie=0;const Lie=()=>`dv-tabpanel-${Rie++}`;var Oie=class extends ft{get element(){return this._element}constructor(e,t){var n,s,o,r,a,l,c;super(),this.accessor=e,this.group=t,this.disposable=new Fn,this._onDidFocus=new be,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new be,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-content-container",this._element.tabIndex=-1,this._element.id=Lie(),this._element.setAttribute("role","tabpanel"),this.addDisposables(this._onDidFocus,this._onDidBlur);const d=()=>{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 Kh(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:d,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=wo.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:d,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=(c=this.accessor).onDidOptionsChange)===null||l===void 0?void 0:l.call(c,()=>{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 c,d;this._element.appendChild(this.panel.view.content.element),(c=(d=this.panel.view.content).onShow)===null||c===void 0||c.call(d)}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=nP(l);this.focusTracker=u;const h=new ft;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 qh=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},zie=()=>qh({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"}),jP=()=>qh({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"}),Gie=()=>qh({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"}),_P=()=>qh({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"}),Fie=500,Hie=8;var qv=class extends ft{constructor(e,t){super(),this.element=e,this.options=t,this._startX=0,this._startY=0,this.addDisposables(lt(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:Fie,l=(s=this.options.tolerance)!==null&&s!==void 0?s:Hie,c=(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(c),this._installClickGuard(c),this.options.onLongPress(e)},a),this._moveListener=lt(c,"pointermove",d=>{if(d.pointerId!==this._pointerId)return;const u=d.clientX-this._startX,h=d.clientY-this._startY;Math.hypot(u,h)>l&&this._cancelPending()}),this._upListener=lt(c,"pointerup",d=>{d.pointerId===this._pointerId&&this._cancelPending()}),this._cancelListener=lt(c,"pointercancel",d=>{d.pointerId===this._pointerId&&this._cancelPending()})}_installContextMenuGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=lt(e,"contextmenu",s=>{s.preventDefault(),clearTimeout(n),t?.dispose()},{capture:!0})}_installClickGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=lt(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 Bie()?{html5:!1,pointer:!0,pointerHandlesMouse:!0}:{html5:!0,pointer:!0,pointerHandlesMouse:!1}}}function Bie(){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 Vie=0;const $ie=()=>`dv-tab-${Vie++}`;var Wie=class extends ft{get element(){return this._element}constructor(e,t,n){var s,o,r,a,l,c,d,u;super(),this.panel=e,this.accessor=t,this.group=n,this.content=void 0,this.panelTransfer=bo.getInstance(),this._direction="horizontal",this._pinIndicator=void 0,this._onPointDown=new be,this.onPointerDown=this._onPointDown.event,this._onTabClick=new be,this.onTabClick=this._onTabClick.event,this._onDropped=new be,this.onDrop=this._onDropped.event,this._onDragStart=new be,this.onDragStart=this._onDragStart.event,this._onDragEnd=new be,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=$ie(),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),et(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=Vo.createDropTarget(this._element,{acceptedTargetZones:["left","right"],overlayModel:this._buildOverlayModel(),canDisplayOverlay:f,getOverrideTarget:()=>{var x;return(x=n.model.dropTargetContainer)===null||x===void 0?void 0:x.model}}),this.pointerDropTarget=wo.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 Xs(this.accessor.id,this.group.id,this.panel.id)],Xs.prototype),{dispose:()=>{this.panelTransfer.clearData(Xs.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(()=>{et(this.element,"dv-tab--dragging",!0)})},onDragEnd:x=>{this._onDragEnd.fire(x)}};this.html5DragSource=Vo.createDragSource(this._element,gt(gt({},g),{},{disabled:!h.html5})),this.pointerDragSource=wo.createDragSource(this._element,gt(gt({},g),{},{disabled:!h.pointer,touchOnly:!h.pointerHandlesMouse,isCancelled:()=>!ui(this.accessor.options).pointer})),this.onWillShowOverlay=Zs.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:()=>{}},(c=(d=this.panel.api)===null||d===void 0||(u=d.onDidTitleChange)===null||u===void 0?void 0:u.call(d,x=>{var v;this._element.setAttribute("aria-label",(v=x.title)!==null&&v!==void 0?v:this.panel.id)}))!==null&&c!==void 0?c:{dispose:()=>{}},lt(this._element,"dragend",()=>{et(this.element,"dv-tab--dragging",!1)}),this.html5DragSource,lt(this._element,"pointerdown",x=>{this._onPointDown.fire(x)}),lt(this._element,"click",x=>{this._onTabClick.fire(x)}),lt(this._element,"contextmenu",x=>{var v;(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,x)}),new qv(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;et(this.element,"dv-tab--pinned",o),et(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(jP()),this._element.insertBefore(l,this._element.firstChild),this._pinIndicator=l}else!a&&this._pinIndicator&&(this._pinIndicator.remove(),this._pinIndicator=void 0)}setActive(e){et(this.element,"dv-active-tab",e),et(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}},sc=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}},NP=class extends ft{get group(){return this.groupAccessor()}constructor(e){var t,n;super(),this.panelTransfer=bo.getInstance(),this._onDragStart=new be,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,et(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 Xs(this.accessor.id,this.group.id,null)],Xs.prototype),{dispose:()=>{this.panelTransfer.clearData(Xs.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=Vo.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 c=()=>{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=wo.createDragSource(this._element,gt(gt({},l),{},{disabled:!o.pointer,touchOnly:!o.pointerHandlesMouse,touchInitiationDelay:()=>c()?500:250,pressTolerance:()=>c()?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 d=new Fn,u=()=>{const p=this.getFloatingOverlay();d.value=p?p.onDidStartMoving(()=>{this.pointerDragSource.cancelPending()}):an.NONE};u(),this.addDisposables(d);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,et(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}},Uie=class extends ft{get element(){return this._element}constructor(e,t){var n,s,o,r,a,l,c;super(),this.accessor=e,this.group=t,this._onDrop=new be,this.onDrop=this._onDrop.event,this._onDragStart=new be,this.onDragStart=this._onDragStart.event,this._element=document.createElement("div"),this._element.className="dv-void-container",this.addDisposables(this._onDrop,this._onDragStart,lt(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this.group)}),lt(this._element,"pointerdown",u=>{u.shiftKey&&iP(u)},!0)),this.dragSource=new NP({element:this._element,accessor:this.accessor,group:this.group,isFloatingMoveHandle:()=>!this._element.closest(".dv-resize-container-with-titlebar")});const d=(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=Vo.createDropTarget(this._element,{acceptedTargetZones:["center"],canDisplayOverlay:d,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=wo.createDropTarget(this._element,{acceptedTargetZones:["center"],canDisplayOverlay:d,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=Zs.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=(c=this.accessor).onDidOptionsChange)===null||l===void 0?void 0:l.call(c,()=>{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()}},TP=class DP extends ft{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(lt(this.element,"wheel",n=>{this._scrollOffset+=n.deltaY*DP.MouseWheelSpeed,this.scheduleStyleUpdate()}),lt(this._scrollbar,"pointerdown",n=>{var s;n.preventDefault();const o=(s=this._scrollbar.ownerDocument)!==null&&s!==void 0?s:document;et(this.element,"dv-scrollable-scrolling",!0);const r=this._orientation==="horizontal"?n.clientX:n.clientY,a=this._scrollOffset,l=d=>{const u=this._orientation==="horizontal"?d.clientX-r:d.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()},c=()=>{et(this.element,"dv-scrollable-scrolling",!1),o.removeEventListener("pointermove",l),o.removeEventListener("pointerup",c),o.removeEventListener("pointercancel",c)};o.addEventListener("pointermove",l),o.addEventListener("pointerup",c),o.addEventListener("pointercancel",c)}),lt(this.element,"scroll",()=>{this.scheduleStyleUpdate()}),lt(this.scrollableElement,"scroll",()=>{this._scrollOffset=this._orientation==="horizontal"?this.scrollableElement.scrollLeft:this.scrollableElement.scrollTop,this.scheduleStyleUpdate()}),Nr(this.element,()=>{et(this.element,"dv-scrollable-resizing",!0),this._animationTimer&&clearTimeout(this._animationTimer),this._animationTimer=setTimeout(()=>{clearTimeout(this._animationTimer),et(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}};TP.MouseWheelSpeed=1;const IP="dv-tabs-container--wrap";function Kie(e,t){return typeof e=="boolean"?e:!!e?.[t]}function Sg(e){return typeof e=="boolean"?e:e?Object.values(e).some(Boolean):!1}var EP=class extends eP{constructor(e,t,n,s,o){super(),this.nativeEvent=e,this.target=t,this.position=n,this.getData=s,this.group=o}};const Cg=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 qie(e){return!!e.referencePanel}function Yie(e){return!!e.referenceGroup}function Xie(e){return!!e.referencePanel}function Jie(e){return!!e.referenceGroup}const Yv=[{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 PP=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 Sf;function AP(){var e;return(e=Sf)!==null&&e!==void 0||(Sf=new PP(Yv,!0)),Sf}function Xv(e,t,n){const s=(n??AP()).resolveValue(t);s===void 0?e.style.removeProperty("--dv-tab-group-color"):e.style.setProperty("--dv-tab-group-color",s)}function Jv(e,t){return(t??AP()).resolveValue(e)}var KC=class extends ft{get element(){return this._element}constructor(e){super(),this._palette=e,this._onClick=new be,this.onClick=this._onClick.event,this._onContextMenu=new be,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 qv(this._element,{onLongPress:t=>{this._onContextMenu.fire(t)}}),lt(this._element,"click",t=>{this._onClick.fire(t)}),lt(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;Xv(this._element,e,this._palette),et(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,et(this._label,"dv-tab-group-chip-label--empty",!e)}updateCollapsed(e){et(this._element,"dv-tab-group-chip--collapsed",e)}};const Zie="dv-tab-group-chip-continuation",qC=8;var MP=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=Zie,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(IP);s||this._clearContinuationMarkers();const o=n?e.width:e.height,r=this._ctx.getActivePanelId(),a=this._ctx.getTabMap();for(const l of t){const c=this._underlines.get(l.id);if(!c)continue;const d=l.panelIds;if(d.length===0){c.style.display="none";continue}if(c.style.display="",s){this._positionWrappedUnderline(c,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=d[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=d[d.length-1],f=a.get(p);if(!f){n?(c.style.top=`${h}px`,c.style.height="0px",c.style.left="",c.style.width=""):(c.style.left=`${h}px`,c.style.width="0px",c.style.top="",c.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,C=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,C+=k.scrollHeight):(w+=k.getBoundingClientRect().width,C+=k.scrollWidth)}const _=C>0?Math.min(1,w/C):0;h=b+(h-b)*_,x=b+(x-b)*_,v=Math.max(0,x-h)}n?(c.style.top=`${h}px`,c.style.height=`${Math.max(0,v)}px`,c.style.left="",c.style.width="",c.style.bottom=""):(c.style.left=`${h}px`,c.style.width=`${Math.max(0,v)}px`,c.style.top="",c.style.height="",c.style.bottom=""),this.applyShape(c,l,h,v,o,r,e,n)}}_positionWrappedUnderline(e,t,n,s,o){const a=Jv(t.color,this._ctx.getColorPalette());if(a===void 0){e.style.display="none",this._clearContinuationMarkers(t.id);return}const{runs:l,firstRun:c}=this._computeWrappedRuns(t,n,s,o);if(l.length===0){e.style.display="none",this._clearContinuationMarkers(t.id);return}this._positionContinuationMarkers(t.id,l,c,a,o);const d=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-d):n.width,g=o?n.height:Math.max(0,p-h);e.style.left=o?`${d}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,d,h,2))}_computeWrappedRuns(e,t,n,s){const o=[];let r;for(const l of e.panelIds){var a;const c=n.get(l);if(!c)continue;const d=c.value.element.getBoundingClientRect();if(d.width===0&&d.height===0)continue;const u=d.top-t.top,h=d.bottom-t.top,p=d.left-t.left,f=d.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 c=n?l.right-s-r/2:l.left-s+r/2;a+=`M ${c},${l.top} L ${c},${l.bottom} `}else{const c=n?l.top-o+r/2:l.bottom-o-r/2;a+=`M ${l.left},${c} L ${l.right},${c} `}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,c)=>{const d=a[c];if(d.style.backgroundColor=s,o){const u=(l.left+l.right)/2;d.style.left=`${u-qC/2}px`,d.style.top=`${l.top}px`}else{const u=(l.top+l.bottom)/2;d.style.left=`${l.left}px`,d.style.top=`${u-qC/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}}},Qie=class extends MP{_applyStraightLine(e,t,n,s,o,r,a){const l=a?o:s,c=a?s:o;e.setAttribute("width",String(l)),e.setAttribute("height",String(c)),n.style.width=`${l}px`,n.style.height=`${c}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 d=o,u=s,h=Jv(t.color,this._ctx.getColorPalette());if(u<=0||d<=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,C;if(l?(w=b?d-x:x,C=b?x:d-x):(w=y?x:d-x,C=y?d-x:x),!p){this._applyStraightLine(f,g,e,u,d,w,l);return}const _=p.value.element.getBoundingClientRect();let N,S;if(l?(N=Math.max(0,_.top-a.top-n),S=Math.min(u,_.bottom-a.top-n)):(N=Math.max(0,_.left-a.left-n),S=Math.min(u,_.right-a.left-n)),S<=N){this._applyStraightLine(f,g,e,u,d,w,l);return}const k=6,A=C>w?1:-1;if(l){const I=d,D=u;f.setAttribute("width",String(I)),f.setAttribute("height",String(D)),e.style.width=`${I}px`,e.style.height=`${D}px`;const P=[`M ${w},0`,`L ${w},${N-k}`,`Q ${w},${N} ${w+A*k},${N}`,`L ${C-A*k},${N}`,`Q ${C},${N} ${C},${N+k}`,`L ${C},${S-k}`,`Q ${C},${S} ${C-A*k},${S}`,`L ${w+A*k},${S}`,`Q ${w},${S} ${w},${S+k}`,`L ${w},${D}`].join(" ");g.setAttribute("d",P)}else{const I=u,D=d;f.setAttribute("width",String(I)),f.setAttribute("height",String(D)),e.style.width=`${I}px`,e.style.height=`${D}px`;const P=[`M 0,${w}`,`L ${N-k},${w}`,`Q ${N},${w} ${N},${w+A*k}`,`L ${N},${C-A*k}`,`Q ${N},${C} ${N+k},${C}`,`L ${S-k},${C}`,`Q ${S},${C} ${S},${C-A*k}`,`L ${S},${w+A*k}`,`Q ${S},${w} ${S+k},${w}`,`L ${I},${w}`].join(" ");g.setAttribute("d",P)}}},eoe=class extends MP{applyShape(e,t,n,s,o,r,a,l){const d=Jv(t.color,this._ctx.getColorPalette());if(s<=0||d===void 0){e.style.display="none";return}e.style.display="",e.firstElementChild&&e.replaceChildren(),e.style.backgroundColor=d,l?(e.style.width="2px",e.style.height=`${s}px`):(e.style.width=`${s}px`,e.style.height="2px")}};const toe=new Map;var noe=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:toe}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 c=document.createElement("div");c.className="dv-tabs-and-actions-container",c.style.height="auto",c.style.width="auto",l.appendChild(c),c.appendChild(o),this._ctx.accessor.element.appendChild(l);const d=o.querySelector(".dv-tab-group-chip"),u=n.getBoundingClientRect(),h=e.clientX-u.left,p=e.clientY-u.top;if(d){const f=d.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"?eoe:Qie;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=bo.getInstance(),o=()=>(s.setData([new Xs(this._ctx.accessor.id,this._ctx.group.id,null,t.id)],Xs.prototype),{dispose:()=>{s.clearData(Xs.prototype)}}),r=Vo.createDragSource(e.element,{getData:o,disabled:!n.html5,isCancelled:()=>!ui(this._ctx.accessor.options).html5,onDragStart:c=>{"dataTransfer"in c&&c.dataTransfer&&this.setGroupDragImage(c,t,e.element),this._callbacks.onChipDragStart(t,e,c)},onDragEnd:c=>{var d,u;(d=(u=this._callbacks).onChipDragEnd)===null||d===void 0||d.call(u,t,e,c)}}),a=()=>{s.clearData(Xs.prototype)};e.element.addEventListener("dragend",a,{once:!0});const l=wo.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:c=>{this._callbacks.onChipDragStart(t,e,c)}});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 KC(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 KC?r.push(s.onContextMenu(a)):r.push(new qv(s.element,{onLongPress:a}),lt(s.element,"contextmenu",a));const l=this._ctx.getDirection()==="vertical",c=new Kh(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(c,c.onDrop(u=>{this._callbacks.onChipDrop(e,u)}));const d=new ft(...r);this._chipRenderers.set(e.id,{chip:s,html5DragSource:o.html5DragSource,pointerDragSource:o.pointerDragSource,dragSourcesDisposable:o.disposable,disposable:d,dropTarget:c}),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 c of l.panelIds)o.set(c,l);for(const l of t){const c=l.value,d=c.panel.id,u=o.get(d),h=!!u;if(et(c.element,"dv-tab--grouped",h),u){const p=u.panelIds,f=p[0]===d,g=p[p.length-1]===d;et(c.element,"dv-tab--group-first",f),et(c.element,"dv-tab--group-last",g),Xv(c.element,u.color,this._ctx.accessor.tabGroupColorPalette);const x=c.element.classList.contains("dv-tab--group-collapsed");if(!u.collapsed&&x){var r;s=!0,c.element.classList.remove("dv-tab--group-collapsed"),c.element.classList.add("dv-tab--group-expanding"),(r=this._pendingTransitionCleanups.get(d))===null||r===void 0||r();const v=()=>{c.element.classList.remove("dv-tab--group-expanding"),c.element.style.removeProperty("width"),c.element.removeEventListener("transitionend",v),clearTimeout(y),this._pendingTransitionCleanups.delete(d)},y=setTimeout(v,300);this._pendingTransitionCleanups.set(d,v),c.element.addEventListener("transitionend",v)}}else et(c.element,"dv-tab--group-first",!1),et(c.element,"dv-tab--group-last",!1),c.element.classList.remove("dv-tab--group-collapsed","dv-tab--group-expanding"),c.element.style.removeProperty("width"),c.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(c=>{const d=n.get(c);return d&&!d.value.element.classList.contains("dv-tab--group-collapsed")}))if(this._skipNextCollapseAnimation){const c=[];for(const d of l.panelIds){const u=n.get(d);u&&(u.value.element.style.transition="none",u.value.element.classList.add("dv-tab--group-collapsed"),c.push(u.value.element))}if(c.length>0){c[0].offsetHeight;for(const d of c)d.style.removeProperty("transition")}}else{s=!0;const c=this._ctx.getDirection()==="vertical";for(const d of l.panelIds){const u=n.get(d);if(u&&!u.value.element.classList.contains("dv-tab--group-collapsed")){const h=u.value.element.getBoundingClientRect();c?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())}},soe=class extends ft{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(IP)}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 c;(c=a)!==null&&c!==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 d;(d=a)!==null&&d!==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 c=t.get(l.panel.id);if(c){var r;o+=(r=n.chipPositions.get(c))!==null&&r!==void 0?r:0}const d=n.tabPositions.get(l.panel.id);o+=d?d.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,c=n>=a&&n<=l,d=!c&&n===a-1;return!c&&!d?null:o?this._resolveGroupDragTarget(n,a,l,c):this._resolveTabDragTarget(e,t,n,s,a,d)}_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,c=(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+c/2:l.containerLeft+s+c)?{insertionIndex:o,targetTabGroupId:e.id}:{insertionIndex:n,targetTabGroupId:null}:null;const d=l.containerLeft+s+c;return n===o?{insertionIndex:n,targetTabGroupId:t>=d?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,c=f=>s?f.right:f.bottom,d=f=>s?f.top:f.left,u=f=>s?f.height:f.width,h=this._bucketWrappedLines(o,l,c),p=[...((n=h.find(f=>r>=f.start&&r<=f.end))!==null&&n!==void 0?n:this._nearestWrappedLine(h,r)).items].sort((f,g)=>d(f.rect)-d(g.rect));for(const f of p)if(a<d(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",et(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,c]of this._tabGroupManager.chipRenderers)l!==o.sourceTabGroupId&&this._clearMargin(c.chip.element,s);n&&(this._setMargin(n,`${t}px`,s),a=!0);for(let l=0;l<this._tabs.length;l++){const c=this._tabs[l].value;c.panel.id!==o.sourceTabId&&(r?.has(c.panel.id)||(!a&&l>=e?(this._setMargin(c.element,`${t}px`,s),a=!0):this._clearMargin(c.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,et(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"),et(e,n,!1);else{e.style.marginLeft="0px",et(e,n,!0);const o=()=>{e.style.removeProperty("margin-left"),et(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"),et(e.value.element,"dv-tab--shifting",!1);for(const[,e]of this._tabGroupManager.chipRenderers)e.chip.element.style.removeProperty("margin-left"),et(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)`,et(e.value.element,"dv-tab--shifting",!0),!0}if(r!==void 0&&(t<r.from||t>r.to))return!1;const c=o.get(l);if(!c)return!1;const d=e.value.element.getBoundingClientRect(),u=a?c.top-d.top:c.left-d.left;return Math.abs(u)<1?!1:(e.value.element.style.transform=a?`translateY(${u}px)`:`translateX(${u}px)`,et(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)et(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)})}},ioe=class extends ft{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 Wse(this._tabsList);this._observerDisposable.value=new ft(t,t.onDidChange(n=>{const s=n.hasScrollX||n.hasScrollY;this.toggleDropdown({reset:!s}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}),lt(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 ft(lt(e,"dragover",n=>{this._animState&&n.preventDefault()}),lt(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 be,this.onTabDragStart=this._onTabDragStart.event,this._onDrop=new be,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new be,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onOverflowTabsChange=new be,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 TP(this._tabsList),this._scrollbar.orientation=this.direction,this._element=this._scrollbar.element,this.addDisposables(this._scrollbar)),this._tabGroupManager=new noe({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 soe(this),this.addDisposables(this._onOverflowTabsChange,this._observerDisposable,this._pointerActivation,this._onWillShowOverlay,this._onDrop,this._onTabDragStart,this._reorder,Wu.getInstance().onDragEnd(s=>{this._reorder.handlePointerDragEnd(s)}),Wu.getInstance().onDragMove(s=>{this._reorder.handlePointerDragMove(s.clientX,s.clientY)}),lt(this.element,"pointerdown",s=>{s.defaultPrevented||s.button===0&&this.accessor.doSetGroupActive(this.group)}),lt(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}),lt(this._tabsList,"keydown",s=>{this._onKeyDown(s)}),lt(this._tabsList,"dragover",s=>{this._reorder.processDragOver(s.clientX,s.clientY)&&s.preventDefault()},!0),lt(this._tabsList,"dragleave",s=>{this._reorder.processDragLeave(s.relatedTarget)},!0),lt(this._tabsList,"dragend",()=>{this._reorder.resetDragAnimation()}),lt(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 c=l.currentInsertionIndex,d=l.sourceIndex,u=c-(d!==-1&&d<c?1:0),h=this.group.model.getTabGroupForPanel(l.sourceTabId);if(u===d&&!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(d,u),to:Math.max(d,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 c=this._tabs.findIndex(d=>d.value.panel.id===l);c>-1&&this._focusTab(c)}}_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 Wie(e,this.accessor,this.group);n.setContent(e.view.tab),this._direction!=="horizontal"&&n.setDirection(this._direction);const s={value:n,disposable:new ft(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(c=>c.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 c,d;this._pendingCollapse=!1,this._animState&&(this._tabsList.classList.contains("dv-tabs-container--wrap")||(n.element.style.transition="none",et(n.element,"dv-tab--dragging",!0),n.element.offsetHeight),(d=(c=this._animState).currentInsertionIndex)!==null&&d!==void 0||(c.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:c,left:d}=n.element.getBoundingClientRect(),{top:u,left:h}=this.accessor.element.getBoundingClientRect();this.accessor.addFloatingGroup(l,{x:d-h,y:c-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 c;this._commitGroupMove(r.sourceTabGroupId,(c=r.currentInsertionIndex)!==null&&c!==void 0?c: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 d,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=(d=(u=this.group.model.getTabGroupForPanel(n.panel.id))===null||u===void 0?void 0:u.id)!==null&&d!==void 0?d:null;this._onDrop.fire({event:o.nativeEvent,index:x,targetTabGroupId:v})}}),n.onWillShowOverlay(o=>{this._onWillShowOverlay.fire(new sc(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&&!wf(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&&!wf(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),c=l&&!wf(l.chip.element,this._tabsList),d=a.panelIds.length>0&&a.panelIds.every(u=>o.has(u));if((c||d)&&(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(d=>d.value.panel.id===o):-1,a=t.element.getBoundingClientRect();let l=a.width;for(const d of e.panelIds){const u=this._tabMap.get(d);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 c=new Set(e.panelIds);this._pendingCollapse=!0,requestAnimationFrame(()=>{var d,u;if(this._pendingCollapse=!1,!this._animState)return;for(const f of this._tabs)c.has(f.value.panel.id)&&(f.value.element.style.transition="none",et(f.value.element,"dv-tab--dragging",!0));const h=this._tabGroupManager.chipRenderers.get(e.id);h&&(h.chip.element.style.transition="none",et(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=(d=this._animState).currentInsertionIndex)!==null&&u!==void 0||(d.currentInsertionIndex=r),this.applyDragOverTransforms(!0);for(const f of this._tabs)c.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 ooe(){const e=document.createElement("div");e.className="dv-tabs-overflow-dropdown-default";const t=document.createElement("span");t.textContent="";const n=_P();return e.appendChild(n),e.appendChild(t),{element:e,update:s=>{t.textContent=`${s.tabs}`}}}var roe=class extends ft{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 be,this.onDrop=this._onDrop.event,this._onGroupDragStart=new be,this.onGroupDragStart=this._onGroupDragStart.event,this._onWillShowOverlay=new be,this.onWillShowOverlay=this._onWillShowOverlay.event,this._element=document.createElement("div"),this._element.className="dv-tabs-and-actions-container",et(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 ioe(t,e,{showTabsOverflowControl:!e.options.disableTabsOverflowList}),this.voidContainer=new Uie(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 sc(n,{kind:"header_space",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:On}))}),lt(this.leftActionsContainer,"dragleave",n=>{const s=n.relatedTarget;!this.leftActionsContainer.contains(s)&&!this._element.contains(s)&&this.tabs.clearExternalAnimState()}),lt(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())}),lt(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)),et(this._element,"dv-tabs-and-actions-container--pinned-row",!!e))}setDropIndexResolver(e){this._dropIndexResolver=e}resolveDropIndex(e,t){return this._dropIndexResolver(e,t)}updateClassnames(){et(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=ooe();a.update({tabs:o}),this.dropdownPart=a,r.appendChild(a.element),this.rightActionsContainer.prepend(r),this._dropdownDisposable.value=new ft(an.from(()=>{var l,c;r.remove(),(l=this.dropdownPart)===null||l===void 0||(c=l.dispose)===null||c===void 0||c.call(l),this.dropdownPart=null}),lt(r,"pointerdown",l=>{l.preventDefault()},{capture:!0}),lt(r,"click",l=>{const c=eie(r),d={x:l.clientX,y:l.clientY,zIndex:c?.style.zIndex?`calc(${c.style.zIndex} * 2)`:void 0},u=this.createOverflowRenderContext(r,d),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 c of s)if(r.set(c.id,c),n.has(c.id))for(const d of c.panelIds)o.set(d,c);const a=()=>this.accessor.getPopupServiceForGroup(this.group),l=c=>{const d=document.createElement("div");d.className="dv-tabs-overflow-group-header";const u=document.createElement("span");u.className="dv-tabs-overflow-group-color",Xv(u,c.color,this.accessor.tabGroupColorPalette),d.appendChild(u);const h=document.createElement("span");if(h.className="dv-tabs-overflow-group-label",h.textContent=c.label||c.id,d.appendChild(h),c.collapsed){const p=document.createElement("span");p.className="dv-tabs-overflow-group-collapsed-badge",p.textContent=`${c.panelIds.length}`,d.appendChild(p)}return d.addEventListener("click",()=>{a().close(),c.collapsed&&c.expand();const p=c.panelIds[0];if(p){const f=this.group.panels.find(g=>g.id===p);this.accessor.withOrigin("user",()=>f?.api.setActive())}}),d};return{overflowGroupIdForPanel:c=>{var d;return(d=o.get(c))===null||d===void 0?void 0:d.id},buildGroupHeader:c=>{const d=r.get(c);if(!(!d||!n.has(d.id)))return l(d)},buildPinnedHeader:()=>{const c=document.createElement("div");c.className="dv-tabs-overflow-group-header dv-tabs-overflow-pinned-header";const d=jP();d.classList.add("dv-tabs-overflow-pinned-icon"),c.appendChild(d);const u=document.createElement("span");return u.className="dv-tabs-overflow-group-label",u.textContent="Pinned",c.appendChild(u),c},buildRow:c=>{const d=this.group.panels.find(x=>x.id===c);if(!d)return;const u=this.tabs.tabs.find(x=>x.panel.id===c),h=o.get(c),p=d.view.createTabRenderer("headerOverflow").element,f=document.createElement("div");et(f,"dv-tab",!0),et(f,"dv-active-tab",d.api.isActive),et(f,"dv-inactive-tab",!d.api.isActive),h&&et(f,"dv-tab--grouped",!0);const g=()=>{h?.collapsed&&h.expand(),u?.element.scrollIntoView({block:"nearest",inline:"nearest"}),this.accessor.withOrigin("user",()=>d.api.setActive())};return f.addEventListener("click",x=>{a().close(),!x.defaultPrevented&&g()}),f.appendChild(p),{element:f,panel:d,activate:()=>{a().close(),g()}}},open:c=>{a().openPopover(c,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()}},aoe=class extends ft{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 be,this.onDidChange=this._onDidChange.event,this._onDidPanelChange=new be,this.onDidPanelChange=this._onDidPanelChange.event,this._onDidCollapseChange=new be,this.onDidCollapseChange=this._onDidCollapseChange.event,this._onDidDestroy=new be,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()}},Zv=class extends Vv{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()}},RP=class extends Zv{get kind(){return this._kind}constructor(e){super(e),this._kind=e.kind}},loe=class extends ft{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,et(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?hg(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,et(this.container,"dv-groupview-floating",!1),et(this.container,"dv-groupview-popout",!1),et(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"]),et(this.container,"dv-groupview-floating",!0);break;case"popout":t(["top","bottom","left","right","center"]),et(this.container,"dv-groupview-popout",!0);break;case"edge":t(["center"]),et(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 be,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 be,this.onMove=this._onMove.event,this._onDidDrop=new be,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new be,this.onWillDrop=this._onWillDrop.event,this._onWillShowOverlay=new be,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onTabDragStart=new be,this.onTabDragStart=this._onTabDragStart.event,this._onGroupDragStart=new be,this.onGroupDragStart=this._onGroupDragStart.event,this._onDidAddPanel=new be,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPanelTitleChange=new be,this.onDidPanelTitleChange=this._onDidPanelTitleChange.event,this._onDidPanelParametersChange=new be,this.onDidPanelParametersChange=this._onDidPanelParametersChange.event,this._onDidRemovePanel=new be,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidActivePanelChange=new be,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onUnhandledDragOver=new be,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._tabGroups=[],this._tabGroupMap=new Map,this._panelToTabGroup=new Map,this._tabGroupIdCounter=0,this._pendingTabGroupUpdate=!1,this._onDidCreateTabGroup=new be,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new be,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new be,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new be,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new be,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new be,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,et(this.container,"dv-groupview",!0),this.container.setAttribute("role","region"),this._api=new Uv(this.accessor),this.tabsContainer=new roe(this.accessor,this.groupPanel),this.contentContainer=new Oie(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(Nr(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 c;const d=On(),u=(c=d?.panelId)!==null&&c!==void 0?c: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 sc(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:On}))}),this.contentContainer.pointerDropTarget.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(new sc(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 aoe(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 ft(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(c=>this._panels.find(d=>d.id===c)).filter(c=>c!==void 0);if(o.length===0)return;let r=0;for(let c=0;c<Math.min(t,this._panels.length);c++)s.has(this._panels[c].id)&&r++;for(const c of o){const d=this._panels.indexOf(c);d!==-1&&this._panels.splice(d,1)}const a=t-r,l=Math.max(0,Math.min(a,this._panels.length));this._panels.splice(l,0,...o);for(const c of this._panels)this.tabsContainer.delete(c.id);for(let c=0;c<this._panels.length;c++)this.tabsContainer.openPanel(this._panels[c],c);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,et(this.container,"dv-active-group",e),et(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 ft(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,lt(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 EP(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 RP({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 c=On();if(c?.viewId===this.accessor.id){if(e==="content"&&c.groupId===this.id&&(n==="center"||c.panelId===null&&!c.tabGroupId)||e==="header"&&c.groupId===this.id&&c.panelId===null&&!c.tabGroupId)return;if(c.panelId===null){const{groupId:h}=c;this._onMove.fire({target:n,groupId:h,index:s,tabGroupId:c.tabGroupId});return}if(this.tabsContainer.indexOf(c.panelId)!==-1&&this.tabsContainer.size===1)return;const{groupId:d,panelId:u}=c;if(this.id===d&&!n&&this.tabsContainer.indexOf(u)===s)return;this._onMove.fire({target:n,groupId:c.groupId,itemId:c.panelId,index:s})}else this._onDidDrop.fire(new Zv({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()}},Qv=class extends CP{constructor(e,t,n){super(e,t),this._onDidConstraintsChangeInternal=new be,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new be,this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new be,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)}},LP=class extends Kv{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 Qv(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 be,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 Zi="dockview: DockviewGroupPanelApiImpl not initialized";var coe=class extends Qv{get location(){if(!this._group)throw new Error(Zi);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(Zi);return this._group.locked}set locked(e){if(!this._group)throw new Error(Zi);this._group.locked=e}constructor(e,t){super(e,"__dockviewgroup__"),this.accessor=t,this._onDidLocationChange=new be,this.onDidLocationChange=this._onDidLocationChange.event,this._onDidActivePanelChange=new be,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidCollapsedChange=new be,this.onDidCollapsedChange=this._onDidCollapsedChange.event,this._onDidPeekChange=new be,this.onDidPeekChange=this._onDidPeekChange.event,this._onDidHeaderDirectionChange=new be,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(Zi);this._group.model.headerPosition=e}getHeaderPosition(){if(!this._group)throw new Error(Zi);return this._group.model.headerPosition}moveTo(e){if(!this._group)throw new Error(Zi);this.accessor.withOrigin("api",()=>{var t,n,s,o;const r=(t=e.group)!==null&&t!==void 0?t:this.accessor.addGroup({direction:vie((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(Zi);this.location.type==="grid"&&this.accessor.maximizeGroup(this._group)}isMaximized(){if(!this._group)throw new Error(Zi);return this.accessor.isMaximizedGroup(this._group)}exitMaximized(){if(!this._group)throw new Error(Zi);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 doe=100,uoe=100;var pd=class extends LP{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,c;super(t,"groupview_default",{minimumHeight:(s=(o=n.constraints)===null||o===void 0?void 0:o.minimumHeight)!==null&&s!==void 0?s:uoe,minimumWidth:(r=(a=n.constraints)===null||a===void 0?void 0:a.minimumWidth)!==null&&r!==void 0?r:doe,maximumHeight:(l=n.constraints)===null||l===void 0?void 0:l.maximumHeight,maximumWidth:(c=n.constraints)===null||c===void 0?void 0:c.maximumWidth},new coe(t,e)),this._explicitConstraints={},this.api.initialize(this),this._model=new loe(this.element,e,t,n,this),this.addDisposables(this.model.onDidActivePanelChange(d=>{this.api._onDidActivePanelChange.fire(d)}),this.api.onDidConstraintsChangeInternal(d=>{d.minimumWidth!==void 0&&(this._explicitConstraints.minimumWidth=typeof d.minimumWidth=="function"?d.minimumWidth():d.minimumWidth),d.minimumHeight!==void 0&&(this._explicitConstraints.minimumHeight=typeof d.minimumHeight=="function"?d.minimumHeight():d.minimumHeight),d.maximumWidth!==void 0&&(this._explicitConstraints.maximumWidth=typeof d.maximumWidth=="function"?d.maximumWidth():d.maximumWidth),d.maximumHeight!==void 0&&(this._explicitConstraints.maximumHeight=typeof d.maximumHeight=="function"?d.maximumHeight():d.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 hoe={name:"dark",className:"dockview-theme-dark",colorScheme:"dark"},poe={name:"light",className:"dockview-theme-light",colorScheme:"light"},foe={className:"dockview-theme-abyss",tabGroupIndicator:"none"};var moe=class extends Qv{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 be,this.onDidTitleChange=this._onDidTitleChange.event,this._onDidChangePinned=new be,this.onDidChangePinned=this._onDidChangePinned.event,this._onDidActiveGroupChange=new be,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._onDidGroupChange=new be,this.onDidGroupChange=this._onDidGroupChange.event,this._onDidRendererChange=new be,this.onDidRendererChange=this._onDidRendererChange.event,this._onDidLocationChange=new be,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 ft(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}))}))}},Br=class extends ft{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 moe(this,this._group,s,t,n),this.addDisposables(this.api.onActiveChange(()=>{s.setActivePanel(this)}),this.api.onDidSizeChange(c=>{this.group.api.setSize(c)}),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 SP;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()}},YC=class extends ft{get element(){return this._element}constructor(){super(),this._messages=$u,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=zie();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:$u,this.addDisposables(e.api.onDidTitleChange(n=>{this._title=n.title,this.render()}),lt(this.action,"pointerdown",n=>{n.preventDefault()}),lt(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())}},OP=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 YC}console.warn(`dockview: tabComponent '${t}' was not found. falling back to the default tab.`)}return new YC}},goe=class{constructor(e){this.accessor=e}fromJSON(e,t){var n,s,o;const r=e.id,a=e.params,l=e.title,c=e.view,d=c?c.content.id:(n=e.contentComponent)!==null&&n!==void 0?n:"unknown",u=c?(s=c.tab)===null||s===void 0?void 0:s.id:e.tabComponent,h=new OP(this.accessor,r,d,u),p=new Br(r,d,u,this.accessor,new Uv(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}},xoe=class extends ft{get element(){return this._element}constructor(){super(),this._element=document.createElement("div"),this._element.className="dv-watermark"}init(t){}},voe=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 fd=new voe;var e0=class lr extends ft{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 be,this.onDidChange=this._onDidChange.event,this._onDidChangeEnd=new be,this.onDidChangeEnd=this._onDidChangeEnd.event,this._onDidStartMoving=new be,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&&(et(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})),fd.push(this._element)}setVisible(t){t!==this.isVisible&&(this._isVisible=t,et(this.element,"dv-hidden",!this.isVisible))}bringToFront(){fd.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,et(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=an.NONE)}setupDrag(t,n){const s=(o,r)=>{var a,l,c;let d=null,u=!1;this._dragCancelled=!1;const h=this.options.transformDragPosition?(a=(l=(c=this.options).getSiblingBoxes)===null||l===void 0?void 0:l.call(c))!==null&&a!==void 0?a:[]:[],p=ec();if(o&&typeof r=="number"&&typeof o.setPointerCapture=="function")try{o.setPointerCapture(r)}catch{}const f=()=>{et(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=an.NONE,this._onDidChangeEnd.fire()};this._dragMove.value=new ft({dispose:()=>{if(p.release(),o&&typeof r=="number"&&typeof o.releasePointerCapture=="function")try{o.releasePointerCapture(r)}catch{}}},lt(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;et(this._element,"dv-resize-container-dragging",!0);const w=this._element.getBoundingClientRect();(x=d)!==null&&x!==void 0||(d={x:g.clientX-w.left,y:g.clientY-w.top});const C=Math.max(0,this.getMinimumWidth(w.width)),_=Math.max(0,this.getMinimumHeight(w.height));let N=b-d.y,S=y-d.x;if(this.options.transformDragPosition){const O=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}});O&&(N=O.top,S=O.left)}const k=Math.max(0,v.height-w.height+_),A=Math.max(0,v.width-w.width+C),I=Pn(N,-_,k),D=Pn(v.height-w.height-N,-_,k),P=Pn(S,-C,A),T=Pn(v.width-w.width-S,-C,A),z={};I<=D?z.top=I:z.bottom=D,P<=T?z.left=P:z.right=T,this.setBounds(z),u||(u=!0,this._onDidStartMoving.fire())}),lt(globalThis.window,"pointerup",f),lt(globalThis.window,"pointercancel",f))};this.addDisposables(lt(t,"pointerdown",o=>{if(o.defaultPrevented){o.preventDefault();return}BC(o)||s(t,o.pointerId)}),lt(this.options.content,"pointerdown",o=>{o.defaultPrevented||BC(o)||o.shiftKey&&s(this.options.content,o.pointerId)}),lt(this.options.content,"pointerdown",()=>{fd.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,lt(n,"pointerdown",o=>{o.preventDefault();let r=null;const a=ec(),l=o.pointerId;if(typeof n.setPointerCapture=="function")try{n.setPointerCapture(l)}catch{}const c=()=>{s.dispose(),this._onDidChangeEnd.fire()};s.value=new ft(lt(globalThis.window,"pointermove",d=>{var u;const h=this.options.container.getBoundingClientRect(),p=this._element.getBoundingClientRect(),f=d.clientY-h.top,g=d.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,C;const _=()=>{const I=r.originalY+r.originalHeight>h.height?Math.max(0,h.height-lr.MINIMUM_HEIGHT):Math.max(0,r.originalY+r.originalHeight-lr.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:lr.MINIMUM_HEIGHT,D=h.height-Math.max(0,x);y=Pn(f-x,I,D),v=h.height-x-y},S=()=>{const I=r.originalX+r.originalWidth>h.width?Math.max(0,h.width-lr.MINIMUM_WIDTH):Math.max(0,r.originalX+r.originalWidth-lr.MINIMUM_WIDTH);b=Pn(g,0,I),C=r.originalX+r.originalWidth-b,w=h.width-b-C},k=()=>{b=r.originalX-r.originalWidth;const I=b<0&&typeof this.options.minimumInViewportWidth=="number"?-b+this.options.minimumInViewportWidth:lr.MINIMUM_WIDTH,D=h.width-Math.max(0,b);C=Pn(g-b,I,D),w=h.width-b-C};switch(t){case"top":_();break;case"bottom":N();break;case"left":S();break;case"right":k();break;case"topleft":_(),S();break;case"topright":_(),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=C,this.setBounds(A)}),{dispose:()=>{if(a.release(),typeof n.releasePointerCapture=="function")try{n.releasePointerCapture(l)}catch{}}},lt(globalThis.window,"pointerup",c),lt(globalThis.window,"pointercancel",c))}))}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(){fd.destroy(this._element),this._element.remove(),super.dispose()}};e0.MINIMUM_HEIGHT=20;e0.MINIMUM_WIDTH=20;var boe=class extends ft{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 be,this.onDragStart=this._onDragStart.event,this._group=t,this._element=document.createElement("div"),this._element.className="dv-floating-titlebar",this.addDisposables(this._onDragStart,lt(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this._group)}),lt(this._element,"pointerdown",n=>{n.shiftKey&&iP(n)},!0)),this.dragSource=new NP({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 ko(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 woe=new Set(["AdvancedOverflow","AutoEdgeGroup","AutoHideEdgeGroup","ContextMenu","DndCompass","KeyboardDocking","KeyboardNavigation","LayoutHistory","License","MultiRowTabs","PinnedTabs","SmartGuides"]),XC=new Set;function zP(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 woe.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("|")}`;XC.has(n)||(XC.add(n),console.error(zP(e,t)))}function Ms(e,t,n){if(e!==void 0)return e;GP(t,n)}var yoe=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 Soe=[];function Coe(){return[...Soe]}const koe=[{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=>Sg(e.autoHideEdgeGroups)},{optionKey:"dockToEdgeGroups",reason:"dockToEdgeGroups",moduleName:"AutoEdgeGroup",when:e=>Sg(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 joe(e,t){const n=new Map;for(const s of koe){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 Do={left:100,top:100,width:300,height:300};var _oe=class extends ft{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)}},Noe=class{get floatingGroups(){return this._floatingGroups}constructor(e){this._floatingGroups=[],this._host=e}add(e,t,n){const s=new _oe(e,t,n),o=new ft(e.api.onDidActiveChange(a=>{a.isActive&&t.bringToFront()}),(()=>{let a=-1,l=-1;return Nr(n.element,c=>{const d=Math.round(c.contentRect.width),u=Math.round(c.contentRect.height);d===a&&u===l||(a=d,l=u,n.layout(d,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(),lP(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 Toe=ko({name:"FloatingGroup",serviceKey:"floatingGroupService",create:e=>new Noe(e)});var Doe=class{constructor(e){this._entries=[],this._restorationCleanups=new Set,this._restorationPromise=Promise.resolve(),this._onDidRemove=new be,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){lP(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 d=e.window;if(this._host.isDisposed||!d||d.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())},c=new o(()=>{var d;const u=(d=e.window)===null||d===void 0?void 0:d.requestAnimationFrame;u?u.call(e.window,l):l()});return c.observe(t.element),{dispose:()=>c.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 Ioe=ko({name:"PopoutWindow",serviceKey:"popoutWindowService",create:e=>new Doe(e)});var Eoe=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",qse(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 Poe=ko({name:"Watermark",serviceKey:"watermarkService",create:e=>new Eoe(e),init:(e,t)=>(t.update(),new ft(Zs.any(e.onDidAdd,e.onDidRemove)(()=>{t.update()}),e.onDidViewVisibilityChangeMicroTaskQueue(()=>{t.update()})))});var Aoe=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 Moe=ko({name:"EdgeGroup",serviceKey:"edgeGroupService",create:()=>new Aoe}),Roe={activationSize:{type:"pixels",value:10},size:{type:"pixels",value:20}},Loe={activationSize:{type:"pixels",value:32},size:{type:"pixels",value:20}};function JC(e,t){return typeof e.dndEdges=="object"&&e.dndEdges!==null?e.dndEdges:t&&Sg(e.dockToEdgeGroups)?Loe:Roe}var Ooe=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=JC(e.options,!1);this._html5Target=Vo.createDropTarget(e.element,{className:"dv-drop-target-edge",canDisplayOverlay:t,acceptedTargetZones:["top","bottom","left","right","center"],overlayModel:n,getOverrideTarget:()=>e.rootDropTargetOverrideTarget(),getPositionResolver:()=>e.options.dropPositionResolver}),this._pointerTarget=wo.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=Zs.any(this._html5Target.onWillShowOverlay,this._pointerTarget.onWillShowOverlay),this.onDrop=Zs.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=JC({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 zoe=ko({name:"RootDropTarget",serviceKey:"rootDropTargetService",create:e=>new Ooe(e),init:(e,t)=>(t.setOptions(e.options),an.NONE)}),Goe={left:"createLeftHeaderActionComponent",right:"createRightHeaderActionComponent",prefix:"createPrefixHeaderActionComponent"};var Foe=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[Goe[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 Hoe=ko({name:"HeaderActions",serviceKey:"headerActionsService",create:e=>new Foe(e),init:(e,t)=>new ft(e.onDidRemoveGroup(n=>{t.disposeGroup(n)}))}),ZC=e=>e==="load"||e==="clear";function md(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 Boe=class extends ft{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:md(n,"polite"),assertive:md(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:md(o,"polite"),assertive:md(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=hP(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 Voe=ko({name:"LiveRegion",serviceKey:"liveRegionService",create:e=>new Boe(e)}),$oe=30,Woe=-10;var Uoe=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:$oe,offsetY:Woe,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 Koe=ko({name:"AdvancedDnD",serviceKey:"advancedDnDService",create:e=>new Uoe(e)});var qoe=class{constructor(e){this._host=e}attachToGroup(e){return new ft(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 Yoe=ko({name:"TabGroupChips",serviceKey:"tabGroupChipsService",create:e=>new qoe(e),init:(e,t)=>{const n=new Map;return new ft(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()}})}}),Xoe=[Toe,Ioe,Poe,Moe,zoe,Hoe,Voe,Koe,Yoe];var Joe=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=pg(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 QC=-1;function Zoe(){const e=document.createElement("div");return e.tabIndex=-1,e}var ek=class extends ft{constructor(e,t){super(),this.element=e,this.accessor=t,this.map={},this._disposed=!1,this._generation=0,this.positionCache=new Joe,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=Zoe();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=QC;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),C=this.positionCache.getPosition(this.element),_=w.left-C.left,N=w.top-C.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=`${_}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 D=this.element.ownerDocument.defaultView,P=(A=D?.scrollX)!==null&&A!==void 0?A:0,T=(I=D?.scrollY)!==null&&I!==void 0?I:0,z=b.top+T,O=b.left+P,L=Math.max(0,z-w.top),V=Math.max(0,O-w.left),X=Math.max(0,w.left+S-(b.right+P)),F=Math.max(0,w.top+k-(b.bottom+T));r.style.clipPath=`inset(${L}px ${X}px ${F}px ${V}px)`}else r.style.clipPath="";et(r,"dv-render-overlay-float",t.group.api.location.type==="floating")});f.pendingUpdate===QC&&(f.pendingUpdate=g)},c=()=>{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"},d=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()});d.value=an.from(()=>x.disconnect()),x.observe(f,{attributeFilter:["aria-level"],attributes:!0}),g()}):r.style.zIndex=""},h=new ft(d,new mP(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(()=>{c()}),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||c()}),this.map[t.api.id].disposable.dispose(),this.map[t.api.id].disposable=h,this.map[t.api.id].resize=l,r}};function tk(e,t,n,s,o,r,a){try{var l=e[r](a),c=l.value}catch(d){n(d);return}l.done?t(c):Promise.resolve(c).then(s,o)}function FP(e){return function(){var t=this,n=arguments;return new Promise(function(s,o){var r=e.apply(t,n);function a(c){tk(r,s,o,a,l,"next",c)}function l(c){tk(r,s,o,a,l,"throw",c)}a(void 0)})}}function Qoe(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 ere=class extends ft{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 be,this.onWillClose=this._onWillClose.event,this._onDidClose=new be,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 FP(function*(){var t,n;if(e._window)throw new Error("instance of popout window is already open");const s=`${e.options.url}`;Qoe(s);const o=Object.entries({top:e.options.top,left:e.options.left,width:e.options.width,height:e.options.height}).map(([c,d])=>`${c}=${d}`).join(","),r=window.open(s,e.target,o);if(!r)return null;const a=new ft;e._window={value:r,disposable:a},a.addDisposables(an.from(()=>{r.close()}),lt(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((c,d)=>{r.addEventListener("unload",()=>{}),a.addDisposables(e.onWillClose(()=>c(null))),r.addEventListener("load",()=>{try{const u=r.document;u.title=document.title,u.body.appendChild(l),Kse(u,globalThis.document.styleSheets,{nonce:e.options.nonce}),lt(r,"beforeunload",()=>{e.close()}),c(l)}catch(u){d(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}},tre=class extends ft{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 nre(e){if(!e.matchMedia)return!1;const t=e.matchMedia("(pointer: coarse)").matches,n=e.matchMedia("(pointer: fine)").matches;return t&&!n}function sre(e){var t,n,s,o,r,a,l;const c=(t=e.window)!==null&&t!==void 0?t:window,d=(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 ft,y=b=>{var w,C;if(e.isInside)return e.isInside(b);const _=b.target;return _ instanceof Node?((w=(C=e.elements)===null||C===void 0?void 0:C.call(e))!==null&&w!==void 0?w:[]).some(N=>N.contains(_)):!1};if((u||h.length>0)&&v.addDisposables(lt(c,"keydown",b=>{(u&&b.key==="Escape"||h.includes(b.key))&&e.onDismiss()},d)),(p||e.onInsidePointerDown)&&v.addDisposables(lt(c,"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()},d)),e.resize&&v.addDisposables(lt(c,"resize",()=>{nre(c)||e.onDismiss()})),e.focusOut){const b=C=>{var _,N;return e.isFocusInside?e.isFocusInside(C):((_=(N=e.elements)===null||N===void 0?void 0:N.call(e))!==null&&_!==void 0?_:[]).some(S=>S.contains(C))},w=C=>{const _=C.target;_ instanceof Element&&!b(_)&&e.onDismiss()};c.addEventListener("focusin",w,d),v.addDisposables({dispose:()=>c.removeEventListener("focusin",w,d)})}return v}var nk=class extends ft{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=sre({window:this._window,onDismiss:()=>this.close(),elements:()=>this._active?[this._active]:[],keys:["Enter"],pointerDownGraceMs:l,resize:!0}),this._window.requestAnimationFrame(()=>{Qse(s,this._root)})}close(){this._active&&(this._active.remove(),this._activeDisposable.dispose(),this._active=null)}},Cf=class extends ft{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}},ire=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 be,this.onDidChange=this._onDidChange.event,this.snap=!1,this.priority="low",this._isCollapsed=!1,this._tabSizeDisposables=new ft,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(Nr(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()}},ore=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 be,this.onDidChange=this._onDidChange.event}layout(e,t){this._layoutDockview(t,e)}setVisible(e){}dispose(){this._onDidChange.dispose()}},rre=class{get element(){return this._element}constructor(e,t=0){this._onDidChange=new be,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 kr(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()}},are=class{constructor(e,t,n,s=0,o=35){this._disposables=new ft,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 ore(t,n);this._middleColumn=new rre(r,s),this._outerSplitview=new kr(this._shellElement,{orientation:"HORIZONTAL",proportionalLayout:!1,margin:s}),this._middleIndex=0,this._outerSplitview.addView(this._middleColumn,{type:"distribute"},0),this._disposables.addDisposables(Nr(this._shellElement,a=>{if(!this._shellElement.offsetParent||!oP(this._shellElement))return;const l=Math.round(a.contentRect.width),c=Math.round(a.contentRect.height);l===this._currentWidth&&c===this._currentHeight||(this._currentWidth=l,this._currentHeight=c,this.layout(l,c))}),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",c=l?r:a,d=l?"horizontal":"vertical",u=new ire(gt({collapsedSize:this._defaultCollapsedSize},t),n,d,c),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),c=a>1?e*(a-1)/a:0,d=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,d);const p=this._viewConfigs.get("bottom");this._bottomView&&p&&u(this._bottomView,p,d);const f=this._viewConfigs.get("left");this._leftView&&f&&u(this._leftView,f,c);const g=this._viewConfigs.get("right");this._rightView&&g&&u(this._rightView,g,c),!((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,c,d,u;(a=this._rightView)===null||a===void 0||a.restoreExpandedSize(e.right.size),(l=this._rightView)===null||l===void 0||l.setCollapsed((c=e.right.collapsed)!==null&&c!==void 0?c:!1),this._outerSplitview.resizeView(this._rightIndex,e.right.collapsed&&(d=(u=this._rightView)===null||u===void 0?void 0:u.collapsedSize)!==null&&d!==void 0?d: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,C;(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=(C=this._bottomView)===null||C===void 0?void 0:C.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 lre(e){var t;return new PP((t=e.tabGroupColors)!==null&&t!==void 0?t:Yv,e.tabGroupAccent!=="off")}function gd(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 kg=()=>({dispose:()=>{}}),cre=kg;var dre=class extends uP{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:kg}get onDidSnapTogether(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.onDidSnapTogether)!==null&&e!==void 0?e:kg}_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}),c=l?gt(gt({},o.proposed),l):o.proposed,d=s?(r=this._smartGuidesService)===null||r===void 0?void 0:r.transformFloatingGroupDrag({group:e,proposed:c,container:o.container,others:o.others,modifiers:o.modifiers}):void 0;return(a=d??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 RP({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 Zv({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:cre}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 EP(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 c=l.element.getBoundingClientRect(),d=c.left+c.width/2-s,u=c.top+c.height/2-o;let h;switch(t){case"left":h=d<0&&Math.abs(d)>=Math.abs(u);break;case"right":h=d>0&&Math.abs(d)>=Math.abs(u);break;case"up":h=u<0&&Math.abs(u)>=Math.abs(d);break;default:h=u>0&&Math.abs(u)>=Math.abs(d);break}if(!h)continue;const p=d*d+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=$v(),this._deserializer=new goe(this),this._moduleRegistry=new yoe,this._onWillDragPanel=new be,this.onWillDragPanel=this._onWillDragPanel.event,this._onWillDragGroup=new be,this.onWillDragGroup=this._onWillDragGroup.event,this._onDidDrop=new be,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new be,this.onWillDrop=this._onWillDrop.event,this._mutationDepth=0,this._pendingLocationChanges=new Map,this._origin="user",this._originDepth=0,this._onWillMutateLayout=new be,this.onWillMutateLayout=this._onWillMutateLayout.event,this._onDidMutateLayout=new be,this.onDidMutateLayout=this._onDidMutateLayout.event,this._onWillShowOverlay=new be,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onUnhandledDragOver=new be,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._onDidRemovePanel=new be,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidAddPanel=new be,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPopoutGroupSizeChange=new be,this.onDidPopoutGroupSizeChange=this._onDidPopoutGroupSizeChange.event,this._onDidPopoutGroupPositionChange=new be,this.onDidPopoutGroupPositionChange=this._onDidPopoutGroupPositionChange.event,this._onDidAddPopoutGroup=new be,this.onDidAddPopoutGroup=this._onDidAddPopoutGroup.event,this._onDidRemovePopoutGroup=new be,this.onDidRemovePopoutGroup=this._onDidRemovePopoutGroup.event,this._onDidChangePopouts=new be,this.onDidChangePopouts=this._onDidChangePopouts.event,this._onDidOpenPopoutWindowFail=new be,this.onDidOpenPopoutWindowFail=this._onDidOpenPopoutWindowFail.event,this._onDidStartFloatingGroupDrag=new be,this.onDidStartFloatingGroupDrag=this._onDidStartFloatingGroupDrag.event,this._onDidEndFloatingGroupDrag=new be,this.onDidEndFloatingGroupDrag=this._onDidEndFloatingGroupDrag.event,this._onDidLayoutFromJSON=new be,this.onDidLayoutFromJSON=this._onDidLayoutFromJSON.event,this._onDidActivePanelChange=new be({replay:!0}),this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidPanelPinnedChange=new be,this.onDidPanelPinnedChange=this._onDidPanelPinnedChange.event,this._onDidMovePanel=new be,this.onDidMovePanel=this._onDidMovePanel.event,this._onDidCreateTabGroup=new be,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new be,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new be,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new be,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new be,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new be,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,this._onDidMaximizedGroupChange=new be,this.onDidMaximizedGroupChange=this._onDidMaximizedGroupChange.event,this._inShellLayout=!1,this._onDidRemoveGroup=new be,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidEdgeGroupAutoHideChange=new be,this.onDidEdgeGroupAutoHideChange=this._onDidEdgeGroupAutoHideChange.event,this._onDidAddGroup=new be,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidOptionsChange=new be,this.onDidOptionsChange=this._onDidOptionsChange.event,this._onDidActiveGroupChange=new be,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._peekingGroups=new Set,this._moving=!1,this._options=t,this._tabGroupColorPalette=lre(t);const l=t.modules,c=l??[...Xoe,...Coe()];for(const h of c)this._moduleRegistry.register(h);this._moduleRegistry.initialize(this),this.reportMissingOptionModules(t);const d=this._popoutWindowService;d&&this.addDisposables(d.onDidRemove(h=>{this._onDidRemovePopoutGroup.fire({id:h.popoutGroup.id,group:h.popoutGroup,window:h.getWindow()})})),this.popupService=new nk(this.element),this._api=new Uv(this),this.disableResizing=!0,this.element.remove(),this._shellManager=new are(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 Uh(this._shellManager.element),this.rootDropTargetContainer=new Cf(this._shellManager.element,{disabled:!0}),this.floatingDropTargetContainer=new Cf(this._shellManager.element,{disabled:!1}),this.overlayRenderContainer=new ek(this._shellManager.element,this),this._floatingOverlayHost=document.createElement("div"),this._floatingOverlayHost.className="dv-floating-overlay-host",this._shellManager.element.appendChild(this._floatingOverlayHost),et(this.gridview.element,"dv-dockview",!0),et(this.element,"dv-debug",!!t.debug),this.updateTheme(),t.debug&&this.addDisposables(new tre(this)),this.addDisposables(an.from(()=>this._pendingLocationChanges.clear()),this.rootDropTargetContainer,this.floatingDropTargetContainer,lt(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,Zs.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})}),Zs.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 sc(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 pd&&e.model.location.type==="edge")return Promise.resolve(!1);if(e instanceof Br&&e.group.size===1)return this.addPopoutGroup(e.group,t);const c=Xse(this.gridview.element),d=this.element;function u(){var v,y;if(t?.position)return t.position;const b=(e instanceof pd?e.element:(v=(y=e.group)===null||y===void 0?void 0:y.element)!==null&&v!==void 0?v:d).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 ere(`${this.id}-${p}`,c??"",{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 ft(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 Br?e.group:e,C=e.api.location.type,_=w.element.parentElement!==null;let N;if(t?.overridePopoutGridview){var S;N=(S=t.overridePopoutGroup)!==null&&S!==void 0?S:w}else _?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 ek(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 D=!1;const P=()=>{D||(D=!0,I.dispose())};let T,z=[];if(!t?.overridePopoutGroup&&!t?.overridePopoutGridview&&_)if(e instanceof Br){const ke=e.group;this.movingLock(()=>{const Me=w.model.removePanel(e);N.model.openPanel(Me)}),z=[{panel:e,from:ke}]}else switch(this.movingLock(()=>gd({from:w,to:N})),z=N.panels.map(ke=>({panel:ke,from:w})),C){case"grid":w.api.setVisible(!1);break;case"floating":case"popout":var O;T=(O=this.floatingGroups.find(ke=>ke.group.api.id===e.api.id))===null||O===void 0?void 0:O.overlay.toJSON(),this.removeGroup(w);break}v.classList.add("dv-dockview"),v.style.overflow="hidden",v.appendChild(k),v.appendChild(I.element);const L=document.createElement("div"),V=new Cf(L,{disabled:this.rootDropTargetContainer.disabled});v.appendChild(L),N.model.dropTargetContainer=V;const X=new nk(v,g.window);if(x.addDisposables(X),N.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f},t?.overridePopoutGridview){const ke=this.groups.filter(Me=>I.element.contains(Me.element));for(const Me of ke)Me.model.renderContainer=A,Me.model.dropTargetContainer=V,Me.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f}}_&&e.api.location.type==="grid"&&e.api.setVisible(!1),this.doSetGroupAndPanelActive(N);const F=l.observeGridviewSize(g,I,A);F&&x.addDisposables(F);const ee=new Fn;x.addDisposables(ee);const H=ke=>{ee.value=new ft(ke.api.onDidActiveChange(Me=>{if(Me.isActive){var ge;(ge=g.window)===null||ge===void 0||ge.focus()}}),ke.api.onWillFocus(()=>{var Me;(Me=g.window)===null||Me===void 0||Me.focus()}))};H(N);const Q={},q=_&&w&&this.getPanel(w.id),ne={window:g,popoutGroup:N,gridview:I,overlayRenderContainer:A,dropTargetContainer:V,getWindow:()=>g.window,popoutUrl:f,referenceGroup:q?w.id:void 0,popupService:X,setAnchorGroup:ke=>{ne.popoutGroup=ke,H(ke)},disposable:{dispose:()=>(x.dispose(),Q.returnedGroup)}},me=Jse(g.window);x.addDisposables(me,Zse(g.window,()=>{this._onDidPopoutGroupSizeChange.fire({width:g.window.innerWidth,height:g.window.innerHeight,group:ne.popoutGroup})}),me.event(()=>{this._onDidPopoutGroupPositionChange.fire({screenX:g.window.screenX,screenY:g.window.screenY,group:ne.popoutGroup})}),lt(g.window,"resize",()=>{I.layout(g.window.innerWidth,g.window.innerHeight)}),A,an.from(()=>this.disposePopoutWindow({group:N,referenceGroup:w,popoutGridview:I,isGroupAddedToDom:_,floatingBox:T,disposePopoutGridview:P,closeResult:Q}))),l.add(ne),this._onDidAddPopoutGroup.fire({id:ne.popoutGroup.id,group:ne.popoutGroup,window:ne.getWindow()});for(const{panel:ke,from:Me}of z)this.fireDidMovePanel(ke,Me);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(()=>gd({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:c}=e;if(this.isDisposed){l();return}const d=!!(!((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(d){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(()=>gd({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,c.returnedGroup=n,!d){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 pd&&e.model.location.type==="edge")return;let n,s=[];if(e instanceof Br){const c=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:c}]}else{var o;n=e;const c=(o=this._popoutWindowService)===null||o===void 0?void 0:o.findReferenceGroupId(n),d=c?this.getPanel(c):void 0;typeof t?.skipRemoveGroup=="boolean"&&t.skipRemoveGroup||(d?(this.movingLock(()=>gd({from:e,to:d})),this.doRemoveGroup(e,{skipPopoutReturn:!0,skipPopoutAssociated:!0}),this.doRemoveGroup(d,{skipDispose:!0}),n=d,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 c={};return"left"in t.position?c.left=Math.max(t.position.left,0):"right"in t.position?c.right=Math.max(t.position.right,0):c.left=Do.left,"top"in t.position?c.top=Math.max(t.position.top,0):"bottom"in t.position?c.bottom=Math.max(t.position.bottom,0):c.top=Do.top,typeof t.width=="number"?c.width=Math.max(t.width,0):c.width=Do.width,typeof t.height=="number"?c.height=Math.max(t.height,0):c.height=Do.height,c}return{left:typeof t?.x=="number"?Math.max(t.x,0):Do.left,top:typeof t?.y=="number"?Math.max(t.y,0):Do.top,width:typeof t?.width=="number"?Math.max(t.width,0):Do.width,height:typeof t?.height=="number"?Math.max(t.height,0):Do.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:c,from:d}of s)this.fireDidMovePanel(c,d)}createNestedGridview(e="HORIZONTAL"){var t,n;return new dP(!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,c,d,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 boe(this,t):void 0,v=new e0(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:(c=(d=this.options.floatingGroupBounds)===null||d===void 0?void 0:d.minimumWidthWithinViewport)!==null&&c!==void 0?c: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 c;(c=this._watermarkService)===null||c===void 0||c.refresh();for(const u of this.groups)u.model.refreshWatermark()}if("tabGroupColors"in e||"tabGroupAccent"in e){var d;this._tabGroupColorPalette.setEntries((d=this._options.tabGroupColors)!==null&&d!==void 0?d:Yv),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){joe(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(zP("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:Kie(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:[],c=(n=(s=this._popoutWindowService)===null||s===void 0?void 0:s.serialize())!==null&&n!==void 0?n:[],d={grid:r,panels:a,activeGroup:(o=this.activeGroup)===null||o===void 0?void 0:o.id};l.length>0&&(d.floatingGroups=l),c.length>0&&(d.popoutGroups=c);const u=this._serializeEdgeGroups();return u&&(d.edgeGroups=u),d}_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=[],c=()=>{for(const w of l)try{w.dispose()}catch(C){console.error("dockview: failed to dispose a temporary group created for reuseExistingPanels",C)}l.length=0};if(t?.reuseExistingPanels){const w=Object.keys(e.panels);let C;const _=()=>{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=_();else{var d;(d=C)!==null&&d!==void 0||(C=_()),S=C}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 c(),N}}else this.clear();const{grid:u,panels:h,activeGroup:p}=e;try{var f,g,x,v,y;const w=this.width,C=this.height,_=S=>{const{id:k,locked:A,hideHeader:I,headerPosition:D,views:P,activeView:T}=S;if(typeof k!="string")throw new TypeError("dockview: group id must be of type string");const z=this.createGroup({id:k,locked:!!A,hideHeader:!!I,headerPosition:D});this._onDidAddGroup.fire(z);const O=[],L=P.filter(V=>h[V]);for(const V of L){const X=o.get(V),F=r.get(V);if(F&&X)this.movingLock(()=>{F.model.removePanel(X)}),O.push(X),X.updateFromStateModel(h[V]);else{const ee=this._deserializer.fromJSON(h[V],z);O.push(ee)}}for(const V of O){const X=typeof T=="string"&&T===V.id;o.has(V.api.id)?this.movingLock(()=>{z.model.openPanel(V,{skipSetActive:!X,skipSetGroupActive:!0})}):z.model.openPanel(V,{skipSetActive:!X,skipSetGroupActive:!0})}return S.tabGroups&&S.tabGroups.length>0&&z.model.restoreTabGroups(S.tabGroups),!z.activePanel&&z.panels.length>0&&z.model.openPanel(z.panels[z.panels.length-1],{skipSetGroupActive:!0}),z};this.gridview.deserialize(u,{fromJSON:S=>_(S.data)}),this._layoutFromShell(w,C),e.edgeGroups&&this.deserializeEdgeGroups(e.edgeGroups,h,o,r),this.deserializeFloatingWindows((f=e.floatingGroups)!==null&&f!==void 0?f:[],_);const N=this.deserializePopoutWindows((g=e.popoutGroups)!==null&&g!==void 0?g:[],_);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 C of this.groups)for(const _ of C.panels)this.removePanel(_,{removeEmptyGroup:!1,skipDispose:!1});for(const C of this.groups)C.dispose(),this._groups.delete(C.id),this._onDidRemoveGroup.fire(C);throw(b=this._floatingGroupService)===null||b===void 0||b.disposeAll(),this.clear(),w}finally{c()}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 c=l.group,d=(r=c?.id)!==null&&r!==void 0?r:`${a}-group`;this.addEdgeGroup(a,{id:d,autoReveal:l.autoReveal,autoHide:l.autoHide,minimumSize:l.minimumSize,maximumSize:l.maximumSize,collapsedSize:l.collapsedSize})}}for(const[a,l]of o.entries()){const c=e[a],d=c?.group;if(d){const{views:u,activeView:h}=d,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})}d.tabGroups&&d.tabGroups.length>0&&l.model.restoreTabGroups(d.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:c,url:d}=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:c?p:void 0,overridePopoutGridview:u,referenceGroup:c?this.getPanel(c):void 0,popoutUrl:d})},()=>{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(qie(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(Yie(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(UC(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 c;if(t){var d;const u=Vu(((d=e.position)===null||d===void 0?void 0:d.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})),c=this.createPanel(e,h),h.model.openPanel(c,{skipSetActive:o(h),skipSetGroupActive:e.inactive,index:s})}else if(t.api.location.type==="floating"||t.api.location.type==="edge"||u==="center")c=this.createPanel(e,t),t.model.openPanel(c,{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=$s(this.gridview.orientation,h,u),f=this.createGroupAtLocation(p,this.orientationAtLocation(p)==="VERTICAL"?n?.height:n?.width);c=this.createPanel(e,f),f.model.openPanel(c,{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})),c=this.createPanel(e,u),u.model.openPanel(c,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s})}else{const u=this.createGroupAtLocation([0],this.gridview.orientation==="VERTICAL"?n?.height:n?.width);c=this.createPanel(e,u),u.model.openPanel(c,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(u)}return c}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 xoe}addGroup(e){return this.mutation("add",()=>this._doAddGroup(e))}_doAddGroup(e){if(e){let o;if(Xie(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(Jie(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(UC(e.direction),e);return e.skipSetActive||this.doSetGroupAndPanelActive(u),u}const r=Vu(e.direction||"within"),a=Tn(o.element),l=$s(this.gridview.orientation,a,r),c=this.createGroup(e),d=this.getLocationOrientation(l)==="VERTICAL"?e.initialHeight:e.initialWidth;return this.doAddGroup(c,l,d),e.skipSetActive||this.doSetGroupAndPanelActive(c),c}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,c;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)}(c=this._popoutWindowService)===null||c===void 0||c.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 d=super.doRemoveGroup(e,t);return t?.skipActive||this.activePanel!==r&&this.fireActivePanelChange(this.activePanel),d}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 FP(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 d=this.movingLock(()=>l.model.removePanel(o,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!d)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(d,{index:a,skipSetActive:((h=e.skipSetActive)!==null&&h!==void 0?h:!1)&&!u,skipSetGroupActive:!0})}),e.skipSetActive||this.doSetGroupAndPanelActive(n),this.fireDidMovePanel(d,l)}else{const d=this.getGridviewForGroup(n),u=Tn(n.element),h=$s(d.orientation,u,r);if(l.size<2){const[p,f]=co(h);if(l.api.location.type==="grid"&&d===this.gridview){const[y,b]=co(Tn(l.element));if(aP(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 c;const y=(c=this._popoutWindowService)===null||c===void 0?void 0:c.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=$s(d.orientation,Tn(n.element),r),C=this.createGroupAtLocation(w,void 0,void 0,d);this.movingLock(()=>C.model.openPanel(b,{skipSetActive:!0})),this.doSetGroupAndPanelActive(C),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,d);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=$s(d.orientation,x,r);this.movingLock(()=>this.doAddGroup(g,v,void 0,d)),this.setGroupLocationForRoot(g,d),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=$s(d.orientation,u,r),g=this.createGroupAtLocation(f,void 0,void 0,d);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,c=a.color,d=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:c,collapsed:d,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=$s(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 c,d;const u=(c=this._popoutWindowService)===null||c===void 0?void 0:c.findByGroup(n);if(!u)throw new Error("dockview: failed to find popout group");if(this.detachFromNestedWindow(n))break;if((d=this._popoutWindowService)===null||d===void 0||d.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=$s(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 pd(this,n,e);if(s.init({params:{},accessor:this}),!this._groups.has(s.id)){const o=new ft(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:c,index:d,tabGroupId:u}=r;this.moveGroupOrPanel({from:{groupId:a,panelId:l,tabGroupId:u},to:{group:s,position:c,index:d}})}),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)}),Zs.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 OP(this,e.id,r,a),c=new Br(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 c.init({title:(s=e.title)!==null&&s!==void 0?s:e.id,params:(o=e?.params)!==null&&o!==void 0?o:{}}),c}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:Pi(t)}updateTheme(){var e,t,n,s,o,r,a,l;const c=(e=this._options.theme)!==null&&e!==void 0?e:foe;(t=this._shellThemeClassnames)===null||t===void 0||t.setClassNames(c.className);const d=(n=c.gap)!==null&&n!==void 0?n:0;this.gridview.margin=d;for(const f of this.floatingGroups)f.gridview.margin=d;for(const f of(s=(o=this._popoutWindowService)===null||o===void 0?void 0:o.entries)!==null&&s!==void 0?s:[])f.gridview.margin=d;if((r=this._shellManager)===null||r===void 0||r.updateTheme(d,(a=c.edgeGroupCollapsedSize)!==null&&a!==void 0?a:35),c.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",c.dndOverlayBorder),(h=this._shellManager)===null||h===void 0||h.element.style.setProperty("--dv-drag-over-border",c.dndOverlayBorder)}c.dndOverlayMounting==="absolute"?this.rootDropTargetContainer.disabled=!1:this.rootDropTargetContainer.disabled=!0;const p=((l=c.tabGroupIndicator)!==null&&l!==void 0?l:"wrap")==="none";et(this.element,"dv-tab-group-indicator-none",p),this._shellManager&&et(this._shellManager.element,"dv-tab-group-indicator-none",p);for(const f of this.groups)f.model.updateTabGroups()}},ure=class extends uP{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 be,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidRemoveGroup=new be,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidAddGroup=new be,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidActiveGroupChange=new be,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,c=this.options.createComponent({id:l.id,name:l.component});return s.push(()=>c.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(c),this.registerPanel(c),c}}),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=Vu(t.direction);if(o==="center")throw new Error(`${o} not supported as an option`);const r=Tn(s.element),a=$s(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 c=Vu(e.position.direction);if(c==="center")throw new Error(`${c} not supported as an option`);{const d=Tn(l.element);o=$s(this.gridview.orientation,d,c)}}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 ft(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]=co($s(this.gridview.orientation,o,n)),[l,c]=co(Tn(s.element));if(aP(l,r)){this.gridview.moveView(l,c,a);return}const d=this.doRemoveGroup(s,{skipActive:!0,skipDispose:!0}),u=Tn(e.element),h=$s(this.gridview.orientation,u,n);this.doAddGroup(d,h)}removeGroup(e){super.removeGroup(e)}dispose(){super.dispose(),this._onDidLayoutfromJSON.dispose()}},hre=class extends Wv{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 ft(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 be,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidAddView=new be,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new be,this.onDidRemoveView=this._onDidRemoveView.event,this._onDidLayoutChange=new be,this.onDidLayoutChange=this._onDidLayoutChange.event,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new Uh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.splitview=new kr(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 kr(this.element,{orientation:n,proportionalLayout:this.options.proportionalLayout,descriptor:{size:s,views:t.map(c=>{const d=c.data;if(this._panels.has(d.id))throw new Error(`panel ${d.id} already exists`);const u=this.options.createComponent({id:d.id,name:d.component});return r.push(()=>{var h;u.init({params:(h=d.params)!==null&&h!==void 0?h:{},minimumSize:d.minimumSize,maximumSize:d.maximumSize,snap:c.snap,priority:c.priority,accessor:this})}),u.orientation=n,this.doAddView(u),setTimeout(()=>{this._onDidAddView.fire(u)},0),{size:c.size,view:u}})}}),this.layout(a,l),r.forEach(c=>c()),typeof o=="string"){const c=this.getPanel(o);c&&this.setActive(c)}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()}},sk=class extends ft{get element(){return this._element}constructor(){super(),this._expandedIcon=Gie(),this._collapsedIcon=_P(),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(lt(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);et(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 pre=$v(),ik=22,ok=0,rk=Number.MAX_SAFE_INTEGER;var ak=class extends Mie{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}},fre=class extends Wv{get id(){return this._id}get panels(){return this.paneview.getPanes()}set paneview(e){this._paneview=e,this._disposable.value=new ft(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=pre.next(),this._disposable=new Fn,this._viewDisposables=new Map,this._onDidLayoutfromJSON=new be,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidLayoutChange=new be,this.onDidLayoutChange=this._onDidLayoutChange.event,this._onDidDrop=new be,this.onDidDrop=this._onDidDrop.event,this._onDidAddView=new be,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new be,this.onDidRemoveView=this._onDidRemoveView.event,this._onUnhandledDragOver=new be,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 Uh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.paneview=new $C(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 sk);const a=new ak({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:ik,minimumBodySize:ok,maximumBodySize:rk});this.doAddPanel(a);const l=typeof e.size=="number"?e.size:js.Distribute,c=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 nc(this),accessor:this}),this.paneview.addPane(a,l,c),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 $C(this.element,{orientation:"VERTICAL",descriptor:{size:n,views:t.map(a=>{var l,c,d,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 sk);const g=new ak({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:(c=a.headerSize)!==null&&c!==void 0?c:ik,minimumBodySize:(d=a.minimumSize)!==null&&d!==void 0?d:ok,maximumBodySize:(u=a.maximumSize)!==null&&u!==void 0?u:rk});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 nc(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 ft(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()}},mre=class extends Kv{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 kP(e,t)),this._evaluatedMinimumSize=0,this._evaluatedMaximumSize=Number.POSITIVE_INFINITY,this._minimumSize=0,this._maximumSize=Number.POSITIVE_INFINITY,this._snap=!1,this._onDidChange=new be,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 gre(e,t){return new dre(e,t).api}function xre(e,t){return new pP(new hre(e,t))}function vre(e,t){return new fP(new ure(e,t))}function bre(e,t){return new nc(new fre(e,t))}function ic(e){"@babel/helpers - typeof";return ic=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},ic(e)}function wre(e,t){if(ic(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(ic(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function yre(e){var t=wre(e,"string");return ic(t)=="symbol"?t:t+""}function Sre(e,t,n){return(t=yre(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lk(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?lk(Object(n),!0).forEach(function(s){Sre(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lk(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}const HP=(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)};HP.displayName="DockviewReactJsBridge";const Cre=(()=>{let e=1;return{next:()=>`dockview_react_portal_key_${(e++).toString()}`}})(),kre=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(!jre(this.component))throw new Error("Dockview: Only React.memo(...), React.ForwardRef(...) and functional components are accepted as components");const e=Ne.createElement(Ne.forwardRef(HP),{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(kre.Provider,{value:this.context},e):e,n=Xk.createPortal(t,this.parent,Cre.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 Yh=()=>{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 jre(e){return typeof e=="function"||!!e?.$$typeof}var ck=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._onDidFocus=new be,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new be,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()}},dk=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()}},uk=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()}},_re=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 ft(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}})}},Nre=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()}},hk=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()}},pk=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 Or(e,t){return e?n=>new _re(e,t,n):void 0}const xd="props.defaultTabComponent";function Tre(e){return Cg.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]=Yh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};Cg.forEach(c=>{const d=c,u=e[d];d in e&&u!==a.current[d]&&(l[d]=u)}),s.current&&s.current.updateOptions(l),a.current=e},Cg.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return;const l=Es({},e.tabComponents);e.defaultTabComponent&&(l[xd]=e.defaultTabComponent);const c={createLeftHeaderActionComponent:Or(e.leftHeaderActionsComponent,{addPortal:r}),createRightHeaderActionComponent:Or(e.rightHeaderActionsComponent,{addPortal:r}),createPrefixHeaderActionComponent:Or(e.prefixHeaderActionsComponent,{addPortal:r}),createComponent:f=>new ck(f.id,e.components[f.name],{addPortal:r}),createTabComponent(f){return new dk(f.id,l[f.name],{addPortal:r})},createWatermarkComponent:e.watermarkComponent?()=>new uk("watermark",e.watermarkComponent,{addPortal:r}):void 0,defaultTabComponent:e.defaultTabComponent?xd:void 0,createContextMenuItemComponent:f=>{if(f.component)return new Nre(f.id,f.component,{addPortal:r})}},d=Tre(e);if(e.tabGroupChipComponent){const f=e.tabGroupChipComponent;d.createTabGroupChipComponent=()=>new hk(f,{addPortal:r})}if(e.groupDragGhostComponent){const f=e.groupDragGhostComponent;d.createGroupDragGhostComponent=()=>new pk(f,{addPortal:r})}const u=gre(n.current,Es(Es({},d),c)),{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(c=>{e.onDidDrop&&e.onDidDrop(c)});return()=>{l.dispose()}},[e.onDidDrop]),Ne.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onWillDrop(c=>{e.onWillDrop&&e.onWillDrop(c)});return()=>{l.dispose()}},[e.onWillDrop]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createTabGroupChipComponent:e.tabGroupChipComponent?()=>new hk(e.tabGroupChipComponent,{addPortal:r}):void 0})},[e.tabGroupChipComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createGroupDragGhostComponent:e.groupDragGhostComponent?()=>new pk(e.groupDragGhostComponent,{addPortal:r}):void 0})},[e.groupDragGhostComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new ck(l.id,e.components[l.name],{addPortal:r})})},[e.components]),Ne.useEffect(()=>{if(!s.current)return;const l=Es({},e.tabComponents);e.defaultTabComponent&&(l[xd]=e.defaultTabComponent),s.current.updateOptions({defaultTabComponent:e.defaultTabComponent?xd:void 0,createTabComponent(c){return new dk(c.id,l[c.name],{addPortal:r})}})},[e.tabComponents,e.defaultTabComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createWatermarkComponent:e.watermarkComponent?()=>new uk("watermark",e.watermarkComponent,{addPortal:r}):void 0})},[e.watermarkComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createRightHeaderActionComponent:Or(e.rightHeaderActionsComponent,{addPortal:r})})},[e.rightHeaderActionsComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createLeftHeaderActionComponent:Or(e.leftHeaderActionsComponent,{addPortal:r})})},[e.leftHeaderActionsComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createPrefixHeaderActionComponent:Or(e.prefixHeaderActionsComponent,{addPortal:r})})},[e.prefixHeaderActionsComponent]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});BP.displayName="DockviewComponent";var fk=class extends mre{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 pP(this._params.accessor)})}};function Dre(e){return fg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Ire=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=Yh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};fg.forEach(c=>{const d=c,u=e[d];d in e&&u!==a.current[d]&&(l[d]=u)}),s.current&&s.current.updateOptions(l),a.current=e},fg.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return()=>{};const l=xre(n.current,Es(Es({},Dre(e)),{createComponent:u=>new fk(u.id,u.name,e.components[u.name],{addPortal:r})})),{clientWidth:c,clientHeight:d}=n.current;return l.layout(c,d),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 fk(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Ire.displayName="SplitviewComponent";var mk=class extends LP{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 fP(this._params.accessor)})}};function Ere(e){return bg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Pre=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=Yh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};bg.forEach(c=>{const d=c,u=e[d];d in e&&u!==a.current[d]&&(l[d]=u)}),s.current&&s.current.updateOptions(l),a.current=e},bg.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return()=>{};const l=vre(n.current,Es(Es({},Ere(e)),{createComponent:u=>new mk(u.id,u.name,e.components[u.name],{addPortal:r})})),{clientWidth:c,clientHeight:d}=n.current;return l.layout(c,d),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 mk(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Pre.displayName="GridviewComponent";var vd=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 Are(e){return yg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Mre=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=Yh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};yg.forEach(c=>{const d=c,u=e[d];d in e&&u!==a.current[d]&&(l[d]=u)}),s.current&&s.current.updateOptions(l),a.current=e},yg.map(l=>e[l])),Ne.useEffect(()=>{var l;if(!n.current)return()=>{};const c=(l=e.headerComponents)!==null&&l!==void 0?l:{},d=bre(n.current,Es(Es({},Are(e)),{createComponent:p=>new vd(p.id,e.components[p.name],{addPortal:r}),createHeaderComponent:p=>new vd(p.id,c[p.name],{addPortal:r})})),{clientWidth:u,clientHeight:h}=n.current;return d.layout(u,h),e.onReady&&e.onReady({api:d}),s.current=d,()=>{s.current=void 0,d.dispose()}},[]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new vd(l.id,e.components[l.name],{addPortal:r})})},[e.components]),Ne.useEffect(()=>{var l;if(!s.current)return;const c=(l=e.headerComponents)!==null&&l!==void 0?l:{};s.current.updateOptions({createHeaderComponent:d=>new vd(d.id,c[d.name],{addPortal:r})})},[e.headerComponents]),Ne.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onDidDrop(c=>{e.onDidDrop&&e.onDidDrop(c)});return()=>{l.dispose()}},[e.onDidDrop]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Mre.displayName="PaneviewComponent";function ia(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Rre(e,t,n){if(!ia(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 VP(e,t){if(ia(e)){if(e.type==="leaf"){const n=ia(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=VP(s,t);return o?[o]:[]}):[];return n.length===0?void 0:{type:"branch",data:n,size:e.size}}}}function Lre(e,t){if(!ia(e)||!ia(e.panels))return;const n={};for(const[a,l]of Object.entries(e.panels))Rre(a,l,t)&&(n[a]=l);const s=new Set(Object.keys(n));if(s.size===0)return;const o=ia(e.grid)?e.grid:void 0,r=o?VP(o.root,s):void 0;if(r)return{...e,panels:n,grid:{...o,root:r}}}function gk(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 Ore(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=gk(e)&&e!=="."?e:e.split("/").pop()??"",o=s.lastIndexOf("/"),r=o===-1?"":s.slice(0,o),a=r?`${r}/${n}`:n,l=[];for(const d of a.split("/"))if(!(d===""||d===".")){if(d===".."){if(l.length===0)return null;l.pop();continue}l.push(d)}const c=l.join("/");return!c||!gk(c)?null:c}function xk(e,t){const n=new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>]+))`,"i").exec(e);return n?n[1]??n[2]??n[3]??"":null}function zre(e,t,n){return e.replace(new RegExp(`\\b${t}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>]+)`,"i"),`${t}="${n}"`)}function Gre(e){return e?.trim().toLowerCase().split(/\s+/).includes("stylesheet")??!1}function Fre(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}catch{return null}}function Hre(e,t){const n=[],s=(o,r,a,l)=>{const c=r[1]??"";if(!l(c))return;const d=xk(c,a);if(d===null)return;const u=Ore(t,d);u&&n.push({start:r.index,end:r.index+r[0].length,kind:o,rel:u,attrs:c,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=>Gre(xk(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 Bre(e,t,n){const s=Hre(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 c=o.get(l.rel);if(!c){a+=l.full;continue}if(l.kind==="img"){const u=c.mime||"application/octet-stream";a+=`<img${zre(l.attrs,"src",`data:${u};base64,${c.base64}`)}>`;continue}const d=Fre(c.base64);if(d===null){a+=l.full;continue}a+=l.kind==="script"?`<script>${d.replace(/<\/script/gi,"<\\/script")}<\/script>`:`<style>${d.replace(/<\/style/gi,"<\\/style")}</style>`}return a+e.slice(r)}const Vre="plugin-view.html";function vk(){return document.documentElement.classList.contains("dark")?"dark":"light"}function $re({pluginId:e,viewId:t,sessionId:n}){const{t:s}=se(),o=I_().find(r=>r.pluginId===e&&r.id===t);return o?i.jsx($P,{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 $P({pluginId:e,entry:t,title:n,sessionId:s,file:o}){const r=m.useRef(null),[a,l]=m.useState(null),c=m.useRef(s);c.current=s;const d=m.useRef(o);d.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(bO(vk()))}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(xO(N.name,N.data))}catch{}}),C=CO(async(N,S)=>{const k=await window.electronAPI.extensionPlugins.call({pluginId:e,method:"renderer.call",payload:{method:N,args:S},sessionId:c.current});if(!k.ok)throw new Error(k.error);return k.value}),_=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=P=>{const T=wO(P.data);if(T){window.electronAPI.extensionPlugins.viewStateSet(e,T);return}const z=yO(P.data);if(z!==null){h.current=z,d.current?.onEdit(z);return}C(P.data).then(O=>{O&&!x&&v===S&&S.port1.postMessage(O)})};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 Bre(SO(k.base64),t,async P=>{const T=await window.electronAPI.extensionPlugins.asset(e,P);return T.ok?{mime:T.mime,base64:T.base64}:null});if(x||v!==S)return;const D=d.current;g.contentWindow?.postMessage({type:"enso-view-init",html:I,theme:vk(),storage:A.ok?A.state:{},...D?{file:{rel:D.rel,text:D.text}}:{}},"*",[S.port2])};return window.addEventListener("message",_),g.src=new URL(Vre,document.baseURI).href,()=>{x=!0,b.disconnect(),w(),window.removeEventListener("message",_),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(vO(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 Wre({conversationId:e,panelApi:t}){const{t:n}=se(),s=t.id.startsWith("btw:")?t.id.slice(4):t.id,o=Ca(),r=ye(L=>L.virtualModels),a=ye(L=>L.defaultModel),l=ye(L=>L.projects),c=ye(L=>L.projectGroups),d=yo(L=>L.snapshot),u=Xg(),[h,p]=m.useState("contextual"),[f,g]=m.useState(!1),[x]=m.useState(()=>uU(oe.getState().conversations[e]?.messages??[])),v=oe(Hf(L=>L.conversations[s]??null)),y=v?.title,b=v?.projectId,w=m.useMemo(()=>l.find(L=>L.id===b),[b,l]),C=m.useMemo(()=>eu(w,c),[w,c]),_=m.useMemo(()=>tu({defaultModel:a,...C,lastProviderId:v?.lastProviderId,lastModelId:v?.lastModelId,providers:o,credentials:Ll(d),virtualModels:r}),[r,v?.lastModelId,v?.lastProviderId,C,a,d,o]),N=_.source==="none"?void 0:u.find(L=>L.id===_.providerId),S=_.source==="none"?"":_.modelId,k=_.source==="none"?"":Bf(_)?_.providerId:N?.id??"",A=m.useMemo(()=>hU(v?.messages??[]),[v?.messages]),I=m.useRef(null),D=v?.status==="running",P=f||(v?l_({started:v.started,sessionFile:v.sessionFile,messages:v.messages,spawning:v.spawning,status:v.status,historyLoadAttempted:v.historyLoadAttempted}):!0),T=m.useMemo(()=>{const L={name:"/compact",description:n("Compact the context now (/compact [summary focus])")},V=new Set([L.name]);return[L,...(v?.commands??[]).filter(X=>!V.has(X.name))]},[v?.commands,n]);m.useEffect(()=>{const L=oe.getState().conversations[e],V=ye.getState();oe.getState().ensureBtwConversation({id:s,projectId:L?.projectId??"",btwParentId:e,rolePrompt:oy("contextual",x),lastProviderId:L?.lastProviderId??V.defaultModel?.providerId,lastModelId:L?.lastModelId??V.defaultModel?.modelId,reasoningEnabled:L?.reasoningEnabled??V.defaultReasoningEnabled,thinkingLevel:L?.thinkingLevel??V.defaultThinkingLevel,approvalMode:L?.approvalMode??"full",presetId:L?.presetId})},[e,s,x]),m.useEffect(()=>{y&&t.setTitle(y)},[t,y]);const z=L=>{L===h||f||(g(!0),(async()=>(oe.getState().abort(s),await oe.getState().resetBtwSession(s,oy(L,x)),p(L),t.setTitle(n("Btw")),g(!1)))())},O=()=>{const L=fU(A);if(L){if(!Eh(L)){ze({type:"warning",title:n("No Composer for this selection")});return}Co()}};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(bk,{label:n("Contextual"),active:h==="contextual",onClick:()=>z("contextual")}),i.jsx(bk,{label:n("Tangent"),active:h==="tangent",onClick:()=>z("tangent")}),i.jsx("button",{type:"button",className:"ml-auto rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",disabled:!A,onClick:O,children:n("Insert into chat")})]}),v?i.jsx(oE,{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(yr,{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(Fh,{retry:v.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(s)}}):null,i.jsx(qu.Provider,{value:b?{conversationId:s,projectId:b,...w?.path?{cwd:w.path}:{}}:null,children:i.jsx(Lv,{sessionId:s,tasks:v?.backgroundTasks??[],subagents:v?.subagents??[]},s)}),i.jsx(jh,{approvals:v?.pendingApprovals??[],allowSession:!0,onRespond:(L,V)=>{window.electronAPI.agent.respondApproval(s,L,V)}}),i.jsx(_h,{asks:v?.pendingAsks??[],onAnswer:(L,V)=>{window.electronAPI.agent.respondAsk(s,L,V)}}),i.jsx(xE,{conversationId:s,queued:v?.queuedMessages??[]}),i.jsx(Mv,{isolated:!0,cwd:w?.path,commands:T,running:D,busy:P,locked:(v?.pendingApprovals??[]).length>0,focusKey:s,injectedDraft:v?.draftText,injectedImages:v?.draftImages,injectedDraftAppend:v?.draftAppend,onDraftConsumed:()=>oe.getState().clearDraft(s),queuedCount:v?.queuedMessages?.length??0,onSteerQueued:()=>oe.getState().steerQueued(s),autoFocus:!1,placeholder:n("Ask aside…"),toolbar:i.jsx(ch,{providers:u,activeAccount:Yg(o,v??void 0),virtualModels:r,providerId:k,modelId:S,reasoningEnabled:v?.reasoningEnabled??!1,thinkingLevel:v?.thinkingLevel??"medium",onSelect:(L,V)=>oe.getState().setModel(s,L,V),onReasoningChange:L=>oe.getState().setReasoning(s,L),onThinkingChange:L=>oe.getState().setThinking(s,L),side:"top"}),onSend:L=>!k||!S||!w?!1:(I.current?.scrollToBottom(),oe.getState().send(L.text,{providerId:k,modelId:S,cwd:w.path},L.images,s),!0),onAbort:()=>{oe.getState().abort(s)}}),i.jsx(jE,{conversationId:s,cwd:w?.path})]})})]})}function bk({label:e,active:t,onClick:n}){return i.jsx("button",{type:"button",className:U("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 WP(e,t,n,s={}){const o=new Set,r=e.map(a=>{const l=`diff:${a.path}`;o.add(l);const c=t.has(l),d=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=!d||d.oldText!==u||d.newText!==h,f=p||!d?vo({name:a.path,contents:u},{name:a.path,contents:h}):d.fileDiff;(p||!d)&&(f.cacheKey=rv(a.path,u,h));const g=d?p||d.collapsed!==c?d.version+1:d.version:0;return n.set(l,{oldText:u,newText:h,collapsed:c,version:g,fileDiff:f}),{id:l,type:"diff",fileDiff:f,version:g,collapsed:c}});for(const a of n.keys())o.has(a)||n.delete(a);return r}const Ure={theme:wa,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0},Kre={height:"100%",overflow:"auto"},qre=new Set;function UP({result:e,loading:t}){const{t:n}=se(),s=rc(Ure),[o,r]=m.useState(!1),[a,l]=m.useState(!1),c=m.useRef(new Map);m.useEffect(()=>{let h=!0;return la().then(()=>{h&&r(!0)},()=>{h&&l(!0)}),()=>{h=!1}},[]);const d=m.useMemo(()=>WP(e?.ok?[e]:[],qre,c.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."):d[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(dD,{className:"min-h-0 w-full flex-1",items:d,style:Kre,options:s})})}function KP({tree:e,onToggle:t}){const{t:n}=se(),s=n(e?"List view":"Tree view");return i.jsx(xe,{variant:"ghost",size:"icon-xs",title:s,"aria-label":s,onClick:t,children:e?i.jsx(Hx,{className:"size-3.5"}):i.jsx(G6,{className:"size-3.5"})})}function qP({files:e,tree:t,children:n}){const s=m.useId(),[o,r]=m.useState(()=>new Set),a=m.useMemo(()=>{const c={name:"",path:"",directories:new Map,files:[]};if(!t)return c;for(const d of e){const u=d.path.split("/");let h=c;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(d)}return c},[e,t]),l=c=>i.jsxs(i.Fragment,{children:[[...c.directories.values()].sort((d,u)=>d.name.localeCompare(u.name)).map(d=>{const u=!o.has(d.path),h=`${s}-${encodeURIComponent(d.path)}`;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",title:d.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(d.path)?f.delete(d.path):f.add(d.path),f}),children:[i.jsx(Vn,{"aria-hidden":"true",className:U("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(Cc,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:d.name})]}),u&&i.jsx("div",{id:h,className:"ml-3 min-w-0 border-l pl-1",children:l(d)})]},`directory:${d.path}`)}),c.files.slice().sort((d,u)=>d.path.localeCompare(u.path)).map(d=>i.jsx(m.Fragment,{children:n(d)},`file:${d.path}`))]});return t?l(a):e.map(c=>i.jsx(m.Fragment,{children:n(c)},c.path))}const Yre={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 YP({file:e,selected:t,onSelect:n,actions:s,showDirectory:o=!0}){const{t:r}=se(),a=e.path.lastIndexOf("/"),l=e.path.slice(a+1),c=e.path.slice(0,Math.max(0,a)),d=Yre[e.status];return i.jsxs("div",{className:U("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(So,{"aria-hidden":"true",className:U("size-3.5 shrink-0",d.color)}),i.jsx("span",{className:U("truncate",!o&&"flex-1"),children:l}),o&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-[11px] text-muted-foreground",children:c}),i.jsxs("span",{className:U("shrink-0 font-mono text-[11px]",d.color),title:r(e.status),children:[i.jsx("span",{"aria-hidden":"true",children:d.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 XP({title:e,hasSelection:t,navigation:n,actions:s,children:o}){const{t:r}=se(),a=m.useId(),[l,c]=m.useState(!0),d=!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:U("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",d?"flex-1 @min-[720px]/git:w-[280px]":"shrink-0 @min-[720px]/git:w-8",d&&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":d,"aria-controls":a,disabled:!t,title:r(d?"Collapse list":"Expand list"),onClick:()=>c(!d),children:[i.jsx(Vn,{className:U("size-3.5 shrink-0",!d&&"-rotate-90")}),i.jsx("span",{className:U("truncate",!d&&"@min-[720px]/git:hidden"),children:e})]}),d&&s&&i.jsx("div",{className:"mr-1 flex shrink-0 items-center",children:s})]}),i.jsx("div",{id:a,className:U("flex min-h-0 flex-1 flex-col overflow-hidden",!d&&"hidden"),children:n})]}),i.jsx("div",{className:U("min-h-0 min-w-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex",t?"flex":"hidden"),children:o})]})})}function Xre({request:e,head:t,tree:n,onToggleTree:s}){const{t:o}=se(),r=m.useId(),[a,l]=m.useState([]),[c,d]=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,D]=m.useState(null),[P,T]=m.useState(null),[z,O]=m.useState(!1);return m.useEffect(()=>{let L=!0;return x(!0),y(null),window.electronAPI.git.history({...e,head:t??void 0,skip:c,limit:20}).then(V=>{L&&(V.ok?(l(X=>c===0?V.commits:[...X,...V.commits]),f(V.hasMore)):y(V.error))}).catch(()=>{L&&y("Could not load Git history.")}).finally(()=>{L&&x(!1)}),()=>{L=!1}},[e,t,c,u]),m.useEffect(()=>{if(!b)return;let L=!0;return S(!0),A(null),window.electronAPI.git.commitFiles({...e,hash:b.hash}).then(V=>{L&&(V.ok?_(V.files):A(V.error))}).catch(()=>{L&&A("Could not load the changed files.")}).finally(()=>{L&&S(!1)}),()=>{L=!1}},[e,b]),m.useEffect(()=>{if(!I||!b)return;let L=!0;return O(!0),window.electronAPI.git.commitDiff({...e,hash:b.hash,path:I}).then(V=>{L&&T(V)}).catch(()=>{L&&T({ok:!1,error:"Could not load the diff."})}).finally(()=>{L&&O(!1)}),()=>{L=!1}},[e,b,I]),i.jsxs(XP,{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(L=>{const V=b?.hash===L.hash;return i.jsxs("div",{children:[i.jsxs("button",{type:"button","aria-expanded":V,"aria-controls":V?`${r}-${L.hash}`:void 0,className:U("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",V&&"bg-brand/10 dark:bg-brand/15"),title:`${L.subject}
|
|
110
|
-
${L.hash}
|
|
111
|
-
${L.author} · ${L.date}`,onClick:()=>{w(V?null:L),_([]),S(!V),A(null),D(null),T(null),O(!1)},children:[i.jsx(Vn,{"aria-hidden":"true",className:U("mt-0.5 size-3.5 shrink-0 text-muted-foreground",!V&&"-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:L.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:L.hash.slice(0,7)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:L.author}),i.jsx("time",{className:"shrink-0",dateTime:L.date,children:new Date(L.date).toLocaleDateString()})]})]})]}),V&&i.jsx("div",{id:`${r}-${L.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)}):C.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(qP,{files:C,tree:n,children:X=>i.jsx(YP,{file:X,showDirectory:!n,selected:I===X.path,onSelect:()=>{I!==X.path&&(D(X.path),T(null),O(!0))}})},L.hash)})]},L.hash)}),g&&i.jsx("div",{className:"flex justify-center p-3",children:i.jsx(Yt,{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(xe,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>d(a.length),children:o("Load more commits")}),v&&i.jsx(xe,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>h(L=>L+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(UP,{result:P,loading:z})]})}function Jre({conversationId:e,projectId:t,disabled:n,unavailable:s,editWriteKey:o}){const{t:r}=se(),{visible:a}=UD(),l=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),[c,d]=m.useState(null),[u,h]=m.useState(!0),[p,f]=m.useState(null),[g,x]=m.useState(null),[v,y]=m.useState(null),[b,w]=m.useState("changes"),[C,_]=m.useState(!0),[N,S]=m.useState(""),[k,A]=m.useState(""),I=m.useRef(null),[D,P]=m.useState(null),[T,z]=m.useState(null),[O,L]=m.useState(null),[V,X]=m.useState(!1),[F,ee]=m.useState(0),H=m.useRef(!1),Q=m.useRef(!1),q=m.useRef(0),ne=m.useRef(0),me=m.useCallback(async(te=!1)=>{if(!a||n||s||Q.current||ne.current!==0&&!te)return;const pe=++q.current;ne.current=pe,te&&h(!0);try{const Te=await window.electronAPI.git.status(l);if(!H.current||pe!==q.current)return;Te.ok?(d(Te),f(null)):(d(null),f(Te.error))}catch{H.current&&pe===q.current&&(d(null),f("Could not read Git status."))}finally{ne.current===pe&&(ne.current=0),H.current&&pe===q.current&&h(!1)}},[a,n,s,l]);m.useEffect(()=>{H.current=!0;const te=()=>{me()},pe=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&me()},5e3);return window.addEventListener("focus",te),()=>{H.current=!1,q.current+=1,window.clearInterval(pe),window.removeEventListener("focus",te)}},[me]),m.useEffect(()=>{me(!0)},[me,o]),m.useEffect(()=>{if(!D||!c)return;(D.staged?c.staged:c.unstaged).some(pe=>pe.path===D.path)||(P(null),L(null),X(!1))},[D,c]),m.useEffect(()=>{if(!a||!D||n||s||v!==null||b!=="changes")return;let te=!0,pe=!1;const Te=async()=>{if(!pe){pe=!0;try{const Ze=await window.electronAPI.git.fileDiff({...l,...D});te&&L(Ze)}catch{te&&L({ok:!1,error:"Could not load the diff."})}finally{pe=!1,te&&X(!1)}}};Te();const $e=()=>{Te()},Ie=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&Te()},5e3);return window.addEventListener("focus",$e),()=>{te=!1,window.clearInterval(Ie),window.removeEventListener("focus",$e)}},[a,l,D,F,n,s,b,v]);const ke=async(te,pe,Te)=>{if(!(Q.current||n||s||u||!c)){Q.current=!0,q.current+=1,y(te),x(null);try{const $e=await pe();if(!H.current)return;$e.ok?Te?.():x($e.error)}catch{H.current&&x("Could not complete the Git operation.")}finally{Q.current=!1,H.current&&(y(null),ee($e=>$e+1),me(!0),oe.getState().refreshWorktreeStatuses().catch(()=>{}))}}},Me=n||s||u||v!==null||!c,ge=!Me&&!!N.trim()&&!!c?.staged.length,$=(te,pe)=>{D?.path===te.path&&D.staged===pe||(L(null),X(!0),P({path:te.path,staged:pe}))},W=[{id:"staged",staged:!0,title:r("Staged changes"),files:c?.staged??[]},{id:"unstaged",staged:!1,title:r("Unstaged changes"),files:c?.unstaged.filter(te=>te.status!=="untracked")??[]},{id:"untracked",staged:!1,title:r("Untracked changes"),files:c?.unstaged.filter(te=>te.status==="untracked")??[]}],ue=k.trim().toLowerCase(),Z=W.map(te=>({...te,files:te.files.filter(pe=>pe.path.toLowerCase().includes(ue))})),J=Z.reduce((te,pe)=>te+pe.files.length,0),ae=()=>{ge&&ke("Commit",()=>window.electronAPI.git.commit({...l,message:N}),()=>S(""))};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:[c&&!n&&!s&&!p&&i.jsxs("div",{className:"flex shrink-0 items-center gap-1",role:"tablist","aria-label":r("Git views"),children:[i.jsxs(xe,{role:"tab","aria-selected":b==="changes",variant:b==="changes"?"secondary":"ghost",size:"xs",onClick:()=>w("changes"),children:[i.jsx(l6,{className:"size-3.5"}),r("Changes")]}),i.jsxs(xe,{role:"tab","aria-selected":b==="history",variant:b==="history"?"secondary":"ghost",size:"xs",onClick:()=>w("history"),children:[i.jsx(Ko,{className:"size-3.5"}),r("History")]})]}),i.jsx(Ri,{className:"size-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-xs",title:c?.branch??void 0,children:c?.branch??r(c?"Detached HEAD":"Git")}),c?.upstream&&i.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",title:c.upstream,children:["↓",c.behind," ↑",c.ahead]}),c&&!c.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(sr,{title:r("Fetch"),disabled:Me,onClick:()=>{ke("Fetch",()=>window.electronAPI.git.fetch(l))},children:i.jsx(oc,{className:"size-3.5"})}),i.jsx(sr,{title:r("Pull"),disabled:Me||!c?.upstream,onClick:()=>{ke("Pull",()=>window.electronAPI.git.pull(l))},children:i.jsx(Qu,{className:"size-3.5"})}),i.jsx(sr,{title:r("Push"),disabled:Me||!c?.upstream,onClick:()=>{ke("Push",()=>window.electronAPI.git.push(l))},children:i.jsx(dc,{className:"size-3.5"})}),i.jsx(sr,{title:r("Refresh"),disabled:n||s||v!==null||u,onClick:()=>{ee(te=>te+1),me(!0)},children:i.jsx(Wo,{className:U("size-3.5",u&&!s&&!n&&"animate-spin")})})]}),v&&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(Yt,{className:"size-3 animate-spin"}),r(v),"…"]}),g&&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(g)}),s||n||p||!c?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.":p??"Loading...")}):b==="history"?i.jsx(Xre,{request:l,head:c.head,tree:C,onToggleTree:()=>_(te=>!te)},`${c.head}:${F}`):i.jsxs(XP,{title:r("Changed files"),hasSelection:D!==null,actions:i.jsx(KP,{tree:C,onToggle:()=>_(te=>!te)}),navigation:i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"shrink-0 px-2 pb-1.5",children:i.jsxs(sh,{className:"text-xs",children:[i.jsx(oh,{ref:I,size:"sm",type:"search",value:k,onChange:te=>A(te.target.value),placeholder:r("Filter changed files…"),"aria-label":r("Filter changed files…")}),k.length>0&&i.jsx(ih,{align:"inline-end",children:i.jsx(xe,{type:"button",variant:"ghost",size:"icon-xs",title:r("Clear"),"aria-label":r("Clear"),onClick:()=>{A(""),I.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:[Z.map(te=>te.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:[te.title," ",i.jsx("span",{className:"ml-1 font-normal",children:te.files.length})]}),i.jsx(sr,{title:r(te.staged?"Unstage all":"Stage all"),disabled:Me,onClick:()=>{ke(te.staged?"Unstage":"Stage",()=>window.electronAPI.git[te.staged?"unstage":"stage"]({...l,paths:te.files.map(pe=>pe.path)}))},children:te.staged?i.jsx(G0,{className:"size-3.5"}):i.jsx(us,{className:"size-3.5"})})]}),i.jsx(qP,{files:te.files,tree:C,children:pe=>i.jsx(YP,{file:pe,showDirectory:!C,selected:D?.path===pe.path&&D.staged===te.staged,onSelect:()=>$(pe,te.staged),actions:i.jsxs(i.Fragment,{children:[!te.staged&&i.jsx(sr,{title:r(pe.status==="untracked"?"Delete untracked file":"Discard changes"),disabled:Me||pe.status==="conflicted",onClick:()=>z(pe),children:i.jsx(fa,{className:"size-3.5"})}),i.jsx(sr,{title:r(te.staged?"Unstage":"Stage"),disabled:Me,onClick:()=>{ke(te.staged?"Unstage":"Stage",()=>window.electronAPI.git[te.staged?"unstage":"stage"]({...l,paths:[pe.path]}))},children:te.staged?i.jsx(G0,{className:"size-3.5"}):i.jsx(us,{className:"size-3.5"})})]})})},ue)]},te.id)),J===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(c.staged.length+c.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(Qs,{size:"sm",rows:3,value:N,"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:v!==null,onChange:te=>S(te.target.value),onKeyDown:te=>{(te.ctrlKey||te.metaKey)&&te.key==="Enter"&&!te.nativeEvent.isComposing&&(te.preventDefault(),ae())}}),i.jsxs(xe,{size:"xs",className:"mb-0.5 shrink-0",title:r("{{count}} staged files",{count:c.staged.length}),"aria-label":r("Commit"),disabled:!ge,onClick:ae,children:[i.jsx(N6,{className:"size-3.5"}),r("Commit"),c.staged.length>0&&i.jsx("span",{className:"font-mono text-[11px]",children:c.staged.length})]})]})]}),children:[D&&i.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:D.path,children:[r(D.staged?"Staged changes":"Unstaged changes")," · ",D.path]}),i.jsx(UP,{result:O,loading:D!==null&&V})]}),i.jsx(ms,{open:T!==null&&!Me,onOpenChange:te=>{te||z(null)},title:r(T?.status==="untracked"?"Delete untracked file":"Discard changes"),description:T?.status==="untracked"?r("Delete untracked file {{path}} permanently?",{path:T.path}):r("Restore {{path}} to its staged version? Unstaged changes will be lost.",{path:T?.path??""}),confirmLabel:r(T?.status==="untracked"?"Delete":"Discard"),onConfirm:()=>{T&&ke("Discard",()=>window.electronAPI.git.discard({...l,paths:[T.path],confirmUntracked:T.status==="untracked"}))}})]})}function sr({title:e,disabled:t,onClick:n,children:s}){return i.jsx(xe,{variant:"ghost",size:"icon-xs",title:e,"aria-label":e,disabled:t,onClick:n,children:s})}const JP=28,Zre={theme:wa,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0,itemMetrics:{diffHeaderHeight:JP}},Qre={height:"max-content",overflow:"auto"},eae={files:[],snapshots:{}},wk=[];function tae({conversationId:e,projectId:t}){const{t:n}=se(),s=rc(Zre),o=fn(ee=>ee.changesModeByConversation[e])??"all",r=fn(ee=>ee.setChangesMode),a=m.useRef(null),l=m.useRef(null),c=m.useRef(!1);m.useLayoutEffect(()=>{const ee=a.current,H=l.current,Q=ee?.querySelector('[aria-selected="true"]');!ee||!H||!Q||(c.current||(H.style.transition="none"),H.style.transform=`translate(${Q.offsetLeft}px, ${Q.offsetTop}px)`,H.style.width=`${Q.offsetWidth}px`,H.style.height=`${Q.offsetHeight}px`,c.current||(H.offsetWidth,H.style.transition="",c.current=!0))},[o]);const d=fn(ee=>ee.snapshotsByConversation[e]),u=fn(ee=>ee.saveSnapshots),h=fn(ee=>ee.loadSnapshots),p=oe(ee=>E_(ee.conversations[e]?.messages??wk)),f=oe(ee=>ee.workspaceRevisionByConversation[e]??0),g=oe(ee=>!!ee.conversations[e]?.workspaceMigrating),x=ye(ee=>ee.projects.find(H=>H.id===t)),v=oe(ee=>x?.kind==="scratch"?ex({kind:"scratch",canonicalPath:x.path,conversationId:e})??void 0:ee.conversations[e]?.worktree?.path??x?.path),y=oe(ee=>ee.conversations[e]?.status==="running"),b=m.useRef([]),w=m.useMemo(()=>{const ee=oe.getState().conversations[e],Q=wr(ee?.messages??wk,y,ee?.customEntries??[],v).flatMap(q=>q.kind!=="tool"?[]:q.name==="apply_patch"?(q.fileChanges??[]).map(ne=>({path:ne.path,edits:null,writeContent:null,fileChange:ne})):q.state!=="ok"||q.name!=="edit"&&q.name!=="write"?[]:q.summary?q.name==="edit"&&!(q.edits&&q.edits.length>0)?[]:q.name==="write"&&q.writeContent==null?[]:[{path:q.summary,edits:q.edits,writeContent:q.writeContent}]:[]);return J9(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 la().then(()=>{ee&&_(!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 H=!0;return Promise.all(ee.map(async Q=>{const q=Pg(Q,v),ne=q?await window.electronAPI.files.read({conversationId:e,projectId:t,rel:q}):lj(Q)?await window.electronAPI.files.read({conversationId:e,projectId:t,path:Q}):null;return[Q,ne]})).then(Q=>{if(!H)return;const q=Object.fromEntries(Q);S(ne=>Z9(ne,q)?ne:q)}),()=>{H=!1}},[e,o,t,v,w,g,f]);const k=m.useMemo(()=>d?Q9({tools:w,snapshots:d,currentByPath:N}):eae,[w,d,N]);m.useEffect(()=>{if(o!=="all"||!d)return;const ee=k.snapshots,H=Object.keys(ee);H.length===Object.keys(d).length&&H.every(Q=>d[Q]===ee[Q])||u(e,ee)},[k.snapshots,e,o,u,d]);const A=k.files,I=k.incompletePaths??[],[D,P]=m.useState(()=>new Set),T=m.useCallback(ee=>{P(H=>{const Q=new Set(H);return Q.delete(ee)||Q.add(ee),Q})},[]),z=m.useRef(new Map),O=m.useMemo(()=>WP(A,D,z.current),[A,D]),L=O.length>0&&O.every(ee=>ee.collapsed),V=()=>P(L?new Set:new Set(O.map(ee=>ee.id))),X=m.useCallback(ee=>i.jsx(nae,{item:ee,onToggle:()=>T(ee.id)}),[T]),F=!C||!d;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(yk,{active:o==="all",onClick:()=>r(e,"all"),children:n("Session")}),i.jsx(yk,{active:o==="git",onClick:()=>r(e,"git"),children:n("Git")})]}),o==="all"&&O.length>0&&i.jsx("button",{type:"button",onClick:V,title:n(L?"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:L?i.jsx(e_,{className:"h-3.5 w-3.5"}):i.jsx(A$,{className:"h-3.5 w-3.5"})})]}),i.jsx("div",{className:"min-h-0 flex-1",children:o==="git"?i.jsx(Jre,{conversationId:e,projectId:t,disabled:g,unavailable:x?.kind==="ssh",editWriteKey:p},`${e}:${v}:${f}`):F||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(F?"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(br,{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(dD,{className:"min-h-0 w-full",items:O,style:Qre,options:s,renderCustomHeader:X})})]})})]})}function nae({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:JP},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(Vn,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:r,children:r}),o>0&&i.jsxs("span",{className:"shrink-0 text-red-500",children:["-",o]}),s>0&&i.jsxs("span",{className:"shrink-0 text-green-600",children:["+",s]})]})}function yk({active:e,onClick:t,children:n}){return i.jsx("button",{type:"button",role:"tab",onClick:t,"aria-selected":e,className:U("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 sae(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 kf(e,t){const n=(e.split("/").at(-1)??"").toLowerCase();return t.map(s=>({viewer:s,length:sae(n,s.extensions)})).filter(s=>s.length>0).sort((s,o)=>o.length-s.length).map(s=>s.viewer)}const Ja=e=>`${e.pluginId}:${e.id}`;let ZP=[];const jg=new Set;function Sk(e){ZP=e;for(const t of jg)t()}function iae(e){return jg.add(e),()=>jg.delete(e)}const Ck=()=>ZP;function oae(){return m.useSyncExternalStore(iae,Ck,Ck)}function rae({conversationId:e,projectId:t,onOpenFile:n,onClose:s,menu:o}){const{t:r}=se(),a=m.useRef(0),[l,c]=m.useState(""),[d,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:d}).then(b=>{v===a.current&&(p(b),g(!1))})},150);return()=>clearTimeout(y)},[e,d,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=>c(x.target.value),onKeyDown:x=>{x.key==="Escape"&&s()},placeholder:r(d==="names"?"Search file names":"Search file contents"),"aria-label":r("Search")}),i.jsxs("div",{className:"flex gap-0.5",children:[i.jsx(jk,{active:d==="names",onClick:()=>u("names"),label:r("File name"),icon:kO}),i.jsx(jk,{active:d==="content",onClick:()=>u("content"),label:r("Content"),icon:So})]})]}),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(lae(h.error))}):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=Tc(x.name,!1);return i.jsx(kk,{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:U("mt-0.5 size-3.5 shrink-0",Dc(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(kk,{rel:x.relativePath,name:v,menu:o,onOpenFile:n,children:aae(x,n)},QP(x))}):null:i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Type to search this workspace.")})})]})}function QP(e){return`${e.relativePath}:${e.line}:${e.column}`}function aae(e,t){const n=e.relativePath.split("/").pop()||e.relativePath,s=Tc(n,!1);return i.jsxs("button",{type:"button","data-search-hit":QP(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:U("mt-0.5 size-3.5 shrink-0",Dc(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 kk({rel:e,name:t,menu:n,onOpenFile:s,children:o}){return i.jsx(dh,{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 lae(e){switch(e){case"unsupported":return"Search is not available for SSH workspaces.";case"rg-missing":return"Search needs ripgrep (rg). Install it and make sure it is on PATH.";case"timeout":return"Search timed out. Try a more specific query or a smaller folder.";default:return"Could not complete the file action."}}function jk({active:e,onClick:t,label:n,icon:s}){return i.jsxs(xe,{type:"button",variant:"ghost",size:"sm",className:U("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 cae=/^data:image\/(png|jpe?g|gif|webp|bmp|x-icon|svg\+xml);/i;function dae(){return{...Ac,attributes:{...Ac.attributes,source:[]},protocols:{...Ac.protocols,src:[...Ac.protocols?.src??[],"data"]}}}function uae(){return e=>{jO(e,"element",t=>{if(t.tagName!=="img")return;const n=t.properties?.src;typeof n!="string"||!n.startsWith("data:")||cae.test(n)||delete t.properties.src})}}const hae=[EO],pae=dae(),fae=[DO,[IO,pae],uae],mae=({children:e,node:t,...n})=>i.jsx("p",{className:"my-1.5 leading-relaxed first:mt-0 last:mb-0",...n,children:e}),gae=({children:e,node:t,...n})=>i.jsx("h1",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),xae=({children:e,node:t,...n})=>i.jsx("h2",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),vae=({children:e,node:t,...n})=>i.jsx("h3",{className:"mt-2 mb-1 text-sm font-semibold",...n,children:e}),bae=({children:e,node:t,...n})=>i.jsx("ul",{className:"my-1.5 list-disc pl-5 space-y-0.5",...n,children:e}),wae=({children:e,node:t,...n})=>i.jsx("ol",{className:"my-1.5 list-decimal pl-5 space-y-0.5",...n,children:e}),yae=({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}),Sae=({children:e,node:t,...n})=>i.jsx("td",{className:"whitespace-nowrap border-b border-border/50 px-2 py-1",...n,children:e}),Cae={p:mae,h1:gae,h2:xae,h3:vae,ul:bae,ol:wae,th:yae,td:Sae};function kae({text:e,baseDirRel:t,resolveImage:n,resolveRemoteImage:s}){const o=m.useRef(new Map),r=m.useMemo(()=>({..._O,...Cae,img:({node:c,src:d,alt:u,...h})=>i.jsx(jae,{src:typeof d=="string"?d: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(NO.Provider,{value:a,children:i.jsx("div",{style:PO(AO),children:i.jsx(TO,{remarkPlugins:hae,rehypePlugins:fae,components:r,urlTransform:l=>l,children:e})})})}function jae({src:e,alt:t,rest:n,baseDirRel:s,resolveImage:o,resolveRemoteImage:r,cache:a}){const l=e?MO(e):"unsupported",c=l==="local"&&e?`local:${F0(s,e)??""}`:e,[d,u]=m.useState(()=>l==="data"?e??null:c?a.get(c)??null:null);return m.useEffect(()=>{if(!e||l==="unsupported"){u(null);return}if(l==="data"){u(e);return}const h=c?a.get(c):void 0;if(h){u(h);return}let p=!0;return(l==="local"?(()=>{const g=F0(s,e);return g?o(g):Promise.resolve(null)})():r(RO(e))).then(g=>{p&&(g&&c&&a.set(c,g),u(g))}),()=>{p=!1}},[e,l,s,o,r,a,c]),d?i.jsx("img",{...n,src:d,alt:t,className:"max-w-full rounded",loading:"lazy"}):null}function eA(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 bd(e){const t=eA(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 _ae(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:eA(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 t0="\0preview";function tA(e){return`${e}${t0}`}function nA(e){return e.endsWith(t0)}function mr(e){return nA(e)?e.slice(0,-t0.length):e}function Nae(e,t){return e===t||e.startsWith(`${t}/`)}function _g(e,t){return Nae(mr(e),t)}function Tae(e,t){const n=e.trim();return!n||n===t?"cancel":"commit"}function wd(e,t,n){const s=nA(e),o=mr(e);let r=null;return o===t?r=n:o.startsWith(`${t}/`)&&(r=n+o.slice(t.length)),r==null?null:s?tA(r):r}function Dae(e){return e==="preview"?"source":"preview"}function Iae(e,t){const n=mr(e),s=[{id:"copy-path",rel:n,mode:"absolute"}];return t&&s.push({id:"reveal",rel:n}),s}function yd(e,t,n){return e.some(s=>s.epoch>n&&_g(t,s.rel))}async function Eae(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 _k(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 Ng(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 Pae={theme:wa,disableFileHeader:!0,overflow:"scroll",preferredHighlighter:"shiki-js"};function Aae(e){return new BO(e)}function Mae(e,t){return e?`${e}/${t}`:t}function zr(e){return e.split("/").pop()||e}function Rae(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}const jf=[];function Lae({conversationId:e,projectId:t}){const{t:n}=se(),s=rc(Pae),o=KD("files"),r=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),a=oe(K=>K.workspaceRevisionByConversation[e]??0),l=oe(K=>!!K.conversations[e]?.workspaceMigrating),c=m.useCallback(K=>Eae(()=>window.electronAPI.workspaceFiles.read({...r,rel:K}),()=>{const fe=oe.getState();return{revision:fe.workspaceRevisionByConversation[e]??0,migrating:!!fe.conversations[e]?.workspaceMigrating}}),[e,r]),[d,u]=m.useState(!1),[h,p]=m.useState([]),[f,g]=m.useState(null),x=oae(),v=m.useRef(x);v.current=x;const y=Sa(),[b,w]=m.useState(!0),C=m.useCallback(K=>{g(K),w(!1)},[]);m.useEffect(()=>{f||w(!0)},[f]);const[_,N]=m.useState(0),[S,k]=m.useState(()=>new Set),[A,I]=m.useState(!1),[D,P]=m.useState(null),[T,z]=m.useState(null),[O,L]=m.useState(null),V=ye(K=>K.projects.find(fe=>fe.id===t)),X=V?.kind!=="ssh",F=m.useRef(h);F.current=h;const ee=m.useRef(f);ee.current=f;const H=m.useRef(null),Q=m.useRef(null),q=m.useRef(null),ne=m.useRef(0),me=m.useRef([]),ke=m.useCallback(K=>{ne.current+=1,me.current.push({epoch:ne.current,rel:K}),me.current.length>200&&me.current.splice(0,100)},[]);m.useEffect(()=>{const K=q.current;if(!K||!f)return;K.querySelector(`[data-file-tab="${CSS.escape(f)}"]`)?.scrollIntoView({inline:"nearest",block:"nearest"})},[f]),m.useEffect(()=>{let K=!0;return la().then(()=>{K&&u(!0)}),()=>{K=!1}},[]);const Me=m.useCallback((K,fe)=>{p(De=>De.map(Pe=>Pe.rel===K?_k(Pe,fe):Pe))},[]),ge=m.useCallback(K=>{ze({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]),$=m.useCallback(async(K,fe)=>{if(F.current.find(st=>st.rel===K)){fe&&p(st=>st.map(we=>we.rel===K?{...we,viewMode:fe,viewer:void 0}:we)),C(K);return}const Pe=ne.current,Ge=await c(K);if(!(!Ge||yd(me.current,K,Pe))){if(!Ge.ok){if(Ge.error!=="too-large"){ge(Ge.error);return}p(st=>[...st,{rel:K,contents:"",draft:"",version:0,dirty:!1,conflict:!1,tooLarge:!0}]),C(K);return}p(st=>[...st,{rel:K,contents:Ge.content,draft:Ge.content,version:0,dirty:!1,conflict:!1,viewMode:fe,viewer:fe?void 0:(()=>{const we=kf(K,v.current).find(Qe=>Qe.default);return we?Ja(we):void 0})()}]),C(K),window.electronAPI.workspaceFiles.watchStart({...r,rel:K})}},[ge,c,r,C]),[W,ue]=m.useState(null),Z=m.useCallback(K=>{const fe=F.current,De=fe.filter(Pe=>!K(Pe.rel));for(const Pe of fe)K(Pe.rel)&&window.electronAPI.workspaceFiles.watchStop({...r,rel:Pe.rel});p(De),g(Pe=>Pe&&De.some(Ge=>Ge.rel===Pe)?Pe:De.at(-1)?.rel??null)},[r]),J=m.useCallback(K=>{Z(fe=>fe===K)},[Z]),ae=m.useCallback(K=>{if(F.current.find(De=>De.rel===K)?.dirty){ue({kind:"one",rel:K});return}J(K)},[J]);m.useEffect(()=>LO(e,()=>{const K=ee.current;return!K||F.current.length===0?!1:(ae(K),!0)}),[e,ae]),m.useEffect(()=>()=>{for(const K of F.current)window.electronAPI.workspaceFiles.watchStop({...r,rel:K.rel})},[r]),m.useEffect(()=>{let K=!0;const fe=window.electronAPI.workspaceFiles.onChange(De=>{De.conversationId!==e||!F.current.find(Ge=>Ge.rel===De.rel)||c(De.rel).then(Ge=>{K&&Ge?.ok&&Me(De.rel,Ge.content)})});return()=>{K=!1,fe()}},[Me,e,c]);const te=oe(K=>K.conversations[e]?.status==="running"),pe=oe(K=>V?.kind==="scratch"?ex({kind:"scratch",canonicalPath:V.path,conversationId:e})??void 0:K.conversations[e]?.worktree?.path??V?.path),Te=oe(K=>K.conversations[e]?.historyBaseIndex),$e=oe(K=>E_(K.conversations[e]?.messages??jf)),Ie=m.useMemo(()=>{const K=oe.getState().conversations[e];return wr(K?.messages??jf,te,K?.customEntries??[],pe).flatMap(fe=>fe.kind!=="tool"||fe.state!=="ok"?[]:fe.name!=="edit"&&fe.name!=="write"?[]:fe.summary?[fe.summary]:[]).join(`
|
|
112
|
-
`)},[e,$e,pe,te]);m.useEffect(()=>{let K=!0;const fe=new Set(Ie?Ie.split(`
|
|
113
|
-
`):[]);for(const De of fe)F.current.some(Pe=>Pe.rel===De)&&c(De).then(Pe=>{K&&Pe?.ok&&Me(De,Pe.content)});return()=>{K=!1}},[Me,c,Ie]);const Ze=m.useRef(null),Nt=m.useRef(e),Ut=m.useRef(Te),Pt=m.useCallback(()=>N(K=>K+1),[]);m.useEffect(()=>{if(a===0||l)return;let K=!0;Pt();for(const fe of F.current){const De=mr(fe.rel),Pe=ne.current;c(De).then(Ge=>{!K||!Ge||yd(me.current,De,Pe)||p(st=>st.map(we=>we.rel===fe.rel?_k(we,Ge.ok?Ge.content:null):we))})}return()=>{K=!1}},[Pt,c,l,a]);const _t=m.useCallback(K=>{K&&k(fe=>{if(fe.has(K))return fe;const De=new Set(fe);return De.add(K),De})},[]),B=m.useCallback(K=>{K.length!==0&&k(fe=>{let De=!1;const Pe=new Set(fe);for(const Ge of K)!Ge||Pe.has(Ge)||(Pe.add(Ge),De=!0);return De?Pe:fe})},[]);m.useEffect(()=>{const K=oe.getState().conversations[e],fe=Te;(Nt.current!==e||Ut.current!==fe)&&(Nt.current=e,Ut.current=fe,Ze.current=null);const De=wr(K?.messages??jf,te,K?.customEntries??[],pe),{refreshRels:Pe,nextSeen:Ge}=_ae(De,Ze.current,c_(K?.messages??[]));Ze.current=Ge,Pe.length!==0&&(B(Pe.flatMap(bd)),Pt())},[Pt,e,$e,B,Te,pe,te]);const je=m.useCallback(K=>{k(fe=>{const De=new Set(fe);return De.has(K)?De.delete(K):De.add(K),De})},[]),Ye=m.useCallback(K=>{_t(K),P({parent:K,kind:"file"})},[_t]),Tt=m.useCallback(K=>{_t(K),P({parent:K,kind:"dir"})},[_t]),Wt=m.useCallback(async(K,fe=!1)=>{if(fe){await $(K,"preview");return}const De=tA(K);if(F.current.find(we=>we.rel===De)){C(De);return}const Ge=ne.current,st=await c(K);if(!(!st||yd(me.current,K,Ge))){if(!st.ok){ge(st.error);return}p(we=>[...we,{rel:De,contents:st.content,draft:st.content,version:0,dirty:!1,conflict:!1,preview:!0}]),C(De)}},[ge,c,$,C]);m.useEffect(()=>OO(e,(K,fe,De)=>{H.current=fe?{rel:K,line:fe}:null;const Pe=Q.current,Ge=F.current.find(st=>st.rel===K);if(fe&&Pe?.rel===K&&ee.current===K&&Ge?.viewMode!=="preview"&&!Ge?.viewer){H.current=null,Pe.editor.focus({lineNumber:fe});return}De==="markdown"&&!fe?Wt(K,!0):$(K,!fe&&kf(K,v.current).some(st=>st.default)?void 0:"source")}),[e,$,Wt]);const le=m.useCallback(K=>window.electronAPI.workspaceFiles.readImage({...r,rel:K}).then(fe=>fe.ok?fe.dataUrl:null),[r]),ht=m.useCallback(K=>window.electronAPI.workspaceFiles.fetchRemoteImage({...r,url:K}).then(fe=>fe.ok?fe.dataUrl:null),[r]),Ot=m.useCallback(async K=>{const fe=await window.electronAPI.workspaceFiles.absPath({...r,rel:K});if(!fe.ok||!fe.local||!fe.fileUrl){ge(fe.ok?"unsupported":fe.error);return}const De=`browser:file:${e}:${K}`;Qg({conversationId:e,tabId:De,title:zr(K)});const Pe=await window.electronAPI.browser.navigate(De,e,fe.fileUrl);Pe.ok||ge(Pe.error)},[e,ge,r]),Fe=m.useCallback(async K=>{if(oe.getState().conversations[e]?.workspaceMigrating){ze({type:"error",title:n("Wait for the workspace operation to finish before saving.")});return}const fe=F.current.find(st=>st.rel===K);if(!fe||fe.preview||!fe.dirty)return;const De=fe.draft,Pe=ne.current,Ge=await window.electronAPI.workspaceFiles.write({...r,rel:K,content:De});if(!yd(me.current,K,Pe)){if(!Ge.ok){ge(Ge.error);return}p(st=>st.map(we=>we.rel===K?{...we,contents:De,dirty:we.draft!==De,conflict:!1}:we))}},[e,ge,r,n]),jt=m.useCallback(K=>{p(fe=>fe.map(De=>De.rel===K?{...De,viewMode:Dae(De.viewMode)}:De))},[]),Ft=m.useCallback((K,fe)=>{p(De=>De.map(Pe=>Pe.rel===K?{...Pe,viewer:fe}:Pe))},[]),cn=m.useCallback((K,fe)=>{p(De=>De.map(Pe=>Pe.rel===K?{...Pe,draft:fe,dirty:fe!==Pe.contents}:Pe))},[]);m.useEffect(()=>{if(!o)return;const K=fe=>{!(Vf?fe.metaKey:fe.ctrlKey)||fe.key.toLowerCase()!=="s"||f&&(fe.preventDefault(),Fe(f))};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[f,Fe,o]);const re=h.find(K=>K.rel===f)??null,Ue=re&&!re.preview&&!re.tooLarge?kf(re.rel,x):[],ut=re?.viewer?Ue.find(K=>Ja(K)===re.viewer):void 0,xt=m.useMemo(()=>({enabledSelectionAction:!0,renderSelectionAction(K){const fe=document.createElement("button");return fe.type="button",fe.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",fe.textContent=n("Send to conversation"),fe.addEventListener("mouseenter",()=>{fe.style.background="color-mix(in lab, currentColor 8%, transparent)"}),fe.addEventListener("mouseleave",()=>{fe.style.background="transparent"}),fe.addEventListener("mousedown",De=>De.preventDefault()),fe.addEventListener("click",()=>{const De=K.getSelectionText().trim(),Pe=f;if(!De||!Pe){K.close();return}const Ge=K.selection.start.line+1;let st=K.selection.end.line+1;K.selection.end.character===0&&st>Ge&&(st-=1);const we=Ge===st?`L${Ge}`:`L${Ge}-L${st}`;Zl({kind:"file",id:`${Pe}#${we}`,label:`${zr(Pe)}#${we}`,relativePath:`${Pe}#${we}`}),Co(),K.close()}),fe},onChange(K){const fe=f;if(!fe)return;const De=K.contents;p(Pe=>Pe.map(Ge=>Ge.rel===fe?{...Ge,draft:De,dirty:De!==Ge.contents}:Ge))},onAttach(K){if(!f)return;Q.current={rel:f,editor:K};const fe=H.current;fe?.rel===f&&(H.current=null,K.focus({lineNumber:fe.line}))}}),[f,n]),pt=m.useCallback(async(K,fe)=>{const De=await window.electronAPI.workspaceFiles.rename({...r,rel:K,name:fe});if(!De.ok)return ge(De.error),!1;z(null);const Pe=De.rel;if(Pe){ke(K);for(const Ge of F.current){if(Ge.preview||Ge.tooLarge)continue;const st=wd(Ge.rel,K,Pe);st!=null&&(window.electronAPI.workspaceFiles.watchStop({...r,rel:Ge.rel}),window.electronAPI.workspaceFiles.watchStart({...r,rel:st}))}p(Ge=>Ge.map(st=>{const we=wd(st.rel,K,Pe);return we==null?st:{...st,rel:we}})),g(Ge=>Ge==null?Ge:wd(Ge,K,Pe)??Ge),k(Ge=>{let st=!1;const we=new Set;for(const Qe of Ge){const it=wd(Qe,K,Pe)??Qe;it!==Qe&&(st=!0),we.add(it)}return st?we:Ge})}return Pt(),!0},[Pt,ge,ke,r]);return i.jsxs(zO,{createEditor:Aae,children:[i.jsxs("div",{className:"flex h-full min-h-0 bg-background",children:[i.jsxs("div",{className:U("flex shrink-0 flex-col overflow-hidden text-sm",y?b?"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(xe,{variant:"ghost",size:"icon-sm",onClick:()=>I(K=>!K),"aria-label":n("Search"),"aria-pressed":A,children:i.jsx(ei,{})}),i.jsx(xe,{variant:"ghost",size:"icon-sm",onClick:Pt,"aria-label":n("Refresh"),children:i.jsx(Wo,{})})]}),A?i.jsx(rae,{conversationId:e,projectId:t,onOpenFile:K=>{$(K)},onClose:()=>I(!1),menu:{local:X,onPreview:K=>{Wt(K)},onBrowser:K=>{Ot(K)},onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...r,rel:K}).then(fe=>{fe.ok||ge(fe.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...r,rel:K})},onNewFile:K=>{I(!1),B(bd(K)),Ye(K)},onNewFolder:K=>{I(!1),B(bd(K)),Tt(K)},onRename:(K,fe)=>{I(!1),B(bd(K)),z({rel:K,name:fe,at:"tree"})},onDelete:(K,fe)=>L({rel:K,name:fe}),onSend:(K,fe)=>{Zl({kind:"file",id:K,label:fe,relativePath:K})}}}):i.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:i.jsx(dh,{target:{kind:"blank"},local:X,onNewFile:Ye,onNewFolder:Tt,onCopyPath:()=>{},onCopyRel:()=>{},children:i.jsx("div",{className:"min-h-full",children:i.jsx(sA,{rel:"",depth:0,conversationId:e,projectId:t,treeEpoch:_,draft:D,renaming:T,local:X,expandedDirs:S,onToggleDir:je,onOpen:$,onPreview:Wt,onBrowser:Ot,onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...r,rel:K}).then(fe=>{fe.ok||ge(fe.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...r,rel:K})},onNewFile:Ye,onNewFolder:Tt,onRenameStart:(K,fe)=>z({rel:K,name:fe,at:"tree"}),onDelete:(K,fe)=>L({rel:K,name:fe}),onDraftCancel:()=>P(null),onRenameCancel:()=>z(null),onDraftCommit:async(K,fe,De)=>{const Ge=await(fe==="dir"?window.electronAPI.workspaceFiles.mkdir:window.electronAPI.workspaceFiles.createFile)({...r,rel:K||void 0,name:De});return Ge.ok?(P(null),Pt(),fe==="file"&&Ge.rel&&$(Ge.rel),!0):(ge(Ge.error),!1)},onRenameCommit:pt})})})})]}),i.jsxs("div",{className:U("flex min-w-0 flex-1 flex-col",y&&b&&"hidden"),children:[h.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:[y&&i.jsx("button",{type:"button",className:"flex shrink-0 items-center rounded-md px-1 text-muted-foreground hover:bg-muted/50",onClick:()=>w(!0),"aria-label":n("Files"),title:n("Files"),children:i.jsx(GO,{className:"h-4 w-4"})}),h.map(K=>{const fe=T?.rel===K.rel&&T.at==="tab"&&!K.preview,De=i.jsxs("button",{type:"button","data-file-tab":K.rel,className:U("flex items-center gap-1.5 rounded-md px-2 py-1 text-xs",K.rel===f?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:()=>{fe||g(K.rel)},onDoubleClick:Pe=>{K.preview||(Pe.preventDefault(),Pe.stopPropagation(),z({rel:K.rel,name:zr(K.rel),at:"tab"}))},children:[fe?i.jsx(Uu,{depth:0,kind:"file",variant:"tab",initial:T.name,onCancel:()=>z(null),onCommit:Pe=>pt(K.rel,Pe)}):i.jsxs("span",{className:"max-w-36 truncate",children:[zr(K.preview?mr(K.rel):K.rel),K.preview?` ${n("Preview")}`:"",K.dirty?"*":""]}),i.jsx("button",{type:"button",className:"text-muted-foreground hover:text-destructive",onClick:Pe=>{Pe.stopPropagation(),ae(K.rel)},children:"×"})]});return i.jsxs(po,{children:[i.jsx(fo,{render:De}),i.jsxs(mo,{className:"min-w-40",children:[Iae(K.rel,X).map(Pe=>Pe.id==="copy-path"?i.jsx(Vt,{onClick:()=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:Pe.rel,mode:Pe.mode})},children:n("Copy Path")},Pe.id):i.jsx(Vt,{onClick:()=>{window.electronAPI.workspaceFiles.reveal({...r,rel:Pe.rel})},children:n(FO())},Pe.id)),i.jsx(ah,{}),!K.preview&&i.jsx(Vt,{onClick:()=>z({rel:K.rel,name:zr(K.rel),at:"tab"}),children:n("Rename")}),i.jsx(Vt,{onClick:()=>ae(K.rel),children:n("Close")}),i.jsx(Vt,{onClick:()=>{const Pe=F.current,Ge=K.rel,st=Pe.some(we=>we.rel!==Ge&&we.dirty);Z(we=>we!==Ge&&!Pe.find(Qe=>Qe.rel===we)?.dirty),st&&ue({kind:"others",rel:Ge})},children:n("Close others")}),i.jsx(Vt,{onClick:()=>{const Pe=F.current,Ge=Ng(Pe.map(we=>we.rel),K.rel,"right"),st=Ge.some(we=>Pe.find(Qe=>Qe.rel===we)?.dirty);Z(we=>Ge.includes(we)&&!Pe.find(Qe=>Qe.rel===we)?.dirty),st&&ue({kind:"right",rel:K.rel})},children:n("Close tabs to the right")}),i.jsx(Vt,{onClick:()=>{const Pe=F.current;Z(Ge=>!Pe.find(st=>st.rel===Ge)?.dirty)},children:n("Close saved")}),i.jsx(Vt,{onClick:()=>{const Pe=F.current,Ge=Pe.some(st=>st.dirty);Z(st=>!Pe.find(we=>we.rel===st)?.dirty),Ge&&ue({kind:"all"})},children:n("Close all")}),i.jsx(Vt,{onClick:()=>Z(Pe=>Pe!==K.rel),children:n("Force close others")}),i.jsx(Vt,{onClick:()=>Z(()=>!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:l,onClick:()=>{c(mr(re.rel)).then(K=>{K?.ok&&p(fe=>fe.map(De=>De.rel===re.rel?{...De,contents:K.content,draft:K.content,version:De.version+1,dirty:!1,conflict:!1}:De))})},children:n("Reload")})]}),i.jsxs("div",{className:"relative min-h-0 flex-1",children:[re&&!re.preview&&!re.tooLarge&&(ap(re.rel)||Ue.length>0)&&i.jsx("div",{className:"absolute top-2 right-2 z-10 flex gap-1",children:ut?i.jsxs(xe,{type:"button",variant:"outline",size:"sm","aria-label":n("View Source"),onClick:()=>Ft(re.rel,void 0),children:[i.jsx(bm,{className:"h-3.5 w-3.5"}),n("View Source")]}):i.jsxs(i.Fragment,{children:[Ue.map(K=>i.jsxs(xe,{type:"button",variant:"outline",size:"sm","aria-label":K.title,title:K.pluginName,onClick:()=>Ft(re.rel,Ja(K)),children:[i.jsx(H0,{className:"h-3.5 w-3.5"}),K.title]},Ja(K))),ap(re.rel)&&i.jsxs(xe,{type:"button",variant:"outline",size:"sm","aria-label":re.viewMode==="preview"?n("View Source"):n("Preview"),onClick:()=>jt(re.rel),children:[re.viewMode==="preview"?i.jsx(bm,{className:"h-3.5 w-3.5"}):i.jsx(H0,{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.")}):ut?i.jsx($P,{pluginId:ut.pluginId,entry:ut.entry,title:ut.title,sessionId:e,file:{rel:re.rel,text:re.draft,onEdit:K=>cn(re.rel,K)}},`${re.rel}:${Ja(ut)}`):re.preview||re.viewMode==="preview"&&ap(re.rel)?i.jsx("div",{className:"h-full overflow-auto px-3 py-2 text-sm",children:i.jsx(kae,{text:re.preview?re.contents:re.draft,baseDirRel:Rae(mr(re.rel)),resolveImage:le,resolveRemoteImage:ht})}):i.jsx(HO,{style:{height:"100%",overflow:"auto"},children:i.jsx(uj,{file:{name:zr(re.rel),contents:re.draft},disableWorkerPool:!0,edit:!0,editorOptions:xt,options:s},`${re.rel}:${re.version}`)})]})]})]}),i.jsx(ms,{open:W!==null,onOpenChange:K=>{K||ue(null)},title:n("Unsaved changes"),description:W?.kind==="one"?n("This file has unsaved changes. Close anyway?"):n("Some files have unsaved changes. Close anyway?"),confirmLabel:n("Close"),onConfirm:()=>{if(W){if(W.kind==="one"&&W.rel)J(W.rel);else if(W.kind==="others"&&W.rel){const K=W.rel;Z(fe=>fe!==K)}else if(W.kind==="right"&&W.rel){const K=W.rel,fe=new Set(Ng(F.current.map(De=>De.rel),K,"right"));Z(De=>fe.has(De))}else Z(()=>!0);ue(null)}}}),i.jsx(ms,{open:O!==null,onOpenChange:K=>{K||L(null)},title:n("Delete"),description:n("Delete {{name}} permanently?",{name:O?.name??""}),confirmLabel:n("Delete"),onConfirm:()=>{if(!O)return;const{rel:K}=O;window.electronAPI.workspaceFiles.remove({...r,rel:K}).then(fe=>{if(!fe.ok){ge(fe.error);return}ke(K),Z(De=>_g(De,K)),k(De=>{let Pe=!1;const Ge=new Set;for(const st of De){if(_g(st,K)){Pe=!0;continue}Ge.add(st)}return Pe?Ge:De}),L(null),Pt()})}})]})}function Uu({depth:e,kind:t,initial:n,onCancel:s,onCommit:o,variant:r="tree"}){const[a,l]=m.useState(n),c=m.useRef(null),d=m.useRef(!0),u=m.useRef(!1);m.useEffect(()=>{const p=window.setTimeout(()=>{const g=c.current;g&&(g.focus(),g.select())},0),f=window.setTimeout(()=>{d.current=!1},50);return()=>{window.clearTimeout(p),window.clearTimeout(f)}},[]);const h=p=>{if(!u.current){if(p==="commit"&&Tae(a,n)==="commit"){u.current=!0,o(a.trim()).then(f=>{f||(u.current=!1,c.current?.focus())});return}u.current=!0,s()}};return i.jsx("input",{ref:c,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(d.current){c.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 sA({rel:e,depth:t,conversationId:n,projectId:s,treeEpoch:o,...r}){const[a,l]=m.useState(null);if(m.useEffect(()=>{let d=!0;return window.electronAPI.workspaceFiles.listDir({conversationId:n,projectId:s,rel:e||void 0}).then(u=>{d&&l(u.ok?u.entries:[])}),()=>{d=!1}},[n,s,e,o]),!a)return i.jsx("div",{className:"px-2 py-1 text-muted-foreground",children:"…"});const c=r.draft?.parent===e;return i.jsxs("div",{children:[a.map(d=>{const u=Mae(e,d.name),h=r.expandedDirs.has(u);if(d.kind==="dir"){const f=r.renaming?.rel===u&&r.renaming.at==="tree"?i.jsx(Uu,{depth:t,kind:"dir",initial:d.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:U("h-3.5 w-3.5 shrink-0",h&&"rotate-90")}),(()=>{const g=Tc(d.name,!0,h);return i.jsx(g,{className:U("h-4 w-4 shrink-0",Dc(d.name,!0))})})(),i.jsx("span",{className:"truncate",children:d.name})]});return i.jsxs("div",{children:[i.jsx(dh,{target:{kind:"dir",rel:u,name:d.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(sA,{rel:u,depth:t+1,conversationId:n,projectId:s,treeEpoch:o,...r})]},u)}return i.jsx(Oae,{rel:u,name:d.name,depth:t,renaming:r.renaming?.rel===u&&r.renaming.at==="tree",handlers:r},u)}),c&&r.draft&&i.jsx(Uu,{depth:t,kind:r.draft.kind,initial:"",onCancel:r.onDraftCancel,onCommit:d=>r.onDraftCommit(e,r.draft.kind,d)})]})}function Oae({rel:e,name:t,depth:n,renaming:s,handlers:o}){const{setNodeRef:r,listeners:a,isDragging:l}=lx({id:`workspace-file:${e}`,data:{type:"workspace-file",relativePath:e,name:t}}),c=s?i.jsx(Uu,{depth:n,kind:"file",initial:t,onCancel:o.onRenameCancel,onCommit:d=>o.onRenameCommit(e,d)}):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 d=Tc(t,!1);return i.jsx(d,{className:U("h-4 w-4 shrink-0",Dc(t,!1))})})(),i.jsx("span",{className:"truncate",children:t})]});return i.jsx(dh,{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:(d,u)=>{Zl({kind:"file",id:d,label:u,relativePath:d})},children:c})}function Nk(e){return e.closest(".dv-tabs-overflow-container")}function Tk(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 zae(e){for(const t of e.children)if(t.classList.contains("dv-tab"))return!0;return!1}function Gae(e){const t=e.closest(".dv-popover-anchor"),n=e.parentElement;if(t&&n&&n.parentElement===t){n.remove();return}e.remove()}function Dk(e,t){for(const n of t)n.parentElement===e&&n.remove();zae(e)||Gae(e)}function Fae({open:e,onClose:t,onFindNext:n,onFindPrevious:s,onClear:o,theme:r}){const{t:a}=se(),l=m.useRef(null),[c,d]=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(!c){y(null);return}y(N==="next"?n(c,b()):s(c,b()))};if(!e)return null;const C=r?.background??"#1e1e1e",_=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:C,borderColor:`${_}30`},children:[i.jsx("input",{ref:l,value:c,onChange:N=>{const S=N.target.value;d(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:U("w-40 bg-transparent text-sm outline-none placeholder:opacity-50",v===!1&&c&&"text-red-400"),style:{color:_}}),i.jsx("button",{type:"button",onClick:()=>h(N=>!N),className:U("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:_},title:a("Case sensitive"),children:"Aa"}),i.jsx("button",{type:"button",onClick:()=>f(N=>!N),className:U("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:_},title:a("Whole word"),children:"W"}),i.jsx("button",{type:"button",onClick:()=>x(N=>!N),className:U("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:_},title:a("Regular expression"),children:".*"}),i.jsx("div",{className:"mx-1 h-4 w-px",style:{backgroundColor:`${_}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:_},title:a("Previous match"),children:i.jsx(a_,{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:_},title:a("Next match"),children:i.jsx(Vn,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:t,className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:_},title:a("Close"),children:i.jsx(ln,{className:"h-4 w-4"})})]})}function Ik(e,t){const n=Ju(e);return t?KO(n):n}function Hae({termId:e,conversationId:t,projectId:n,onTitle:s}){const{t:o}=se(),r=m.useRef(null),a=m.useRef(null),l=m.useRef(""),[c,d]=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=ye(z=>z.terminalTheme),g=ye(z=>z.terminalFontFamily),x=ye(z=>z.terminalFontSize),v=ye(z=>z.terminalFontWeight),y=ye(z=>z.terminalFontWeightBold),b=Uk()!==null,w=m.useRef(b);w.current=b;const[C,_]=m.useState(!1);m.useEffect(()=>{const z=r.current;if(!z)return;let O=!1,L=0,V;const X=()=>{if(O)return;if(!z.isConnected||z.clientWidth===0||z.clientHeight===0){L=requestAnimationFrame(X);return}const ee=ye.getState(),H=UO(e,z,{theme:Ik(ee.terminalTheme,w.current),fontFamily:ee.terminalFontFamily,fontSize:ee.terminalFontSize,fontWeight:ee.terminalFontWeight,fontWeightBold:ee.terminalFontWeightBold});if(!H.opened){L=requestAnimationFrame(X);return}H.onTitle=q=>p.current?.(q);const Q=()=>{!z.isConnected||z.clientWidth===0||(H.fit.fit(),window.electronAPI.terminal.resize(e,H.term.cols,H.term.rows))};Q(),window.electronAPI.terminal.create({termId:e,conversationId:u.current,projectId:h.current,cols:H.term.cols,rows:H.term.rows}),H.term.focus(),a.current=H.term,V=new ResizeObserver(Q),V.observe(z)};document.fonts.load('14px "Enso Nerd Symbols"',"").then(X,ee=>{console.warn("Failed to load terminal icon font",ee),X()});const F=ee=>{(ee.metaKey||ee.ctrlKey)&&ee.key==="f"&&(ee.preventDefault(),ee.stopPropagation(),_(!0))};return z.addEventListener("keydown",F,!0),()=>{O=!0,cancelAnimationFrame(L),V?.disconnect(),z.removeEventListener("keydown",F,!0),a.current=null,VO(e)}},[e]),m.useEffect(()=>{$O(Ik(f,b),g,x,v,y)},[f,g,x,v,y,b]);const N=m.useCallback((z,O)=>B0(e,z,"next",O),[e]),S=m.useCallback((z,O)=>B0(e,z,"prev",O),[e]),k=m.useCallback(()=>WO(e),[e]),A=()=>{const z=a.current?.getSelection().trim()??"";l.current=z,d(z.length>0)},I=()=>{const z=l.current||a.current?.getSelection().trim()||"";z&&(Eh(z),Co(),a.current?.clearSelection(),d(!1))},D=()=>{const z=l.current||a.current?.getSelection().trim()||"";z&&navigator.clipboard.writeText(z)},P=Ju(f),T=i.jsx("div",{ref:r,"data-slot":"terminal-pane",className:"relative h-full w-full overflow-hidden p-2",style:{backgroundColor:P?.background,"--terminal-bg":P?.background},onContextMenu:A,children:i.jsx(Fae,{open:C,onClose:()=>_(!1),onFindNext:N,onFindPrevious:S,onClear:k,theme:P})});return i.jsxs(po,{children:[i.jsx(fo,{render:T}),i.jsxs(mo,{className:"min-w-40",children:[i.jsx(Vt,{disabled:!c,onClick:D,children:o("Copy")}),i.jsx(Vt,{disabled:!c,onClick:I,children:o("Send to conversation")})]})]})}const iA={running:"bg-amber-500",completed:"bg-emerald-500",failed:"bg-destructive",cancelled:"bg-muted-foreground"},Bae=[],Vae={project:"Project",custom:"Custom",global:"Global",plugin:"Plugin",builtin:"Built-in"};function $ae(e,t,n,s){const o=oe.getState(),r=o.conversations[e],a=ye.getState(),l=a.projects.find(u=>u.id===r?.projectId);if(!r||!l)return!1;const c=tu({defaultModel:a.defaultModel,...eu(l,a.projectGroups),lastProviderId:r.lastProviderId,lastModelId:r.lastModelId,providers:P_(),credentials:Ll(yo.getState().snapshot),virtualModels:a.virtualModels});if(c.source==="none")return ze({type:"warning",title:s("No usable model is available. Configure provider credentials and enable a model first.")}),!1;const d={};for(const u of t.args){const h=n[u.key]?.trim();h&&(d[u.key]=h)}return o.send(qO({id:t.id,name:t.source==="builtin"?s(t.name):t.name,args:d}),{providerId:c.providerId,modelId:c.modelId,cwd:l.path},void 0,e),!0}function Wae({conversationId:e,preset:t,open:n,onToggle:s}){const{t:o}=se(),[r,a]=m.useState({}),l=t.args.some(u=>u.required&&!u.default?.trim()&&!r[u.key]?.trim()),c=t.source==="builtin"?o(t.name):t.name,d=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:c}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:o(Vae[t.source])})]}),i.jsx("p",{className:"mt-0.5 line-clamp-2 text-muted-foreground",children:d})]}),n?i.jsxs("form",{className:"space-y-2 border-t px-2 py-2",onSubmit:u=>{u.preventDefault(),!(l||!$ae(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(xe,{type:"submit",size:"xs",disabled:l,children:[i.jsx(Og,{}),o("Run")]})})]}):null]})}function Uae({conversationId:e}){const{t}=se(),[n,s]=m.useState([]),[o,r]=m.useState(null),a=ye(u=>u.disabledWorkflowPresets),l=oe(u=>u.conversations[e]?.presetId),c=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(c,[c]);const d=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(xe,{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(g_,{})}),i.jsx(xe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Refresh"),onClick:()=>c(),children:i.jsx(Wo,{})})]}),i.jsx("ul",{className:"space-y-1.5",children:d.map(u=>i.jsx(Wae,{conversationId:e,preset:u,open:o===u.id,onToggle:()=>r(h=>h===u.id?null:u.id)},`${u.source}:${u.id}`))})]})}function Kae(e,t){const n=oe.getState();n.activeId!==e&&n.selectConversation(e),n.selectTab(e,t)}function qae({conversationId:e,member:t}){const{t:n}=se(),s=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:U("h-1.5 w-1.5 shrink-0 rounded-full",iA[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:()=>Kae(e,o),children:s})}):i.jsx("li",{className:"text-xs",children:s})}function Yae({conversationId:e}){const{t}=se(),n=Wf(r=>r.byConversation[e])??Bae,s=Wf(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(Uae,{conversationId:e}),o?i.jsx("div",{className:"flex justify-end",children:i.jsxs(xe,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>s(e),children:[i.jsx(Zg,{}),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:U("h-2 w-2 shrink-0 rounded-full",iA[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(xe,{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(uc,{})}):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:E4(r.members).map((a,l,c)=>{const d=!!a.phase&&a.phase!==c[l-1]?.phase;return i.jsxs("div",{children:[i.jsxs("div",{className:"mb-1 flex items-center gap-2 text-xs",children:[d?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(qae,{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 Xh=m.createContext({}),oA=m.createContext(!1);function n0({api:e,children:t}){const{conversationId:n}=m.useContext(Xh);return n?i.jsx(iX,{dockConversationId:n,api:e,children:t}):t}function Xae(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 rA(e,t){const n=e.panels.length;return n===0?t:`${t} ${n+1}`}function aA(e,t,n,s){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:rA(e,s),params:{conversationId:t,projectId:n}})}function lA(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 Jae(e){return i.jsx(Hae,{termId:e.api.id,conversationId:e.params.conversationId,projectId:e.params.projectId,onTitle:t=>e.api.setTitle(t)})}function Zae(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(n0,{api:e.api,children:i.jsx(tae,{conversationId:t,projectId:n})})}function cA(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 Qae(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(n0,{api:e.api,children:i.jsx(Lae,{conversationId:t,projectId:n})})}function dA(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 ele(e){const{conversationId:t}=e.params;return t?i.jsx(Wre,{conversationId:t,panelApi:e.api}):null}function uA(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 tle(e){const{conversationId:t}=e.params;return t?i.jsx(n0,{api:e.api,children:i.jsx(qD,{conversationId:t,panelApi:e.api})}):null}function hA(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 s0(e){return ye(t=>ZO(t,e))}function pA(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 nle(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($re,{pluginId:n,viewId:s,sessionId:t??null})}function sle(e){const{conversationId:t}=e.params;return t?i.jsx(Yae,{conversationId:t}):null}function ile(e,t){const n=e.group.panels.map(r=>r.id),s=new Set(Ng(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 ole(e){const{t}=se(),n=m.useRef(null),[s,o]=m.useState(e.api.isActive),[r,a]=m.useState(e.api.title??""),[l,c]=m.useState(e.params.favicon??null),[d,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;c(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?Nk(n.current):null,v=x?Tk(x):null,y=ile(e.api,g);!x||!v||Dk(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:U("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(Gx,{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(yr,{className:"h-3 w-3 shrink-0"}):e.api.id==="workflow"?i.jsx(Mg,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("plugin:")?i.jsx(Zu,{pluginId:e.api.id.split(":")[1]??"",className:"h-3 w-3 shrink-0"}):h&&l&&!d?i.jsx("img",{src:l,alt:"",className:"h-3 w-3 shrink-0",onError:()=>u(!0)}):h?i.jsx(go,{className:"h-3 w-3 shrink-0"}):i.jsx($o,{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=Nk(g.currentTarget),v=x?Tk(x).get(e.api.id):void 0;e.api.close(),x&&v&&Dk(x,[v])},children:i.jsx(ln,{className:"h-3 w-3"})})]});return i.jsxs(po,{children:[i.jsx(fo,{render:f}),i.jsxs(mo,{className:"min-w-40",children:[i.jsx(Vt,{onClick:()=>p("self"),children:t("Close")}),i.jsx(Vt,{onClick:()=>p("others"),children:t("Close others")}),i.jsx(Vt,{onClick:()=>p("right"),children:t("Close tabs to the right")}),i.jsx(Vt,{onClick:()=>p("all"),children:t("Close all")})]})]})}function fA({onNewTerminal:e,onNewChanges:t,onNewFiles:n,onNewBrowser:s,onNewBtw:o,onNewWorkflow:r,onNewPluginView:a,compact:l}){const{t:c}=se(),d=I_();return i.jsxs(Hi,{children:[i.jsxs(Bi,{className:U("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":c("New tab"),children:[i.jsx(us,{className:"h-4 w-4"}),!l&&i.jsx("span",{children:c("New tab")})]}),i.jsxs(Vi,{align:l?"end":"center",className:"min-w-36",children:[i.jsxs(mn,{onClick:e,children:[i.jsx($o,{className:"h-4 w-4"}),c("Terminal")]}),i.jsxs(mn,{onClick:t,children:[i.jsx(Gx,{className:"h-4 w-4"}),c("Changes")]}),i.jsxs(mn,{onClick:n,children:[i.jsx(ni,{className:"h-4 w-4"}),c("Files")]}),i.jsxs(mn,{onClick:s,children:[i.jsx(go,{className:"h-4 w-4"}),c("Browser")]}),i.jsxs(mn,{onClick:o,children:[i.jsx(yr,{className:"h-4 w-4"}),c("Btw")]}),r?i.jsxs(mn,{onClick:r,children:[i.jsx(Mg,{className:"h-4 w-4"}),c("Workflow")]}):null,a?d.map(u=>i.jsxs(mn,{onClick:()=>a(u),children:[i.jsx(Zu,{pluginId:u.pluginId,className:"h-4 w-4"}),u.title]},`${u.pluginId}:${u.id}`)):null]})]})}function mA({containerApi:e,group:t}){const{t:n}=se(),{conversationId:s,projectId:o}=m.useContext(Xh),r=fn(f=>f.fullscreen),a=fn(f=>f.toggleFullscreen),l=s0(o),c=Sa(),d=m.useContext(oA),u=Xae(e,t),h=fn(f=>f.toggleOpen),p=lh()==="windows";return i.jsxs("div",{className:"flex h-full items-center gap-0.5",children:[i.jsx(fA,{compact:!0,onNewTerminal:()=>{if(t){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:rA(e,n("Terminal")),params:{conversationId:s,projectId:o},position:{referenceGroup:t}});return}aA(e,s,o,n("Terminal"))},onNewChanges:()=>lA(e,s,o,n("Changes")),onNewFiles:()=>cA(e,s,o,n("Files")),onNewBrowser:()=>uA(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}dA(e,s,o,n("Btw"))},onNewWorkflow:l?()=>hA(e,s,o,n("Workflow")):void 0,onNewPluginView:f=>pA(e,s,o,f,t)}),i.jsx("button",{type:"button",className:U("flex h-6 w-6 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",c&&"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(tz,{className:"h-3.5 w-3.5"}):i.jsx(nz,{className:"h-3.5 w-3.5"})}),d&&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($N,{className:"h-4 w-4"})}),d&&u&&p&&i.jsx("span",{"aria-hidden":!0,className:"shrink-0",style:{width:`calc(100vw - env(titlebar-area-width, calc(100vw - ${sz}px)) - 19px)`}})]})}function rle(e){const{t}=se(),{conversationId:n,projectId:s}=m.useContext(Xh),o=s0(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(mA,{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(fA,{onNewTerminal:()=>aA(e.containerApi,n,s,t("Terminal")),onNewChanges:()=>lA(e.containerApi,n,s,t("Changes")),onNewFiles:()=>cA(e.containerApi,n,s,t("Files")),onNewBrowser:()=>uA(e.containerApi,n,s,t("Browser")),onNewBtw:()=>dA(e.containerApi,n,s,t("Btw")),onNewWorkflow:o?()=>hA(e.containerApi,n,s,t("Workflow")):void 0,onNewPluginView:r=>pA(e.containerApi,n,s,r)})]})]})}function ale(e){return i.jsx(mA,{containerApi:e.containerApi,group:e.group})}const Ek={terminal:Jae,changes:Zae,files:Qae,browser:tle,btw:ele,workflow:sle,plugin:nle};function lle(){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 cle({conversationId:e,hidden:t}){const n=oe(s=>s.conversations[e]?.projectId);return n?i.jsx("div",{className:U("absolute inset-0",t&&"hidden"),children:i.jsx(dle,{conversationId:e,projectId:n})}):null}function dle({conversationId:e,projectId:t}){const n=lle(),s=s0(t),[o,r]=m.useState(null);m.useEffect(()=>{s||o?.getPanel("workflow")?.api.close()},[o,s]);const a=l=>{QO(e,l.api);const c=fn.getState().layouts[e],d=Lre(c,new Set(Object.keys(Ek)));let u=!!c&&!d;if(d)try{l.api.fromJSON(d)}catch{u=!0}l.api.onDidLayoutChange(()=>{const h=l.api.toJSON();u&&Object.keys(h.panels??{}).length===0||(u=!1,fn.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:")){oe.getState().disposeBtwConversation(h.id.slice(4));return}ez(h.id),window.electronAPI.terminal.dispose(h.id)}}),r(l.api)};return i.jsx(Xh.Provider,{value:{conversationId:e,projectId:t},children:i.jsx("div",{className:"enso-side-dock h-full",children:i.jsx(BP,{components:Ek,defaultTabComponent:ole,watermarkComponent:rle,rightHeaderActionsComponent:ale,theme:n?hoe:poe,onReady:a})})})}function ule({width:e,resizing:t=!1,card:n=!1,titleRow:s=!1}){const{t:o}=se(),r=oe(T=>T.activeId),a=fn(T=>r?!!T.uiByConversation[r]?.open:!1),l=Sa(),d=fn(T=>T.fullscreen)||l&&a;m.useEffect(()=>{const T=window.electronAPI.browser.onReveal(O=>{D_(O.conversationId)||Qg({conversationId:O.conversationId,tabId:O.tabId})}),z=window.electronAPI.browser.onTabClosed(O=>{YO(O.conversationId,O.tabId)});return window.electronAPI.browser.restoreTabs(),()=>{T(),z()}},[]),m.useEffect(()=>Wf.subscribe((T,z)=>{for(const[O,L]of Object.entries(T.byConversation)){if(z.byConversation[O]===L)continue;const V=L.find(X=>X.status==="running");V&&XO({conversationId:O,runId:V.runId,title:o("Workflow")})}}),[o]),m.useEffect(()=>oe.subscribe((T,z)=>{for(const O of Object.keys(z.conversations))T.conversations[O]||JO(O)}),[]);const u=oe(T=>T.activeId),[h,p]=m.useState([]),f=oe(T=>h.filter(z=>!!T.conversations[z]).join(`
|
|
115
|
-
`)),[g,x]=m.useState(d),[v,y]=m.useState(0),b=n&&!s?A_:$g,w=Zj(e,v,b),C=m.useRef(null),[_,N]=m.useState({id:u,from:u});u!==_.id&&N({id:u,from:_.id}),d&&!g&&x(!0),m.useEffect(()=>{const T=C.current?.parentElement;if(!T)return;const z=()=>{const L=getComputedStyle(T);y(T.clientWidth-parseFloat(L.paddingLeft)-parseFloat(L.paddingRight))};z();const O=new ResizeObserver(z);return O.observe(T),()=>O.disconnect()},[]),m.useEffect(()=>{_.from!==_.id&&N(T=>T.from===T.id?T:{...T,from:T.id})},[_.from,_.id]);const S=g?void 0:Math.max(0,w-(a&&!n?1:0)),k=u,A=PY({resizing:t,conversationId:_.id??void 0,previousConversationId:_.from??void 0}),I=d?v||w:a?w:0,D=!!s&&!l;k&&!h.includes(k)&&p(T=>T.includes(k)?T:[...T,k]);const P=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:C,"data-slot":"side-panel",initial:!1,animate:{width:I},style:g?{position:"absolute"}:{position:"relative",maxWidth:`max(0px, calc(100% - ${Jj+b}px))`},transition:OD({skip:A,cover:g,targetW:I}),onAnimationComplete:()=>{d||x(!1)},className:U("flex min-h-0 flex-col",D&&a?"overflow-clip [overflow-clip-margin:4px]":"overflow-hidden",a&&(D||!g)?"bg-transparent":D?"":"bg-background",g?D?"top-px right-[8px] bottom-[8px]":n?"top-0 right-[8px] bottom-[8px]":"inset-y-0 right-0":"shrink-0",D?U("no-drag -mt-[44px]",g?"rounded-b-[10px]":"rounded-br-[10px]"):n?U("rounded-[10px]",a&&"shadow-surface"):a&&"border-l"),"data-enso":"side-panel","data-title-row":D||void 0,children:[a&&(D||!g)?i.jsx(fle,{titleRow:D,full:g}):null,a&&!g&&S!==void 0?i.jsx("div",{"aria-hidden":!0,className:U("pointer-events-none absolute right-0 bottom-0 bg-background",s?"top-[44px]":"top-0"),style:{left:S}}):null,i.jsx("div",{className:U("relative flex h-full min-h-0 flex-col",g&&"w-full",!a&&"invisible"),style:{width:S,clipPath:D?g?ple:hle:void 0},children:P.length>0?i.jsx("div",{className:"relative min-h-0 flex-1",children:i.jsx(oA.Provider,{value:D,children:P.map(T=>i.jsx(cle,{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 hle="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)",ple="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 fle({titleRow:e,full:t}){const n=m.useRef(null),s=fn(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})),c=qN(l)??"";o.style.clipPath=c;const d=o.closest('[data-enso="side-panel"]');return d&&(c?d.style.setProperty("--enso-side-panel-holes-clip",c):d.style.removeProperty("--enso-side-panel-holes-clip")),()=>{d?.style.removeProperty("--enso-side-panel-holes-clip")}},[s]),i.jsxs(i.Fragment,{children:[e&&i.jsx("div",{"aria-hidden":!0,className:U("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:U("pointer-events-none absolute inset-x-0 bottom-0 bg-background",e?U("top-[44px]",t?"rounded-[10px]":"rounded-r-[10px]"):"top-0")})]})}function i0(){return ao()&&oe.persist.hasHydrated()&&ye.persist.hasHydrated()}function Pk(e,t){i0()&&e>0&&(async()=>(t&&await oe.getState().refreshWorktreeStatuses(),await oe.getState().autoArchiveStaleConversations()))()}function Ak(e){!i0()||!(e>0)||oe.getState().autoDeleteStaleArchived()}function mle(){const e=ye(s=>s.autoArchiveIdleDays),t=ye(s=>s.autoArchiveMergedWorktrees),n=ye(s=>s.autoDeleteArchivedDays);m.useEffect(()=>{if(i0()){Pk(e,t),Ak(n);return}const s=()=>{Pk(e,t),Ak(n)},o=[oe.persist.onFinishHydration(s),ye.persist.onFinishHydration(s)];return()=>{for(const r of o)r()}},[e,t,n])}function gle(){const e=oe(t=>Math.min(999,iz(t.order,Ev(t.conversations))));m.useEffect(()=>{window.electronAPI.app.setBadgeCount(e)},[e])}function xle(){const e=ye(n=>n.generationStallTimeoutMin),{t}=se();m.useEffect(()=>{if(e<=0)return;const n=new Set,s=new Set,o=new Map,r=setInterval(()=>{if(!ao())return;const a=e*6e4,l=Date.now(),c=oe.getState();for(const d of Object.values(c.conversations)){d.status==="running"&&d.lastOutputAt&&o.delete(d.id);const u=(d.coworkerIds??[]).some(p=>!!c.conversations[p]?.spawning),h=oz({shouldAbort:rz({status:d.status,spawning:d.spawning,lastOutputAt:cz(d,c.conversations),now:l,timeoutMs:a,hasLiveWork:az({...lz(d),spawningCoworker:u})}),status:d.status,spawning:d.spawning,pendingRetry:s.has(d.id),attempts:o.get(d.id)??0});if(h==="abort"){if(n.has(d.id))continue;n.add(d.id),s.add(d.id),window.electronAPI.agent.abort(d.id).finally(()=>{n.delete(d.id)}),ze(Mk(d,t("No output for {{minutes}} minutes — retrying",{minutes:e})));continue}if(h==="retry"){s.delete(d.id),o.set(d.id,(o.get(d.id)??0)+1),c.retry(d.id);continue}h==="give-up"&&(s.delete(d.id),o.delete(d.id),ze(Mk(d,t("Stopped after repeated stalls"))))}},1e3);return()=>clearInterval(r)},[e,t])}function Mk(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 vle=3e4;function ble(e,t=vle){return e()?Promise.resolve(!0):new Promise(n=>{const s=l=>{clearTimeout(a);for(const c of r)c();n(l)},o=()=>e()&&s(!0),r=[oe.subscribe(o),ye.subscribe(o)],a=setTimeout(()=>s(e()),t)})}function wle(){return oe.persist.hasHydrated()&&ye.persist.hasHydrated()}function yle(){const{t:e}=se();m.useEffect(()=>{if(!ao())return;const t=()=>{oT(async()=>{if(!await ble(wle))return;const s=await window.electronAPI.window.takeOpenFolders().catch(()=>[]);let o=!1;for(const r of s)try{if(!await lT(r)){ze({type:"error",title:e("Failed to add project")});continue}o=!0}catch(a){ze({type:"error",title:e("Failed to add project"),description:a instanceof Error?a.message:String(a)})}o&&$x()})},n=window.electronAPI.window.onOpenFolderRequested(t);return t(),n},[e])}async function Sle(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 Cle=3e4;function Rk(e,t=Cle){return e()?Promise.resolve(!0):new Promise(n=>{const s=l=>{clearTimeout(a);for(const c of r)c();n(l)},o=()=>e()&&s(!0),r=[oe.subscribe(o),yo.subscribe(o),ye.subscribe(o)],a=setTimeout(()=>s(e()),t)})}function kle(){const e=yo.getState().snapshot.availability.status;return oe.persist.hasHydrated()&&ye.persist.hasHydrated()&&e!=="unloaded"&&e!=="loading"}function jle(){const{t:e}=se();m.useEffect(()=>{ao()&&(async()=>{const t=await window.electronAPI.updater.takeInterruptedSessions().catch(()=>[]);if(t.length===0||!await Rk(kle))return;const n=oe.getState,s=await Sle(t,{conversation:o=>n().conversations[o],resume:o=>n().resumeConversation(o),retry:o=>window.electronAPI.agent.retry(o,{unfinishedOnly:!0}),waitUntil:Rk});s.length!==0&&ze({type:"info",title:e("Continued {{count}} conversation(s) interrupted by the update",{count:s.length})})})()},[e])}const Lk="enso-win",gA="enso-win-flush",Sd="enso-win-pending",Ok="enso-win-native";function _le(e,t,n){return{maximized:n.maximized?e.maximized:t.maximized,fullscreen:n.fullscreen?e.fullscreen:t.fullscreen}}function Nle(e,t){return e||t}function Tle(e,t){document.documentElement.classList.toggle(gA,Nle(e,t))}function Dle(){m.useEffect(()=>{if(window.electronAPI?.env.platform!=="win32")return;const e=document.documentElement;e.classList.add(Lk,Sd),e.classList.add(Ok);let t={maximized:!1,fullscreen:!1};const n={maximized:0,fullscreen:0};let s=!1,o=0,r;const a=()=>Tle(t.maximized,t.fullscreen),l=window.electronAPI.window,c=()=>{const p=++o,f={...n};Promise.all([l.isMaximized(),l.isFullScreen()]).then(([g,x])=>{s||p!==o||(t=_le(t,{maximized:g,fullscreen:x},{maximized:n.maximized!==f.maximized,fullscreen:n.fullscreen!==f.fullscreen}),e.classList.remove(Sd),a())}).catch(()=>{!s&&p===o&&e.classList.remove(Sd)})};c();const d=()=>{r&&clearTimeout(r),r=setTimeout(c,50)};window.addEventListener("resize",d);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",d),u(),h(),e.classList.remove(Lk,gA,Sd,Ok)}},[])}function Ile(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 zk(e){const t=e.permissions.includes("composer.draft")?"1":"0";return`${e.id}\0${e.version}\0${e.build}\0${e.renderer??""}\0${t}`}function xA(e,t){try{t?.dispose()}catch(n){console.warn(`[plugin] ${e} 渲染模块卸载失败`,n)}}async function Ele(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 c=o.get(a);(!c||zk(c)!==l.key)&&r.push(a)}for(const a of r)xA(a,e.get(a)),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 c=zk(a),d=e.get(a.id);if(d?.key===c){l.dispose();return}d?.dispose(),e.set(a.id,{key:c,dispose:()=>l.dispose()})}))}const gs=(e,t)=>({ok:!1,code:e,error:t});async function Ple(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 c=a.indexOf("::");if(c>0){const d=a.slice(0,c);return t.conversation(d)?(t.focusSubagent(d,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:c}=e.payload;return typeof a!="string"||!a||typeof l!="string"||!l||typeof c!="string"||!c?gs("BAD_REQUEST","缺少视图标识"):(t.openPluginView?.(e.sessionId,{pluginId:a,viewId:l,title:c}),{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 Ale={conversation:e=>oe.getState().conversations[e]??null,focus:(e,t)=>{const n=oe.getState();n.selectConversation(e),t!==e&&n.selectTab(e,t)},focusSubagent:(e,t)=>oe.getState().focusSubagent(e,t),openChildRun:(e,t)=>oe.getState().openChildRun(e,t),create:(e,t)=>oe.getState().newConversation(e,t?{presetId:t}:void 0),prefill:pz,ensure:async e=>{const t=oe.getState(),n=t.conversations[e];if(n?.started||n?.spawning)return null;await t.resumeConversation(e,{fresh:!0});const s=oe.getState().conversations[e];return s?.started||s?.spawning?null:s?.error??"无法启动会话:请检查默认模型与登录状态"},openPluginView:(e,t)=>fz({conversationId:e,...t})};function Mle(){return m.useEffect(()=>{const e=gz(()=>MQ(oe.getState()));let t=0;const n=new Map,s=new Set,o=()=>{const l=++t;window.electronAPI.extensionPlugins.list().then(async c=>{if(l!==t)return;for(const{pluginName:u,event:h}of Ile(c,s))ze({type:"warning",title:`插件 ${u} 的检查连续失败,已临时放行`,description:`${h} 事件 30 秒内不再经过该插件;详情见设置里的插件日志`});const d=c.filter(u=>u.state==="enabled");uz(Object.fromEntries(c.flatMap(u=>u.icon?[[u.id,u.icon]]:[]))),V0(hz(c)),ZS(aee(c)),$0(d.flatMap(u=>u.views.map(h=>({pluginId:u.id,pluginName:u.name,...h})))),Sk(d.flatMap(u=>(u.fileViewers??[]).map(h=>({pluginId:u.id,pluginName:u.name,...h})))),tC(d.flatMap(u=>u.triggers.filter(h=>h.symbol==="#").map(h=>({pluginId:u.id,name:h.name})))),await Ele(n,c,u=>mz(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"){Ple(l,Ale).catch(c=>({ok:!1,code:"SESSION_FAILED",error:c instanceof Error?c.message:String(c)})).then(c=>window.electronAPI.extensionPlugins.respondDraft({requestId:l.requestId,...c}));return}window.electronAPI.extensionPlugins.respondDraft({requestId:l.requestId,...dz(l)})});return()=>{t+=1,r(),a(),V0([]),tC([]),$0([]),Sk([]),ZS([]);for(const[l,c]of n)xA(l,c);n.clear()}},[]),null}function Rle(e,t=[]){return JSON.stringify({pinnedOrder:t,entries:e.map(n=>{const{updatedAt:s,...o}=n;return o})})}function Lle(e){return JSON.stringify(e)}function Ole(e,t,n=[]){const s=xz(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:m_,name:"Auto",models:o.map(r=>({id:r.id,label:r.name}))}),s}function zle(e,t,n=[]){const s=Ole(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 Gle=300;let Cd=null,Gk=!1,Tg=null;function Fle(){const e=ye.getState(),t=oe.getState(),n=Fv(e.projects,Ei(zd)),s=new Set(e.projects.filter(w=>w.kind==="scratch").map(w=>w.id)),o=n.filter(w=>w.kind!=="scratch"),r=new Set(Ei(ro)),a=wz(yz(e.language),"Temporary chats"),l=new Map(e.projects.map(w=>[w.id,w.kind==="scratch"?a:Lo(w)])),c=new Map(e.projects.map(w=>[w.id,w.path])),d=new Map(e.projects.map(w=>[w.id,w.kind])),u=w=>{const C=(w.parentId?t.conversations[w.parentId]:void 0)??w;return d.get(C.projectId)==="scratch"?ex({kind:"scratch",canonicalPath:c.get(C.projectId)??"",conversationId:C.id})??void 0:C.worktree?.path??c.get(w.projectId)},h=e.skills.filter(w=>w.enabled!==!1).map(w=>({name:`/skill:${w.name}`,description:w.description})),p=w=>{const C=CE(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:M_(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(_=>({id:_.id,text:_.text,..._.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}:{},...C?{context:C}:{},...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=zle(P_(),yo.getState().snapshot,e.virtualModels);return{catalog:y,pinnedOrder:Ei(ym),projects:o.map(w=>({...cse(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:Ju(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 Hle(e){return Lle({catalog:Rle(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 Ble(){return oe.persist.hasHydrated()&&ye.persist.hasHydrated()}function Qi(){Cd&&clearTimeout(Cd),Cd=setTimeout(()=>{if(Cd=null,!ao()||!Ble())return;const e=Fle(),t=Hle(e);t!==Tg&&(Tg=t,window.electronAPI.pair.pushCatalog(e))},Gle)}function Vle(){Gk||(Gk=!0,Qi(),oe.persist.onFinishHydration(Qi),ye.persist.onFinishHydration(Qi),oe.subscribe((e,t)=>{(e.conversations!==t.conversations||e.order!==t.order)&&Qi()}),yo.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Qi()}),vz.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Qi()}),ye.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()}),sT(Qi),bz(e=>{e&&(Tg=null,Qi())}),window.electronAPI.pair.onResumeSession(e=>{W0(e),ao()&&(oe.getState().markConversationRead(e),oe.getState().resumeConversation(e))}),window.electronAPI.pair.onSessionCreated(e=>{W0(e.sessionId),ao()&&oe.getState().adoptPairSession(e)}),window.electronAPI.pair.onSessionConfig(e=>{if(!ao())return;const t=oe.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(!ao())return;const t=oe.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 $le=3e4;async function Wle(e,t=Date.now()){const{order:n,conversations:s,activeId:o}=oe.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:M_(h)}]}),a=Sz(r,e,t),l=oe.getState();for(const u of a)l.removeConversation(u);const c=Date.now()+$le,d=()=>a.filter(u=>oe.getState().conversations[u]);for(;d().length>0&&Date.now()<c;)await new Promise(u=>setTimeout(u,200));return a.length-d().length}const Ule=e=>{const t=u3(e);return t.length>0?t:G_(e)},Fk="enso-sidebar-width",Hk="enso-sidebar-collapsed";function _f(){const e=oe.getState(),n=(e.activeId?e.conversations[e.activeId]:null)?.projectId??ye.getState().projects[0]?.id;n&&e.newConversation(n)}const kd="no-drag flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",Bk=200,Vk=420;function Kle(){const e=ye(W=>W.onboarded),t=m.useSyncExternalStore(W=>ye.persist?.onFinishHydration?.(W)??(()=>{}),()=>ye.persist?.hasHydrated?.()??!0);Cz(),xle(),mle(),jle(),yle(),gle();const[n,s]=m.useState(!1),[o,r]=m.useState(null);Dle();const[a,l]=m.useState(()=>{const W=Number(localStorage.getItem(Fk));return Number.isFinite(W)&&W>=Bk?Math.min(W,Vk):280}),[c,d]=m.useState(()=>localStorage.getItem(Hk)==="1"),u=Sa(),h=kz(),[p,f]=m.useState(!1),g=m.useCallback(()=>f(!1),[]);m.useEffect(()=>{u||f(!1)},[u]),m.useEffect(()=>oe.subscribe((W,ue)=>{W.activeId!==ue.activeId&&f(!1)}),[]);const{t:x}=se(),v=ye(W=>W.chatWide),y=oe(W=>W.activeId),b=fn(W=>y?!!W.uiByConversation[y]?.open:!1),w=fn(W=>W.uiByConversation[y??""]?.width??W.lastWidth),C=fn(W=>W.fullscreen),_=fn(W=>W.toggleOpen),N=de(W=>W.panelOpen),S=de(W=>W.togglePanel);m.useEffect(()=>{C&&!b&&fn.getState().setFullscreen(!1)},[b,C]),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(W=>{jz().finally(()=>{window.electronAPI.app.respondFlushPersist(W)})}),[]);const k=W=>{const ue=o;ue&&(r(null),window.electronAPI.app.respondCloseRequest(ue,{action:W}))},[A,I]=m.useState(!1),D=m.useRef(null);m.useEffect(()=>{localStorage.setItem(Fk,String(a))},[a]),m.useEffect(()=>{localStorage.setItem(Hk,c?"1":"0")},[c]),m.useEffect(()=>window.electronAPI.resources.onSessionsCleanRequest(({requestId:W,request:ue})=>{Wle(ue).catch(()=>0).then(Z=>window.electronAPI.resources.sessionsCleanDone(W,Z))}),[]),m.useEffect(()=>{Vle()},[]),m.useEffect(()=>{const W=is.getState();if(window.electronAPI.remote){W.activeNodeId!=="local"&&W.switchNode("local");return}return W.bind()},[]);const P=is(W=>W.activeNodeId),T=P!=="local",z=pW(),O=ye(W=>W.botModeEnabled),L=uo(W=>W.mode);m.useEffect(()=>{const W=ye.persist?.hasHydrated?.()??!0;L==="bot"&&(W&&!O||T)&&uo.getState().setMode("code")},[L,O,T]),m.useEffect(()=>{if(!O)return;const W=de.getState().bind(),ue=window.electronAPI.bots.onEvent(Z=>{Z.kind==="open"&&fW(Z)});return()=>{W(),ue()}},[O]),m.useEffect(()=>window.electronAPI.agent.onFocusSession(W=>{oe.getState().conversations[W]&&$x()}),[]);const V=m.useCallback(W=>{l(ue=>Math.min(Vk,Math.max(Bk,ue+W)))},[]),X=ye(W=>W.keybindings);m.useEffect(()=>{const W=Oi(X),ue=J=>{const ae=oe.getState(),te=ae.activeId?ae.conversations[ae.activeId]:null;if(!te)return;const pe=[void 0,...te.coworkerIds??[]];if(pe.length<=1)return;const Te=pe.indexOf(te.activeTabId);ae.selectTab(te.id,pe[(Te+J+pe.length)%pe.length])},Z=J=>{const ae=Al(J);if(!ae)return;if(ae===W["toggle-app-mode"]){if(!ye.getState().botModeEnabled||is.getState().activeNodeId!=="local")return;J.preventDefault();const Te=uo.getState();Te.setMode(Te.mode==="bot"?"code":"bot");return}const te=is.getState().activeNodeId!=="local"||Gc();if(Gc()&&ae===W["toggle-side-panel"]){J.preventDefault(),de.getState().togglePanel();return}if(Gc()&&ae===W["search-workspace"]){J.preventDefault(),de.getState().setSearchOpen(!0);return}if(!(te&&["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(pe=>ae===W[pe]))){if(ae===W["toggle-sidebar"])J.preventDefault(),Ez(window.innerWidth)?f(pe=>!pe):d(pe=>!pe);else if(ae===W["open-settings"])J.preventDefault(),window.electronAPI.window.openSettings();else if(ae===W["new-conversation"])J.preventDefault(),_f();else if(ae===W["new-side-tab"])J.preventDefault(),Pz(J.target)?Az():_f();else if(ae===W["new-btw-tab"])J.preventDefault(),Mz();else if(ae===W["next-tab"])J.preventDefault(),ue(1);else if(ae===W["prev-tab"])J.preventDefault(),ue(-1);else if(ae===W["toggle-side-panel"])J.preventDefault(),fn.getState().toggleOpen();else if(ae===W["toggle-side-panel-fullscreen"])J.preventDefault(),fn.getState().toggleFullscreen();else if(ae===W["close-side-tab"])J.preventDefault(),Rz();else if(ae===W["focus-composer"])J.preventDefault(),Co();else if(ae===W["find-in-chat"])J.preventDefault(),iE();else if(ae===W["search-workspace"])J.preventDefault(),s(!0);else if(!te){const pe=Lz(u_(),X,W).byBinding.get(ae);if(!pe)return;J.preventDefault();const Te=oe.getState(),$e=Te.activeId?Te.conversations[Te.activeId]:null;Kg(pe,$e?$e.activeTabId??$e.id:null).then(Ie=>{Ie&&ze({type:"error",title:pe.title,description:Ie})})}}};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[X]),m.useEffect(()=>{if(!b||!C)return;const W=ue=>{ue.key==="Escape"&&is.getState().activeNodeId==="local"&&(Gc()||(ue.preventDefault(),fn.getState().setFullscreen(!1)))};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[b,C]);const F=n3(t3(rx,{activationConstraint:{distance:6}})),ee=lh(),H=ee!=="mobile"&&!T&&!z,Q=m.useCallback(W=>{const ue=D.current;if(!ue)return;const Z=getComputedStyle(ue),J=ue.clientWidth-parseFloat(Z.paddingLeft)-parseFloat(Z.paddingRight);fn.getState().nudgeWidth(-W,J,H?A_:$g)},[H]),q=O&&!T?i.jsx(IQ,{}):null,ne=H&&(ee==="mac"||ee==="windows"||ee==="web"),me=ne&&b&&!u&&!z&&!T,ke=T?null:i.jsx("button",{type:"button",className:U("flex items-center justify-center rounded-md transition-colors hover:bg-accent/50",u?"h-9 w-9":H?kd:"h-7 w-7",(z?N:b)?"text-foreground":"text-muted-foreground"),onClick:z?S:_,"aria-label":x("Toggle side panel"),title:x("Toggle side panel"),children:i.jsx($N,{className:"h-4 w-4"})}),Me=i.jsx("button",{type:"button",className:U("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:()=>ye.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(g6,{className:"h-4 w-4"}):i.jsx(y4,{className:"h-4 w-4"})}),ge=i.jsxs(i.Fragment,{children:[Me,ke]}),$=H?{trailing:Me}:null;return i.jsxs("div",{"data-enso":"canvas",className:U("relative isolate flex flex-col",u?"h-dvh":"h-screen"),children:[i.jsx(_z,{}),i.jsx(Nz,{}),i.jsx(K4,{}),i.jsx(xW,{}),i.jsx(Tz,{}),ee!=="mobile"?i.jsx(U0,{leading:i.jsxs("div",{className:"flex items-center gap-0.5",children:[!T&&i.jsx("div",{className:U(ee!=="mac"&&"flex justify-center",ee!=="mac"&&(H?"w-[48px]":"w-12")),children:i.jsx("button",{type:"button","data-enso":"sidebar-toggle",className:kd,onClick:()=>d(W=>!W),title:x(c?"Expand sidebar":"Collapse sidebar"),children:c?i.jsx(VN,{className:"h-4 w-4"}):i.jsx(Bx,{className:"h-4 w-4"})})}),H&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-enso":"search-button",className:kd,onClick:()=>s(!0),title:x("Search anything"),children:i.jsx(ei,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"new-session",className:kd,onClick:_f,title:x("New conversation"),children:i.jsx(WN,{className:"h-4 w-4"})})]})]}),centered:(me&&C?null:q)??void 0,className:U(ee!=="mac"&&!T&&"pl-0",H&&"border-b-0",H&&"bg-transparent",H&&ee==="mac"&&"pr-4"),actions:H?me?void 0:ke:ge}):i.jsx(U0,{title:"EnsoCode",centered:q??void 0,leading:u&&!T&&!z?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($6,{className:"h-5 w-5"})}),!q&&i.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"EnsoCode"})]}):void 0,actions:ge}),!H&&i.jsx(Mw,{}),!H&&i.jsx(Rw,{}),i.jsx("div",{className:"flex min-h-0 flex-1",children:T?i.jsx(xse,{nodeId:P,sidebarWidth:a}):z?i.jsx(jQ,{sidebarWidth:a,collapsed:c,onToggleCollapse:()=>d(W=>!W),onResize:V}):i.jsxs(sG,{sensors:F,collisionDetection:Ule,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:Cn.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:Cn.MOBILE_DRAWER},initial:!1,animate:{x:p?0:"-105%"},transition:na,inert:!p,children:i.jsx(_C,{width:Math.min(320,Math.round(h*.85)),collapsed:!1,onToggleCollapse:g,onOpenSearch:()=>s(!0),onNavigate:g})})]}):i.jsxs(i.Fragment,{children:[i.jsx(_C,{width:c?void 0:a,collapsed:c,onToggleCollapse:()=>d(W=>!W),onOpenSearch:()=>s(!0)}),!c&&i.jsx(ku,{edge:H,onResize:V})]}),i.jsxs("div",{ref:D,className:U("relative flex min-h-0 min-w-0 flex-1",ne?"overflow-x-clip":"overflow-hidden",H&&"-mt-px -ml-px pt-px pr-[8px] pb-[8px] pl-px"),children:[i.jsxs("div",{"data-enso":"main",className:U("flex min-h-0 min-w-0 flex-1 flex-col bg-background",H&&"overflow-hidden rounded-[10px] shadow-surface",me&&"rounded-r-none"),style:b&&C?{visibility:"hidden",transition:`visibility 0s ${Eu.duration}s`}:void 0,children:[i.jsx(Mle,{}),i.jsx(Dz.Provider,{value:$,children:i.jsx(tne,{})}),H&&i.jsx(Mw,{}),H&&i.jsx(Rw,{})]}),b&&!C&&!u&&i.jsx(ku,{gap:H&&!me,onResize:Q,onResizingChange:I}),i.jsx(ule,{width:w,resizing:A,card:H,titleRow:ne})]})]})}),t&&!e&&!window.electronAPI.remote&&i.jsx(bse,{}),i.jsx(Bse,{open:n,onOpenChange:s}),i.jsx(v_,{open:o!==null,onOpenChange:W=>{!W&&o&&k("cancel")},children:i.jsxs(b_,{className:"sm:max-w-sm",children:[i.jsxs(w_,{children:[i.jsx(y_,{className:"text-base",children:x("Confirm exit")}),i.jsx(S_,{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(C_,{variant:"bare",children:[i.jsx(Iz,{render:i.jsx(xe,{variant:"outline",size:"sm"}),children:x("Cancel")}),i.jsx(xe,{size:"sm",onClick:()=>k("tray"),children:x("Minimize to tray")}),i.jsx(xe,{variant:"destructive",size:"sm",onClick:()=>k("quit"),children:x("Exit")})]})]})})]})}function qle(e){return new Worker(""+new URL("worker-DsKBD11i.js",import.meta.url).href,{type:"module",name:e?.name})}const Yle={workerFactory:()=>new qle,poolSize:2},Xle={theme:wa,langs:[...zz],preferredHighlighter:"shiki-js"};function Jle({children:e}){return i.jsx(Oz,{poolOptions:Yle,highlighterOptions:Xle,children:e})}function $k({conversations:e,activeId:t}){const n=document.documentElement.dataset,s=gne(e),o=AE(t?e[t]:void 0,e);n.ensoActivity!==s&&(n.ensoActivity=s),n.ensoSession!==o&&(n.ensoSession=o)}function Zle(){$k(oe.getState()),oe.subscribe((e,t)=>{(e.conversations!==t.conversations||e.activeId!==t.activeId)&&$k(e)})}Gz();Zle();Fz();jj();Hz.createRoot(document.getElementById("root")).render(i.jsx(m.StrictMode,{children:i.jsx(Jle,{children:i.jsx(Kle,{})})}));
|