@ensocode/server 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/out/phone/assets/{abnfDiagram-VCTEODGH-7wNFPVNX.js → abnfDiagram-VCTEODGH-CLgfII9z.js} +1 -1
  2. package/out/phone/assets/architecture-7GRP2DOG-CQOPTv6S.js +1 -0
  3. package/out/phone/assets/{architectureDiagram-5GKGNRK7-CnuIop2x.js → architectureDiagram-5GKGNRK7-I2RDn32D.js} +1 -1
  4. package/out/phone/assets/{blockDiagram-I7D4REHJ-JVET2iOX.js → blockDiagram-I7D4REHJ-D5xNQZkS.js} +1 -1
  5. package/out/phone/assets/{c4Diagram-7LVT6UL2-BLFmpm8Y.js → c4Diagram-7LVT6UL2-CRKpzdlA.js} +1 -1
  6. package/out/phone/assets/channel-DdXebl9x.js +1 -0
  7. package/out/phone/assets/{chunk-4HAMMTFA-t_CWzvX0.js → chunk-4HAMMTFA-CcezrqKz.js} +1 -1
  8. package/out/phone/assets/{chunk-75Z2AOVW-Ck9s4XbN.js → chunk-75Z2AOVW-DDCXp4y1.js} +1 -1
  9. package/out/phone/assets/{chunk-DU6HZSFF-Clg-W8ZP.js → chunk-DU6HZSFF-CjWveEkB.js} +1 -1
  10. package/out/phone/assets/{chunk-F27PBJKO-Dg6DF7tm.js → chunk-F27PBJKO-Bgl_xI02.js} +1 -1
  11. package/out/phone/assets/{chunk-GMAD6QVW-tyN1lr56.js → chunk-GMAD6QVW-EmL8nOme.js} +1 -1
  12. package/out/phone/assets/{chunk-GVQU2GXP-Cp6zlp3q.js → chunk-GVQU2GXP-Dox_nphF.js} +1 -1
  13. package/out/phone/assets/{chunk-IMKFNOWR-DivN0qgp.js → chunk-IMKFNOWR-BapGpI4S.js} +1 -1
  14. package/out/phone/assets/{chunk-L3NEJ4N5-H6AVmtE_.js → chunk-L3NEJ4N5-Cq_UZI8A.js} +1 -1
  15. package/out/phone/assets/{chunk-OSK3NFVY-D8Gtw0_S.js → chunk-OSK3NFVY-2VVlErAd.js} +1 -1
  16. package/out/phone/assets/{chunk-P2QGCYS3-RZSHAUZq.js → chunk-P2QGCYS3-Cci-G-p1.js} +1 -1
  17. package/out/phone/assets/{chunk-POPQ4Y6H-BVS8pZqz.js → chunk-POPQ4Y6H-CJ47EOfE.js} +1 -1
  18. package/out/phone/assets/{chunk-PWAF6VOD-D7FryQWf.js → chunk-PWAF6VOD-D9dLdFqC.js} +1 -1
  19. package/out/phone/assets/{chunk-SHT3W25Y-DGdqMpPQ.js → chunk-SHT3W25Y-BlGSiWZn.js} +1 -1
  20. package/out/phone/assets/{chunk-SVP7TREG-BwyiT08_.js → chunk-SVP7TREG-C0zdsa_A.js} +1 -1
  21. package/out/phone/assets/{chunk-TICWLB2K-CY7mq27-.js → chunk-TICWLB2K-DAQW8nQU.js} +1 -1
  22. package/out/phone/assets/classDiagram-ZZMXUADV-BCctWEp1.js +1 -0
  23. package/out/phone/assets/classDiagram-v2-VYDZK3BY-BCctWEp1.js +1 -0
  24. package/out/phone/assets/{cynefin-OW5HDTMX-ep90c-ad.js → cynefin-OW5HDTMX-_zsx5mdV.js} +1 -1
  25. package/out/phone/assets/{cynefinDiagram-5FMLGOSQ-M8djyXi6.js → cynefinDiagram-5FMLGOSQ-Cww-w0ex.js} +1 -1
  26. package/out/phone/assets/{dagre-GXQ25YYZ-Qp6_rUFB.js → dagre-GXQ25YYZ-C0i7DPqX.js} +1 -1
  27. package/out/phone/assets/desk-mfuEW2n4.js +2 -0
  28. package/out/phone/assets/{diagram-S7CK7UJ4-78nJmih8.js → diagram-S7CK7UJ4-Bx-G5hYz.js} +1 -1
  29. package/out/phone/assets/{diagram-UQ7AKVKN-DK3Lux6Z.js → diagram-UQ7AKVKN-DaTblkjV.js} +1 -1
  30. package/out/phone/assets/{diagram-VSXAHHWV-8uHrV5vL.js → diagram-VSXAHHWV-gmN2e1b4.js} +1 -1
  31. package/out/phone/assets/{diagram-VX7I27RA-DM2jP_ep.js → diagram-VX7I27RA-WYtRtOo8.js} +1 -1
  32. package/out/phone/assets/{diagram-Z3DM3KII-Dk6weE7F.js → diagram-Z3DM3KII-Cr6uUB5B.js} +1 -1
  33. package/out/phone/assets/{ebnfDiagram-PWID7BFC-CcOU0Q-s.js → ebnfDiagram-PWID7BFC-BCicfvpA.js} +1 -1
  34. package/out/phone/assets/{erDiagram-RLTQ6QDP-Cv4zHR88.js → erDiagram-RLTQ6QDP-B3QlJvfQ.js} +1 -1
  35. package/out/phone/assets/eventmodeling-NTZA5JFV-BtfapP6M.js +1 -0
  36. package/out/phone/assets/flowDiagram-HODETNUW-BsyiyBtD.js +1 -0
  37. package/out/phone/assets/{ganttDiagram-EL5Y4UJY-DpMAd_jd.js → ganttDiagram-EL5Y4UJY-LYy2mfCh.js} +1 -1
  38. package/out/phone/assets/{gitGraph-4MIJSDKK-CeZWGC9r.js → gitGraph-4MIJSDKK-dT22Z2jG.js} +1 -1
  39. package/out/phone/assets/{gitGraphDiagram-WWUBYQGX-6QsSrkNy.js → gitGraphDiagram-WWUBYQGX-DHNdY57l.js} +1 -1
  40. package/out/phone/assets/{info-A6RAGUB7-C-8QwtyE.js → info-A6RAGUB7-nIu8NSOs.js} +1 -1
  41. package/out/phone/assets/{infoDiagram-27XIBGKW-BEywxx6y.js → infoDiagram-27XIBGKW-DGkWZIMT.js} +1 -1
  42. package/out/phone/assets/{ishikawaDiagram-5VMMS53U-Dv5MWe8O.js → ishikawaDiagram-5VMMS53U-C8EPXru-.js} +1 -1
  43. package/out/phone/assets/{journeyDiagram-3NMN7TZE-rZqFk8KG.js → journeyDiagram-3NMN7TZE-Dyd9L3l3.js} +1 -1
  44. package/out/phone/assets/{kanban-definition-UXKFOSKX-Vbp8P778.js → kanban-definition-UXKFOSKX-DehTYcsL.js} +1 -1
  45. package/out/phone/assets/{line-DtO-RzWq.js → line-Db4SulF4.js} +1 -1
  46. package/out/phone/assets/main-Dv9ve8mT.css +1 -0
  47. package/out/phone/assets/main-uMMbioCA.js +1638 -0
  48. package/out/phone/assets/{mermaid-parser.core-CZ9_GWM0.js → mermaid-parser.core-D7h_8WV8.js} +3 -3
  49. package/out/phone/assets/{mermaid.core-B15T44DF.js → mermaid.core-Dw_E5kj4.js} +4 -4
  50. package/out/phone/assets/{mindmap-definition-YA3MSWOX-BgFUJmH3.js → mindmap-definition-YA3MSWOX-_5Mxqxsy.js} +1 -1
  51. package/out/phone/assets/{packet-AYTQ26CC--RETlRVk.js → packet-AYTQ26CC-_cgeMDdN.js} +1 -1
  52. package/out/phone/assets/{pegDiagram-XKGWAZYB-D7jmN93W.js → pegDiagram-XKGWAZYB-BhBwaNEr.js} +1 -1
  53. package/out/phone/assets/{pie-WAS4IAKB-CxG1AbYJ.js → pie-WAS4IAKB-BepY80_0.js} +1 -1
  54. package/out/phone/assets/{pieDiagram-E7YTZNPT-CHxSdknk.js → pieDiagram-E7YTZNPT-CQQgqmI8.js} +1 -1
  55. package/out/phone/assets/{quadrantDiagram-AXDQQJYC-707LGShZ.js → quadrantDiagram-AXDQQJYC-DEEatC1J.js} +1 -1
  56. package/out/phone/assets/{radar-RG4KPBEZ-BBg9aR2Q.js → radar-RG4KPBEZ-BqsiI_qQ.js} +1 -1
  57. package/out/phone/assets/{railroad-74A4TZTK-BvqQaIGQ.js → railroad-74A4TZTK-C_2pEUjD.js} +1 -1
  58. package/out/phone/assets/railroad-abnf-HS5TGJTU-TmODpceI.js +1 -0
  59. package/out/phone/assets/railroad-ebnf-LZEXJU2U-BTCjNR9u.js +1 -0
  60. package/out/phone/assets/railroad-peg-WCYAUIDC-DjhKNo8j.js +1 -0
  61. package/out/phone/assets/{railroadDiagram-O6MQD6OU-BQUOk6Jm.js → railroadDiagram-O6MQD6OU-B7786u7W.js} +1 -1
  62. package/out/phone/assets/{requirementDiagram-BXWQKSXE-ByuJLR7x.js → requirementDiagram-BXWQKSXE-Ci3b5uwm.js} +1 -1
  63. package/out/phone/assets/{sankeyDiagram-P5KCCOFB-CaWA3qV1.js → sankeyDiagram-P5KCCOFB-PwT2gJjH.js} +1 -1
  64. package/out/phone/assets/{sequenceDiagram-WJ2MYXX4--wDiyJo9.js → sequenceDiagram-WJ2MYXX4-H6sgB5RI.js} +1 -1
  65. package/out/phone/assets/{stateDiagram-D77RDMKH-ScVywISP.js → stateDiagram-D77RDMKH-BxyRe7OB.js} +1 -1
  66. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-Cncmf_cL.js +1 -0
  67. package/out/phone/assets/{storage-DBoRTPSQ.js → storage-D9RW_4__.js} +1 -1
  68. package/out/phone/assets/{swimlanes-42K2YHIH-Da4TbCnQ.js → swimlanes-42K2YHIH-DWT3f1Hk.js} +1 -1
  69. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-DAahG4fH.js +8 -0
  70. package/out/phone/assets/{timeline-definition-24CTP7MA-Csp8wyPz.js → timeline-definition-24CTP7MA-D67esSVY.js} +1 -1
  71. package/out/phone/assets/{treeView-Q6P3EWNA-DP_TpAnB.js → treeView-Q6P3EWNA-BTIfu3Qr.js} +1 -1
  72. package/out/phone/assets/{treemap-WGGIJYW6-CDX7X9Iz.js → treemap-WGGIJYW6-DkPf6LQc.js} +1 -1
  73. package/out/phone/assets/{vennDiagram-4TSXK5OY-DU4FDr9s.js → vennDiagram-4TSXK5OY-DRMRxJ4f.js} +1 -1
  74. package/out/phone/assets/{wardley-WFR3VGLG-DJY3i8km.js → wardley-WFR3VGLG-hOvC_8-W.js} +1 -1
  75. package/out/phone/assets/{wardleyDiagram-VM6X3IG4-CDWkRMg4.js → wardleyDiagram-VM6X3IG4-a5aYRgrw.js} +1 -1
  76. package/out/phone/assets/{xychartDiagram-S5SC5T6Z-DAWohWCi.js → xychartDiagram-S5SC5T6Z-DXjoRFDL.js} +1 -1
  77. package/out/phone/desk.html +2 -2
  78. package/out/phone/index.html +3 -3
  79. package/out/renderer/assets/{abnfDiagram-VCTEODGH-CyBOQPqT.js → abnfDiagram-VCTEODGH-DhskujJf.js} +1 -1
  80. package/out/renderer/assets/{arc-JLdYPu0k.js → arc-BcW67t47.js} +1 -1
  81. package/out/renderer/assets/{architectureDiagram-5GKGNRK7-Bq5gy8K8.js → architectureDiagram-5GKGNRK7-D-x057Ia.js} +1 -1
  82. package/out/renderer/assets/{blockDiagram-I7D4REHJ-Bno0lw2B.js → blockDiagram-I7D4REHJ-DR3sZkhW.js} +1 -1
  83. package/out/renderer/assets/{c4Diagram-7LVT6UL2-BC6INPz6.js → c4Diagram-7LVT6UL2-CQ4lScWs.js} +1 -1
  84. package/out/renderer/assets/channel-CudRig7z.js +1 -0
  85. package/out/renderer/assets/{chunk-2Q5K7J3B-CcyqDHha.js → chunk-2Q5K7J3B-CtT0yqF3.js} +1 -1
  86. package/out/renderer/assets/{chunk-5VM5RSS4-QSbyABj3.js → chunk-5VM5RSS4-DlCfddrY.js} +1 -1
  87. package/out/renderer/assets/{chunk-F27PBJKO-4574JVSg.js → chunk-F27PBJKO-BAJ5dGzo.js} +1 -1
  88. package/out/renderer/assets/{chunk-IMKFNOWR-DCaKjC49.js → chunk-IMKFNOWR-Dlah_YbP.js} +1 -1
  89. package/out/renderer/assets/{chunk-JWPE2WC7-CbFsKOIM.js → chunk-JWPE2WC7-BiXd3nUZ.js} +1 -1
  90. package/out/renderer/assets/{chunk-POPQ4Y6H-B6j8RfR6.js → chunk-POPQ4Y6H-Ch86i4EJ.js} +1 -1
  91. package/out/renderer/assets/{chunk-SVP7TREG-kRAl0a5G.js → chunk-SVP7TREG-z3inDV-H.js} +1 -1
  92. package/out/renderer/assets/{chunk-TICWLB2K-BgG8vTk6.js → chunk-TICWLB2K-B34A2AKD.js} +1 -1
  93. package/out/renderer/assets/{chunk-XXDRQBXY-DdqB8mBq.js → chunk-XXDRQBXY-Do_L0wRR.js} +1 -1
  94. package/out/renderer/assets/classDiagram-ZZMXUADV-DL20WkD0.js +1 -0
  95. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-DL20WkD0.js +1 -0
  96. package/out/renderer/assets/{cose-bilkent-JH36ORCC-HfctEoii.js → cose-bilkent-JH36ORCC-BQraKmgl.js} +1 -1
  97. package/out/renderer/assets/{cynefin-OW5HDTMX-BNigpbGU.js → cynefin-OW5HDTMX-BwixoR4r.js} +1 -1
  98. package/out/renderer/assets/{cynefinDiagram-5FMLGOSQ-CL-lRXZ7.js → cynefinDiagram-5FMLGOSQ-BLTBma3J.js} +1 -1
  99. package/out/renderer/assets/{cytoscape-fcose-B40eUKiT.js → cytoscape-fcose-BRpJ5tyq.js} +1 -1
  100. package/out/renderer/assets/{dagre-GXQ25YYZ-D7VwJTHe.js → dagre-GXQ25YYZ-aWsjA_wn.js} +1 -1
  101. package/out/renderer/assets/{diagram-S7CK7UJ4-CAp3JWMB.js → diagram-S7CK7UJ4-Cur2zK4q.js} +1 -1
  102. package/out/renderer/assets/{diagram-UQ7AKVKN-H_c4KXAy.js → diagram-UQ7AKVKN-DlrY8YcD.js} +1 -1
  103. package/out/renderer/assets/{diagram-VSXAHHWV-CsEX84Cq.js → diagram-VSXAHHWV-BBdjreqR.js} +1 -1
  104. package/out/renderer/assets/{diagram-VX7I27RA-ebIy3O1D.js → diagram-VX7I27RA-XiWMdc8S.js} +1 -1
  105. package/out/renderer/assets/{diagram-Z3DM3KII-BtVfEzv9.js → diagram-Z3DM3KII-CBB5leat.js} +1 -1
  106. package/out/renderer/assets/{ebnfDiagram-PWID7BFC-C25YK-UV.js → ebnfDiagram-PWID7BFC-nl8RPo8j.js} +1 -1
  107. package/out/renderer/assets/{erDiagram-RLTQ6QDP-1imAb8Go.js → erDiagram-RLTQ6QDP-C_oaG80x.js} +1 -1
  108. package/out/renderer/assets/{flowDiagram-HODETNUW-OwceYbhd.js → flowDiagram-HODETNUW-nDoVZFS7.js} +1 -1
  109. package/out/renderer/assets/{ganttDiagram-EL5Y4UJY-DDoN4Uki.js → ganttDiagram-EL5Y4UJY-DOrcuM3Q.js} +1 -1
  110. package/out/renderer/assets/{gitGraphDiagram-WWUBYQGX-yrrX43-g.js → gitGraphDiagram-WWUBYQGX-D_DB3jro.js} +1 -1
  111. package/out/renderer/assets/globals-Bkw7iiQG.css +1 -0
  112. package/out/renderer/assets/globals-D1ocHHQV.js +2533 -0
  113. package/out/renderer/assets/index-Cm5iq85v.js +117 -0
  114. package/out/renderer/assets/{infoDiagram-27XIBGKW-BoYY6yGv.js → infoDiagram-27XIBGKW-BbBrANxo.js} +1 -1
  115. package/out/renderer/assets/{ishikawaDiagram-5VMMS53U-BbtGOrLg.js → ishikawaDiagram-5VMMS53U-7UlfWlWV.js} +1 -1
  116. package/out/renderer/assets/{journeyDiagram-3NMN7TZE-BWTb58Kr.js → journeyDiagram-3NMN7TZE-CJP9bosH.js} +1 -1
  117. package/out/renderer/assets/{kanban-definition-UXKFOSKX-BSN2oIEH.js → kanban-definition-UXKFOSKX-D772kW7T.js} +1 -1
  118. package/out/renderer/assets/{layout-k2BpK8-6.js → layout-BzVfJEvx.js} +1 -1
  119. package/out/renderer/assets/{linear-DFArNkXT.js → linear-DBjhr05m.js} +1 -1
  120. package/out/renderer/assets/{mermaid.core-DthanE8x.js → mermaid.core-CJpNSowm.js} +5 -5
  121. package/out/renderer/assets/{mindmap-definition-YA3MSWOX-BhETDMxE.js → mindmap-definition-YA3MSWOX-C2oqlH5E.js} +1 -1
  122. package/out/renderer/assets/{pegDiagram-XKGWAZYB-B9w_o-Iv.js → pegDiagram-XKGWAZYB-CcZ8Hae-.js} +1 -1
  123. package/out/renderer/assets/{pieDiagram-E7YTZNPT-klH2bEkC.js → pieDiagram-E7YTZNPT-DTw-_k2D.js} +1 -1
  124. package/out/renderer/assets/{quadrantDiagram-AXDQQJYC-DerYxAqw.js → quadrantDiagram-AXDQQJYC-D5eX0DO7.js} +1 -1
  125. package/out/renderer/assets/{railroadDiagram-O6MQD6OU-D4EFSRd0.js → railroadDiagram-O6MQD6OU-DzpBB_Re.js} +1 -1
  126. package/out/renderer/assets/{requirementDiagram-BXWQKSXE-C4O9MABZ.js → requirementDiagram-BXWQKSXE-UbOUXLgl.js} +1 -1
  127. package/out/renderer/assets/{sankeyDiagram-P5KCCOFB-ILgR3far.js → sankeyDiagram-P5KCCOFB-jRbXLLsa.js} +1 -1
  128. package/out/renderer/assets/{sequenceDiagram-WJ2MYXX4-SHHY6jka.js → sequenceDiagram-WJ2MYXX4-s0WBQQPf.js} +1 -1
  129. package/out/renderer/assets/settings-DxYo7s4h.js +34 -0
  130. package/out/renderer/assets/{sizeCapture-INFHLROL-CX9hC7Eu.js → sizeCapture-INFHLROL-DvUs5rDx.js} +1 -1
  131. package/out/renderer/assets/{stateDiagram-D77RDMKH-CZ1zq3yT.js → stateDiagram-D77RDMKH-C1_V497y.js} +1 -1
  132. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-C9dfLXR8.js +1 -0
  133. package/out/renderer/assets/{swimlanes-42K2YHIH-BxCpUxk0.js → swimlanes-42K2YHIH-BulPeZ6y.js} +1 -1
  134. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-LXwy6qGO.js +8 -0
  135. package/out/renderer/assets/{timeline-definition-24CTP7MA-BZrSf5qo.js → timeline-definition-24CTP7MA-gQ5OygZn.js} +1 -1
  136. package/out/renderer/assets/{vennDiagram-4TSXK5OY-g01Cyb5O.js → vennDiagram-4TSXK5OY-A8QyA5Ix.js} +1 -1
  137. package/out/renderer/assets/{wardleyDiagram-VM6X3IG4-Bt_RS10y.js → wardleyDiagram-VM6X3IG4-CfP6E41T.js} +1 -1
  138. package/out/renderer/assets/{xychartDiagram-S5SC5T6Z-DuwmVyP6.js → xychartDiagram-S5SC5T6Z-DTG5UHh7.js} +1 -1
  139. package/out/renderer/index.html +3 -3
  140. package/out/renderer/plugin-view.html +27 -0
  141. package/out/renderer/settings.html +4 -4
  142. package/out/renderer/web-preload.js +1 -1
  143. package/out/server/agent.js +831 -77
  144. package/out/server/chunks/{agent-D37_gFfr.js → agent-BhQn6jGA.js} +330 -137
  145. package/out/server/chunks/{gpuBackendInstall-FekvL7Rv.js → gpuBackendInstall-CdExgjGi.js} +4 -4
  146. package/out/server/chunks/{loadProvider-CSeEHHnd.js → loadProvider-BnkyjMSW.js} +2 -2
  147. package/out/server/chunks/{manifest-Bj0K5UgY.js → manifest-2odvnxjZ.js} +97 -19
  148. package/out/server/chunks/{workflowPresets-DBDQwf8e.js → workflowPresets-DqSsjOj6.js} +725 -460
  149. package/out/server/index.js +2958 -554
  150. package/out/server/plugin-host.js +38 -6
  151. package/package.json +1 -1
  152. package/out/phone/assets/architecture-7GRP2DOG-_byK4-L4.js +0 -1
  153. package/out/phone/assets/channel-Dgd_LVvp.js +0 -1
  154. package/out/phone/assets/classDiagram-ZZMXUADV-C83rE770.js +0 -1
  155. package/out/phone/assets/classDiagram-v2-VYDZK3BY-C83rE770.js +0 -1
  156. package/out/phone/assets/desk-DOJjOIls.js +0 -2
  157. package/out/phone/assets/eventmodeling-NTZA5JFV-7mnBgbcg.js +0 -1
  158. package/out/phone/assets/flowDiagram-HODETNUW-sLsydHyr.js +0 -1
  159. package/out/phone/assets/main-CX13EK2l.js +0 -1636
  160. package/out/phone/assets/main-DZEEX8Mv.css +0 -1
  161. package/out/phone/assets/railroad-abnf-HS5TGJTU-Cm1qeEMZ.js +0 -1
  162. package/out/phone/assets/railroad-ebnf-LZEXJU2U-MFhpnZ_W.js +0 -1
  163. package/out/phone/assets/railroad-peg-WCYAUIDC-DCsilESk.js +0 -1
  164. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-D1LtnHXy.js +0 -1
  165. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-C2SWpfVX.js +0 -8
  166. package/out/renderer/assets/channel-C0GtgNRj.js +0 -1
  167. package/out/renderer/assets/classDiagram-ZZMXUADV-DUyds1A3.js +0 -1
  168. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-DUyds1A3.js +0 -1
  169. package/out/renderer/assets/globals-C6gFTVZy.css +0 -1
  170. package/out/renderer/assets/globals-CYDlkaHa.js +0 -2509
  171. package/out/renderer/assets/index-D1rFnBbz.js +0 -116
  172. package/out/renderer/assets/settings-DB_fAikP.js +0 -33
  173. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-NCbr7wNQ.js +0 -1
  174. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N--ymqRTT2.js +0 -8
@@ -1,116 +0,0 @@
1
- import{r as m,ey as Ce,ez as Fs,j as o,c as ot,eA as cv,eB as dv,eC as SC,q as xe,eD as pn,eE as Dh,eF as Kp,eG as mP,eH as gP,p as te,d4 as CC,as as Xl,X as ln,aO as xP,e as q,cS as kC,cb as Eo,az as Jr,eI as vP,eJ as bP,eK as _C,ce as wP,eL as jC,cf as da,df as Ao,cH as NC,eM as yP,av as zm,eN as SP,eO as CP,eP as kP,eQ as _P,eR as wl,eS as ua,eT as ro,eU as jP,eV as NP,eW as TP,eX as fs,eY as hd,eZ as IP,e_ as DP,e$ as yl,f0 as Sl,f1 as ki,f2 as Ph,f3 as PP,f4 as pd,f5 as Cr,f6 as EP,f7 as AP,f8 as MP,f9 as RP,fa as LP,fb as OP,fc as Eh,fd as zr,fe as uv,ff as TC,fg as hv,fh as zP,fi as GP,fj as Wr,fk as FP,fl as si,fm as HP,fn as er,fo as IC,fp as pv,fq as Zr,fr as BP,fs as bc,ft as VP,fu as $P,fv as WP,fw as UP,fx as fv,fy as DC,fz as qp,fA as KP,fB as qP,fC as PC,fD as YP,fE as mv,fF as EC,fG as XP,fH as JP,fI as Yp,fJ as ZP,fK as AC,fL as QP,fM as eE,fN as tE,fO as nE,fP as sE,fQ as gv,fR as iE,fS as oE,fT as rE,fU as xv,fV as Ah,fW as aE,fX as lE,fY as cE,fZ as MC,f_ as Mr,f$ as Ba,g0 as Qo,g1 as RC,g2 as Mh,g3 as Xp,g4 as dE,g5 as Iu,g6 as uE,g7 as hE,g8 as pE,g9 as _a,ga as fE,gb as mE,gc as gE,gd as LC,ge as xE,gf as vE,gg as bE,gh as wE,gi as yE,gj as OC,gk as zC,gl as eo,gm as SE,gn as CE,go as vv,gp as kE,cK as Qr,cI as Jl,cJ as ha,bm as ea,ej as Zs,Y as Zl,gq as _E,gr as jE,gs as NE,gt as TE,gu as IE,gv as DE,gw as PE,gx as EE,gy as AE,gz as ME,gA as RE,gB as LE,a3 as Gm,af as OE,gC as zE,gD as GE,gE as FE,gF as HE,gG as BE,gH as VE,gI as $E,a4 as GC,gJ as WE,gK as UE,gL as KE,gM as qE,b as Ql,gN as YE,gO as XE,gP as JE,gQ as ZE,gR as QE,gS as eA,d as tA,gT as nA,gU as sA,gV as iA,gW as oA,db as rA,ck as FC,ek as Du,gX as aA,cN as HC,gY as js,cq as Jn,bF as Pu,dr as Ls,gZ as Ds,g_ as rs,g$ as lA,b9 as Eu,b8 as cA,da as ie,cg as BC,bS as $n,bb as kn,h0 as VC,h1 as ao,h2 as lo,h3 as co,h4 as Ht,Z as yn,G as We,h5 as dA,aA as ur,h6 as uA,h7 as hA,d3 as Fm,bf as Mo,h8 as bv,ca as pA,h9 as fA,ar as Vt,ha as wv,hb as $C,hc as WC,hd as mA,he as gA,hf as UC,hg as xA,hh as vA,hi as bA,hj as wA,hk as yA,hl as SA,hm as CA,hn as kA,ho as _A,hp as jA,hq as wc,hr as Pi,hs as Ei,ht as Ai,aP as hs,hu as NA,hv as TA,hw as IA,hx as yv,bH as DA,hy as KC,hz as PA,ch as Hm,hA as EA,cx as go,D as gn,hB as AA,s as xn,v as vn,w as bn,y as Rn,em as qC,hC as MA,hD as RA,hE as LA,hF as OA,B as le,ef as ai,b2 as Jp,e5 as Sv,bB as Bm,bd as ja,be as Qs,hG as YC,cd as uo,hH as zA,hI as XC,e3 as Au,e4 as GA,hJ as re,bl as ps,hK as FA,hL as Ld,hM as JC,hN as Od,d$ as HA,hO as BA,hP as Mu,eh as ZC,d1 as ar,cE as Mi,cF as Cl,hQ as VA,hR as QC,hS as Cv,cz as Ii,hT as $A,hU as WA,hV as UA,hW as ek,bA as Jt,hX as tk,hY as KA,hZ as qA,h_ as ho,h$ as YA,i0 as nk,i1 as kl,i2 as XA,i3 as Zp,i4 as JA,i5 as ZA,i6 as QA,i7 as eM,i8 as tM,i9 as nM,ia as sM,ib as iM,ic as oM,id as rM,x as Os,bi as aM,E as ls,ie as lM,bP as Bt,bQ as Vm,bX as sk,aQ as _i,I as Wt,ig as kv,ih as _v,ii as jv,z as ec,ij as _l,c6 as Rh,dU as Lh,bY as Ys,bE as Xs,bn as di,ik as cM,il as ik,im as dM,io as bs,ip as uM,e2 as $m,M as ms,N as gs,O as xs,P as vs,Q as ts,bO as Wm,iq as Qp,ir as ef,is as tf,bw as Ru,bx as Lu,by as Ns,bz as no,bW as ok,it as rk,iu as ak,iv as Ja,iw as zd,ix as lk,iy as hM,iz as pM,iA as fM,iB as Um,iC as mM,iD as gM,iE as ck,dI as zi,dJ as Gi,dL as Fi,dP as dn,iF as dk,iG as uk,iH as hk,dN as pa,cj as Km,bI as qm,iI as pk,iJ as Ou,iK as Cs,bT as fk,bL as xM,bM as vM,bZ as bM,iL as wM,b$ as yM,iM as SM,iN as mk,iO as CM,iP as kM,iQ as _M,iR as jM,iS as NM,iT as TM,iU as hr,iV as Ym,iW as Va,iX as Xm,iY as Jm,cX as zu,cZ as Gu,cc as Js,cY as Fu,e0 as gk,e8 as fa,iZ as IM,i_ as xk,i$ as vk,j0 as DM,j1 as Za,j2 as PM,at as Zm,j3 as bk,j4 as Qm,j5 as wk,cl as ma,j6 as yk,j7 as EM,c$ as AM,c_ as MM,j8 as RM,A as LM,j9 as OM,ja as zM,n as GM,jb as FM,jc as HM,jd as BM,m as VM,je as $M,jf as WM,C as UM,f as Sk,h as KM,i as qM,k as YM,S as XM,l as JM,o as ZM,jg as QM,jh as eR,ji as tR,jj as nR,jk as sR,jl as iR,jm as Ck,cD as ii,jn as oR,ci as ta,eo as nf,jo as rR,jp as aR,jq as eg,jr as kk,js as _k,jt as jk,ju as tg,jv as lR,jw as cR,jx as dR,bv as Nk,bD as qo,bu as uR,jy as hR,jz as Tk,jA as kr,bC as Nv,bK as pR,jB as fR,bU as Tv,eb as Hu,jC as Iv,cr as es,jD as mR,en as gR,jE as Ik,jF as xR,jG as vR,jH as bR,dG as wR,jI as Dk,jJ as Pk,jK as yR,jL as SR,jM as ng,jN as CR,jO as Ek,eg as kR,jP as _R,jQ as jR,jR as Dv,jS as Pv,jT as NR,ec as Ak,jU as TR,jV as sg,e6 as IR,cu as Hs,cv as Bs,jW as Mk,jX as DR,jY as PR,jZ as ER,j_ as AR,j$ as MR,ei as Gd,k0 as RR,k1 as LR,k2 as OR,k3 as Rk,k4 as zR,k5 as GR,cn as FR,k6 as HR,k7 as Lk,k8 as ig,k9 as BR,d6 as Ok,ka as VR,kb as Ev,kc as $R,kd as WR,cV as UR,cU as KR,d2 as qR,el as YR,ke as zk,kf as sf,aB as Gk,aC as Fk,aD as Hk,aE as Bk,aF as Vk,aG as $k,kg as fd,kh as Wk,ea as XR,ki as JR,aI as og,kj as Fd,kk as jl,kl as na,km as of,kn as ZR,dt as Hd,ko as QR,aL as Bu,kp as Uk,dS as Av,dR as e2,kq as cs,kr as En,ks as lr,kt as Kk,aM as t2,ku as Bd,kv as jo,c7 as n2,kw as qk,kx as Qa,ky as Rr,kz as s2,kA as Yk,kB as i2,kC as o2,kD as r2,cp as Mv,kE as a2,kF as Xk,kG as Rv,kH as Lv,dK as rg,kI as l2,cw as c2,kJ as d2,kK as u2,kL as rf,kM as h2,b1 as p2,ct as f2,kN as m2,e7 as g2,dh as x2,kO as v2,dC as b2,dD as w2,cy as y2,kP as S2,e9 as C2,dT as k2,kQ as _2,kR as j2,kS as Jk,kT as ag,kU as Zk,kV as N2,kW as T2,kX as I2,kY as D2,kZ as Ov,k_ as Qk,k$ as lg,d5 as P2,l0 as Vu,l1 as yc,l2 as E2,l3 as A2,l4 as M2,l5 as R2,l6 as L2,l7 as O2,l8 as z2,l9 as G2,la as zv,lb as F2,lc as H2,ld as B2,le as V2,cL as $2,ba as W2,lf as Gv,bG as U2,cM as K2,cO as q2,lg as Y2,lh as X2,li as Fv,lj as J2,lk as Z2,ll as Q2,lm as af,ln as e_,lo as eL,lp as tL,lq as nL,lr as sL,ls as t_,lt as iL,lu as oL,lv as rL,lw as aL,lx as lL,ly as cL,lz as tr,lA as dL,lB as uL,lC as hL,lD as pL,lE as fL,lF as mL,lG as gL,lH as Hv,lI as xL,lJ as vL,lK as bL,lL as wL,lM as yL,di as SL,lN as CL,lO as Bv,lP as kL,lQ as _L,lR as n_,dQ as jL,lS as NL,lT as TL,ew as IL,es as DL,ex as Vv,et as PL,aH as EL,lU as AL,lV as ML,lW as RL,lX as LL,lY as OL,lZ as zL,l_ as GL,ep as FL,eq as HL,er as BL}from"./globals-CYDlkaHa.js";function VL(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return m.useMemo(()=>s=>{t.forEach(i=>i(s))},t)}const $u=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ga(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function cg(e){return"nodeType"in e}function ks(e){var t,n;return e?ga(e)?e:cg(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function dg(e){const{Document:t}=ks(e);return e instanceof t}function tc(e){return ga(e)?!1:e instanceof ks(e).HTMLElement}function s_(e){return e instanceof ks(e).SVGElement}function xa(e){return e?ga(e)?e.document:cg(e)?dg(e)?e:tc(e)||s_(e)?e.ownerDocument:document:document:document}const ui=$u?m.useLayoutEffect:m.useEffect;function Wu(e){const t=m.useRef(e);return ui(()=>{t.current=e}),m.useCallback(function(){for(var n=arguments.length,s=new Array(n),i=0;i<n;i++)s[i]=arguments[i];return t.current==null?void 0:t.current(...s)},[])}function $L(){const e=m.useRef(null),t=m.useCallback((s,i)=>{e.current=setInterval(s,i)},[]),n=m.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Nl(e,t){t===void 0&&(t=[e]);const n=m.useRef(e);return ui(()=>{n.current!==e&&(n.current=e)},t),n}function nc(e,t){const n=m.useRef();return m.useMemo(()=>{const s=e(n.current);return n.current=s,s},[...t])}function Vd(e){const t=Wu(e),n=m.useRef(null),s=m.useCallback(i=>{i!==n.current&&t?.(i,n.current),n.current=i},[]);return[n,s]}function $d(e){const t=m.useRef();return m.useEffect(()=>{t.current=e},[e]),t.current}let Oh={};function sc(e,t){return m.useMemo(()=>{if(t)return t;const n=Oh[e]==null?0:Oh[e]+1;return Oh[e]=n,e+"-"+n},[e,t])}function i_(e){return function(t){for(var n=arguments.length,s=new Array(n>1?n-1:0),i=1;i<n;i++)s[i-1]=arguments[i];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 Ur=i_(1),Wd=i_(-1);function WL(e){return"clientX"in e&&"clientY"in e}function Uu(e){if(!e)return!1;const{KeyboardEvent:t}=ks(e.target);return t&&e instanceof t}function UL(e){if(!e)return!1;const{TouchEvent:t}=ks(e.target);return t&&e instanceof t}function Ud(e){if(UL(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 WL(e)?{x:e.clientX,y:e.clientY}:null}const Ri=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[Ri.Translate.toString(e),Ri.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:s}=e;return t+" "+n+"ms "+s}}}),$v="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function KL(e){return e.matches($v)?e:e.querySelector($v)}const qL={display:"none"};function YL(e){let{id:t,value:n}=e;return Ce.createElement("div",{id:t,style:qL},n)}function XL(e){let{id:t,announcement:n,ariaLiveType:s="assertive"}=e;const i={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 Ce.createElement("div",{id:t,style:i,role:"status","aria-live":s,"aria-atomic":!0},n)}function JL(){const[e,t]=m.useState("");return{announce:m.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const o_=m.createContext(null);function r_(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 ZL(){const[e]=m.useState(()=>new Set),t=m.useCallback(s=>(e.add(s),()=>e.delete(s)),[e]);return[m.useCallback(s=>{let{type:i,event:r}=s;e.forEach(a=>{var l;return(l=a[i])==null?void 0:l.call(a,r)})},[e]),t]}const QL={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
- `},eO={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 tO(e){let{announcements:t=eO,container:n,hiddenTextDescribedById:s,screenReaderInstructions:i=QL}=e;const{announce:r,announcement:a}=JL(),l=sc("DndLiveRegion"),[c,d]=m.useState(!1);if(m.useEffect(()=>{d(!0)},[]),r_(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=Ce.createElement(Ce.Fragment,null,Ce.createElement(YL,{id:s,value:i.draggable}),Ce.createElement(XL,{id:l,announcement:a}));return n?Fs.createPortal(u,n):u}var Yn;(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"})(Yn||(Yn={}));function Kd(){}function nO(e,t){return m.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function sO(){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 hi=Object.freeze({x:0,y:0});function iO(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function oO(e,t){const n=Ud(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 rO(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return n-s}function aO(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return s-n}function lO(e){let{left:t,top:n,height:s,width:i}=e;return[{x:t,y:n},{x:t+i,y:n},{x:t,y:n+s},{x:t+i,y:n+s}]}function cO(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function dO(e,t){const n=Math.max(t.top,e.top),s=Math.max(t.left,e.left),i=Math.min(t.left+t.width,e.left+e.width),r=Math.min(t.top+t.height,e.top+e.height),a=i-s,l=r-n;if(s<i&&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 a_=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:s}=e;const i=[];for(const r of s){const{id:a}=r,l=n.get(a);if(l){const c=dO(l,t);c>0&&i.push({id:a,data:{droppableContainer:r,value:c}})}}return i.sort(aO)};function uO(e,t){const{top:n,left:s,bottom:i,right:r}=t;return n<=e.y&&e.y<=i&&s<=e.x&&e.x<=r}const hO=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:s}=e;if(!s)return[];const i=[];for(const r of t){const{id:a}=r,l=n.get(a);if(l&&uO(s,l)){const d=lO(l).reduce((h,p)=>h+iO(s,p),0),u=Number((d/4).toFixed(4));i.push({id:a,data:{droppableContainer:r,value:u}})}}return i.sort(rO)};function pO(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function l_(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:hi}function fO(e){return function(n){for(var s=arguments.length,i=new Array(s>1?s-1:0),r=1;r<s;r++)i[r-1]=arguments[r];return i.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 mO=fO(1);function c_(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 gO(e,t,n){const s=c_(t);if(!s)return e;const{scaleX:i,scaleY:r,x:a,y:l}=s,c=e.left-a-(1-i)*parseFloat(n),d=e.top-l-(1-r)*parseFloat(n.slice(n.indexOf(" ")+1)),u=i?e.width/i: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 xO={ignoreTransform:!1};function va(e,t){t===void 0&&(t=xO);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=ks(e).getComputedStyle(e);d&&(n=gO(n,d,u))}const{top:s,left:i,width:r,height:a,bottom:l,right:c}=n;return{top:s,left:i,width:r,height:a,bottom:l,right:c}}function Wv(e){return va(e,{ignoreTransform:!0})}function vO(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function bO(e,t){return t===void 0&&(t=ks(e).getComputedStyle(e)),t.position==="fixed"}function wO(e,t){t===void 0&&(t=ks(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const r=t[i];return typeof r=="string"?n.test(r):!1})}function ug(e,t){const n=[];function s(i){if(t!=null&&n.length>=t||!i)return n;if(dg(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!tc(i)||s_(i)||n.includes(i))return n;const r=ks(e).getComputedStyle(i);return i!==e&&wO(i,r)&&n.push(i),bO(i,r)?n:s(i.parentNode)}return e?s(e):n}function d_(e){const[t]=ug(e,1);return t??null}function zh(e){return!$u||!e?null:ga(e)?e:cg(e)?dg(e)||e===xa(e).scrollingElement?window:tc(e)?e:null:null}function u_(e){return ga(e)?e.scrollX:e.scrollLeft}function h_(e){return ga(e)?e.scrollY:e.scrollTop}function lf(e){return{x:u_(e),y:h_(e)}}var Qn;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(Qn||(Qn={}));function p_(e){return!$u||!e?!1:e===document.scrollingElement}function f_(e){const t={x:0,y:0},n=p_(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},s={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},i=e.scrollTop<=t.y,r=e.scrollLeft<=t.x,a=e.scrollTop>=s.y,l=e.scrollLeft>=s.x;return{isTop:i,isLeft:r,isBottom:a,isRight:l,maxScroll:s,minScroll:t}}const yO={x:.2,y:.2};function SO(e,t,n,s,i){let{top:r,left:a,right:l,bottom:c}=n;s===void 0&&(s=10),i===void 0&&(i=yO);const{isTop:d,isBottom:u,isLeft:h,isRight:p}=f_(e),f={x:0,y:0},x={x:0,y:0},g={height:t.height*i.y,width:t.width*i.x};return!d&&r<=t.top+g.height?(f.y=Qn.Backward,x.y=s*Math.abs((t.top+g.height-r)/g.height)):!u&&c>=t.bottom-g.height&&(f.y=Qn.Forward,x.y=s*Math.abs((t.bottom-g.height-c)/g.height)),!p&&l>=t.right-g.width?(f.x=Qn.Forward,x.x=s*Math.abs((t.right-g.width-l)/g.width)):!h&&a<=t.left+g.width&&(f.x=Qn.Backward,x.x=s*Math.abs((t.left+g.width-a)/g.width)),{direction:f,speed:x}}function CO(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:i}=e.getBoundingClientRect();return{top:t,left:n,right:s,bottom:i,width:e.clientWidth,height:e.clientHeight}}function m_(e){return e.reduce((t,n)=>Ur(t,lf(n)),hi)}function kO(e){return e.reduce((t,n)=>t+u_(n),0)}function _O(e){return e.reduce((t,n)=>t+h_(n),0)}function g_(e,t){if(t===void 0&&(t=va),!e)return;const{top:n,left:s,bottom:i,right:r}=t(e);d_(e)&&(i<=0||r<=0||n>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const jO=[["x",["left","right"],kO],["y",["top","bottom"],_O]];class hg{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=ug(n),i=m_(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[r,a,l]of jO)for(const c of a)Object.defineProperty(this,c,{get:()=>{const d=l(s),u=i[r]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class el{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 i;(i=this.target)==null||i.addEventListener(t,n,s),this.listeners.push([t,n,s])}}function NO(e){const{EventTarget:t}=ks(e);return e instanceof t?e:xa(e)}function Gh(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 Gs;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Gs||(Gs={}));function Uv(e){e.preventDefault()}function TO(e){e.stopPropagation()}var an;(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"})(an||(an={}));const x_={start:[an.Space,an.Enter],cancel:[an.Esc],end:[an.Space,an.Enter,an.Tab]},IO=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case an.Right:return{...n,x:n.x+25};case an.Left:return{...n,x:n.x-25};case an.Down:return{...n,y:n.y+25};case an.Up:return{...n,y:n.y-25}}};class v_{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 el(xa(n)),this.windowListeners=new el(ks(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Gs.Resize,this.handleCancel),this.windowListeners.add(Gs.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Gs.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,s=t.node.current;s&&g_(s),n(hi)}handleKeyDown(t){if(Uu(t)){const{active:n,context:s,options:i}=this.props,{keyboardCodes:r=x_,coordinateGetter:a=IO,scrollBehavior:l="smooth"}=i,{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}:hi;this.referenceCoordinates||(this.referenceCoordinates=u);const h=a(t,{active:n,context:s.current,currentCoordinates:u});if(h){const p=Wd(h,u),f={x:0,y:0},{scrollableAncestors:x}=s.current;for(const g of x){const v=t.code,{isTop:w,isRight:y,isLeft:b,isBottom:_,maxScroll:j,minScroll:N}=f_(g),C=CO(g),k={x:Math.min(v===an.Right?C.right-C.width/2:C.right,Math.max(v===an.Right?C.left:C.left+C.width/2,h.x)),y:Math.min(v===an.Down?C.bottom-C.height/2:C.bottom,Math.max(v===an.Down?C.top:C.top+C.height/2,h.y))},E=v===an.Right&&!y||v===an.Left&&!b,I=v===an.Down&&!_||v===an.Up&&!w;if(E&&k.x!==h.x){const T=g.scrollLeft+p.x,A=v===an.Right&&T<=j.x||v===an.Left&&T>=N.x;if(A&&!p.y){g.scrollTo({left:T,behavior:l});return}A?f.x=g.scrollLeft-T:f.x=v===an.Right?g.scrollLeft-j.x:g.scrollLeft-N.x,f.x&&g.scrollBy({left:-f.x,behavior:l});break}else if(I&&k.y!==h.y){const T=g.scrollTop+p.y,A=v===an.Down&&T<=j.y||v===an.Up&&T>=N.y;if(A&&!p.x){g.scrollTo({top:T,behavior:l});return}A?f.y=g.scrollTop-T:f.y=v===an.Down?g.scrollTop-j.y:g.scrollTop-N.y,f.y&&g.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(t,Ur(Wd(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()}}v_.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:s=x_,onActivation:i}=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(),i?.({event:e.nativeEvent}),!0)}return!1}}];function Kv(e){return!!(e&&"distance"in e)}function qv(e){return!!(e&&"delay"in e)}class pg{constructor(t,n,s){var i;s===void 0&&(s=NO(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=xa(a),this.documentListeners=new el(this.document),this.listeners=new el(s),this.windowListeners=new el(ks(a)),this.initialCoordinates=(i=Ud(r))!=null?i:hi,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(Gs.Resize,this.handleCancel),this.windowListeners.add(Gs.DragStart,Uv),this.windowListeners.add(Gs.VisibilityChange,this.handleCancel),this.windowListeners.add(Gs.ContextMenu,Uv),this.documentListeners.add(Gs.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(qv(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Kv(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:i}=this.props;i(s,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Gs.Click,TO,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Gs.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:s,initialCoordinates:i,props:r}=this,{onMove:a,options:{activationConstraint:l}}=r;if(!i)return;const c=(n=Ud(t))!=null?n:hi,d=Wd(i,c);if(!s&&l){if(Kv(l)){if(l.tolerance!=null&&Gh(d,l.tolerance))return this.handleCancel();if(Gh(d,l.distance))return this.handleStart()}if(qv(l)&&Gh(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===an.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const DO={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class fg extends pg{constructor(t){const{event:n}=t,s=xa(n.target);super(t,DO,s)}}fg.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 PO={move:{name:"mousemove"},end:{name:"mouseup"}};var cf;(function(e){e[e.RightClick=2]="RightClick"})(cf||(cf={}));class EO extends pg{constructor(t){super(t,PO,xa(t.event.target))}}EO.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return n.button===cf.RightClick?!1:(s?.({event:n}),!0)}}];const Fh={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class AO extends pg{constructor(t){super(t,Fh)}static setup(){return window.addEventListener(Fh.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Fh.move.name,t)};function t(){}}}AO.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;const{touches:i}=n;return i.length>1?!1:(s?.({event:n}),!0)}}];var tl;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(tl||(tl={}));var qd;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(qd||(qd={}));function MO(e){let{acceleration:t,activator:n=tl.Pointer,canScroll:s,draggingRect:i,enabled:r,interval:a=5,order:l=qd.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:p}=e;const f=LO({delta:h,disabled:!r}),[x,g]=$L(),v=m.useRef({x:0,y:0}),w=m.useRef({x:0,y:0}),y=m.useMemo(()=>{switch(n){case tl.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case tl.DraggableRect:return i}},[n,i,c]),b=m.useRef(null),_=m.useCallback(()=>{const N=b.current;if(!N)return;const C=v.current.x*w.current.x,k=v.current.y*w.current.y;N.scrollBy(C,k)},[]),j=m.useMemo(()=>l===qd.TreeOrder?[...d].reverse():d,[l,d]);m.useEffect(()=>{if(!r||!d.length||!y){g();return}for(const N of j){if(s?.(N)===!1)continue;const C=d.indexOf(N),k=u[C];if(!k)continue;const{direction:E,speed:I}=SO(N,k,y,t,p);for(const T of["x","y"])f[T][E[T]]||(I[T]=0,E[T]=0);if(I.x>0||I.y>0){g(),b.current=N,x(_,a),v.current=I,w.current=E;return}}v.current={x:0,y:0},w.current={x:0,y:0},g()},[t,_,s,g,r,a,JSON.stringify(y),JSON.stringify(f),x,d,j,u,JSON.stringify(p)])}const RO={x:{[Qn.Backward]:!1,[Qn.Forward]:!1},y:{[Qn.Backward]:!1,[Qn.Forward]:!1}};function LO(e){let{delta:t,disabled:n}=e;const s=$d(t);return nc(i=>{if(n||!s||!i)return RO;const r={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[Qn.Backward]:i.x[Qn.Backward]||r.x===-1,[Qn.Forward]:i.x[Qn.Forward]||r.x===1},y:{[Qn.Backward]:i.y[Qn.Backward]||r.y===-1,[Qn.Forward]:i.y[Qn.Forward]||r.y===1}}},[n,t,s])}function OO(e,t){const n=t!=null?e.get(t):void 0,s=n?n.node.current:null;return nc(i=>{var r;return t==null?null:(r=s??i)!=null?r:null},[s,t])}function zO(e,t){return m.useMemo(()=>e.reduce((n,s)=>{const{sensor:i}=s,r=i.activators.map(a=>({eventName:a.eventName,handler:t(a.handler,s)}));return[...n,...r]},[]),[e,t])}var Tl;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Tl||(Tl={}));var df;(function(e){e.Optimized="optimized"})(df||(df={}));const Yv=new Map;function GO(e,t){let{dragging:n,dependencies:s,config:i}=t;const[r,a]=m.useState(null),{frequency:l,measure:c,strategy:d}=i,u=m.useRef(e),h=v(),p=Nl(h),f=m.useCallback(function(w){w===void 0&&(w=[]),!p.current&&a(y=>y===null?w:y.concat(w.filter(b=>!y.includes(b))))},[p]),x=m.useRef(null),g=nc(w=>{if(h&&!n)return Yv;if(!w||w===Yv||u.current!==e||r!=null){const y=new Map;for(let b of e){if(!b)continue;if(r&&r.length>0&&!r.includes(b.id)&&b.rect.current){y.set(b.id,b.rect.current);continue}const _=b.node.current,j=_?new hg(c(_),_):null;b.rect.current=j,j&&y.set(b.id,j)}return y}return w},[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"||x.current!==null||(x.current=setTimeout(()=>{f(),x.current=null},l))},[l,h,f,...s]),{droppableRects:g,measureDroppableContainers:f,measuringScheduled:r!=null};function v(){switch(d){case Tl.Always:return!1;case Tl.BeforeDragging:return n;default:return!n}}}function mg(e,t){return nc(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function FO(e,t){return mg(e,t)}function HO(e){let{callback:t,disabled:n}=e;const s=Wu(t),i=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(()=>()=>i?.disconnect(),[i]),i}function Ku(e){let{callback:t,disabled:n}=e;const s=Wu(t),i=m.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:r}=window;return new r(s)},[n]);return m.useEffect(()=>()=>i?.disconnect(),[i]),i}function BO(e){return new hg(va(e),e)}function Xv(e,t,n){t===void 0&&(t=BO);const[s,i]=m.useState(null);function r(){i(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=HO({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=Ku({callback:r});return ui(()=>{r(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),s}function VO(e){const t=mg(e);return l_(e,t)}const Jv=[];function $O(e){const t=m.useRef(e),n=nc(s=>e?s&&s!==Jv&&e&&t.current&&e.parentNode===t.current.parentNode?s:ug(e):Jv,[e]);return m.useEffect(()=>{t.current=e},[e]),n}function WO(e){const[t,n]=m.useState(null),s=m.useRef(e),i=m.useCallback(r=>{const a=zh(r.target);a&&n(l=>l?(l.set(a,lf(a)),new Map(l)):null)},[]);return m.useEffect(()=>{const r=s.current;if(e!==r){a(r);const l=e.map(c=>{const d=zh(c);return d?(d.addEventListener("scroll",i,{passive:!0}),[d,lf(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=zh(c);d?.removeEventListener("scroll",i)})}},[i,e]),m.useMemo(()=>e.length?t?Array.from(t.values()).reduce((r,a)=>Ur(r,a),hi):m_(e):hi,[e,t])}function Zv(e,t){t===void 0&&(t=[]);const n=m.useRef(null);return m.useEffect(()=>{n.current=null},t),m.useEffect(()=>{const s=e!==hi;s&&!n.current&&(n.current=e),!s&&n.current&&(n.current=null)},[e]),n.current?Wd(e,n.current):hi}function UO(e){m.useEffect(()=>{if(!$u)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 KO(e,t){return m.useMemo(()=>e.reduce((n,s)=>{let{eventName:i,handler:r}=s;return n[i]=a=>{r(a,t)},n},{}),[e,t])}function b_(e){return m.useMemo(()=>e?vO(e):null,[e])}const Qv=[];function qO(e,t){t===void 0&&(t=va);const[n]=e,s=b_(n?ks(n):null),[i,r]=m.useState(Qv);function a(){r(()=>e.length?e.map(c=>p_(c)?s:new hg(t(c),c)):Qv)}const l=Ku({callback:a});return ui(()=>{l?.disconnect(),a(),e.forEach(c=>l?.observe(c))},[e]),i}function w_(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return tc(t)?t:e}function YO(e){let{measure:t}=e;const[n,s]=m.useState(null),i=m.useCallback(d=>{for(const{target:u}of d)if(tc(u)){s(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),r=Ku({callback:i}),a=m.useCallback(d=>{const u=w_(d);r?.disconnect(),u&&r?.observe(u),s(u?t(u):null)},[t,r]),[l,c]=Vd(a);return m.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const XO=[{sensor:fg,options:{}},{sensor:v_,options:{}}],JO={current:{}},md={draggable:{measure:Wv},droppable:{measure:Wv,strategy:Tl.WhileDragging,frequency:df.Optimized},dragOverlay:{measure:va}};class nl 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 ZO={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new nl,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Kd},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:md,measureDroppableContainers:Kd,windowRect:null,measuringScheduled:!1},y_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Kd,draggableNodes:new Map,over:null,measureDroppableContainers:Kd},ic=m.createContext(y_),S_=m.createContext(ZO);function QO(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new nl}}}function e5(e,t){switch(t.type){case Yn.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Yn.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 Yn.DragEnd:case Yn.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Yn.RegisterDroppable:{const{element:n}=t,{id:s}=n,i=new nl(e.droppable.containers);return i.set(s,n),{...e,droppable:{...e.droppable,containers:i}}}case Yn.SetDroppableDisabled:{const{id:n,key:s,disabled:i}=t,r=e.droppable.containers.get(n);if(!r||s!==r.key)return e;const a=new nl(e.droppable.containers);return a.set(n,{...r,disabled:i}),{...e,droppable:{...e.droppable,containers:a}}}case Yn.UnregisterDroppable:{const{id:n,key:s}=t,i=e.droppable.containers.get(n);if(!i||s!==i.key)return e;const r=new nl(e.droppable.containers);return r.delete(n),{...e,droppable:{...e.droppable,containers:r}}}default:return e}}function t5(e){let{disabled:t}=e;const{active:n,activatorEvent:s,draggableNodes:i}=m.useContext(ic),r=$d(s),a=$d(n?.id);return m.useEffect(()=>{if(!t&&!s&&r&&a!=null){if(!Uu(r)||document.activeElement===r.target)return;const l=i.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=KL(u);if(h){h.focus();break}}})}},[s,t,i,a,r]),null}function C_(e,t){let{transform:n,...s}=t;return e!=null&&e.length?e.reduce((i,r)=>r({transform:i,...s}),n):n}function n5(e){return m.useMemo(()=>({draggable:{...md.draggable,...e?.draggable},droppable:{...md.droppable,...e?.droppable},dragOverlay:{...md.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function s5(e){let{activeNode:t,measure:n,initialRect:s,config:i=!0}=e;const r=m.useRef(!1),{x:a,y:l}=typeof i=="boolean"?{x:i,y:i}:i;ui(()=>{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=l_(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=d_(d);p&&p.scrollBy({top:h.y,left:h.x})}},[t,a,l,s,n])}const qu=m.createContext({...hi,scaleX:1,scaleY:1});var Co;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Co||(Co={}));const i5=m.memo(function(t){var n,s,i,r;let{id:a,accessibility:l,autoScroll:c=!0,children:d,sensors:u=XO,collisionDetection:h=a_,measuring:p,modifiers:f,...x}=t;const g=m.useReducer(e5,void 0,QO),[v,w]=g,[y,b]=ZL(),[_,j]=m.useState(Co.Uninitialized),N=_===Co.Initialized,{draggable:{active:C,nodes:k,translate:E},droppable:{containers:I}}=v,T=C!=null?k.get(C):null,A=m.useRef({initial:null,translated:null}),D=m.useMemo(()=>{var $e;return C!=null?{id:C,data:($e=T?.data)!=null?$e:JO,rect:A}:null},[C,T]),W=m.useRef(null),[J,O]=m.useState(null),[B,L]=m.useState(null),se=Nl(x,Object.values(x)),Q=sc("DndDescribedBy",a),V=m.useMemo(()=>I.getEnabled(),[I]),H=n5(p),{droppableRects:ne,measureDroppableContainers:he,measuringScheduled:pe}=GO(V,{dragging:N,dependencies:[E.x,E.y],config:H.droppable}),ke=OO(k,C),Me=m.useMemo(()=>B?Ud(B):null,[B]),fe=ge(),F=FO(ke,H.draggable.measure);s5({activeNode:C!=null?k.get(C):null,config:fe.layoutShiftCompensation,initialRect:F,measure:H.draggable.measure});const U=Xv(ke,H.draggable.measure,F),de=Xv(ke?ke.parentElement:null),Y=m.useRef({activatorEvent:null,active:null,activeNode:ke,collisionRect:null,collisions:null,droppableRects:ne,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:I,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),X=I.getNodeFor((n=Y.current.over)==null?void 0:n.id),z=YO({measure:H.dragOverlay.measure}),ue=(s=z.nodeRef.current)!=null?s:ke,_e=N?(i=z.rect)!=null?i:U:null,Ee=!!(z.nodeRef.current&&z.rect),Be=VO(Ee?null:U),De=b_(ue?ks(ue):null),Ue=$O(N?X??ke:null),St=qO(Ue),Ut=C_(f,{transform:{x:E.x-Be.x,y:E.y-Be.y,scaleX:1,scaleY:1},activatorEvent:B,active:D,activeNodeRect:U,containerNodeRect:de,draggingNodeRect:_e,over:Y.current.over,overlayNodeRect:z.rect,scrollableAncestors:Ue,scrollableAncestorRects:St,windowRect:De}),tn=Me?Ur(Me,E):null,Ne=WO(Ue),Z=Zv(Ne),je=Zv(Ne,[U]),tt=Ur(Ut,Z),Et=_e?mO(_e,Ut):null,zt=D&&Et?h({active:D,collisionRect:Et,droppableRects:ne,droppableContainers:V,pointerCoordinates:tn}):null,we=cO(zt,"id"),[ft,mt]=m.useState(null),ze=Ee?Ut:Ur(Ut,je),Ct=pO(ze,(r=ft?.rect)!=null?r:null,U),K=m.useRef(null),be=m.useCallback(($e,it)=>{let{sensor:xt,options:Mt}=it;if(W.current==null)return;const Gt=k.get(W.current);if(!Gt)return;const sn=$e.nativeEvent,wn=new xt({active:W.current,activeNode:Gt,event:sn,options:Mt,context:Y,onAbort(rn){if(!k.get(rn))return;const{onDragAbort:Bn}=se.current,P={id:rn};Bn?.(P),y({type:"onDragAbort",event:P})},onPending(rn,cn,Bn,P){if(!k.get(rn))return;const{onDragPending:R}=se.current,S={id:rn,constraint:cn,initialCoordinates:Bn,offset:P};R?.(S),y({type:"onDragPending",event:S})},onStart(rn){const cn=W.current;if(cn==null)return;const Bn=k.get(cn);if(!Bn)return;const{onDragStart:P}=se.current,M={activatorEvent:sn,active:{id:cn,data:Bn.data,rect:A}};Fs.unstable_batchedUpdates(()=>{P?.(M),j(Co.Initializing),w({type:Yn.DragStart,initialCoordinates:rn,active:cn}),y({type:"onDragStart",event:M}),O(K.current),L(sn)})},onMove(rn){w({type:Yn.DragMove,coordinates:rn})},onEnd:On(Yn.DragEnd),onCancel:On(Yn.DragCancel)});K.current=wn;function On(rn){return async function(){const{active:Bn,collisions:P,over:M,scrollAdjustedTranslate:R}=Y.current;let S=null;if(Bn&&R){const{cancelDrop:G}=se.current;S={activatorEvent:sn,active:Bn,collisions:P,delta:R,over:M},rn===Yn.DragEnd&&typeof G=="function"&&await Promise.resolve(G(S))&&(rn=Yn.DragCancel)}W.current=null,Fs.unstable_batchedUpdates(()=>{w({type:rn}),j(Co.Uninitialized),mt(null),O(null),L(null),K.current=null;const G=rn===Yn.DragEnd?"onDragEnd":"onDragCancel";if(S){const ae=se.current[G];ae?.(S),y({type:G,event:S})}})}}},[k]),Re=m.useCallback(($e,it)=>(xt,Mt)=>{const Gt=xt.nativeEvent,sn=k.get(Mt);if(W.current!==null||!sn||Gt.dndKit||Gt.defaultPrevented)return;const wn={active:sn};$e(xt,it.options,wn)===!0&&(Gt.dndKit={capturedBy:it.sensor},W.current=Mt,be(xt,it))},[k,be]),Ve=zO(u,Re);UO(u),ui(()=>{U&&_===Co.Initializing&&j(Co.Initialized)},[U,_]),m.useEffect(()=>{const{onDragMove:$e}=se.current,{active:it,activatorEvent:xt,collisions:Mt,over:Gt}=Y.current;if(!it||!xt)return;const sn={active:it,activatorEvent:xt,collisions:Mt,delta:{x:tt.x,y:tt.y},over:Gt};Fs.unstable_batchedUpdates(()=>{$e?.(sn),y({type:"onDragMove",event:sn})})},[tt.x,tt.y]),m.useEffect(()=>{const{active:$e,activatorEvent:it,collisions:xt,droppableContainers:Mt,scrollAdjustedTranslate:Gt}=Y.current;if(!$e||W.current==null||!it||!Gt)return;const{onDragOver:sn}=se.current,wn=Mt.get(we),On=wn&&wn.rect.current?{id:wn.id,rect:wn.rect.current,data:wn.data,disabled:wn.disabled}:null,rn={active:$e,activatorEvent:it,collisions:xt,delta:{x:Gt.x,y:Gt.y},over:On};Fs.unstable_batchedUpdates(()=>{mt(On),sn?.(rn),y({type:"onDragOver",event:rn})})},[we]),ui(()=>{Y.current={activatorEvent:B,active:D,activeNode:ke,collisionRect:Et,collisions:zt,droppableRects:ne,draggableNodes:k,draggingNode:ue,draggingNodeRect:_e,droppableContainers:I,over:ft,scrollableAncestors:Ue,scrollAdjustedTranslate:tt},A.current={initial:_e,translated:Et}},[D,ke,zt,Et,k,ue,_e,ne,I,ft,Ue,tt]),MO({...fe,delta:E,draggingRect:Et,pointerCoordinates:tn,scrollableAncestors:Ue,scrollableAncestorRects:St});const Ke=m.useMemo(()=>({active:D,activeNode:ke,activeNodeRect:U,activatorEvent:B,collisions:zt,containerNodeRect:de,dragOverlay:z,draggableNodes:k,droppableContainers:I,droppableRects:ne,over:ft,measureDroppableContainers:he,scrollableAncestors:Ue,scrollableAncestorRects:St,measuringConfiguration:H,measuringScheduled:pe,windowRect:De}),[D,ke,U,B,zt,de,z,k,I,ne,ft,he,Ue,St,H,pe,De]),nt=m.useMemo(()=>({activatorEvent:B,activators:Ve,active:D,activeNodeRect:U,ariaDescribedById:{draggable:Q},dispatch:w,draggableNodes:k,over:ft,measureDroppableContainers:he}),[B,Ve,D,U,w,Q,k,ft,he]);return Ce.createElement(o_.Provider,{value:b},Ce.createElement(ic.Provider,{value:nt},Ce.createElement(S_.Provider,{value:Ke},Ce.createElement(qu.Provider,{value:Ct},d)),Ce.createElement(t5,{disabled:l?.restoreFocus===!1})),Ce.createElement(tO,{...l,hiddenTextDescribedById:Q}));function ge(){const $e=J?.autoScrollEnabled===!1,it=typeof c=="object"?c.enabled===!1:c===!1,xt=N&&!$e&&!it;return typeof c=="object"?{...c,enabled:xt}:{enabled:xt}}}),o5=m.createContext(null),e0="button",r5="Draggable";function gg(e){let{id:t,data:n,disabled:s=!1,attributes:i}=e;const r=sc(r5),{activators:a,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:p}=m.useContext(ic),{role:f=e0,roleDescription:x="draggable",tabIndex:g=0}=i??{},v=c?.id===t,w=m.useContext(v?qu:o5),[y,b]=Vd(),[_,j]=Vd(),N=KO(a,t),C=Nl(n);ui(()=>(h.set(t,{id:t,key:r,node:y,activatorNode:_,data:C}),()=>{const E=h.get(t);E&&E.key===r&&h.delete(t)}),[h,t]);const k=m.useMemo(()=>({role:f,tabIndex:g,"aria-disabled":s,"aria-pressed":v&&f===e0?!0:void 0,"aria-roledescription":x,"aria-describedby":u.draggable}),[s,f,g,v,x,u.draggable]);return{active:c,activatorEvent:l,activeNodeRect:d,attributes:k,isDragging:v,listeners:s?void 0:N,node:y,over:p,setNodeRef:b,setActivatorNodeRef:j,transform:w}}function oc(){return m.useContext(S_)}const a5="Droppable",l5={timeout:25};function rc(e){let{data:t,disabled:n=!1,id:s,resizeObserverConfig:i}=e;const r=sc(a5),{active:a,dispatch:l,over:c,measureDroppableContainers:d}=m.useContext(ic),u=m.useRef({disabled:n}),h=m.useRef(!1),p=m.useRef(null),f=m.useRef(null),{disabled:x,updateMeasurementsFor:g,timeout:v}={...l5,...i},w=Nl(g??s),y=m.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(w.current)?w.current:[w.current]),f.current=null},v)},[v]),b=Ku({callback:y,disabled:x||!a}),_=m.useCallback((k,E)=>{b&&(E&&(b.unobserve(E),h.current=!1),k&&b.observe(k))},[b]),[j,N]=Vd(_),C=Nl(t);return m.useEffect(()=>{!b||!j.current||(b.disconnect(),h.current=!1,b.observe(j.current))},[j,b]),m.useEffect(()=>(l({type:Yn.RegisterDroppable,element:{id:s,key:r,disabled:n,node:j,rect:p,data:C}}),()=>l({type:Yn.UnregisterDroppable,key:r,id:s})),[s]),m.useEffect(()=>{n!==u.current.disabled&&(l({type:Yn.SetDroppableDisabled,id:s,key:r,disabled:n}),u.current.disabled=n)},[s,r,n,l]),{active:a,rect:p,isOver:c?.id===s,node:j,over:c,setNodeRef:N}}function c5(e){let{animation:t,children:n}=e;const[s,i]=m.useState(null),[r,a]=m.useState(null),l=$d(n);return!n&&!s&&l&&i(l),ui(()=>{if(!r)return;const c=s?.key,d=s?.props.id;if(c==null||d==null){i(null);return}Promise.resolve(t(d,r)).then(()=>{i(null)})},[t,s,r]),Ce.createElement(Ce.Fragment,null,n,s?m.cloneElement(s,{ref:a}):null)}const d5={x:0,y:0,scaleX:1,scaleY:1};function u5(e){let{children:t}=e;return Ce.createElement(ic.Provider,{value:y_},Ce.createElement(qu.Provider,{value:d5},t))}const h5={position:"fixed",touchAction:"none"},p5=e=>Uu(e)?"transform 250ms ease":void 0,f5=m.forwardRef((e,t)=>{let{as:n,activatorEvent:s,adjustScale:i,children:r,className:a,rect:l,style:c,transform:d,transition:u=p5}=e;if(!l)return null;const h=i?d:{...d,scaleX:1,scaleY:1},p={...h5,width:l.width,height:l.height,top:l.top,left:l.left,transform:Ri.Transform.toString(h),transformOrigin:i&&s?oO(s,l):void 0,transition:typeof u=="function"?u(s):u,...c};return Ce.createElement(n,{className:a,style:p,ref:t},r)}),m5=e=>t=>{let{active:n,dragOverlay:s}=t;const i={},{styles:r,className:a}=e;if(r!=null&&r.active)for(const[l,c]of Object.entries(r.active))c!==void 0&&(i[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(i))n.node.style.setProperty(c,d);a!=null&&a.active&&n.node.classList.remove(a.active)}},g5=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Ri.Transform.toString(t)},{transform:Ri.Transform.toString(n)}]},x5={duration:250,easing:"ease",keyframes:g5,sideEffects:m5({styles:{active:{opacity:"0"}}})};function v5(e){let{config:t,draggableNodes:n,droppableContainers:s,measuringConfiguration:i}=e;return Wu((r,a)=>{if(t===null)return;const l=n.get(r);if(!l)return;const c=l.node.current;if(!c)return;const d=w_(a);if(!d)return;const{transform:u}=ks(a).getComputedStyle(a),h=c_(u);if(!h)return;const p=typeof t=="function"?t:b5(t);return g_(c,i.draggable.measure),p({active:{id:r,data:l.data,node:c,rect:i.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:a,rect:i.dragOverlay.measure(d)},droppableContainers:s,measuringConfiguration:i,transform:h})})}function b5(e){const{duration:t,easing:n,sideEffects:s,keyframes:i}={...x5,...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=i({...d,active:a,dragOverlay:l,transform:{initial:c,final:p}}),[x]=f,g=f[f.length-1];if(JSON.stringify(x)===JSON.stringify(g))return;const v=s?.({active:a,dragOverlay:l,...d}),w=l.node.animate(f,{duration:t,easing:n,fill:"forwards"});return new Promise(y=>{w.onfinish=()=>{v?.(),y()}})}}let t0=0;function w5(e){return m.useMemo(()=>{if(e!=null)return t0++,t0},[e])}const y5=Ce.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:s,style:i,transition:r,modifiers:a,wrapperElement:l="div",className:c,zIndex:d=999}=e;const{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggableNodes:x,droppableContainers:g,dragOverlay:v,over:w,measuringConfiguration:y,scrollableAncestors:b,scrollableAncestorRects:_,windowRect:j}=oc(),N=m.useContext(qu),C=w5(h?.id),k=C_(a,{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggingNodeRect:v.rect,over:w,overlayNodeRect:v.rect,scrollableAncestors:b,scrollableAncestorRects:_,transform:N,windowRect:j}),E=mg(p),I=v5({config:s,draggableNodes:x,droppableContainers:g,measuringConfiguration:y}),T=E?v.setRef:void 0;return Ce.createElement(u5,null,Ce.createElement(c5,{animation:I},h&&C?Ce.createElement(f5,{key:C,id:h.id,ref:T,as:l,activatorEvent:u,adjustScale:t,className:c,transition:r,rect:E,style:{zIndex:d,...i},transform:k},n):null))}),xg=m.createContext({});function vg(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const S5=typeof window<"u",Yd=S5?m.useLayoutEffect:m.useEffect,Yu=m.createContext(null);function bg(e,t){e.indexOf(t)===-1&&e.push(t)}function Xd(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const Li=(e,t,n)=>n>t?t:n<e?e:n;let Xu=()=>{};const No={},k_=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),__=e=>typeof e=="object"&&e!==null,j_=e=>/^0[^.\s]+$/u.test(e);function N_(e){let t;return()=>(t===void 0&&(t=e()),t)}const Ks=e=>e,ac=(...e)=>e.reduce((t,n)=>s=>n(t(s))),Il=(e,t,n)=>{const s=t-e;return s?(n-e)/s:1};class wg{constructor(){this.subscriptions=[]}add(t){return bg(this.subscriptions,t),()=>Xd(this.subscriptions,t)}notify(t,n,s){const i=this.subscriptions.length;if(i)if(i===1)this.subscriptions[0](t,n,s);else for(let r=0;r<i;r++){const a=this.subscriptions[r];a&&a(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Ms=e=>e*1e3,Vs=e=>e/1e3,T_=(e,t)=>t?e*(1e3/t):0,I_=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,C5=1e-7,k5=12;function _5(e,t,n,s,i){let r,a,l=0;do a=t+(n-t)/2,r=I_(a,s,i)-e,r>0?n=a:t=a;while(Math.abs(r)>C5&&++l<k5);return a}function lc(e,t,n,s){if(e===t&&n===s)return Ks;const i=r=>_5(r,0,1,e,n);return r=>r===0||r===1?r:I_(i(r),t,s)}const D_=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,P_=e=>t=>1-e(1-t),E_=lc(.33,1.53,.69,.99),yg=P_(E_),A_=D_(yg),M_=e=>e>=1?1:(e*=2)<1?.5*yg(e):.5*(2-Math.pow(2,-10*(e-1))),Sg=e=>1-Math.sin(Math.acos(e)),R_=P_(Sg),L_=D_(Sg),j5=lc(.42,0,1,1),N5=lc(0,0,.58,1),O_=lc(.42,0,.58,1),T5=e=>Array.isArray(e)&&typeof e[0]!="number",z_=e=>Array.isArray(e)&&typeof e[0]=="number",I5={linear:Ks,easeIn:j5,easeInOut:O_,easeOut:N5,circIn:Sg,circInOut:L_,circOut:R_,backIn:yg,backInOut:A_,backOut:E_,anticipate:M_},D5=e=>typeof e=="string",n0=e=>{if(z_(e)){Xu(e.length===4);const[t,n,s,i]=e;return lc(t,n,s,i)}else if(D5(e))return I5[e];return e},Sc=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function P5(e){let t=new Set,n=new Set,s=!1,i=!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){i=!0;return}s=!0;const u=t;t=n,n=u,t.forEach(l),t.clear(),s=!1,i&&(i=!1,c.process(d))}};return c}const E5=40;function G_(e,t){let n=!1,s=!0;const i={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,a=Sc.reduce((b,_)=>(b[_]=P5(r),b),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:p,render:f,postRender:x}=a,g=()=>{const b=No.useManualTiming,_=b?i.timestamp:performance.now();n=!1,b||(i.delta=s?1e3/60:Math.max(Math.min(_-i.timestamp,E5),1)),i.timestamp=_,i.isProcessing=!0,l.process(i),c.process(i),d.process(i),u.process(i),h.process(i),p.process(i),f.process(i),x.process(i),i.isProcessing=!1,n&&t&&(s=!1,e(g))},v=()=>{n=!0,s=!0,i.isProcessing||e(g)};return{schedule:Sc.reduce((b,_)=>{const j=a[_];return b[_]=(N,C=!1,k=!1)=>(n||v(),j.schedule(N,C,k)),b},{}),cancel:b=>{for(let _=0;_<Sc.length;_++)a[Sc[_]].cancel(b)},state:i,steps:a}}const{schedule:Cn,cancel:To,state:os,steps:Hh}=G_(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ks,!0);let gd;function A5(){gd=void 0}const ws={now:()=>(gd===void 0&&ws.set(os.isProcessing||No.useManualTiming?os.timestamp:performance.now()),gd),set:e=>{gd=e,queueMicrotask(A5)}},F_=e=>t=>typeof t=="string"&&t.startsWith(e),H_=F_("--"),M5=F_("var(--"),Cg=e=>M5(e)?R5.test(e.split("/*")[0].trim()):!1,R5=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function s0(e){return typeof e!="string"?!1:e.split("/*")[0].includes("var(--")}const ba={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Dl={...ba,transform:e=>Li(0,1,e)},Cc={...ba,default:1},sl=e=>Math.round(e*1e5)/1e5,kg=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function L5(e){return e==null}const O5=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,_g=(e,t)=>n=>!!(typeof n=="string"&&O5.test(n)&&n.startsWith(e)||t&&!L5(n)&&Object.prototype.hasOwnProperty.call(n,t)),B_=(e,t,n)=>s=>{if(typeof s!="string")return s;const[i,r,a,l]=s.match(kg);return{[e]:parseFloat(i),[t]:parseFloat(r),[n]:parseFloat(a),alpha:l!==void 0?parseFloat(l):1}},z5=e=>Li(0,255,e),Bh={...ba,transform:e=>Math.round(z5(e))},nr={test:_g("rgb","red"),parse:B_("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+Bh.transform(e)+", "+Bh.transform(t)+", "+Bh.transform(n)+", "+sl(Dl.transform(s))+")"};function G5(e){let t="",n="",s="",i="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,s+=s,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:i?parseInt(i,16)/255:1}}const uf={test:_g("#"),parse:G5,transform:nr.transform},cc=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Ji=cc("deg"),Di=cc("%"),gt=cc("px"),F5=cc("vh"),H5=cc("vw"),i0={...Di,parse:e=>Di.parse(e)/100,transform:e=>Di.transform(e*100)},Gr={test:_g("hsl","hue"),parse:B_("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Di.transform(sl(t))+", "+Di.transform(sl(n))+", "+sl(Dl.transform(s))+")"},Vn={test:e=>nr.test(e)||uf.test(e)||Gr.test(e),parse:e=>nr.test(e)?nr.parse(e):Gr.test(e)?Gr.parse(e):uf.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?nr.transform(e):Gr.transform(e),getAnimatableNone:e=>{const t=Vn.parse(e);return t.alpha=0,Vn.transform(t)}},B5=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function V5(e){return isNaN(e)&&typeof e=="string"&&(e.match(kg)?.length||0)+(e.match(B5)?.length||0)>0}const V_="number",$_="color",$5="var",W5="var(",o0="${}",U5=/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 sa(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},i=[];let r=0;const l=t.replace(U5,c=>(Vn.test(c)?(s.color.push(r),i.push($_),n.push(Vn.parse(c))):c.startsWith(W5)?(s.var.push(r),i.push($5),n.push(c)):(s.number.push(r),i.push(V_),n.push(parseFloat(c))),++r,o0)).split(o0);return{values:n,split:l,indexes:s,types:i}}function K5(e){return sa(e).values}function W_({split:e,types:t}){const n=e.length;return s=>{let i="";for(let r=0;r<n;r++)if(i+=e[r],s[r]!==void 0){const a=t[r];a===V_?i+=sl(s[r]):a===$_?i+=Vn.transform(s[r]):i+=s[r]}return i}}function q5(e){return W_(sa(e))}const Y5=e=>typeof e=="number"?0:Vn.test(e)?Vn.getAnimatableNone(e):e,X5=(e,t)=>typeof e=="number"?t?.trim().endsWith("/")?e:0:Y5(e);function J5(e){const t=sa(e);return W_(t)(t.values.map((s,i)=>X5(s,t.split[i])))}const li={test:V5,parse:K5,createTransformer:q5,getAnimatableNone:J5};function Vh(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 Z5({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let i=0,r=0,a=0;if(!t)i=r=a=n;else{const l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;i=Vh(c,l,e+1/3),r=Vh(c,l,e),a=Vh(c,l,e-1/3)}return{red:Math.round(i*255),green:Math.round(r*255),blue:Math.round(a*255),alpha:s}}function Jd(e,t){return n=>n>0?t:e}const Sn=(e,t,n)=>e+(t-e)*n,$h=(e,t,n)=>{const s=e*e,i=n*(t*t-s)+s;return i<0?0:Math.sqrt(i)},Q5=[uf,nr,Gr],ez=e=>Q5.find(t=>t.test(e));function r0(e){const t=ez(e);if(!t)return!1;let n=t.parse(e);return t===Gr&&(n=Z5(n)),n}const a0=(e,t)=>{const n=r0(e),s=r0(t);if(!n||!s)return Jd(e,t);const i={...n};return r=>(i.red=$h(n.red,s.red,r),i.green=$h(n.green,s.green,r),i.blue=$h(n.blue,s.blue,r),i.alpha=Sn(n.alpha,s.alpha,r),nr.transform(i))},hf=new Set(["none","hidden"]);function tz(e,t){return hf.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function nz(e,t){return n=>Sn(e,t,n)}function jg(e){return typeof e=="number"?nz:typeof e=="string"?Cg(e)?Jd:Vn.test(e)?a0:oz:Array.isArray(e)?U_:typeof e=="object"?Vn.test(e)?a0:sz:Jd}function U_(e,t){const n=[...e],s=n.length,i=e.map((r,a)=>jg(r)(r,t[a]));return r=>{for(let a=0;a<s;a++)n[a]=i[a](r);return n}}function sz(e,t){const n={...e,...t},s={};for(const i in n)e[i]!==void 0&&t[i]!==void 0&&(s[i]=jg(e[i])(e[i],t[i]));return i=>{for(const r in s)n[r]=s[r](i);return n}}function iz(e,t){const n=[],s={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){const r=t.types[i],a=e.indexes[r][s[r]],l=e.values[a]??0;n[i]=l,s[r]++}return n}const oz=(e,t)=>{const n=li.createTransformer(t),s=sa(e),i=sa(t);return s.indexes.var.length===i.indexes.var.length&&s.indexes.color.length===i.indexes.color.length&&s.indexes.number.length>=i.indexes.number.length?hf.has(e)&&!i.values.length||hf.has(t)&&!s.values.length?tz(e,t):ac(U_(iz(s,i),i.values),n):Jd(e,t)};function K_(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?Sn(e,t,n):jg(e)(e,t)}const rz=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>Cn.update(t,n),stop:()=>To(t),now:()=>os.isProcessing?os.timestamp:ws.now()}},q_=(e,t,n=10)=>{let s="";const i=Math.max(Math.round(t/n),2);for(let r=0;r<i;r++)s+=Math.round(e(r/(i-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},Zd=2e4;function Ng(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<Zd;)t+=n,s=e.next(t);return t>=Zd?1/0:t}function az(e,t=100,n){const s=n({...e,keyframes:[0,t]}),i=Math.min(Ng(s),Zd);return{type:"keyframes",ease:r=>s.next(i*r).value/t,duration:Vs(i)}}const zn={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 pf(e,t){return e*Math.sqrt(1-t*t)}const lz=12;function cz(e,t,n){let s=n;for(let i=1;i<lz;i++)s=s-e(s)/t(s);return s}const Wh=.001;function dz({duration:e=zn.duration,bounce:t=zn.bounce,velocity:n=zn.velocity,mass:s=zn.mass}){let i,r,a=1-t;a=Li(zn.minDamping,zn.maxDamping,a),e=Li(zn.minDuration,zn.maxDuration,Vs(e)),a<1?(i=d=>{const u=d*a,h=u*e,p=u-n,f=pf(d,a),x=Math.exp(-h);return Wh-p/f*x},r=d=>{const h=d*a*e,p=h*n+n,f=Math.pow(a,2)*Math.pow(d,2)*e,x=Math.exp(-h),g=pf(Math.pow(d,2),a);return(-i(d)+Wh>0?-1:1)*((p-f)*x)/g}):(i=d=>{const u=Math.exp(-d*e),h=(d-n)*e+1;return-Wh+u*h},r=d=>{const u=Math.exp(-d*e),h=(n-d)*(e*e);return u*h});const l=5/e,c=cz(i,r,l);if(e=Ms(e),isNaN(c))return{stiffness:zn.stiffness,damping:zn.damping,duration:e};{const d=Math.pow(c,2)*s;return{stiffness:d,damping:a*2*Math.sqrt(s*d),duration:e}}}const uz=["duration","bounce"],hz=["stiffness","damping","mass"];function l0(e,t){return t.some(n=>e[n]!==void 0)}function pz(e){let t={velocity:zn.velocity,stiffness:zn.stiffness,damping:zn.damping,mass:zn.mass,isResolvedFromDuration:!1,...e};if(!l0(e,hz)&&l0(e,uz))if(t.velocity=0,e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),i=s*s,r=2*Li(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:zn.mass,stiffness:i,damping:r}}else{const n=dz({...e,velocity:0});t={...t,...n,mass:zn.mass},t.isResolvedFromDuration=!0}return t}function Qd(e=zn.visualDuration,t=zn.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:i}=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}=pz({...n,velocity:-Vs(n.velocity||0)}),x=p||0,g=d/(2*Math.sqrt(c*u)),v=a-r,w=Vs(Math.sqrt(c/u)),y=Math.abs(v)<5;s||(s=y?zn.restSpeed.granular:zn.restSpeed.default),i||(i=y?zn.restDelta.granular:zn.restDelta.default);let b,_,j,N,C,k;if(g<1)j=pf(w,g),N=(x+g*w*v)/j,b=I=>{const T=Math.exp(-g*w*I);return a-T*(N*Math.sin(j*I)+v*Math.cos(j*I))},C=g*w*N+v*j,k=g*w*v-N*j,_=I=>Math.exp(-g*w*I)*(C*Math.sin(j*I)+k*Math.cos(j*I));else if(g===1){b=T=>a-Math.exp(-w*T)*(v+(x+w*v)*T);const I=x+w*v;_=T=>Math.exp(-w*T)*(w*I*T-x)}else{const I=w*Math.sqrt(g*g-1);b=W=>{const J=Math.exp(-g*w*W),O=Math.min(I*W,300);return a-J*((x+g*w*v)*Math.sinh(O)+I*v*Math.cosh(O))/I};const T=(x+g*w*v)/I,A=g*w*T-v*I,D=g*w*v-T*I;_=W=>{const J=Math.exp(-g*w*W),O=Math.min(I*W,300);return J*(A*Math.sinh(O)+D*Math.cosh(O))}}const E={calculatedDuration:f&&h||null,velocity:I=>Ms(_(I)),next:I=>{if(!f&&g<1){const A=Math.exp(-g*w*I),D=Math.sin(j*I),W=Math.cos(j*I),J=a-A*(N*D+v*W),O=Ms(A*(C*D+k*W));return l.done=Math.abs(O)<=s&&Math.abs(a-J)<=i,l.value=l.done?a:J,l}const T=b(I);if(f)l.done=I>=h;else{const A=Ms(_(I));l.done=Math.abs(A)<=s&&Math.abs(a-T)<=i}return l.value=l.done?a:T,l},toString:()=>{const I=Math.min(Ng(E),Zd),T=q_(A=>E.next(I*A).value,I,30);return I+"ms "+T},toTransition:()=>{}};return E}Qd.applyToOptions=e=>{const t=az(e,100,Qd);return e.ease=t.ease,e.duration=Ms(t.duration),e.type="keyframes",e};const fz=5;function Y_(e,t,n){const s=Math.max(t-fz,0);return T_(n-e(s),t-s)}function ff({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:i=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,x=k=>l===void 0?c:c===void 0||Math.abs(l-k)<Math.abs(c-k)?l:c;let g=n*t;const v=h+g,w=a===void 0?v:a(v);w!==v&&(g=w-h);const y=k=>-g*Math.exp(-k/s),b=k=>w+y(k),_=k=>{const E=y(k),I=b(k);p.done=Math.abs(E)<=d,p.value=p.done?w:I};let j,N;const C=k=>{f(p.value)&&(j=k,N=Qd({keyframes:[p.value,x(p.value)],velocity:Y_(b,k,p.value),damping:i,stiffness:r,restDelta:d,restSpeed:u}))};return C(0),{calculatedDuration:null,next:k=>{let E=!1;return!N&&j===void 0&&(E=!0,_(k),C(k)),j!==void 0&&k>=j?N.next(k-j):(!E&&_(k),p)}}}function mz(e,t,n){const s=[],i=n||No.mix||K_,r=e.length-1;for(let a=0;a<r;a++){let l=i(e[a],e[a+1]);if(t){const c=Array.isArray(t)?t[a]||Ks:t;l=ac(c,l)}s.push(l)}return s}function gz(e,t,{clamp:n=!0,ease:s,mixer:i}={}){const r=e.length;if(Xu(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=mz(t,s,i),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=Il(e[h],e[h+1],u);return l[h](p)};return n?u=>d(Li(e[0],e[r-1],u)):d}function xz(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const i=Il(0,t,s);e.push(Sn(n,1,i))}}function vz(e){const t=[0];return xz(t,e.length-1),t}function bz(e,t){return e.map(n=>n*t)}function wz(e,t){return e.map(()=>t||O_).splice(0,e.length-1)}function il({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const i=T5(s)?s.map(n0):n0(s),r={done:!1,value:t[0]},a=bz(n&&n.length===t.length?n:vz(t),e),l=gz(a,t,{ease:Array.isArray(i)?i:wz(t,i)});return{calculatedDuration:e,next:c=>(r.value=l(c),r.done=c>=e,r)}}const yz=e=>e!==null;function Ju(e,{repeat:t,repeatType:n="loop"},s,i=1){const r=e.filter(yz),l=i<0||t&&n!=="loop"&&t%2===1?0:r.length-1;return!l||s===void 0?r[l]:s}const Sz={decay:ff,inertia:ff,tween:il,keyframes:il,spring:Qd};function X_(e){typeof e.type=="string"&&(e.type=Sz[e.type])}class Tg{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 Cz=e=>e/100;class eu extends Tg{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!==ws.now()&&this.tick(ws.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;X_(t);const{type:n=il,repeat:s=0,repeatDelay:i=0,repeatType:r,velocity:a=0}=t;let{keyframes:l}=t;const c=n||il;c!==il&&typeof l[0]!="number"&&(this.mixKeyframes=ac(Cz,K_(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=Ng(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+i,this.totalDuration=this.resolvedDuration*(s+1)-i,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:i,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:x,onUpdate:g,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-i/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const w=this.currentTime-d*(this.playbackSpeed>=0?1:-1),y=this.playbackSpeed>=0?w<0:w>i;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=i);let b=this.currentTime,_=s;if(h){const k=Math.min(this.currentTime,i)/l;let E=Math.floor(k),I=k%1;!I&&k>=1&&(I=1),I===1&&E--,E=Math.min(E,h+1),E%2&&(p==="reverse"?(I=1-I,f&&(I-=f/l)):p==="mirror"&&(_=a)),b=Li(0,1,I)*l}let j;y?(this.delayState.value=u[0],j=this.delayState):j=_.next(b),r&&!y&&(j.value=r(j.value));let{done:N}=j;!y&&c!==null&&(N=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const C=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return C&&x!==ff&&(j.value=Ju(u,this.options,v,this.speed)),g&&g(j.value),C&&this.finish(),j}then(t,n){return this.finished.then(t,n)}get duration(){return Vs(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Vs(t)}get time(){return Vs(this.currentTime)}set time(t){t=Ms(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 Y_(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(ws.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=Vs(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=rz,startTime:n}=this.options;this.driver||(this.driver=t(i=>this.tick(i))),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(ws.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 kz(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const sr=e=>e*180/Math.PI,mf=e=>{const t=sr(Math.atan2(e[1],e[0]));return gf(t)},_z={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:mf,rotateZ:mf,skewX:e=>sr(Math.atan(e[1])),skewY:e=>sr(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},gf=e=>(e=e%360,e<0&&(e+=360),e),c0=mf,d0=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),u0=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),jz={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:d0,scaleY:u0,scale:e=>(d0(e)+u0(e))/2,rotateX:e=>gf(sr(Math.atan2(e[6],e[5]))),rotateY:e=>gf(sr(Math.atan2(-e[2],e[0]))),rotateZ:c0,rotate:c0,skewX:e=>sr(Math.atan(e[4])),skewY:e=>sr(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function xf(e){return e.includes("scale")?1:0}function vf(e,t){if(!e||e==="none")return xf(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,i;if(n)s=jz,i=n;else{const l=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=_z,i=l}if(!i)return xf(t);const r=s[t],a=i[1].split(",").map(Tz);return typeof r=="function"?r(a):a[r]}const Nz=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return vf(n,t)};function Tz(e){return parseFloat(e.trim())}const wa=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ya=new Set([...wa,"pathRotation"]),h0=e=>e===ba||e===gt,Iz=new Set(["x","y","z"]),Dz=wa.filter(e=>!Iz.has(e));function Pz(e){const t=[];return Dz.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const _o={width:({x:e},{paddingLeft:t="0",paddingRight:n="0",boxSizing:s})=>{const i=e.max-e.min;return s==="border-box"?i:i-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t="0",paddingBottom:n="0",boxSizing:s})=>{const i=e.max-e.min;return s==="border-box"?i:i-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})=>vf(t,"x"),y:(e,{transform:t})=>vf(t,"y")};_o.translateX=_o.x;_o.translateY=_o.y;const cr=new Set;let bf=!1,wf=!1,yf=!1;function J_(){if(wf){const e=Array.from(cr).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const i=Pz(s);i.length&&(n.set(s,i),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const i=n.get(s);i&&i.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)})}wf=!1,bf=!1,cr.forEach(e=>e.complete(yf)),cr.clear()}function Z_(){cr.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(wf=!0)})}function Ez(){yf=!0,Z_(),J_(),yf=!1}class Ig{constructor(t,n,s,i,r,a=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=i,this.element=r,this.isAsync=a}scheduleResolve(){this.state="scheduled",this.isAsync?(cr.add(this),bf||(bf=!0,Cn.read(Z_),Cn.resolveKeyframes(J_))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:i}=this;if(t[0]===null){const r=i?.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),i&&r===void 0&&i.set(t[0])}kz(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),cr.delete(this)}cancel(){this.state==="scheduled"&&(cr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Az=e=>e.startsWith("--");function Q_(e,t,n){Az(t)?e.style.setProperty(t,n):e.style[t]=n}const Mz={};function ej(e,t){const n=N_(e);return()=>Mz[t]??n()}const Rz=ej(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),tj=ej(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),$a=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,p0={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:$a([0,.65,.55,1]),circOut:$a([.55,0,1,.45]),backIn:$a([.31,.01,.66,-.59]),backOut:$a([.33,1.53,.69,.99])};function nj(e,t){if(e)return typeof e=="function"?tj()?q_(e,t):"ease-out":z_(e)?$a(e):Array.isArray(e)?e.map(n=>nj(n,t)||p0.easeOut):p0[e]}function Lz(e,t,n,{delay:s=0,duration:i=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=nj(l,i);Array.isArray(h)&&(u.easing=h);const p={delay:s,duration:i,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 sj(e){return typeof e=="function"&&"applyToOptions"in e}function Oz({type:e,...t}){return sj(e)&&tj()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class ij extends Tg{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:n,name:s,keyframes:i,pseudoElement:r,allowFlatten:a=!1,finalKeyframe:l,onComplete:c}=t;this.isPseudoElement=!!r,this.allowFlatten=a,this.options=t,Xu(typeof t.type!="string");const d=Oz(t);this.animation=Lz(n,s,i,d,r),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=Ju(i,this.options,l,this.speed);this.updateMotionValue&&this.updateMotionValue(u),Q_(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 Vs(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Vs(t)}get time(){return Vs(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ms(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:i}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&Rz()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),s&&(this.animation.rangeEnd=s),Ks):i(this)}}const oj={anticipate:M_,backInOut:A_,circInOut:L_};function zz(e){return e in oj}function Gz(e){typeof e.ease=="string"&&zz(e.ease)&&(e.ease=oj[e.ease])}const Uh=10;class Fz extends ij{constructor(t){Gz(t),X_(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:i,element:r,...a}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const l=new eu({...a,autoplay:!1}),c=Math.max(Uh,ws.now()-this.startTime),d=Li(0,Uh,c-Uh),u=l.sample(c).value,{name:h}=this.options;r&&h&&Q_(r,h,u),n.setWithVelocity(l.sample(Math.max(0,c-d)).value,u,d),l.stop()}}const f0=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(li.test(e)||e==="0")&&!e.startsWith("url("));function Hz(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 Bz(e,t,n,s){const i=e[0];if(i===null)return!1;if(t==="display"||t==="visibility")return!0;const r=e[e.length-1],a=f0(i,t),l=f0(r,t);return!a||!l?!1:Hz(e)||(n==="spring"||sj(n))&&s}function Sf(e){e.duration=0,e.type="keyframes"}const rj=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),Vz=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function $z(e){for(let t=0;t<e.length;t++)if(typeof e[t]=="string"&&Vz.test(e[t]))return!0;return!1}const Wz=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),Uz=N_(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Kz(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:i,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 Uz()&&n&&(rj.has(n)||Wz.has(n)&&$z(l))&&(n!=="transform"||!u)&&!d&&!s&&i!=="mirror"&&r!==0&&a!=="inertia"}const qz=40;class Yz extends Tg{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:i=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=ws.now();const p={autoplay:t,delay:n,type:s,repeat:i,repeatDelay:r,repeatType:a,name:c,motionValue:d,element:u,...h},f=u?.KeyframeResolver||Ig;this.keyframeResolver=new f(l,(x,g,v)=>this.onKeyframesResolved(x,g,p,!v),c,d,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,i){this.keyframeResolver=void 0;const{name:r,type:a,velocity:l,delay:c,isHandoff:d,onUpdate:u}=s;this.resolvedAt=ws.now();let h=!0;Bz(t,r,a,l)||(h=!1,(No.instantAnimations||!c)&&u?.(Ju(t,s,n)),t[0]=t[t.length-1],Sf(s),s.repeat=0);const f={startTime:i?this.resolvedAt?this.resolvedAt-this.createdAt>qz?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},x=h&&!d&&Kz(f),g=f.motionValue?.owner?.current;let v;if(x)try{v=new Fz({...f,element:g})}catch{v=new eu(f)}else v=new eu(f);v.finished.then(()=>{this.notifyFinished()}).catch(Ks),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(),Ez()),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 aj(e,t,n,s=0,i=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):i===1?r*s:l-r*s}const m0=30,Xz=e=>!isNaN(parseFloat(e));class Jz{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const i=ws.now();if(this.updatedAt!==i&&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=ws.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Xz(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 wg);const s=this.events[t].add(n);return t==="change"?()=>{s(),Cn.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=ws.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>m0)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,m0);return T_(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 ia(e,t){return new Jz(e,t)}function lj(e,t){if(e?.inherit&&t){const{inherit:n,...s}=e;return{...t,...s}}return e}function Dg(e,t){const n=e?.[t]??e?.default??e;return n!==e?lj(n,e):n}const Zz={type:"spring",stiffness:500,damping:25,restSpeed:10},Qz=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),eG={type:"keyframes",duration:.8},tG={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},nG=(e,{keyframes:t})=>t.length>2?eG:ya.has(e)?e.startsWith("scale")?Qz(t[1]):Zz:tG,sG=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function iG(e){for(const t in e)if(!sG.has(t))return!0;return!1}const Pg=(e,t,n,s={},i,r)=>a=>{const l=Dg(s,e)||{},c=l.delay||s.delay||0;let{elapsed:d=0}=s;d=d-Ms(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:i};iG(l)||Object.assign(u,nG(e,u)),u.duration&&(u.duration=Ms(u.duration)),u.repeatDelay&&(u.repeatDelay=Ms(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Sf(u),u.delay===0&&(h=!0)),(No.instantAnimations||No.skipAnimations||i?.shouldSkipAnimations||l.skipAnimations)&&(h=!0,Sf(u),u.delay=0),u.allowFlatten=!l.type&&!l.ease,h&&!r&&t.get()!==void 0){const p=Ju(u.keyframes,l);if(p!==void 0){Cn.update(()=>{u.onUpdate(p),u.onComplete()});return}}return l.isSync?new eu(u):new Yz(u)},oG=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function rG(e){const t=oG.exec(e);if(!t)return[,];const[,n,s,i]=t;return[`--${n??s}`,i]}function cj(e,t,n=1){const[s,i]=rG(e);if(!s)return;const r=window.getComputedStyle(t).getPropertyValue(s);if(r){const a=r.trim();return k_(a)?parseFloat(a):a}return Cg(i)?cj(i,t,n+1):i}function g0(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Eg(e,t,n,s){if(typeof t=="function"){const[i,r]=g0(s);t=t(n!==void 0?n:e.custom,i,r)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[i,r]=g0(s);t=t(n!==void 0?n:e.custom,i,r)}return t}function dr(e,t,n){const s=e.getProps();return Eg(s,t,n!==void 0?n:s.custom,e)}const dj=new Set(["width","height","top","left","right","bottom",...wa]),Cf=e=>Array.isArray(e);function aG(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,ia(n))}function lG(e){return Cf(e)?e[e.length-1]||0:e}function cG(e,t){const n=dr(e,t);let{transitionEnd:s={},transition:i={},...r}=n||{};r={...r,...s};for(const a in r){const l=lG(r[a]);aG(e,a,l)}}const as=e=>!!(e&&e.getVelocity);function dG(e){return!!(as(e)&&e.add)}function kf(e,t){const n=e.getValue("willChange");if(dG(n))return n.add(t);if(!n&&No.WillChange){const s=new No.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Ag(e){return e.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const uG="framerAppearId",uj="data-"+Ag(uG);function hj(e){return e.props[uj]}const hG=typeof window<"u";function pG({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function pj(e,t,{delay:n=0,transitionOverride:s,type:i}={}){let{transition:r,transitionEnd:a,...l}=t;const c=e.getDefaultTransition();r=r?lj(r,c):c;const d=r?.reduceMotion,u=r?.skipAnimations;s&&(r=s);const h=[],p=i&&e.animationState&&e.animationState.getState()[i],f=r?.path;f&&f.animateVisualElement(e,l,r,n,h);for(const x in l){const g=e.getValue(x,e.latestValues[x]??null),v=l[x];if(v===void 0||p&&pG(p,x))continue;const w={delay:n,...Dg(r||{},x)};u&&(w.skipAnimations=!0);const y=g.get();if(y!==void 0&&!g.isAnimating()&&!Array.isArray(v)&&v===y&&!w.velocity){Cn.update(()=>g.set(v));continue}let b=!1;if(hG&&window.MotionHandoffAnimation){const N=hj(e);if(N){const C=window.MotionHandoffAnimation(N,x,Cn);C!==null&&(w.startTime=C,b=!0)}}kf(e,x);const _=d??e.shouldReduceMotion;g.start(Pg(x,g,v,_&&dj.has(x)?{type:!1}:w,e,b));const j=g.animation;j&&h.push(j)}if(a){const x=()=>Cn.update(()=>{a&&cG(e,a)});h.length?Promise.all(h).then(x):x()}return h}function _f(e,t,n={}){const s=dr(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:i=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(i=n.transitionOverride);const r=s?()=>Promise.all(pj(e,s,n)):()=>Promise.resolve(),a=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:h}=i;return fG(e,t,c,d,u,h,n)}:()=>Promise.resolve(),{when:l}=i;if(l){const[c,d]=l==="beforeChildren"?[r,a]:[a,r];return c().then(()=>d())}else return Promise.all([r(),a(n.delay)])}function fG(e,t,n=0,s=0,i=0,r=1,a){const l=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),l.push(_f(c,t,{...a,delay:n+(typeof s=="function"?0:s)+aj(e.variantChildren,c,s,i,r)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(l)}function mG(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const i=t.map(r=>_f(e,r,n));s=Promise.all(i)}else if(typeof t=="string")s=_f(e,t,n);else{const i=typeof t=="function"?dr(e,t,n.custom):t;s=Promise.all(pj(e,i,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}const gG={test:e=>e==="auto",parse:e=>e},fj=e=>t=>t.test(e),mj=[ba,gt,Di,Ji,H5,F5,gG],x0=e=>mj.find(fj(e));function xG(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||j_(e):!0}const vG=new Set(["brightness","contrast","saturate","opacity"]);function bG(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(kg)||[];if(!s)return e;const i=n.replace(s,"");let r=vG.has(t)?1:0;return s!==n&&(r*=100),t+"("+r+i+")"}const wG=/\b([a-z-]*)\(.*?\)/gu,jf={...li,getAnimatableNone:e=>{const t=e.match(wG);return t?t.map(bG).join(" "):e}},Nf={...li,getAnimatableNone:e=>{const t=li.parse(e);return li.createTransformer(e)(t.map(s=>typeof s=="number"?0:typeof s=="object"?{...s,alpha:1}:s))}},v0={...ba,transform:Math.round},yG={rotate:Ji,pathRotation:Ji,rotateX:Ji,rotateY:Ji,rotateZ:Ji,scale:Cc,scaleX:Cc,scaleY:Cc,scaleZ:Cc,skew:Ji,skewX:Ji,skewY:Ji,distance:gt,translateX:gt,translateY:gt,translateZ:gt,x:gt,y:gt,z:gt,perspective:gt,transformPerspective:gt,opacity:Dl,originX:i0,originY:i0,originZ:gt},tu={borderWidth:gt,borderTopWidth:gt,borderRightWidth:gt,borderBottomWidth:gt,borderLeftWidth:gt,borderRadius:gt,borderTopLeftRadius:gt,borderTopRightRadius:gt,borderBottomRightRadius:gt,borderBottomLeftRadius:gt,width:gt,maxWidth:gt,height:gt,maxHeight:gt,top:gt,right:gt,bottom:gt,left:gt,inset:gt,insetBlock:gt,insetBlockStart:gt,insetBlockEnd:gt,insetInline:gt,insetInlineStart:gt,insetInlineEnd:gt,padding:gt,paddingTop:gt,paddingRight:gt,paddingBottom:gt,paddingLeft:gt,paddingBlock:gt,paddingBlockStart:gt,paddingBlockEnd:gt,paddingInline:gt,paddingInlineStart:gt,paddingInlineEnd:gt,margin:gt,marginTop:gt,marginRight:gt,marginBottom:gt,marginLeft:gt,marginBlock:gt,marginBlockStart:gt,marginBlockEnd:gt,marginInline:gt,marginInlineStart:gt,marginInlineEnd:gt,fontSize:gt,backgroundPositionX:gt,backgroundPositionY:gt,...yG,zIndex:v0,fillOpacity:Dl,strokeOpacity:Dl,numOctaves:v0},SG={...tu,color:Vn,backgroundColor:Vn,outlineColor:Vn,fill:Vn,stroke:Vn,borderColor:Vn,borderTopColor:Vn,borderRightColor:Vn,borderBottomColor:Vn,borderLeftColor:Vn,filter:jf,WebkitFilter:jf,mask:Nf,WebkitMask:Nf},gj=e=>SG[e],CG=new Set([jf,Nf]);function xj(e,t){let n=gj(e);return CG.has(n)||(n=li),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const kG=new Set(["auto","none","0"]);function _G(e,t,n){let s=0,i;for(;s<e.length&&!i;){const r=e[s];typeof r=="string"&&!kG.has(r)&&sa(r).values.length&&(i=e[s]),s++}if(i&&n)for(const r of t)e[r]=xj(n,i)}class jG extends Ig{constructor(t,n,s,i,r){super(t,n,s,i,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(),Cg(h))){const p=cj(h,n.current);p!==void 0&&(t[u]=p),u===t.length-1&&(this.finalKeyframe=h)}}if(this.resolveNoneKeyframes(),!dj.has(s)||t.length!==2)return;const[i,r]=t,a=x0(i),l=x0(r),c=s0(i),d=s0(r);if(c!==d&&_o[s]){this.needsMeasurement=!0;return}if(a!==l)if(h0(a)&&h0(l))for(let u=0;u<t.length;u++){const h=t[u];typeof h=="string"&&(t[u]=parseFloat(h))}else _o[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let i=0;i<t.length;i++)(t[i]===null||xG(t[i]))&&s.push(i);s.length&&_G(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=_o[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const i=n[n.length-1];i!==void 0&&t.getValue(s,i).jump(i,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const i=t.getValue(n);i&&i.jump(this.measuredOrigin,!1);const r=s.length-1,a=s[r];s[r]=_o[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 Mg=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function vj(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const i=n?.[e]??s.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(s=>s!=null)}const Tf=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function xd(e){return __(e)&&"offsetHeight"in e&&!("ownerSVGElement"in e)}const{schedule:Rg}=G_(queueMicrotask,!1),ni={x:!1,y:!1};function bj(){return ni.x||ni.y}function NG(e){return e==="x"||e==="y"?ni[e]?null:(ni[e]=!0,()=>{ni[e]=!1}):ni.x||ni.y?null:(ni.x=ni.y=!0,()=>{ni.x=ni.y=!1})}function wj(e,t){const n=vj(e),s=new AbortController,i={passive:!0,...t,signal:s.signal};return[n,i,()=>s.abort()]}function TG(e){return!(e.pointerType==="touch"||bj())}function IG(e,t,n={}){const[s,i,r]=wj(e,n);return s.forEach(a=>{let l=!1,c=!1,d;const u=()=>{a.removeEventListener("pointerleave",x)},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,i),window.addEventListener("pointercancel",p,i)},x=v=>{if(v.pointerType!=="touch"){if(l){c=!0;return}h(v)}},g=v=>{if(!TG(v))return;c=!1;const w=t(a,v);typeof w=="function"&&(d=w,a.addEventListener("pointerleave",x,i))};a.addEventListener("pointerenter",g,i),a.addEventListener("pointerdown",f,i)}),r}const yj=(e,t)=>t?e===t?!0:yj(e,t.parentElement):!1,Lg=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,DG=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function PG(e){return DG.has(e.tagName)||e.isContentEditable===!0}const EG=new Set(["INPUT","SELECT","TEXTAREA"]);function AG(e){return EG.has(e.tagName)||e.isContentEditable===!0}const vd=new WeakSet;function b0(e){return t=>{t.key==="Enter"&&e(t)}}function Kh(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const MG=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=b0(()=>{if(vd.has(n))return;Kh(n,"down");const i=b0(()=>{Kh(n,"up")}),r=()=>Kh(n,"cancel");n.addEventListener("keyup",i,t),n.addEventListener("blur",r,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function w0(e){return Lg(e)&&!bj()}const y0=new WeakSet;function RG(e,t,n={}){const[s,i,r]=wj(e,n),a=l=>{const c=l.currentTarget;if(!w0(l)||y0.has(l))return;vd.add(c),n.stopPropagation&&y0.add(l);const d=t(c,l),u={...i,capture:!0},h=(x,g)=>{window.removeEventListener("pointerup",p,u),window.removeEventListener("pointercancel",f,u),vd.has(c)&&vd.delete(c),w0(x)&&typeof d=="function"&&d(x,{success:g})},p=x=>{h(x,c===window||c===document||n.useGlobalTarget||yj(c,x.target))},f=x=>{h(x,!1)};window.addEventListener("pointerup",p,u),window.addEventListener("pointercancel",f,u)};return s.forEach(l=>{(n.useGlobalTarget?window:l).addEventListener("pointerdown",a,i),xd(l)&&(l.addEventListener("focus",d=>MG(d,i)),!PG(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),r}function Og(e){return __(e)&&"ownerSVGElement"in e}const bd=new WeakMap;let wd;const Sj=(e,t,n)=>(s,i)=>i&&i[0]?i[0][e+"Size"]:Og(s)&&"getBBox"in s?s.getBBox()[t]:s[n],LG=Sj("inline","width","offsetWidth"),OG=Sj("block","height","offsetHeight");function zG({target:e,borderBoxSize:t}){bd.get(e)?.forEach(n=>{n(e,{get width(){return LG(e,t)},get height(){return OG(e,t)}})})}function GG(e){e.forEach(zG)}function FG(){typeof ResizeObserver>"u"||(wd=new ResizeObserver(GG))}function HG(e,t){wd||FG();const n=vj(e);return n.forEach(s=>{let i=bd.get(s);i||(i=new Set,bd.set(s,i)),i.add(t),wd?.observe(s)}),()=>{n.forEach(s=>{const i=bd.get(s);i?.delete(t),i?.size||wd?.unobserve(s)})}}const yd=new Set;let Fr;function BG(){Fr=()=>{const e={get width(){return window.innerWidth},get height(){return window.innerHeight}};yd.forEach(t=>t(e))},window.addEventListener("resize",Fr)}function VG(e){return yd.add(e),Fr||BG(),()=>{yd.delete(e),!yd.size&&typeof Fr=="function"&&(window.removeEventListener("resize",Fr),Fr=void 0)}}function S0(e,t){return typeof e=="function"?VG(e):HG(e,t)}function $G(e){return Og(e)&&e.tagName==="svg"}const WG=[...mj,Vn,li],UG=e=>WG.find(fj(e)),C0=()=>({translate:0,scale:1,origin:0,originPoint:0}),Hr=()=>({x:C0(),y:C0()}),k0=()=>({min:0,max:0}),Un=()=>({x:k0(),y:k0()}),KG=new WeakMap;function Zu(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Pl(e){return typeof e=="string"||Array.isArray(e)}const zg=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Gg=["initial",...zg];function Qu(e){return Zu(e.animate)||Gg.some(t=>Pl(e[t]))}function Cj(e){return!!(Qu(e)||e.variants)}function qG(e,t,n){for(const s in t){const i=t[s],r=n[s];if(as(i))e.addValue(s,i);else if(as(r))e.addValue(s,ia(i,{owner:e}));else if(r!==i)if(e.hasValue(s)){const a=e.getValue(s);a.liveStyle===!0?a.jump(i):a.hasAnimated||a.set(i)}else{const a=e.getStaticValue(s);e.addValue(s,ia(a!==void 0?a:i,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const nu={current:null},Fg={current:!1},YG=typeof window<"u";function kj(){if(Fg.current=!0,!!YG)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>nu.current=e.matches;e.addEventListener("change",t),t()}else nu.current=!1}const _0=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let su={};function _j(e){su=e}function XG(){return su}class JG{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:i,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=Ig,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=ws.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,Cn.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=i,this.skipAnimationsConfig=r,this.options=c,this.blockInitialAnimation=!!a,this.isControllingVariants=Qu(n),this.isVariantNode=Cj(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 x=p[f];d[f]!==void 0&&as(x)&&x.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,KG.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:(Fg.current||kj(),this.shouldReduceMotion=nu.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(),To(this.notifyUpdate),To(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&&rj.has(t)&&this.current instanceof HTMLElement){const{factory:a,keyframes:l,times:c,ease:d,duration:u}=n.accelerate,h=new ij({element:this.current,name:t,keyframes:l,times:c,ease:d,duration:Ms(u)}),p=a(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const s=ya.has(t);s&&this.onBindTransform&&this.onBindTransform();const i=n.on("change",a=>{this.latestValues[t]=a,this.props.onUpdate&&Cn.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,()=>{i(),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 su){const n=su[t];if(!n)continue;const{isEnabled:s,Feature:i}=n;if(!this.features[t]&&i&&s(this.props)&&(this.features[t]=new i(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):Un()}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<_0.length;s++){const i=_0[s];this.propEventSubscriptions[i]&&(this.propEventSubscriptions[i](),delete this.propEventSubscriptions[i]);const r="on"+i,a=t[r];a&&(this.propEventSubscriptions[i]=this.on(i,a))}this.prevMotionValues=qG(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=ia(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"&&(k_(s)||j_(s))?s=parseFloat(s):!UG(s)&&li.test(n)&&(s=xj(t,n)),this.setBaseTarget(t,as(s)?s.get():s)),as(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=Eg(this.props,n,this.presenceContext?.custom);r&&(s=r[t])}if(n&&s!==void 0)return s;const i=this.getBaseTargetFromProps(this.props,t);return i!==void 0&&!as(i)?i:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new wg),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Rg.render(this.render)}}class jj extends JG{constructor(){super(...arguments),this.KeyframeResolver=jG}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;as(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Ro{constructor(t){this.isMounted=!1,this.node=t}update(){}}function Nj({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function ZG({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function QG(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 qh(e){return e===void 0||e===1}function If({scale:e,scaleX:t,scaleY:n}){return!qh(e)||!qh(t)||!qh(n)}function Yo(e){return If(e)||Tj(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Tj(e){return j0(e.x)||j0(e.y)}function j0(e){return e&&e!=="0%"}function iu(e,t,n){const s=e-n,i=t*s;return n+i}function N0(e,t,n,s,i){return i!==void 0&&(e=iu(e,i,s)),iu(e,n,s)+t}function Df(e,t=0,n=1,s,i){e.min=N0(e.min,t,n,s,i),e.max=N0(e.max,t,n,s,i)}function Ij(e,{x:t,y:n}){Df(e.x,t.translate,t.scale,t.originPoint),Df(e.y,n.translate,n.scale,n.originPoint)}const T0=.999999999999,I0=1.0000000000001;function e3(e,t,n,s=!1){const i=n.length;if(!i)return;t.x=t.y=1;let r,a;for(let l=0;l<i;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&&(wi(e.x,-r.scroll.offset.x),wi(e.y,-r.scroll.offset.y)),a&&(t.x*=a.x.scale,t.y*=a.y.scale,Ij(e,a)),s&&Yo(r.latestValues)&&Sd(e,r.latestValues,r.layout?.layoutBox))}t.x<I0&&t.x>T0&&(t.x=1),t.y<I0&&t.y>T0&&(t.y=1)}function wi(e,t){e.min+=t,e.max+=t}function D0(e,t,n,s,i=.5){const r=Sn(e.min,e.max,i);Df(e,t,n,r,s)}function P0(e,t){return typeof e=="string"?parseFloat(e)/100*(t.max-t.min):e}function Sd(e,t,n){const s=n??e;D0(e.x,P0(t.x,s.x),t.scaleX,t.scale,t.originX),D0(e.y,P0(t.y,s.y),t.scaleY,t.scale,t.originY)}function Dj(e,t){return Nj(QG(e.getBoundingClientRect(),t))}function t3(e,t,n){const s=Dj(e,n),{scroll:i}=t;return i&&(wi(s.x,i.offset.x),wi(s.y,i.offset.y)),s}const n3={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},s3=wa.length;function i3(e,t,n){let s="",i=!0;for(let a=0;a<s3;a++){const l=wa[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=Tf(c,tu[l]);if(!d){i=!1;const h=n3[l]||l;s+=`${h}(${u}) `}n&&(t[l]=u)}}const r=e.pathRotation;return r&&(i=!1,s+=`rotate(${Tf(r,tu.pathRotation)}) `),s=s.trim(),n?s=n(t,i?"":s):i&&(s="none"),s}function Hg(e,t,n){const{style:s,vars:i,transformOrigin:r}=e;let a=!1,l=!1;for(const c in t){const d=t[c];if(ya.has(c)){a=!0;continue}else if(H_(c)){i[c]=d;continue}else{const u=Tf(d,tu[c]);c.startsWith("origin")?(l=!0,r[c]=u):s[c]=u}}if(t.transform||(a||n?s.transform=i3(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 Pj(e,{style:t,vars:n},s,i){const r=e.style;let a;for(a in t)r[a]=t[a];i?.applyProjectionStyles(r,s);for(a in n)r.setProperty(a,n[a])}function E0(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Na={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(gt.test(e))e=parseFloat(e);else return e;const n=E0(e,t.target.x),s=E0(e,t.target.y);return`${n}% ${s}%`}},o3={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,i=li.parse(e);if(i.length>5)return s;const r=li.createTransformer(e),a=typeof i[0]!="number"?1:0,l=n.x.scale*t.x,c=n.y.scale*t.y;i[0+a]/=l,i[1+a]/=c;const d=Sn(l,c,.5);return typeof i[2+a]=="number"&&(i[2+a]/=d),typeof i[3+a]=="number"&&(i[3+a]/=d),r(i)}},Pf={borderRadius:{...Na,applyTo:[...Mg]},borderTopLeftRadius:Na,borderTopRightRadius:Na,borderBottomLeftRadius:Na,borderBottomRightRadius:Na,boxShadow:o3};function Ej(e,{layout:t,layoutId:n}){return ya.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Pf[e]||e==="opacity")}function Bg(e,t,n){const s=e.style,i=t?.style,r={};if(!s)return r;for(const a in s)(as(s[a])||i&&as(i[a])||Ej(a,e)||n?.getValue(a)?.liveStyle!==void 0)&&(r[a]=s[a]);return r}function r3(e){return window.getComputedStyle(e)}class a3 extends jj{constructor(){super(...arguments),this.type="html",this.renderInstance=Pj}mount(t){Xu(!!t.style),super.mount(t)}readValueFromInstance(t,n){if(ya.has(n))return this.projection?.isProjecting?xf(n):Nz(t,n);{const s=r3(t),i=(H_(n)?s.getPropertyValue(n):s[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return Dj(t,n)}build(t,n,s){Hg(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Bg(t,n,s)}}const l3={offset:"stroke-dashoffset",array:"stroke-dasharray"},c3={offset:"strokeDashoffset",array:"strokeDasharray"};function d3(e,t,n=1,s=0,i=!0){e.pathLength=1;const r=i?l3:c3;e[r.offset]=`${-s}`,e[r.array]=`${t} ${n}`}const Aj=["transform","opacity","offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Mj(e,{attrX:t,attrY:n,attrScale:s,pathLength:i,pathSpacing:r=1,pathOffset:a=0,...l},c,d,u){if(Hg(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 Aj)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),i!==void 0&&d3(h,i,r,a,!1)}const Rj=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"]),Lj=e=>typeof e=="string"&&e.toLowerCase()==="svg";function u3(e,t,n,s){Pj(e,t,void 0,s);for(const i in t.attrs)e.setAttribute(Rj.has(i)?i:Ag(i),t.attrs[i])}function Oj(e,t,n){const s=Bg(e,t,n);for(const i in e)if(as(e[i])||as(t[i])){const r=wa.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;s[r]=e[i]}return s}class h3 extends jj{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Un}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(ya.has(n)){const s=gj(n);return s&&s.default||0}if(Aj.includes(n)){const i=getComputedStyle(t)[n];if(typeof i=="string"&&i)return i.trim()}return n=Rj.has(n)?n:Ag(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return Oj(t,n,s)}build(t,n,s){Mj(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,i){u3(t,n,s,i)}mount(t){this.isSVGTag=Lj(t.tagName),super.mount(t)}}const p3=Gg.length;function zj(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?zj(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<p3;n++){const s=Gg[n],i=e.props[s];(Pl(i)||i===!1)&&(t[s]=i)}return t}function Gj(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 f3=[...zg].reverse(),m3=zg.length;function g3(e){return t=>Promise.all(t.map(({animation:n,options:s})=>mG(e,n,s)))}function x3(e){let t=g3(e),n=A0(),s=!0,i=!1;const r=d=>(u,h)=>{const p=dr(e,h,d==="exit"?e.presenceContext?.custom:void 0);if(p){const{transition:f,transitionEnd:x,...g}=p;u={...u,...g,...x}}return u};function a(d){t=d(e)}function l(d){const{props:u}=e,h=zj(e.parent)||{},p=[],f=new Set;let x={},g=1/0;for(let w=0;w<m3;w++){const y=f3[w],b=n[y],_=u[y]!==void 0?u[y]:h[y],j=Pl(_),N=y===d?b.isActive:null;N===!1&&(g=w);let C=_===h[y]&&_!==u[y]&&j;if(C&&(s||i)&&e.manuallyAnimateOnMount&&(C=!1),b.protectedKeys={...x},!b.isActive&&N===null||!_&&!b.prevProp||Zu(_)||typeof _=="boolean")continue;if(y==="exit"&&b.isActive&&N!==!0){b.prevResolvedValues&&(x={...x,...b.prevResolvedValues});continue}const k=v3(b.prevProp,_);let E=k||y===d&&b.isActive&&!C&&j||w>g&&j,I=!1;const T=Array.isArray(_)?_:[_];let A=T.reduce(r(y),{});N===!1&&(A={});const{prevResolvedValues:D={}}=b,W={...D,...A},J=L=>{E=!0,f.has(L)&&(I=!0,f.delete(L)),b.needsAnimating[L]=!0;const se=e.getValue(L);se&&(se.liveStyle=!1)};for(const L in W){const se=A[L],Q=D[L];if(x.hasOwnProperty(L))continue;let V=!1;Cf(se)&&Cf(Q)?V=!Gj(se,Q)||k:V=se!==Q,V?se!=null?J(L):f.add(L):se!==void 0&&f.has(L)?J(L):b.protectedKeys[L]=!0}b.prevProp=_,b.prevResolvedValues=A,b.isActive&&(x={...x,...A}),(s||i)&&e.blockInitialAnimation&&(E=!1);const O=C&&k;E&&(!O||I)&&p.push(...T.map(L=>{const se={type:y};if(typeof L=="string"&&(s||i)&&!O&&e.manuallyAnimateOnMount&&e.parent){const{parent:Q}=e,V=dr(Q,L);if(Q.enteringChildren&&V){const{delayChildren:H}=V.transition||{};se.delay=aj(Q.enteringChildren,e,H)}}return{animation:L,options:se}}))}if(f.size){const w={};if(typeof u.initial!="boolean"){const y=dr(e,Array.isArray(u.initial)?u.initial[0]:u.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const b=e.getBaseTarget(y),_=e.getValue(y);_&&(_.liveStyle=!0),w[y]=b??null}),p.push({animation:w})}let v=!!p.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(v=!1),s=!1,i=!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=A0(),i=!0}}}function v3(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!Gj(t,e):!1}function Vo(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function A0(){return{animate:Vo(!0),whileInView:Vo(),whileHover:Vo(),whileTap:Vo(),whileDrag:Vo(),whileFocus:Vo(),exit:Vo()}}function Ef(e,t){e.min=t.min,e.max=t.max}function ei(e,t){Ef(e.x,t.x),Ef(e.y,t.y)}function M0(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}const Fj=1e-4,b3=1-Fj,w3=1+Fj,Hj=.01,y3=0-Hj,S3=0+Hj;function ys(e){return e.max-e.min}function C3(e,t,n){return Math.abs(e-t)<=n}function R0(e,t,n,s=.5){e.origin=s,e.originPoint=Sn(t.min,t.max,e.origin),e.scale=ys(n)/ys(t),e.translate=Sn(n.min,n.max,e.origin)-e.originPoint,(e.scale>=b3&&e.scale<=w3||isNaN(e.scale))&&(e.scale=1),(e.translate>=y3&&e.translate<=S3||isNaN(e.translate))&&(e.translate=0)}function ol(e,t,n,s){R0(e.x,t.x,n.x,s?s.originX:void 0),R0(e.y,t.y,n.y,s?s.originY:void 0)}function L0(e,t,n,s=0){const i=s?Sn(n.min,n.max,s):n.min;e.min=i+t.min,e.max=e.min+ys(t)}function k3(e,t,n,s){L0(e.x,t.x,n.x,s?.x),L0(e.y,t.y,n.y,s?.y)}function O0(e,t,n,s=0){const i=s?Sn(n.min,n.max,s):n.min;e.min=t.min-i,e.max=e.min+ys(t)}function ou(e,t,n,s){O0(e.x,t.x,n.x,s?.x),O0(e.y,t.y,n.y,s?.y)}function z0(e,t,n,s,i){return e-=t,e=iu(e,1/n,s),i!==void 0&&(e=iu(e,1/i,s)),e}function _3(e,t=0,n=1,s=.5,i,r=e,a=e){if(Di.test(t)&&(t=parseFloat(t),t=Sn(a.min,a.max,t/100)-a.min),typeof t!="number")return;let l=Sn(r.min,r.max,s);e===r&&(l-=t),e.min=z0(e.min,t,n,l,i),e.max=z0(e.max,t,n,l,i)}function G0(e,t,[n,s,i],r,a){_3(e,t[n],t[s],t[i],t.scale,r,a)}const j3=["x","scaleX","originX"],N3=["y","scaleY","originY"];function F0(e,t,n,s){G0(e.x,t,j3,n?n.x:void 0,s?s.x:void 0),G0(e.y,t,N3,n?n.y:void 0,s?s.y:void 0)}function H0(e){return e.translate===0&&e.scale===1}function Bj(e){return H0(e.x)&&H0(e.y)}function B0(e,t){return e.min===t.min&&e.max===t.max}function T3(e,t){return B0(e.x,t.x)&&B0(e.y,t.y)}function V0(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Vj(e,t){return V0(e.x,t.x)&&V0(e.y,t.y)}function $0(e){return ys(e.x)/ys(e.y)}function W0(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function bi(e){return[e("x"),e("y")]}function I3(e,t,n){let s="";const i=e.x.translate/t.x,r=e.y.translate/t.y,a=n?.z||0;if((i||r||a)&&(s=`translate3d(${i}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:x,skewY:g}=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) `),x&&(s+=`skewX(${x}deg) `),g&&(s+=`skewY(${g}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 D3=Mg.length,U0=e=>typeof e=="string"?parseFloat(e):e,K0=e=>typeof e=="number"||gt.test(e);function P3(e,t,n,s,i,r){i?(e.opacity=Sn(0,n.opacity??1,E3(s)),e.opacityExit=Sn(t.opacity??1,0,A3(s))):r&&(e.opacity=Sn(t.opacity??1,n.opacity??1,s));for(let a=0;a<D3;a++){const l=Mg[a];let c=q0(t,l),d=q0(n,l);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||K0(c)===K0(d)?(e[l]=Math.max(Sn(U0(c),U0(d),s),0),(Di.test(d)||Di.test(c))&&(e[l]+="%")):e[l]=d}(t.rotate||n.rotate)&&(e.rotate=Sn(t.rotate||0,n.rotate||0,s))}function q0(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const E3=$j(0,.5,R_),A3=$j(.5,.95,Ks);function $j(e,t,n){return s=>s<e?0:s>t?1:n(Il(e,t,s))}function M3(e,t,n){const s=as(e)?e:ia(e);return s.start(Pg("",s,t,n)),s.animation}function El(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}const R3=(e,t)=>e.depth-t.depth;class L3{constructor(){this.children=[],this.isDirty=!1}add(t){bg(this.children,t),this.isDirty=!0}remove(t){Xd(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(R3),this.isDirty=!1,this.children.forEach(t)}}function O3(e,t){const n=ws.now(),s=({timestamp:i})=>{const r=i-n;r>=t&&(To(s),e(r-t))};return Cn.setup(s,!0),()=>To(s)}function Cd(e){return as(e)?e.get():e}class z3{constructor(){this.members=[]}add(t){bg(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 i=s.instance;(!i||i.isConnected===!1)&&!s.snapshot&&(Xd(this.members,s),s.unmount())}t.scheduleRender()}remove(t){if(Xd(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:i}=s.options,{layoutDependency:r}=t.options;(i===void 0||i!==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 kd={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Yh=["","X","Y","Z"],G3=1e3;let F3=0;function Xh(e,t,n,s){const{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),s&&(s[e]=0))}function Wj(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=hj(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:i,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",Cn,!(i||r))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&Wj(s)}function Uj({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:i}){return class{constructor(a={},l=t?.()){this.id=F3++,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(V3),this.nodes.forEach(Y3),this.nodes.forEach(X3),this.nodes.forEach($3)},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 L3)}addEventListener(a,l){return this.eventHandlers.has(a)||this.eventHandlers.set(a,new wg),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=Og(a)&&!$G(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;Cn.read(()=>{h=window.innerWidth}),e(a,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=O3(p,250),kd.hasAnimatedSinceResize&&(kd.hasAnimatedSinceResize=!1,this.nodes.forEach(J0)))})}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 x=this.options.transition||d.getDefaultTransition()||tF,{onLayoutAnimationStart:g,onLayoutAnimationComplete:v}=d.getProps(),w=!this.targetLayout||!Vj(this.targetLayout,f),y=!h&&p;if(this.options.layoutRoot||this.resumeFrom||y||h&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const b={...Dg(x,"layout"),onPlay:g,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b),this.setAnimationOrigin(u,y,b.path)}else h||J0(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(),To(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(J3),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&&Wj(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(U3),this.nodes.forEach(Y0);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(X0);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(K3),this.nodes.forEach(q3),this.nodes.forEach(H3),this.nodes.forEach(B3)):this.nodes.forEach(X0),this.clearAllSnapshots();const l=ws.now();os.delta=Li(0,1e3/60,l-os.timestamp),os.timestamp=l,os.isProcessing=!0,Hh.update.process(os),Hh.preRender.process(os),Hh.render.process(os),os.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Rg.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(W3),this.sharedNodes.forEach(Z3)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Cn.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Cn.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!ys(this.snapshot.measuredBox.x)&&!ys(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=Un()),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(!i)return;const a=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,l=this.projectionDelta&&!Bj(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,u=d!==this.prevTransformTemplateValue;a&&this.instance&&(l||Yo(this.latestValues)||u)&&(i(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)),nF(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:a}=this.options;if(!a)return Un();const l=a.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(sF))){const{scroll:d}=this.root;d&&(wi(l.x,d.offset.x),wi(l.y,d.offset.y))}return l}removeElementScroll(a){const l=Un();if(ei(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&&ei(l,a),wi(l.x,u.offset.x),wi(l.y,u.offset.y))}return l}applyTransform(a,l=!1,c){const d=c||Un();ei(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&&(wi(d.x,-h.scroll.offset.x),wi(d.y,-h.scroll.offset.y)),Yo(h.latestValues)&&Sd(d,h.latestValues,h.layout?.layoutBox)}return Yo(this.latestValues)&&Sd(d,this.latestValues,this.layout?.layoutBox),d}removeTransform(a){const l=Un();ei(l,a);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!Yo(d.latestValues))continue;let u;d.instance&&(If(d.latestValues)&&d.updateSnapshot(),u=Un(),ei(u,d.measurePageBox())),F0(l,d.latestValues,d.snapshot?.layoutBox,u)}return Yo(this.latestValues)&&F0(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!==os.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=os.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=Un(),this.targetWithTransforms=Un()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),k3(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):ei(this.target,this.layout.layoutBox),Ij(this.target,this.targetDelta)):ei(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||If(this.parent.latestValues)||Tj(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=Un(),this.relativeTargetOrigin=Un(),ou(this.relativeTargetOrigin,l,c,this.options.layoutAnchor||void 0),ei(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===os.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;ei(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,p=this.treeScale.y;e3(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=Un());const{target:f}=a;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(M0(this.prevProjectionDelta.x,this.projectionDelta.x),M0(this.prevProjectionDelta.y,this.projectionDelta.y)),ol(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==p||!W0(this.projectionDelta.x,this.prevProjectionDelta.x)||!W0(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=Hr(),this.projectionDelta=Hr(),this.projectionDeltaWithTransform=Hr()}setAnimationOrigin(a,l=!1,c){const d=this.snapshot,u=d?d.latestValues:{},h={...this.latestValues},p=Hr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const f=Un(),x=d?d.source:void 0,g=this.layout?this.layout.source:void 0,v=x!==g,w=this.getStack(),y=!w||w.members.length<=1,b=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(eF));this.animationProgress=0;let _;const j=c?.interpolateProjection(a);this.mixTargetDelta=N=>{const C=N/1e3,k=j?.(C);k?(p.x.translate=k.x,p.x.scale=Sn(a.x.scale,1,C),p.x.origin=a.x.origin,p.x.originPoint=a.x.originPoint,p.y.translate=k.y,p.y.scale=Sn(a.y.scale,1,C),p.y.origin=a.y.origin,p.y.originPoint=a.y.originPoint):(Z0(p.x,a.x,C),Z0(p.y,a.y,C)),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ou(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Q3(this.relativeTarget,this.relativeTargetOrigin,f,C),_&&T3(this.relativeTarget,_)&&(this.isProjectionDirty=!1),_||(_=Un()),ei(_,this.relativeTarget)),v&&(this.animationValues=h,P3(h,u,this.latestValues,C,b,y)),k&&k.rotate!==void 0&&(this.animationValues||(this.animationValues=h),this.animationValues.pathRotation=k.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(a){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(To(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Cn.update(()=>{kd.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ia(0)),this.motionValue.jump(0,!1),this.currentAnimation=M3(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(G3),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&&Kj(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Un();const h=ys(this.layout.layoutBox.x);c.x.min=a.target.x.min,c.x.max=c.x.min+h;const p=ys(this.layout.layoutBox.y);c.y.min=a.target.y.min,c.y.max=c.y.min+p}ei(l,c),Sd(l,u),ol(this.projectionDeltaWithTransform,this.layoutCorrected,l,u)}}registerSharedNode(a,l){this.sharedNodes.has(a)||this.sharedNodes.set(a,new z3),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&&Xh("z",a,d,this.animationValues);for(let u=0;u<Yh.length;u++)Xh(`rotate${Yh[u]}`,a,d,this.animationValues),Xh(`skew${Yh[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=Cd(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=Cd(l?.pointerEvents)||""),this.hasProjected&&!Yo(this.latestValues)&&(a.transform=c?c({},""):"none",this.hasProjected=!1);return}a.visibility="";const u=d.animationValues||d.latestValues;this.applyTransformsToTarget();let h=I3(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 x in Pf){if(u[x]===void 0)continue;const{correct:g,applyTo:v,isCSSVariable:w}=Pf[x],y=h==="none"?u[x]:g(u[x],d);if(v){const b=v.length;for(let _=0;_<b;_++)a[v[_]]=y}else w?this.options.visualElement.renderState.vars[x]=y:a[x]=y}this.options.layoutId&&(a.pointerEvents=d===this?Cd(l?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(a=>a.currentAnimation?.stop()),this.root.nodes.forEach(Y0),this.root.sharedNodes.clear()}}}function H3(e){e.updateLayout()}function B3(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:i}=e.options,r=t.source!==e.layout.source;if(i==="size")bi(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=ys(h);h.min=n[u].min,h.max=h.min+p});else if(i==="x"||i==="y"){const u=i==="x"?"y":"x";Ef(r?t.measuredBox[u]:t.layoutBox[u],n[u])}else Kj(i,t.layoutBox,n)&&bi(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=ys(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=Hr();ol(a,n,t.layoutBox);const l=Hr();r?ol(l,e.applyTransform(s,!0),t.measuredBox):ol(l,n,t.layoutBox);const c=!Bj(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,x=Un();ou(x,t.layoutBox,h.layoutBox,f);const g=Un();ou(g,n,p.layoutBox,f),Vj(x,g)||(d=!0),u.options.layoutRoot&&(e.relativeTarget=g,e.relativeTargetOrigin=x,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 V3(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 $3(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function W3(e){e.clearSnapshot()}function Y0(e){e.clearMeasurements()}function U3(e){e.isLayoutDirty=!0,e.updateLayout()}function X0(e){e.isLayoutDirty=!1}function K3(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function q3(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function J0(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Y3(e){e.resolveTargetDelta()}function X3(e){e.calcProjection()}function J3(e){e.resetSkewAndRotation()}function Z3(e){e.removeLeadSnapshot()}function Z0(e,t,n){e.translate=Sn(t.translate,0,n),e.scale=Sn(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Q0(e,t,n,s){e.min=Sn(t.min,n.min,s),e.max=Sn(t.max,n.max,s)}function Q3(e,t,n,s){Q0(e.x,t.x,n.x,s),Q0(e.y,t.y,n.y,s)}function eF(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const tF={duration:.45,ease:[.4,0,.1,1]},eb=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),tb=eb("applewebkit/")&&!eb("chrome/")?Math.round:Ks;function nb(e){e.min=tb(e.min),e.max=tb(e.max)}function nF(e){nb(e.x),nb(e.y)}function Kj(e,t,n){return e==="position"||e==="preserve-aspect"&&!C3($0(t),$0(n),.2)}function sF(e){return e!==e.root&&e.scroll?.wasRoot}const iF=Uj({attachResizeListener:(e,t)=>El(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Jh={current:void 0},qj=Uj({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Jh.current){const e=new iF({});e.mount(window),e.setOptions({layoutScroll:!0}),Jh.current=e}return Jh.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),Vg=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function sb(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function oF(...e){return t=>{let n=!1;const s=e.map(i=>{const r=sb(i,t);return!n&&typeof r=="function"&&(n=!0),r});if(n)return()=>{for(let i=0;i<s.length;i++){const r=s[i];typeof r=="function"?r():sb(e[i],null)}}}}function rF(...e){return m.useCallback(oF(...e),e)}class aF extends m.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(xd(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,i=xd(s)&&s.offsetWidth||0,r=xd(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=i-l.width-l.left,l.bottom=r-l.height-l.top,l.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function lF({children:e,isPresent:t,anchorX:n,anchorY:s,root:i,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(Vg),u=r!==!1?e.props?.ref??e?.ref:void 0,h=rF(l,u);return m.useInsertionEffect(()=>{const{width:p,height:f,top:x,left:g,right:v,bottom:w,direction:y}=c.current;if(t||r===!1||!l.current||!p||!f)return;const b=y==="rtl",_=n==="left"?b?`right: ${v}`:`left: ${g}`:b?`left: ${g}`:`right: ${v}`,j=s==="bottom"?`bottom: ${w}`:`top: ${x}`;l.current.dataset.motionPopId=a;const N=document.createElement("style");d&&(N.nonce=d);const C=i??document.head;return C.appendChild(N),N.sheet&&N.sheet.insertRule(`
6
- [data-motion-pop-id="${a}"] {
7
- position: absolute !important;
8
- width: ${p}px !important;
9
- height: ${f}px !important;
10
- ${_}px !important;
11
- ${j}px !important;
12
- }
13
- `),()=>{l.current?.removeAttribute("data-motion-pop-id"),C.contains(N)&&C.removeChild(N)}},[t]),o.jsx(aF,{isPresent:t,childRef:l,sizeRef:c,pop:r,children:r===!1?e:m.cloneElement(e,{ref:h})})}const cF=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:i,presenceAffectsLayout:r,mode:a,anchorX:l,anchorY:c,root:d})=>{const u=vg(dF),h=m.useId(),p=m.useRef(n),f=m.useRef(s);Yd(()=>{p.current=n,f.current=s});let x=!0,g=m.useMemo(()=>(x=!1,{id:h,initial:t,isPresent:n,custom:i,onExitComplete:v=>{u.set(v,!0);for(const w of u.values())if(!w)return;s&&s()},register:v=>(u.set(v,!1),()=>{u.delete(v),!p.current&&!u.size&&f.current?.()})}),[n,u,s]);return r&&x&&(g={...g}),m.useMemo(()=>{u.forEach((v,w)=>u.set(w,!1))},[n]),m.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),e=o.jsx(lF,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:d,children:e}),o.jsx(Yu.Provider,{value:g,children:e})};function dF(){return new Map}function Yj(e=!0){const t=m.useContext(Yu);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:i}=t,r=m.useId();m.useEffect(()=>{if(e)return i(r)},[e]);const a=m.useCallback(()=>e&&s&&s(r),[r,s,e]);return!n&&s?[!1,a]:[!0]}const kc=e=>e.key||"";function ib(e){const t=[];return m.Children.forEach(e,n=>{m.isValidElement(n)&&t.push(n)}),t}const rl=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:i=!0,mode:r="sync",propagate:a=!1,anchorX:l="left",anchorY:c="top",root:d})=>{const[u,h]=Yj(a),p=m.useMemo(()=>ib(e),[e]),f=a&&!u?[]:p.map(kc),x=m.useRef(!0),g=m.useRef(p),v=vg(()=>new Map),w=m.useRef(new Set),[y,b]=m.useState(p),[_,j]=m.useState(p);Yd(()=>{a&&!u&&!_.length&&h?.()},[u,a,_.length,h]),Yd(()=>{x.current=!1,g.current=p;for(let k=0;k<_.length;k++){const E=kc(_[k]);f.includes(E)?(v.delete(E),w.current.delete(E)):v.get(E)!==!0&&v.set(E,!1)}},[_,f.length,f.join("-")]);const N=[];if(p!==y){let k=[...p],E=0;for(const I of _){const T=f.indexOf(kc(I));T===-1?(k.splice(E++,0,I),N.push(I)):E=T+N.length+1}return r==="wait"&&N.length&&(k=N),j(ib(k)),b(p),null}const{forceRender:C}=m.useContext(xg);return o.jsx(o.Fragment,{children:_.map(k=>{const E=kc(k),I=a&&!u?!1:p===_||f.includes(E),T=()=>{if(w.current.has(E))return;if(v.has(E))w.current.add(E),v.set(E,!0);else return;let A=!0;v.forEach(D=>{D||(A=!1)}),A&&(C?.(),j(g.current),a&&h?.(),s&&s())};return o.jsx(cF,{isPresent:I,initial:!x.current||n?void 0:!1,custom:t,presenceAffectsLayout:i,mode:r,root:d,onExitComplete:I?void 0:T,anchorX:l,anchorY:c,children:k},E)})})},Xj=m.createContext({strict:!1}),ob={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let rb=!1;function uF(){if(rb)return;const e={};for(const t in ob)e[t]={isEnabled:n=>ob[t].some(s=>!!n[s])};_j(e),rb=!0}function Jj(){return uF(),XG()}function hF(e){const t=Jj();for(const n in e)t[n]={...t[n],...e[n]};_j(t)}const eh=m.createContext({});function pF(e,t){if(Qu(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Pl(n)?n:void 0,animate:Pl(s)?s:void 0}}return e.inherit!==!1?t:{}}function fF(e){const{initial:t,animate:n}=pF(e,m.useContext(eh));return m.useMemo(()=>({initial:t,animate:n}),[ab(t),ab(n)])}function ab(e){return Array.isArray(e)?e.join(" "):e}const $g=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Zj(e,t,n){for(const s in t)!as(t[s])&&!Ej(s,n)&&(e[s]=t[s])}function mF({transformTemplate:e},t){return m.useMemo(()=>{const n=$g();return Hg(n,t,e),Object.assign({},n.vars,n.style)},[t])}function gF(e,t){const n=e.style||{},s={};return Zj(s,n,e),Object.assign(s,mF(e,t)),s}function xF(e,t){const n={},s=gF(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 Qj=()=>({...$g(),attrs:{}});function vF(e,t,n,s){const i=m.useMemo(()=>{const r=Qj();return Mj(r,t,Lj(s),e.transformTemplate,e.style),{...r.attrs,style:{...r.style}}},[t]);if(e.style){const r={};Zj(r,e.style,e),i.style={...r,...i.style}}return i}const bF=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 ru(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||bF.has(e)}function wF(e,t){return e.startsWith("on")?!ru(e):t?.(e)??!ru(e)}function yF(e,t,n,s){const i={};for(const r in e)r==="values"&&typeof e.values=="object"||as(e[r])||(wF(r,s)||n===!0&&ru(r)||!t&&!ru(r)||e.draggable&&r.startsWith("onDrag"))&&(i[r]=e[r]);return i}const SF=["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 Wg(e){return typeof e!="string"||e.includes("-")?!1:!!(SF.indexOf(e)>-1||/[A-Z]/u.test(e))}function CF(e,t,n,{latestValues:s},i,r=!1,a,l){const d=(a??Wg(e)?vF:xF)(t,s,i,e),u=yF(t,typeof e=="string",r,l),h=e!==m.Fragment?{...u,...d,ref:n}:{},{children:p}=t,f=m.useMemo(()=>as(p)?p.get():p,[p]);return m.createElement(e,{...h,children:f})}function kF({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,i){return{latestValues:_F(n,s,i,e),renderState:t()}}function _F(e,t,n,s){const i={},r=s(e,{});for(const p in r)i[p]=Cd(r[p]);let{initial:a,animate:l}=e;const c=Qu(e),d=Cj(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"&&!Zu(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f<p.length;f++){const x=Eg(e,p[f]);if(x){const{transitionEnd:g,transition:v,...w}=x;for(const y in w){let b=w[y];if(Array.isArray(b)){const _=u?b.length-1:0;b=b[_]}b!==null&&(i[y]=b)}for(const y in g)i[y]=g[y]}}}return i}const e1=e=>(t,n)=>{const s=m.useContext(eh),i=m.useContext(Yu),r=()=>kF(e,t,s,i);return n?r():vg(r)},jF=e1({scrapeMotionValuesFromProps:Bg,createRenderState:$g}),NF=e1({scrapeMotionValuesFromProps:Oj,createRenderState:Qj}),TF=Symbol.for("motionComponentSymbol");function IF(e,t,n){const s=m.useRef(n);m.useInsertionEffect(()=>{s.current=n});const i=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"&&(i.current=l)}else i.current?(i.current(),i.current=null):a(r);else a&&(a.current=r)},[t])}const t1=m.createContext({});function Lr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function DF(e,t,n,s,i,r){const{visualElement:a}=m.useContext(eh),l=m.useContext(Xj),c=m.useContext(Yu),d=m.useContext(Vg),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 x=p.current,g=m.useContext(t1);x&&!x.projection&&i&&(x.type==="html"||x.type==="svg")&&PF(p.current,n,i,g);const v=m.useRef(!1);m.useInsertionEffect(()=>{x&&v.current&&x.update(n,c)});const w=n[uj],y=m.useRef(!!w&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(w)&&window.MotionHasOptimisedAnimation?.(w));return Yd(()=>{f.current=!0,x&&(v.current=!0,window.MotionIsMounted=!0,x.updateFeatures(),x.scheduleRenderMicrotask(),y.current&&x.animationState&&x.animationState.animateChanges())}),m.useEffect(()=>{x&&(!y.current&&x.animationState&&x.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(w)}),y.current=!1),x.enteringChildren=void 0)}),x}function PF(e,t,n,s){const{layoutId:i,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:n1(e.parent)),e.projection.setOptions({layoutId:i,layout:r,alwaysMeasureLayout:!!a||l&&Lr(l),visualElement:e,animationType:typeof r=="string"?r:"both",initialPromotionConfig:s,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function n1(e){if(e)return e.options.allowProjection!==!1?e.projection:n1(e.parent)}function Zh(e,{forwardMotionProps:t=!1,type:n}={},s,i){s&&hF(s);const r=n?n==="svg":Wg(e),a=r?NF:jF;function l(d,u){let h;const p={...m.useContext(Vg),...d,layoutId:EF(d)},{isStatic:f,isValidProp:x}=p,g=fF(d),v=a(d,f);if(!f&&typeof window<"u"){AF();const w=MF(p);h=w.MeasureLayout,g.visualElement=DF(e,v,p,i,w.ProjectionNode,r)}return o.jsxs(eh.Provider,{value:g,children:[h&&g.visualElement?o.jsx(h,{visualElement:g.visualElement,...p}):null,CF(e,d,IF(v,g.visualElement,u),v,f,t,r,x)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=m.forwardRef(l);return c[TF]=e,c}function EF({layoutId:e}){const t=m.useContext(xg).id;return t&&e!==void 0?t+"-"+e:e}function AF(e,t){m.useContext(Xj).strict}function MF(e){const t=Jj(),{drag:n,layout:s}=t;if(!n&&!s)return{};const i={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function RF(e,t){if(typeof Proxy>"u")return Zh;const n=new Map,s=(r,a)=>Zh(r,a,e,t),i=(r,a)=>s(r,a);return new Proxy(i,{get:(r,a)=>a==="create"?s:(n.has(a)||n.set(a,Zh(a,void 0,e,t)),n.get(a))})}const LF=(e,t)=>t.isSVG??Wg(e)?new h3(t):new a3(t,{allowProjection:e!==m.Fragment});class OF extends Ro{constructor(t){super(t),t.animationState||(t.animationState=x3(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Zu(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 zF=0;class GF extends Ro{constructor(){super(...arguments),this.id=zF++,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=dr(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 i=this.node.animationState.setActive("exit",!t);n&&!t&&i.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 FF={animation:{Feature:OF},exit:{Feature:GF}};function dc(e){return{point:{x:e.pageX,y:e.pageY}}}const HF=e=>t=>Lg(t)&&e(t,dc(t));function al(e,t,n,s){return El(e,t,HF(n),s)}const s1=({current:e})=>e?e.ownerDocument.defaultView:null,lb=(e,t)=>Math.abs(e-t);function BF(e,t){const n=lb(e.x,t.x),s=lb(e.y,t.y);return Math.sqrt(n**2+s**2)}const cb=new Set(["auto","scroll"]);class i1{constructor(t,n,{transformPagePoint:s,contextWindow:i=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=x=>{this.handleScroll(x.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=_c(this.lastRawMoveEventInfo,this.transformPagePoint));const x=Qh(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,v=BF(x.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!v)return;const{point:w}=x,{timestamp:y}=os;this.history.push({...w,timestamp:y});const{onStart:b,onMove:_}=this.handlers;g||(b&&b(this.lastMoveEvent,x),this.startEvent=this.lastMoveEvent),_&&_(this.lastMoveEvent,x)},this.handlePointerMove=(x,g)=>{this.lastMoveEvent=x,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=_c(g,this.transformPagePoint),Cn.update(this.updatePoint,!0)},this.handlePointerUp=(x,g)=>{this.end();const{onEnd:v,onSessionEnd:w,resumeAnimation:y}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&y&&y(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=Qh(x.type==="pointercancel"?this.lastMoveEventInfo:_c(g,this.transformPagePoint),this.history);this.startEvent&&v&&v(x,b),w&&w(x,b)},!Lg(t))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=i||window;const c=dc(t),d=_c(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=os;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,Qh(d,this.history));const f={passive:!0,capture:!0};this.removeListeners=ac(al(this.contextWindow,"pointermove",this.handlePointerMove,f),al(this.contextWindow,"pointerup",this.handlePointerUp,f),al(this.contextWindow,"pointercancel",this.handlePointerUp,f)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(cb.has(s.overflowX)||cb.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,i=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},r={x:i.x-n.x,y:i.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,i),Cn.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),To(this.updatePoint)}}function _c(e,t){return t?{point:t(e.point)}:e}function db(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Qh({point:e},t){return{point:e,delta:db(e,o1(t)),offset:db(e,VF(t)),velocity:$F(t,.1)}}function VF(e){return e[0]}function o1(e){return e[e.length-1]}function $F(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const i=o1(e);for(;n>=0&&(s=e[n],!(i.timestamp-s.timestamp>Ms(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&i.timestamp-s.timestamp>Ms(t)*2&&(s=e[1]);const r=Vs(i.timestamp-s.timestamp);if(r===0)return{x:0,y:0};const a={x:(i.x-s.x)/r,y:(i.y-s.y)/r};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function WF(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?Sn(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?Sn(n,e,s.max):Math.min(e,n)),e}function ub(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 UF(e,{top:t,left:n,bottom:s,right:i}){return{x:ub(e.x,n,i),y:ub(e.y,t,s)}}function hb(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function KF(e,t){return{x:hb(e.x,t.x),y:hb(e.y,t.y)}}function qF(e,t){let n=.5;const s=ys(e),i=ys(t);return i>s?n=Il(t.min,t.max-s,e.min):s>i&&(n=Il(e.min,e.max-i,t.min)),Li(0,1,n)}function YF(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 Af=.35;function XF(e=Af){return e===!1?e=0:e===!0&&(e=Af),{x:pb(e,"left","right"),y:pb(e,"top","bottom")}}function pb(e,t,n){return{min:fb(e,t),max:fb(e,n)}}function fb(e,t){return typeof e=="number"?e:e[t]||0}const JF=new WeakMap;class ZF{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=Un(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const r=h=>{n&&this.snapToCursor(dc(h).point),this.stopAnimation()},a=(h,p)=>{const{drag:f,dragPropagation:x,onDragStart:g}=this.getProps();if(f&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=NG(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),bi(w=>{let y=this.getAxisMotionValue(w).get()||0;if(Di.test(y)){const{projection:b}=this.visualElement;if(b&&b.layout){const _=b.layout.layoutBox[w];_&&(y=ys(_)*(parseFloat(y)/100))}}this.originPoint[w]=y}),g&&Cn.update(()=>g(h,p),!1,!0),kf(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:x,onDirectionLock:g,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:w}=p;if(x&&this.currentDirection===null){this.currentDirection=eH(w),this.currentDirection!==null&&g&&g(this.currentDirection);return}this.updateAxis("x",p.point,w),this.updateAxis("y",p.point,w),this.visualElement.render(),v&&Cn.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 i1(t,{onSessionStart:r,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:s,contextWindow:s1(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,i=n||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!i||!s)return;const{velocity:a}=i;this.startAnimation(a);const{onDragEnd:l}=this.getProps();l&&Cn.postRender(()=>l(s,i))}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:i}=this.getProps();if(!s||!jc(t,i,this.currentDirection))return;const r=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=WF(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,i=this.constraints;t&&Lr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=UF(s.layoutBox,t):this.constraints=!1,this.elastic=XF(n),i!==this.constraints&&!Lr(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&bi(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=YF(s.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Lr(t))return!1;const s=t.current,{projection:i}=this.visualElement;if(!i||!i.layout)return!1;i.root&&(i.root.scroll=void 0,i.root.updateScroll());const r=t3(s,i.root,this.visualElement.getTransformPagePoint());let a=KF(i.layout.layoutBox,r);if(n){const l=n(ZG(a));this.hasMutatedConstraints=!!l,l&&(a=Nj(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:i,dragTransition:r,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=bi(u=>{if(!jc(u,n,this.currentDirection))return;let h=c&&c[u]||{};(a===!0||a===u)&&(h={min:0,max:0});const p=i?200:1e6,f=i?40:1e7,x={type:"inertia",velocity:s?t[u]:0,bounceStiffness:p,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...r,...h};return this.startAxisValueAnimation(u,x)});return Promise.all(d).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return kf(this.visualElement,t),s.start(Pg(t,s,0,n,this.visualElement,!1))}stopAnimation(){bi(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps()[n];return i||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){bi(n=>{const{drag:s}=this.getProps();if(!jc(n,s,this.currentDirection))return;const{projection:i}=this.visualElement,r=this.getAxisMotionValue(n);if(i&&i.layout){const{min:a,max:l}=i.layout.layoutBox[n],c=r.get()||0;r.set(t[n]-Sn(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Lr(n)||!s||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};bi(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const c=l.get();i[a]=qF({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(),bi(a=>{if(!jc(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:d}=this.constraints[a];l.set(Sn(c,d,i[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;JF.set(this.visualElement,this);const t=this.visualElement.current,n=al(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=d.target,f=p!==t&&AG(p);u&&h&&!f&&this.start(d)});let s;const i=()=>{const{dragConstraints:d}=this.getProps();Lr(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),s||(s=QF(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:r}=this.visualElement,a=r.addEventListener("measure",i);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),Cn.read(i);const l=El(window,"resize",()=>this.scalePositionWithinConstraints()),c=r.addEventListener("didUpdate",(({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(bi(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:i=!1,dragConstraints:r=!1,dragElastic:a=Af,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:i,dragConstraints:r,dragElastic:a,dragMomentum:l}}}function mb(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function QF(e,t,n){const s=S0(e,mb(n)),i=S0(t,mb(n));return()=>{s(),i()}}function jc(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function eH(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class tH extends Ro{constructor(t){super(t),this.removeGroupControls=Ks,this.removeListeners=Ks,this.controls=new ZF(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ks}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 ep=e=>(t,n)=>{e&&Cn.update(()=>e(t,n),!1,!0)};class nH extends Ro{constructor(){super(...arguments),this.removePointerDownListener=Ks}onPointerDown(t){this.session=new i1(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:s1(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:i}=this.node.getProps();return{onSessionStart:ep(t),onStart:ep(n),onMove:ep(s),onEnd:(r,a)=>{delete this.session,i&&Cn.postRender(()=>i(r,a))}}}mount(){this.removePointerDownListener=al(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 tp=!1;class sH extends m.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:i}=this.props,{projection:r}=t;r&&(n.group&&n.group.add(r),s&&s.register&&i&&s.register(r),tp&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),kd.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:i,isPresent:r}=this.props,{projection:a}=s;return a&&(a.isPresent=r,t.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),tp=!0,i||t.layoutDependency!==n||n===void 0||t.isPresent!==r?a.willUpdate():this.safeToRemove(),t.isPresent!==r&&(r?a.promote():a.relegate()||Cn.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(),Rg.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:i}=t;tp=!0,i&&(i.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(i),s&&s.deregister&&s.deregister(i))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function r1(e){const[t,n]=Yj(),s=m.useContext(xg);return o.jsx(sH,{...e,layoutGroup:s,switchLayoutGroup:m.useContext(t1),isPresent:t,safeToRemove:n})}const iH={pan:{Feature:nH},drag:{Feature:tH,ProjectionNode:qj,MeasureLayout:r1}};function gb(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const i="onHover"+n,r=s[i];r&&Cn.postRender(()=>r(t,dc(t)))}class oH extends Ro{mount(){const{current:t}=this.node;t&&(this.unmount=IG(t,(n,s)=>(gb(this.node,s,"Start"),i=>gb(this.node,i,"End"))))}unmount(){}}class rH extends Ro{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=ac(El(this.node.current,"focus",()=>this.onFocus()),El(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function xb(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 i="onTap"+(n==="End"?"":n),r=s[i];r&&Cn.postRender(()=>r(t,dc(t)))}class aH extends Ro{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=RG(t,(i,r)=>(xb(this.node,r,"Start"),(a,{success:l})=>xb(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const Mf=new WeakMap,np=new WeakMap,lH=e=>{const t=Mf.get(e.target);t&&t(e)},cH=e=>{e.forEach(lH)};function dH({root:e,...t}){const n=e||document;np.has(n)||np.set(n,{});const s=np.get(n),i=JSON.stringify(t);return s[i]||(s[i]=new IntersectionObserver(cH,{root:e,...t})),s[i]}function uH(e,t,n){const s=dH(t);return Mf.set(e,n),s.observe(e),()=>{Mf.delete(e),s.unobserve(e)}}const hH={some:0,all:1};class pH extends Ro{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:i="some",once:r}=t,a={root:n?n.current:void 0,rootMargin:s,threshold:typeof i=="number"?i:hH[i]},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=uH(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(fH(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function fH({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const mH={inView:{Feature:pH},tap:{Feature:aH},focus:{Feature:rH},hover:{Feature:oH}},gH={layout:{ProjectionNode:qj,MeasureLayout:r1}},xH={...FF,...mH,...iH,...gH},Es=RF(xH,LF);function vH(){!Fg.current&&kj();const[e]=m.useState(nu.current);return e}const bH=[["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"}]],wH=ot("alarm-clock",bH);const yH=[["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"}]],Al=ot("archive-restore",yH);const SH=[["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"}]],ji=ot("archive",SH);const CH=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],kH=ot("arrow-down-to-line",CH);const _H=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],th=ot("arrow-down",_H);const jH=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],nh=ot("arrow-up",jH);const NH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]],TH=ot("ban",NH);const IH=[["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"}]],vb=ot("bell-off",IH);const DH=[["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"}]],PH=ot("bookmark-plus",DH);const EH=[["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"}]],a1=ot("bug",EH);const AH=[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]],MH=ot("chevrons-down-up",AH);const RH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],LH=ot("circle-dot",RH);const OH=[["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"}]],zH=ot("circle-play",OH);const GH=[["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"}]],FH=ot("circle-question-mark",GH);const HH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],BH=ot("circle-stop",HH);const VH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],l1=ot("circle",VH);const $H=[["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"}]],c1=ot("clipboard-check",$H);const WH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],d1=ot("clock",WH);const UH=[["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"}]],u1=ot("code-xml",UH);const KH=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],qH=ot("code",KH);const YH=[["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"}]],XH=ot("coins",YH);const JH=[["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"}]],ZH=ot("compass",JH);const QH=[["path",{d:"m15 10 5 5-5 5",key:"qqa56n"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]],eB=ot("corner-down-right",QH);const tB=[["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"}]],nB=ot("cpu",tB);const sB=[["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"}]],iB=ot("database",sB);const oB=[["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",oB);const rB=[["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"}]],aB=ot("file-diff",rB);const lB=[["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"}]],cB=ot("file-pen",lB);const dB=[["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"}]],uB=ot("file-plus",dB);const hB=[["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"}]],pB=ot("file",hB);const fB=[["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"}]],mB=ot("fold-horizontal",fB);const gB=[["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"}]],xB=ot("folder-git-2",gB);const vB=[["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"}]],bb=ot("folder-plus",vB);const bB=[["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"}]],uc=ot("folder",bB);const wB=[["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"}]],yB=ot("folders",wB);const SB=[["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"}]],CB=ot("git-branch-plus",SB);const kB=[["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"}]],Ni=ot("git-branch",kB);const _B=[["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"}]],jB=ot("git-commit-horizontal",_B);const NB=[["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"}]],Ug=ot("git-compare",NB);const TB=[["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"}]],wb=ot("hand",TB);const IB=[["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"}]],DB=ot("hourglass",IB);const PB=[["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"}]],yb=ot("house",PB);const EB=[["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"}]],h1=ot("image-off",EB);const AB=[["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"}]],Kg=ot("image-plus",AB);const MB=[["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"}]],RB=ot("images",MB);const LB=[["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"}]],qg=ot("inbox",LB);const OB=[["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"}]],zB=ot("list-tree",OB);const GB=[["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"}]],Yg=ot("list",GB);const FB=[["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"}]],HB=ot("mail",FB);const BB=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],VB=ot("menu",BB);const $B=[["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"}]],pr=ot("message-circle",$B);const WB=[["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"}]],fr=ot("message-square-plus",WB);const UB=[["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"}]],oa=ot("messages-square",UB);const KB=[["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"}]],qB=ot("package-minus",KB);const YB=[["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"}]],Xg=ot("panel-left-close",YB);const XB=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],p1=ot("panel-left",XB);const JB=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],f1=ot("panel-right",JB);const ZB=[["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"}]],QB=ot("pause",ZB);const eV=[["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"}]],au=ot("pin-off",eV);const tV=[["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"}]],Si=ot("pin",tV);const nV=[["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"}]],sV=ot("repeat",nV);const iV=[["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"}]],Lo=ot("rotate-ccw-clock",iV);const oV=[["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"}]],Jg=ot("send",oV);const rV=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],aV=ot("skip-forward",rV);const lV=[["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"}]],m1=ot("square-dashed",lV);const cV=[["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"}]],g1=ot("square-pen",cV);const dV=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]],x1=ot("square-slash",dV);const uV=[["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"}]],hV=ot("square-x",uV);const pV=[["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"}]],fV=ot("tag",pV);const mV=[["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"}]],Sa=ot("target",mV);const gV=[["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"}]],v1=ot("text-search",gV);const xV=[["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"}]],ra=ot("undo-2",xV);const vV=[["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"}]],bV=ot("unfold-horizontal",vV);const wV=[["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"}]],yV=ot("user-minus",wV);const SV=[["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"}]],Ml=ot("user-plus",SV);const CV=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],kV=ot("user-round",CV);const _V=[["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"}]],jV=ot("wallet",_V);function b1(e){if(e.length===0)return;const t="0 0, 100% 0, 100% 100%, 0 100%, 0 0",n=e.map(s=>`${NV(s).map(([i,r])=>`${Cb(i)}px ${Cb(r)}px`).join(", ")}, 0 0`);return`polygon(evenodd, ${[t,...n].join(", ")})`}const Sb=6,Cb=e=>Math.round(e*100)/100;function NV({x:e,y:t,width:n,height:s,radius:i=0}){const r=e+n,a=t+s,l=Math.min(i,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:Sb+1},(f,x)=>{const g=(p+90*x/Sb)*Math.PI/180;return[u+l*Math.cos(g),h+l*Math.sin(g)]}));return[...d,d[0]]}const sp=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e;function TV(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,{status:n,originalCommand:s,rewrittenCommand:i,inputTokens:r,outputTokens:a,reason:l}=t;if(n!=="compressed"&&n!=="unchanged"&&n!=="pending"&&n!=="bypassed"&&n!=="unavailable"||typeof s!="string"||i!==void 0&&typeof i!="string"||l!==void 0&&typeof l!="string")return;const c={status:n,originalCommand:sp(s,16e3)};if(i!==void 0&&(c.rewrittenCommand=sp(i,16e3)),l!==void 0&&(c.reason=sp(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 IV=15e3;function DV(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}const PV=80,EV=300,AV=200,MV=/["[\]\n]/g;function ip(e,t){return typeof e!="string"?"":e.replace(MV," ").replace(/\s+/g," ").trim().slice(0,t)}function RV(e){const t=ip(e.label,PV),n=ip(e.path,EV),s=ip(e.text,AV);return`[Selected UI element "${t}" — path: ${n}; text: ${s}]`}const LV=/^\[Selected UI element "([^"]*)" — path: (.*); text: (.*)\]$/;function OV(e){const t=LV.exec(e);return t?{label:t[1],path:t[2],text:t[3]}:null}function zV(e,t){if(t.length===0)return[...e];const n=new Set(t);return e.filter(s=>!s.id||!n.has(s.id))}function kb(e,t){for(let n=t-1;n>=0;n--){const s=e[n];if(s==="@"){const i=n>0?e[n-1]:" ";return i===" "||i===`
14
- `?e.slice(n+1,t):null}if(s===" "||s===`
15
- `)return null}return null}function GV(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 FV(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 HV(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 BV=/^\[Referenced past chat "(.+)" — transcript file: (.+) \(pi session jsonl; read it if relevant\)\]$/,VV=/^@(\S.*)$/;function $V(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"?HV(t.label,t.sessionFile):RV(t)).join("")}function _b(e,t){cv.lastIndex=t,dv.lastIndex=t;const n=cv.exec(e),s=dv.exec(e),i=n?{index:n.index,length:n[0].length,segment:{type:"chat",label:n[1],sessionFile:n[2]}}:null,r=s?OV(s[0]):null,a=s&&r?{index:s.index,length:s[0].length,segment:{type:"ui-element",id:"",...r,imageId:""}}:null;return i&&a?i.index<=a.index?i:a:i??a}function WV(e){const t=[];let n=0,s=_b(e,0);for(;s;){const r=e.slice(n,s.index);for(const a of jb(r))a.type==="text"&&a.text===""||t.push(a);t.push(s.segment),n=s.index+s.length,s=_b(e,n)}const i=e.slice(n);if(i||t.length===0)for(const r of jb(i))r.type==="text"&&r.text===""&&t.length>0||t.push(r);return t}const UV=/^(?:[A-Za-z]:[\\/])?(?:[\p{L}\p{N}_./\\-]*\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\p{L}\p{N}_./\\-]+[\\/])$/u,KV=/^"([^"\n]*(?:\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\\/]))"/,qV=/#L\d+(?:-L\d+)?$/;function YV(e){return e.replace(qV,"")}function ih(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).at(-1)||e}function jb(e){return SC(e).flatMap(t=>t.type==="file"?[t]:XV(t.text))}function XV(e){const t=[];let n="",s=0;for(;s<e.length;){const i=e.indexOf("@",s);if(i===-1){n+=e.slice(s);break}const r=i>0?e[i-1]:" ",a=r===" "||r===`
16
- `?KV.exec(e.slice(i+1)):null;if(a){n+=e.slice(s,i),n&&(t.push({type:"text",text:n}),n=""),t.push({type:"file",path:a[1]}),s=i+1+a[0].length;continue}const c=(/^\S*/.exec(e.slice(i+1))?.[0]??"").replace(/[),.;!?]+$/,"");(r===" "||r===`
17
- `)&&c&&UV.test(c)?(n+=e.slice(s,i),n&&(t.push({type:"text",text:n}),n=""),t.push({type:"file",path:c}),s=i+1+c.length):(n+=e.slice(s,i+1),s=i+1)}return n&&t.push({type:"text",text:n}),t.length>0?t:[{type:"text",text:e}]}function JV(e){const t={body:e,files:[],chats:[]},n=e.split(`
18
- `),s=[],i=[];let r=n.length-1;for(;r>=0;r--){const a=n[r],l=BV.exec(a);if(l){i.unshift({label:l[1],sessionFile:l[2]});continue}if(VV.test(a)){s.unshift(a.slice(1));continue}break}return s.length+i.length===0||r<0||n[r].trim()!==""?t:{body:n.slice(0,r).join(`
19
- `).trimEnd(),files:s,chats:i}}function Nb(e){const t=$V(e.segments).trim(),n=e.segments.filter(s=>s.type!=="text").map(s=>s.type==="file"?{kind:"file",id:s.path,label:ih(s.path),relativePath:YV(s.path)}:s.type==="chat"?{kind:"chat",id:s.sessionFile,label:s.label,sessionFile:s.sessionFile}:{kind:"ui-element",id:s.id,label:s.label,path:s.path,text:s.text,imageId:s.imageId});return e.recipient&&n.push(e.recipient),{text:e.slash?t?`${e.slash} ${t}`:e.slash:t,images:e.images.map(({data:s,mimeType:i})=>({data:s,mimeType:i})),mentions:n,...e.recipient?{recipient:e.recipient}:{}}}const ZV={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 QV(){const e=xe(b=>b.backgroundImageEnabled),t=xe(b=>b.backgroundSourceType),n=xe(b=>b.backgroundImagePath),s=xe(b=>b.backgroundFolderPath),i=xe(b=>b.backgroundUrlPath),r=xe(b=>b.backgroundRandomEnabled),a=xe(b=>b.backgroundRandomInterval),l=xe(b=>b.backgroundBlur),c=xe(b=>b.backgroundBrightness),d=xe(b=>b.backgroundSaturation),u=xe(b=>b.backgroundMask),h=xe(b=>b.backgroundSizeMode),p=xe(b=>b.backgroundRefreshNonce),[f,x]=m.useState(0);m.useEffect(()=>{p>0&&x(b=>b+1)},[p]),m.useEffect(()=>{if(!e||!r||t==="file")return;const b=Math.max(5,a)*1e3,_=window.setInterval(()=>x(j=>j+1),b);return()=>window.clearInterval(_)},[e,r,a,t]);const[g,v]=m.useState([]);m.useEffect(()=>{if(!e||t!=="folder"||!s){v([]);return}let b=!1;return window.electronAPI.files.listMedia(s).then(_=>{b||v(_)}),()=>{b=!0}},[e,t,s,f]);const[w,y]=m.useState("");return m.useEffect(()=>{if(g.length===0){y("");return}y(b=>{if(g.length===1)return g[0];const _=g.filter(j=>j!==b);return _[Math.floor(Math.random()*_.length)]})},[g]),o.jsx(e$,{children:e&&o.jsx(t$,{state:{sourceType:t,imagePath:n,folderPick:w,urlPath:i,tick:f,blur:l,brightness:c,saturation:d,mask:u,sizeMode:h}})})}function e$({children:e}){const t=pn(s=>s.browserHoles),n=b1(Object.values(t));return o.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})}function t$({state:e}){const{sourceType:t,imagePath:n,folderPick:s,urlPath:i,tick:r,blur:a,brightness:l,saturation:c,mask:d,sizeMode:u}=e,h=m.useMemo(()=>{if(t==="file"&&n)return{src:Kp(n),video:Dh(n)};if(t==="folder"&&s)return{src:Kp(s),video:Dh(s)};if(t==="url"){const y=i.trim();if(/^https?:\/\//i.test(y))return{src:mP(y,r),video:Dh(y)}}return null},[t,n,s,i,r]),[p,f]=m.useState(null);if(m.useEffect(()=>{if(!h){f(null);return}if(h.video){f(h);return}let y=!1;const b=new Image;return b.onload=()=>{y||f(h)},b.src=h.src,()=>{y=!0}},[h]),!p)return null;const{src:x,video:g}=p,v=`blur(${a}px) brightness(${l}) saturate(${c})`,w=a>0?`-${a*2}px`:"0";return o.jsxs(o.Fragment,{children:[g?o.jsx("video",{src:x,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"absolute",style:{inset:w,width:"auto",height:"auto",minWidth:"100%",minHeight:"100%",objectFit:u==="contain"?"contain":"cover",filter:v,transition:"filter 0.3s ease"}},x):o.jsx("div",{className:"absolute",style:{inset:w,backgroundImage:`url("${x}")`,...ZV[u],filter:v,transition:"filter 0.3s ease"}},x),d>0&&o.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,d))*100)}%, transparent)`}})]})}function lu(e,t,n,s){return{left:e,top:t,right:n,bottom:s,x:e,y:t,width:n-e,height:s-t}}function n$(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function w1(e){const t=[];let n,s=Number.POSITIVE_INFINITY,i=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),i=Math.min(i,l.top),r=Math.max(r,l.right),a=Math.max(a,l.bottom),!n||l.top-n.top>n.height/2)t.push(n$(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:lu(s,i,r,a)}}function y1(e,t,n){return e.findIndex(s=>t>s.left-2&&t<s.right+2&&n>s.top-2&&n<s.bottom+2)}function Tb(e){return lu(e.left,e.top,e.right,e.bottom)}function s$(e,t,n){const{lines:s}=w1(e.getClientRects());if(s.length<2)return;const i=y1(s,t,n);return{x:t,y:n,lineIndex:i===-1?void 0:i,element:e}}function i$(e,t,n){const{lines:s,fallback:i}=w1(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 Tb(s[n.lineIndex]);if(r!=null&&a!=null){const x=y1(s,r,a);if(x!==-1)return Tb(s[x])}if(s.length===2&&s[0].left>s[1].right&&r!=null&&a!=null)return i;if(l==="t"||l==="b"){const x=s[0],g=s[s.length-1],v=l==="t"?x:g;return lu(v.left,x.top,v.right,g.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 x of s){d=Math.min(d,x.left),u=Math.max(u,x.right);const g=c?x.left:x.right;c&&g<h||!c&&g>h?(h=g,p=x,f=x):g===h&&(f=x)}return lu(d,p.top,u,f.bottom)}function o$(e){return"contextElement"in e&&e.contextElement?e.contextElement:gP(e)?e:void 0}function r$(e,t){function n(i){S1(e,i.currentTarget,i.clientX,i.clientY)}function s(i){t||n(i)}return{onFocus(){e.current=void 0},onMouseEnter:s,onMouseMove:s}}function S1(e,t,n,s){const i=s$(t,n,s);return e.current=i,i}function a$(e){return{name:"inline",async fn(t){const n=t.elements.reference;if(typeof n?.getClientRects!="function")return{};const s=o$(n),i=e.current,r=i?.element===n||i?.element===s?i:void 0,a=i$(n,t.placement,r);if(!a||typeof t.platform.getElementRects!="function")return{};const l=await t.platform.getElementRects({reference:{contextElement:s,getBoundingClientRect(){return a}},floating:t.elements.floating,strategy:t.strategy});return t.rects.reference.x===l.reference.x&&t.rects.reference.y===l.reference.y&&t.rects.reference.width===l.reference.width&&t.rects.reference.height===l.reference.height?{}:{reset:{rects:l}}}}}function Ib(){const{t:e}=te(),[t,n]=m.useState(null),[s,i]=m.useState(!1),[r,a]=m.useState(!1),[l,c]=m.useState(!1);if(m.useEffect(()=>{let p=!0;window.electronAPI.updater.getState().then(x=>p&&a(x.host==="desktop")).catch(()=>{});const f=window.electronAPI.updater.onStatus(x=>{n(x),x.status!=="checking"&&x.status!=="not-available"&&i(!1)});return()=>{p=!1,f()}},[]),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";return o.jsxs("div",{className:"border-b border-blue-500/20 bg-background",children:[o.jsxs("div",{className:"flex items-center gap-2 bg-blue-500/8 px-4 py-1.5 text-xs",children:[h?o.jsx(CC,{className:"h-3.5 w-3.5 shrink-0 text-blue-500"}):o.jsx(Xl,{className:"h-3.5 w-3.5 shrink-0 animate-pulse text-blue-500"}),o.jsx("span",{className:"min-w-0 flex-1",children: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)&&o.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&&o.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")}),h&&o.jsx("button",{type:"button",onClick:()=>{window.electronAPI.updater.quitAndInstall()},className:"shrink-0 rounded-md bg-primary px-2.5 py-1 text-primary-foreground transition-colors hover:bg-primary/90",children:e("Restart to update")}),o.jsx("button",{type:"button",onClick:()=>i(!0),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",title:e("Close"),children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]}),o.jsx(xP,{open:l,onOpenChange:c,status:t})]})}function l$(e,t){return[t,...e.filter(n=>n.parentId===t.id).sort((n,s)=>n.createdAt-s.createdAt)]}function c$(e,t){return(t.activeThreadId?e.find(s=>s.id===t.activeThreadId&&s.parentId===t.id):void 0)??t}const d$=10,C1=e=>[...e].sort((t,n)=>n.activityAt-t.activityAt);function k1(e,t,n=d$){const s=C1(e),i=a=>a.id===t.currentId||a.id===t.rootId?0:a.unread||a.running?1:2,r=new Set([...s].sort((a,l)=>i(a)-i(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 Db(e,t,n){const s=t.trim().toLowerCase();return C1(e).filter(i=>(n==="all"||(n==="unread"?i.unread:i.running))&&(!s||`${i.title}
20
- ${i.preview??""}`.toLowerCase().includes(s)))}function cu({onResize:e,onResizingChange:t,gap:n=!1,edge:s=!1}){const[i,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 o.jsxs("div",{className:q("relative shrink-0",s?"w-0":n?"w-[8px]":"w-px bg-border"),children:[o.jsx("div",{onMouseDown:l,className:q("absolute inset-y-0 z-10 cursor-col-resize","after:absolute after:inset-y-0 after:w-px after:transition-colors hover:after:bg-ring",s?"left-0 -right-1.5 after:left-0":n?"inset-x-0 after:left-1/2":"-left-1 -right-1 after:left-1",i&&"after:bg-ring")}),i&&o.jsx("div",{className:"fixed inset-0 z-50 cursor-col-resize"})]})}const u$={"external-send":"Protected: external send",delete:"Protected: delete",payment:"Protected: payment",deploy:"Protected: deploy / production",secret:"Protected: secrets",destructive:"Protected: destructive command"};function _1(e,t){return t(u$[e])}const j1={exec:"Isolated sandbox",codemode:"Isolated sandbox",tool_search:"Tool search",apply_patch:"Apply patch",explore_mark:"Explore mark",explore_fold:"Explore fold",subagent:"Subagent",workflow:"Workflow",ask_user:"Ask user",task_output:"Task output",task_stop:"Task stop",message_coworker:"Message coworker",message_main_agent:"Message main agent",enso_app:"Enso app",enso_capabilities:"Enso capabilities",recall:"Recall memory",memory_search:"Memory search",memory_capture:"Memory capture",memory_crystallize:"Memory crystallize",memory_delete:"Memory delete",browser_navigate:"Browser navigate",browser_snapshot:"Browser snapshot",browser_click:"Browser click",browser_type:"Browser type",browser_tabs:"Browser tabs",browser_lock:"Browser lock",browser_fill:"Browser fill",browser_press_key:"Browser press key",browser_scroll:"Browser scroll",browser_select_option:"Browser select option",browser_mouse_click_xy:"Browser click xy",browser_drag:"Browser drag",browser_highlight:"Browser highlight",browser_get_bounding_box:"Browser bounding box",browser_screenshot:"Browser screenshot",browser_cdp:"Browser CDP",web_search:"Web search",web_fetch:"Web fetch"};function aa(e,t){const n=j1[e];return n?t(n):e}const h$={report:"Read report",wait:"Wait",stop:"Stop",dismiss:"Dismiss agent",list:"List agents"};function N1(e,t=0){const[n,s]=m.useState(()=>Date.now());return m.useEffect(()=>{if(e===void 0)return;s(Date.now());const i=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(i)},[e]),e===void 0?void 0:e+t-n}function T1({remainingMs:e,expiredLabel:t}){const{t:n}=te();if(e===void 0)return null;if(e<=0)return o.jsx("span",{className:"shrink-0 text-[10px] text-warning",children:n(t)});const s=Math.ceil(e/1e3),i=`${Math.floor(s/60)}:${String(s%60).padStart(2,"0")}`;return o.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:n("{{time}} left",{time:i})})}const p$={command:Eo,"file-edit":cB,"file-write":uB,mcp:kC};function f$({kind:e,summary:t}){const[n,s]=m.useState(null);m.useEffect(()=>{if(e!=="command")return;let r=!0;return bP(t,"shellscript").then(a=>{r&&s(a)}),()=>{r=!1}},[e,t]);const i=o.jsx(_C,{text:t,className:"absolute top-1 right-1 z-10 rounded-md bg-background/80 p-1 text-muted-foreground backdrop-blur"});return e==="command"&&n!=null?o.jsxs("div",{className:"relative mt-1.5",children:[o.jsx("div",{className:"max-h-24 overflow-auto rounded-md text-xs leading-relaxed [&_pre]:m-0 [&_pre]:py-1.5 [&_pre]:pr-7 [&_pre]:pl-2 [&_pre]:font-mono [&_pre]:whitespace-pre-wrap",dangerouslySetInnerHTML:{__html:n}}),i]}):o.jsxs("div",{className:"relative mt-1.5",children:[o.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}),i]})}const m$={timeout:"Auto-managed review timed out. Please decide.",error:"Auto-managed review failed. Please decide.",invalid:"Auto-managed review returned no valid decision. Please decide."};function Rl({approvals:e,onRespond:t,allowSession:n=!0,handoff:s=!0,clockOffset:i}){const{t:r}=te(),[a,l]=m.useState(null),c=e[0],d=N1(c?.phase==="reviewing"?void 0:c?.expiresAt,i);if(!c)return null;const u=p$[c.kind]??Jr,h=c.phase==="reviewing",p=a===c.requestId||d!==void 0&&d<=0,f=x=>{x!=="review"&&l(c.requestId),t(c.requestId,x)};return o.jsxs("div",{className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx(Jr,{className:"h-3.5 w-3.5 shrink-0 text-amber-500"}),o.jsx("span",{className:"shrink-0 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:r(h?"Assistant reviewing…":"Approval required")}),o.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-muted-foreground",children:[o.jsx(u,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"truncate font-mono",children:c.toolCallId&&vP(c.toolCallId)?`${r("Isolated sandbox")} › ${aa(c.tool,r)}`:aa(c.tool,r)})]}),c.protected&&o.jsx("span",{className:"shrink-0 rounded bg-destructive/15 px-1.5 text-[10px] text-destructive",children:_1(c.protected,r)}),o.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[o.jsx(T1,{remainingMs:d,expiredLabel:"Timed out · denied"}),e.length>1&&o.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["1/",e.length]})]})]}),c.reviewFallback&&o.jsx("p",{className:"mt-1 text-[11px] text-amber-600 dark:text-amber-400",children:r(m$[c.reviewFallback])}),c.guard&&o.jsx("p",{className:"mt-1 text-[11px] text-destructive",title:c.guard.ruleId,children:r("dcg: {{reason}}",{reason:c.guard.reason})}),c.summary&&o.jsx(f$,{kind:c.kind,summary:c.summary}),!h&&o.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[s&&c.kind==="command"&&o.jsx("button",{type:"button",disabled:p,title:r("Send back for a safer command"),onClick:()=>f("revise"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Adjust")}),s&&o.jsx("button",{type:"button",disabled:p,title:r("Let the assistant decide"),onClick:()=>f("review"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Assistant review")}),o.jsx("button",{type:"button",disabled:p,onClick:()=>f("deny"),className:"rounded-md px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50",children:r("Deny")}),n&&!c.protected&&o.jsx("button",{type:"button",disabled:p,onClick:()=>f("allowSession"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Always allow this session")}),o.jsx("button",{type:"button",disabled:p,onClick:()=>f("allow"),className:"rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:r("Allow")})]})]})}function oh({asks:e,onAnswer:t,clockOffset:n,autoFocus:s=!0}){const{t:i}=te(),r=m.useRef(null),[a,l]=m.useState(""),[c,d]=m.useState(null),u=e[0],h=u?.requestId,p=N1(u?.expiresAt,n);if(m.useEffect(()=>{!s||!h||r.current?.focus()},[s,h]),!u)return null;const f=c===u.requestId||p!==void 0&&p<=0,x=g=>{g.trim()&&(d(u.requestId),l(""),t(u.requestId,g.trim()))};return o.jsxs("div",{className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",children:[o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(wP,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-blue-500"}),o.jsx("span",{className:"min-w-0 flex-1 text-xs leading-relaxed whitespace-pre-wrap",children:u.question}),o.jsx(T1,{remainingMs:p,expiredLabel:"Timed out · no answer"}),e.length>1&&o.jsxs("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:["1/",e.length]})]}),u.options&&u.options.length>0&&o.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:u.options.map(g=>o.jsx("button",{type:"button",disabled:f,onClick:()=>x(g),className:"rounded-md border border-border/60 px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:g},g))}),o.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[o.jsx("input",{ref:r,value:a,onChange:g=>l(g.target.value),onKeyDown:g=>{g.nativeEvent.isComposing||g.key==="Enter"&&x(a)},disabled:f,placeholder:i("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"}),o.jsx("button",{type:"button",disabled:f||!a.trim(),onClick:()=>x(a),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",children:o.jsx(Jg,{className:"h-3.5 w-3.5"})})]})]})}const rh=0,Oo=1,Ca=2,I1=4;function Pb(e){return()=>e}function g$(e){e()}function D1(e,t){return n=>e(t(n))}function Eb(e,t){return()=>e(t)}function x$(e,t){return n=>e(t,n)}function Zg(e){return e!==void 0}function v$(...e){return()=>{e.map(g$)}}function ka(){}function ah(e,t){return t(e),e}function b$(e,t){return t(e)}function Pn(...e){return e}function un(e,t){return e(Oo,t)}function Ot(e,t){e(rh,t)}function Qg(e){e(Ca)}function An(e){return e(I1)}function wt(e,t){return un(e,x$(t,rh))}function ci(e,t){const n=e(Oo,s=>{n(),t(s)});return n}function Ab(e){let t,n;return s=>i=>{t=i,n&&clearTimeout(n),n=setTimeout(()=>{s(t)},e)}}function P1(e,t){return e===t}function Dn(e=P1){let t;return n=>s=>{e(t,s)||(t=s,n(s))}}function It(e){return t=>n=>{e(n)&&t(n)}}function ut(e){return t=>D1(t,e)}function yi(e){return t=>()=>{t(e)}}function Fe(e,...t){const n=w$(...t);return((s,i)=>{switch(s){case Ca:Qg(e);return;case Oo:return un(e,n(i))}})}function Ti(e,t){return n=>s=>{n(t=e(t,s))}}function mr(e){return t=>n=>{e>0?e--:t(n)}}function so(e){let t=null,n;return s=>i=>{t=i,!n&&(n=setTimeout(()=>{n=void 0,s(t)},e))}}function $t(...e){const t=Array.from({length:e.length});let n=0,s=null;const i=2**e.length-1;return e.forEach((r,a)=>{const l=2**a;un(r,c=>{const d=n;n|=l,t[a]=c,d!==i&&n===i&&s&&(s(),s=null)})}),r=>a=>{const l=()=>{r([a].concat(t))};n===i?l():s=l}}function w$(...e){return t=>e.reduceRight(b$,t)}function y$(e){let t,n;const s=()=>t?.();return function(i,r){switch(i){case Oo:return r?n===r?void 0:(s(),n=r,t=un(e,r),t):(s(),ka);case Ca:s(),n=null;return}}}function Ye(e){let t=e;const n=Qt();return((s,i)=>{switch(s){case rh:t=i;break;case Oo:{i(t);break}case I1:return t}return n(s,i)})}function us(e,t){return ah(Ye(t),n=>wt(e,n))}function Qt(){const e=[];return((t,n)=>{switch(t){case rh:e.slice().forEach(s=>{s(n)});return;case Ca:e.splice(0);return;case Oo:return e.push(n),()=>{const s=e.indexOf(n);s>-1&&e.splice(s,1)}}})}function Rs(e){return ah(Qt(),t=>wt(e,t))}const S$={singleton:!0};function on(e,t=[],n=S$){const{singleton:s}=n;return{constructor:e,dependencies:t,id:C$(),singleton:s}}const C$=()=>Symbol("id");function k$(e){const t=new Map,n=({constructor:s,dependencies:i,id:r,singleton:a})=>{if(a&&t.has(r))return t.get(r);const l=s(i.map(c=>n(c)));return a&&t.set(r,l),l};return n(e)}function Hn(...e){const t=Qt(),n=Array.from({length:e.length});let s=0;const i=2**e.length-1;return e.forEach((r,a)=>{const l=2**a;un(r,c=>{n[a]=c,s|=l,s===i&&Ot(t,n)})}),function(r,a){switch(r){case Ca:{Qg(t);return}case Oo:return s===i&&a(n),un(t,a)}}}function Tt(e,t=P1){return Fe(e,Dn(t))}function Rf(...e){return function(t,n){switch(t){case Ca:return;case Oo:return v$(...e.map(s=>un(s,n)))}}}const Xn={DEBUG:0,INFO:1,WARN:2,ERROR:3},_$={[Xn.DEBUG]:"debug",[Xn.ERROR]:"error",[Xn.INFO]:"log",[Xn.WARN]:"warn"},j$=()=>typeof globalThis>"u"?window:globalThis,zo=on(()=>{const e=Ye(Xn.ERROR);return{log:Ye((t,n,s=Xn.INFO)=>{const i=j$().VIRTUOSO_LOG_LEVEL??An(e);s>=i&&console[_$[s]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function N$(e){return"self"in e?e.document.documentElement:e}function E1(e){const t=N$(e);return t.ownerDocument.defaultView.getComputedStyle(t).direction==="rtl"}function ir(e,t){return E1(e)?-t:t}function Mb(e,t){return E1(e)?-t:t}function vr(e,t,n){return ex(e,t,n).callbackRef}function ex(e,t,n){const s=Ce.useRef(null);let i=a=>{};const r=Ce.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 i=a=>{a&&t?(r?.observe(a),s.current=a):(s.current&&r?.unobserve(s.current),s.current=null)},{callbackRef:i,ref:s}}function T$(e,t,n,s,i,r,a,l,c){const d=Ce.useCallback(u=>{const h=I$(u.children,t,l?"offsetWidth":"offsetHeight",i);let p=u.parentElement;for(;p.dataset.virtuosoScroller===void 0;)p=p.parentElement;const f=p.lastElementChild?.dataset.viewportType==="window";let x;f&&(x=p.ownerDocument.defaultView);const g=a?l?a.scrollWidth:a.scrollHeight:f?l?x.document.documentElement.scrollWidth:x.document.documentElement.scrollHeight:l?p.scrollWidth:p.scrollHeight,v=a?l?a.offsetWidth:a.offsetHeight:f?l?x.innerWidth:x.innerHeight:l?p.offsetWidth:p.offsetHeight,w=a?l?ir(a,a.scrollLeft):a.scrollTop:f?l?ir(x,x.scrollX||x.document.documentElement.scrollLeft):x.scrollY||x.document.documentElement.scrollTop:l?ir(p,p.scrollLeft):p.scrollTop;s({scrollHeight:g,scrollTop:Math.max(w,0),viewportHeight:v}),r?.(l?Rb("column-gap",getComputedStyle(u).columnGap,i):Rb("row-gap",getComputedStyle(u).rowGap,i)),h!==null&&e(h)},[e,t,i,r,a,s,l]);return ex(d,n,c)}function I$(e,t,n,s){const i=e.length;if(i===0)return null;const r=[];for(let a=0;a<i;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},Xn.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 Rb(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,Xn.WARN),t==="normal"?0:parseInt(t??"0",10)}function A1(e,t,n){const s=Ce.useRef(null),i=Ce.useCallback(c=>{if(!c?.offsetParent)return;const d=c.getBoundingClientRect(),u=d.width;let h,p;if(t){const f=t.getBoundingClientRect(),x=d.top-f.top;p=f.height-Math.max(0,x),h=x+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}=ex(i,!0,n),l=Ce.useCallback(()=>{i(a.current)},[i,a]);return Ce.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 _s=on(()=>{const e=Qt(),t=Qt(),n=Ye(0),s=Qt(),i=Ye(0),r=Qt(),a=Qt(),l=Ye(0),c=Ye(0),d=Ye(0),u=Ye(0),h=Qt(),p=Qt(),f=Ye(!1),x=Ye(!1),g=Ye(!1);return wt(Fe(e,ut(({scrollTop:v})=>v)),t),wt(Fe(e,ut(({scrollHeight:v})=>v)),a),wt(t,i),{deviation:n,fixedFooterHeight:d,fixedHeaderHeight:c,footerHeight:u,headerHeight:l,horizontalDirection:x,scrollBy:p,scrollContainerState:e,scrollHeight:a,scrollingInProgress:f,scrollTo:h,scrollTop:t,skipAnimationFrameInResizeObserver:g,smoothScrollTargetReached:s,statefulScrollTop:i,viewportHeight:r}},[],{singleton:!0}),Ll={lvl:0};function M1(e,t){const n=e.length;if(n===0)return[];let{index:s,value:i}=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:i}),s=l,i=c}return r.push({end:1/0,start:s,value:i}),r}function mn(e){return e===Ll}function Ol(e,t){if(!mn(e))return t===e.k?e.v:t<e.k?Ol(e.l,t):Ol(e.r,t)}function pi(e,t,n="k"){if(mn(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const s=pi(e.r,t,n);return s[0]===-1/0?[e.k,e.v]:s}return pi(e.l,t,n)}function As(e,t,n){return mn(e)?O1(t,n,1):t===e.k?qn(e,{k:t,v:n}):t<e.k?Lb(qn(e,{l:As(e.l,t,n)})):Lb(qn(e,{r:As(e.r,t,n)}))}function Kr(){return Ll}function qr(e,t,n){if(mn(e))return[];const s=pi(e,t)[0];return D$(Of(e,s,n))}function Lf(e,t){if(mn(e))return Ll;const{k:n,l:s,r:i}=e;if(t===n){if(mn(s))return i;if(mn(i))return s;const[r,a]=L1(s);return _d(qn(e,{k:r,l:R1(s),v:a}))}return t<n?_d(qn(e,{l:Lf(s,t)})):_d(qn(e,{r:Lf(i,t)}))}function or(e){return mn(e)?[]:[...or(e.l),{k:e.k,v:e.v},...or(e.r)]}function Of(e,t,n){if(mn(e))return[];const{k:s,l:i,r,v:a}=e;let l=[];return s>t&&(l=l.concat(Of(i,t,n))),s>=t&&s<=n&&l.push({k:s,v:a}),s<=n&&(l=l.concat(Of(r,t,n))),l}function _d(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(op(t))return z1(qn(e,{lvl:n-1}));if(!mn(t)&&!mn(t.r))return qn(t.r,{l:qn(t,{r:t.r.l}),lvl:n,r:qn(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}if(op(e))return zf(qn(e,{lvl:n-1}));if(!mn(s)&&!mn(s.l)){const i=s.l,r=op(i)?s.lvl-1:s.lvl;return qn(i,{l:qn(e,{lvl:n-1,r:i.l}),lvl:i.lvl+1,r:zf(qn(s,{l:i.r,lvl:r}))})}throw new Error("Unexpected empty nodes")}function qn(e,t){return O1(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 R1(e){return mn(e.r)?e.l:_d(qn(e,{r:R1(e.r)}))}function op(e){return mn(e)||e.lvl>e.r.lvl}function L1(e){return mn(e.r)?[e.k,e.v]:L1(e.r)}function O1(e,t,n,s=Ll,i=Ll){return{k:e,l:s,lvl:n,r:i,v:t}}function Lb(e){return zf(z1(e))}function z1(e){const{l:t}=e;return!mn(t)&&t.lvl===e.lvl?qn(t,{r:qn(e,{l:t.r})}):e}function zf(e){const{lvl:t,r:n}=e;return!mn(n)&&!mn(n.r)&&n.lvl===t&&n.r.lvl===t?qn(n,{l:qn(e,{r:n.l}),lvl:t+1}):e}function D$(e){return M1(e,({k:t,v:n})=>({index:t,value:n}))}function G1(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function zl(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const tx=on(()=>({recalcInProgress:Ye(!1)}),[],{singleton:!0});function F1(e,t,n){return e[du(e,t,n)]}function du(e,t,n,s=0){let i=e.length-1;for(;s<=i;){const r=Math.floor((s+i)/2),a=e[r],l=n(a,t);if(l===0)return r;if(l===-1){if(i-s<2)return r-1;i=r-1}else{if(i===s)return r;s=r+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function P$(e,t,n,s){const i=du(e,t,s),r=du(e,n,s,i);return e.slice(i,r+1)}function Io(e,t){return Math.round(e.getBoundingClientRect()[t])}function lh(e){return!mn(e.groupOffsetTree)}function nx({index:e},t){return t===e?0:t<e?-1:1}function E$(){return{groupIndices:[],groupOffsetTree:Kr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Kr()}}function A$(e,t){let n=mn(e)?0:1/0;for(const s of t){const{endIndex:i,size:r,startIndex:a}=s;if(n=Math.min(n,a),mn(e)){e=As(e,0,r);continue}const l=qr(e,a-1,i+1);if(l.some(F$(s)))continue;let c=!1,d=!1;for(const{end:u,start:h,value:p}of l)c?(i>=h||r===p)&&(e=Lf(e,h)):(d=p!==r,c=!0),u>i&&i>=h&&p!==r&&(e=As(e,i+1,p));d&&(e=As(e,a,r))}return[e,n]}function M$(e){return e.groupIndex!==void 0}function R$({offset:e},t){return t===e?0:t<e?-1:1}function Gl(e,t,n){if(t.length===0)return 0;const{index:s,offset:i,size:r}=F1(t,e,nx),a=e-s,l=r*a+(a-1)*n+i;return l>0?l+n:l}function H1(e,t){if(!lh(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function B1(e,t,n){if(M$(e))return t.groupIndices[e.groupIndex]+1;const s=e.index==="LAST"?n:e.index;let i=H1(s,t);return i=Math.max(0,Math.min(n,i)),i}function L$(e,t,n,s=0){return s>0&&(t=Math.max(t,F1(e,s,nx).offset)),M1(P$(e,t,n,R$),G$)}function O$(e,[t,n,s,i]){t.length>0&&s("received item sizes",t,Xn.DEBUG);const r=e.sizeTree;let a=r,l=0;if(n.length>0&&mn(r)&&t.length===2){const p=t[0].size,f=t[1].size;a=n.reduce((x,g)=>As(As(x,g,p),g+1,f),a)}else[a,l]=A$(a,t);if(a===r)return e;const{lastIndex:c,lastOffset:d,lastSize:u,offsetTree:h}=Gf(e.offsetTree,l,a,i);return{groupIndices:n,groupOffsetTree:n.reduce((p,f)=>As(p,f,Gl(f,h,i)),Kr()),lastIndex:c,lastOffset:d,lastSize:u,offsetTree:h,sizeTree:a}}function z$(e){return or(e).map(({k:t,v:n},s,i)=>{const r=i[s+1];return{endIndex:r===void 0?1/0:r.k-1,size:n,startIndex:t}})}function Ob(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 Gf(e,t,n,s){let i=e,r=0,a=0,l=0,c=0;if(t===0)i=[];else{c=du(i,t-1,nx),l=i[c].offset;const d=pi(n,t-1);r=d[0],a=d[1],i.length&&i[c].size===pi(n,t)[1]&&(c-=1),i=i.slice(0,c+1)}for(const{start:d,value:u}of qr(n,t,1/0)){const h=d-r,p=h*a+l+h*s;i.push({index:d,offset:p,size:u}),r=d,l=p,a=u}return{lastIndex:r,lastOffset:l,lastSize:a,offsetTree:i}}function G$(e){return{index:e.index,value:e}}function F$(e){const{endIndex:t,size:n,startIndex:s}=e;return i=>i.start===s&&(i.end===t||i.end===1/0)&&i.value===n}const H$={offsetHeight:"height",offsetWidth:"width"},Hi=on(([{log:e},{recalcInProgress:t}])=>{const n=Qt(),s=Qt(),i=us(s,0),r=Qt(),a=Qt(),l=Ye(0),c=Ye([]),d=Ye(void 0),u=Ye(void 0),h=Ye(void 0),p=Ye(void 0),f=Ye((C,k)=>Io(C,H$[k])),x=Ye(void 0),g=Ye(0),v=E$(),w=us(Fe(n,$t(c,e,g),Ti(O$,v),Dn()),v),y=us(Fe(c,Dn(),Ti((C,k)=>({current:k,prev:C.current}),{current:[],prev:[]}),ut(({prev:C})=>C)),[]);wt(Fe(c,It(C=>C.length>0),$t(w,g),ut(([C,k,E])=>{const I=C.reduce((T,A,D)=>As(T,A,Gl(A,k.offsetTree,E)||D),Kr());return{...k,groupIndices:C,groupOffsetTree:I}})),w),wt(Fe(s,$t(w),It(([C,{lastIndex:k}])=>C<k),ut(([C,{lastIndex:k,lastSize:E}])=>[{endIndex:k,size:E,startIndex:C}])),n),wt(d,u);const b=us(Fe(d,ut(C=>C===void 0)),!0);wt(Fe(u,It(C=>C!==void 0&&mn(An(w).sizeTree)),ut(C=>{const k=An(h),E=An(c).length>0;return k!==void 0&&k!==0?E?[{endIndex:0,size:k,startIndex:0},{endIndex:1,size:C,startIndex:1}]:[]:[{endIndex:0,size:C,startIndex:0}]})),n),wt(Fe(p,It(C=>C!==void 0&&C.length>0&&mn(An(w).sizeTree)),ut(C=>{const k=[];let E=C[0],I=0;for(let T=1;T<C.length;T++){const A=C[T];A!==E&&(k.push({endIndex:T-1,size:E,startIndex:I}),E=A,I=T)}return k.push({endIndex:C.length-1,size:E,startIndex:I}),k})),n),wt(Fe(c,$t(h,u),It(([,C,k])=>C!==void 0&&k!==void 0),ut(([C,k,E])=>{const I=[];for(let T=0;T<C.length;T++){const A=C[T],D=C[T+1];I.push({startIndex:A,endIndex:A,size:k}),D!==void 0&&I.push({startIndex:A+1,endIndex:D-1,size:E})}return I})),n);const _=Rs(Fe(n,$t(w),Ti(({sizes:C},[k,E])=>({changed:E!==C,sizes:E}),{changed:!1,sizes:v}),ut(C=>C.changed)));un(Fe(l,Ti((C,k)=>({diff:C.prev-k,prev:k}),{diff:0,prev:0}),ut(C=>C.diff)),C=>{const{groupIndices:k}=An(w);if(C>0)Ot(t,!0),Ot(r,C+Ob(C,k));else if(C<0){const E=An(y);E.length>0&&(C-=Ob(-C,E)),Ot(a,C)}}),un(Fe(l,$t(e)),([C,k])=>{C<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},Xn.ERROR)});const j=Rs(r);wt(Fe(r,$t(w),ut(([C,k])=>{const E=k.groupIndices.length>0,I=[],T=k.lastSize;if(E){const A=Ol(k.sizeTree,0);let D=0,W=0;for(;D<C;){const O=k.groupIndices[W],B=k.groupIndices.length===W+1?1/0:k.groupIndices[W+1]-O-1;I.push({endIndex:O,size:A,startIndex:O}),I.push({endIndex:O+1+B-1,size:T,startIndex:O+1}),W++,D+=B+1}const J=or(k.sizeTree);return D!==C&&J.shift(),J.reduce((O,{k:B,v:L})=>{let se=O.ranges;return O.prevSize!==0&&(se=[...O.ranges,{endIndex:B+C-1,size:O.prevSize,startIndex:O.prevIndex}]),{prevIndex:B+C,prevSize:L,ranges:se}},{prevIndex:C,prevSize:0,ranges:I}).ranges}return or(k.sizeTree).reduce((A,{k:D,v:W})=>({prevIndex:D+C,prevSize:W,ranges:[...A.ranges,{endIndex:D+C-1,size:A.prevSize,startIndex:A.prevIndex}]}),{prevIndex:0,prevSize:T,ranges:[]}).ranges})),n);const N=Rs(Fe(a,$t(w,g),ut(([C,{offsetTree:k},E])=>{const I=-C;return Gl(I,k,E)})));return wt(Fe(a,$t(w,g),ut(([C,k,E])=>{if(k.groupIndices.length>0){if(mn(k.sizeTree))return k;let T=Kr();const A=An(y);let D=0,W=0,J=0;for(;D<-C;){J=A[W];const O=A[W+1]-J-1;W++,D+=O+1}if(T=or(k.sizeTree).reduce((O,{k:B,v:L})=>As(O,Math.max(0,B+C),L),T),D!==-C){const O=Ol(k.sizeTree,J);T=As(T,0,O);const B=pi(k.sizeTree,-C+1)[1];T=As(T,1,B)}return{...k,sizeTree:T,...Gf(k.offsetTree,0,T,E)}}const I=or(k.sizeTree).reduce((T,{k:A,v:D})=>As(T,Math.max(0,A+C),D),Kr());return{...k,sizeTree:I,...Gf(k.offsetTree,0,I,E)}})),w),{beforeUnshiftWith:j,data:x,defaultItemSize:u,firstItemIndex:l,fixedItemSize:d,fixedGroupSize:h,gap:g,groupIndices:c,heightEstimates:p,itemSize:f,listRefresh:_,shiftWith:a,shiftWithOffset:N,sizeRanges:n,sizes:w,statefulTotalCount:i,totalCount:s,trackItemSizes:b,unshiftWith:r}},Pn(zo,tx),{singleton:!0});function B$(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const V1=on(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:s,scrollTop:i}])=>{const r=Qt(),a=Qt(),l=Rs(Fe(r,ut(B$)));return wt(Fe(l,ut(c=>c.totalCount)),n),wt(Fe(l,ut(c=>c.groupIndices)),e),wt(Fe(Hn(i,t,s),It(([c,d])=>lh(d)),ut(([c,d,u])=>pi(d.groupOffsetTree,Math.max(c-u,0),"v")[0]),Dn(),ut(c=>[c])),a),{groupCounts:r,topItemsIndexes:a}},Pn(Hi,_s)),Go=on(([{log:e}])=>{const t=Ye(!1),n=Rs(Fe(t,It(s=>s),Dn()));return un(t,s=>{s&&An(e)("props updated",{},Xn.DEBUG)}),{didMount:n,propsReady:t}},Pn(zo),{singleton:!0}),V$=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function $1(e){const t=typeof e=="number"?{index:e}:{...e};return t.align||(t.align="start"),(!t.behavior||!V$)&&(t.behavior="auto"),t.offset===void 0&&(t.offset=0),t}const hc=on(([{gap:e,listRefresh:t,sizes:n,totalCount:s},{fixedFooterHeight:i,fixedHeaderHeight:r,footerHeight:a,headerHeight:l,scrollingInProgress:c,scrollTo:d,smoothScrollTargetReached:u,viewportHeight:h},{log:p}])=>{const f=Qt(),x=Qt(),g=Ye(0);let v=null,w=null,y=null;function b(){v!==null&&(v(),v=null),y!==null&&(y(),y=null),w&&(clearTimeout(w),w=null),Ot(c,!1)}return wt(Fe(f,$t(n,h,s,g,l,a,p),$t(e,r,i),ut(([[_,j,N,C,k,E,I,T],A,D,W])=>{const J=$1(_),{align:O,behavior:B,offset:L}=J,se=C-1,Q=B1(J,j,se);let V=Gl(Q,j.offsetTree,A)+E;O==="end"?(V+=D+pi(j.sizeTree,Q)[1]-N+W,Q===se&&(V+=I)):O==="center"?V+=(D+pi(j.sizeTree,Q)[1]-N+W)/2:V-=k,L!==void 0&&L!==0&&(V+=L);const H=ne=>{b(),ne?(T("retrying to scroll to",{location:_},Xn.DEBUG),Ot(f,_)):(Ot(x,!0),T("list did not change, scroll successful",{},Xn.DEBUG))};if(b(),B==="smooth"){let ne=!1;y=un(t,he=>{ne=ne||he}),v=ci(u,()=>{H(ne)})}else v=ci(Fe(t,$$(150)),H);return w=setTimeout(()=>{b()},1200),Ot(c,!0),T("scrolling from index to",{behavior:B,index:Q,top:V},Xn.DEBUG),{behavior:B,top:V}})),d),{scrollTargetReached:x,scrollToIndex:f,topListHeight:g}},Pn(Hi,_s,zo),{singleton:!0});function $$(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return s=>{s&&(t(!0),clearTimeout(n))}}}function sx(e,t){e===0?t():requestAnimationFrame(()=>{sx(e-1,t)})}function ix(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 Ff(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 pc=on(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:s},{scrollTargetReached:i,scrollToIndex:r},{didMount:a}])=>{const l=Ye(!0),c=Ye(0),d=Ye(!0);return wt(Fe(a,$t(c),It(([u,h])=>!Ff(h)),yi(!1)),l),wt(Fe(a,$t(c),It(([u,h])=>!Ff(h)),yi(!1)),d),un(Fe(Hn(t,a),$t(l,n,e,d),It(([[,u],h,{sizeTree:p},f,x])=>u&&(!mn(p)||Zg(f))&&!h&&!x),$t(c)),([,u])=>{if(u===void 0){Ot(l,!0),Ot(d,!0);return}ci(i,()=>{Ot(d,!0)}),sx(4,()=>{ci(s,()=>{Ot(l,!0)}),Ot(r,u)})}),{initialItemFinalLocationReached:d,initialTopMostItemIndex:c,scrolledToInitialItem:l}},Pn(Hi,_s,hc,Go),{singleton:!0});function W1(e,t){return Math.abs(e-t)<1.01}const Fl="up",ll="down",W$="none",U$={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},K$=0,fc=on(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:s,scrollTop:i,viewportHeight:r}])=>{const a=Ye(!1),l=Ye(!0),c=Qt(),d=Qt(),u=Ye(4),h=Ye(K$),p=us(Fe(Rf(Fe(Tt(i),mr(1),yi(!0)),Fe(Tt(i),mr(1),yi(!1),Ab(100))),Dn()),!1),f=us(Fe(Rf(Fe(n,yi(!0)),Fe(n,yi(!1),Ab(200))),Dn()),!1);wt(Fe(Hn(Tt(i),Tt(h)),ut(([y,b])=>y<=b),Dn()),l),wt(Fe(l,so(50)),d);const x=Rs(Fe(Hn(s,Tt(r),Tt(t),Tt(e),Tt(u)),Ti((y,[{scrollHeight:b,scrollTop:_},j,N,C,k])=>{const E=_+j-b>-k,I={scrollHeight:b,scrollTop:_,viewportHeight:j};if(E){let A,D;return _>y.state.scrollTop?(A="SCROLLED_DOWN",D=y.state.scrollTop-_):(A="SIZE_DECREASED",D=y.state.scrollTop-_||y.scrollTopDelta),{atBottom:!0,atBottomBecause:A,scrollTopDelta:D,state:I}}let T;return I.scrollHeight>y.state.scrollHeight?T="SIZE_INCREASED":j<y.state.viewportHeight?T="VIEWPORT_HEIGHT_DECREASING":_<y.state.scrollTop?T="SCROLLING_UPWARDS":T="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:T,state:I}},U$),Dn((y,b)=>y!==void 0&&y.atBottom===b.atBottom))),g=us(Fe(s,Ti((y,{scrollHeight:b,scrollTop:_,viewportHeight:j})=>{if(!W1(y.scrollHeight,b)){const N=b-(_+j)<1;return y.scrollTop!==_&&N?{changed:!0,jump:y.scrollTop-_,scrollHeight:b,scrollTop:_}:{changed:!0,jump:0,scrollHeight:b,scrollTop:_}}return{changed:!1,jump:0,scrollHeight:b,scrollTop:_}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),It(y=>y.changed),ut(y=>y.jump)),0);wt(Fe(x,ut(y=>y.atBottom)),a),wt(Fe(a,so(50)),c);const v=Ye(ll);wt(Fe(s,ut(({scrollTop:y})=>y),Dn(),Ti((y,b)=>An(f)?{direction:y.direction,prevScrollTop:b}:{direction:b<y.prevScrollTop?Fl:ll,prevScrollTop:b},{direction:ll,prevScrollTop:0}),ut(y=>y.direction)),v),wt(Fe(s,so(50),yi(W$)),v);const w=Ye(0);return wt(Fe(p,It(y=>!y),yi(0)),w),wt(Fe(i,so(100),$t(p),It(([y,b])=>b),Ti(([y,b],[_])=>[b,_],[0,0]),ut(([y,b])=>b-y)),w),{atBottomState:x,atBottomStateChange:c,atBottomThreshold:u,atTopStateChange:d,atTopThreshold:h,isAtBottom:a,isAtTop:l,isScrolling:p,lastJumpDueToItemResize:g,scrollDirection:v,scrollVelocity:w}},Pn(_s)),Hl="top",Bl="bottom",zb="none";function Gb(e,t,n){return typeof e=="number"?n===Fl&&t===Hl||n===ll&&t===Bl?e:0:n===Fl?t===Hl?e.main:e.reverse:t===Bl?e.main:e.reverse}function Fb(e,t){return typeof e=="number"?e:e[t]??0}const ox=on(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:s,viewportHeight:i}])=>{const r=Qt(),a=Ye(0),l=Ye(0),c=Ye(0),d=us(Fe(Hn(Tt(s),Tt(i),Tt(n),Tt(r,zl),Tt(c),Tt(a),Tt(t),Tt(e),Tt(l)),ut(([u,h,p,[f,x],g,v,w,y,b])=>{const _=u-y,j=v+w,N=Math.max(p-_,0);let C=zb;const k=Fb(b,Hl),E=Fb(b,Bl);return f-=y,f+=p+w,x+=p+w,x-=y,f>u+j-k&&(C=Fl),x<u-N+h+E&&(C=ll),C!==zb?[Math.max(_-p-Gb(g,Hl,C)-k,0),_-N-w+h+Gb(g,Bl,C)+E]:null}),It(u=>u!==null),Dn(zl)),[0,0]);return{increaseViewportBy:l,listBoundary:r,overscan:c,topListHeight:a,visibleRange:d}},Pn(_s),{singleton:!0});function q$(e,t,n){if(lh(t)){const s=H1(e,t);return[{index:pi(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 rp={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function jd(e,t,n,s,i,r){const{lastIndex:a,lastOffset:l,lastSize:c}=i;let d=0,u=0;if(e.length>0){d=e[0].offset;const g=e[e.length-1];u=g.offset+g.size}const h=n-a,p=l+h*c+(h-1)*s,f=d,x=p-u;return{bottom:u,firstItemIndex:r,items:Hb(e,i,r),offsetBottom:x,offsetTop:d,top:f,topItems:Hb(t,i,r),topListHeight:t.reduce((g,v)=>v.size+g,0),totalCount:n}}function U1(e,t,n,s,i,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=ix(t,l),d=Array.from({length:l}).map((u,h)=>({data:r[h+c],index:h+c,offset:0,size:0}));return jd(d,[],l,i,n,s)}function Hb(e,t,n){if(e.length===0)return[];if(!lh(t))return e.map(d=>({...d,index:d.index+n,originalIndex:d.index}));const s=e[0].index,i=e[e.length-1].index,r=[],a=qr(t.groupOffsetTree,s,i);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 Bb(e,t){return e===void 0?0:typeof e=="number"?e:e[t]??0}const br=on(([{data:e,firstItemIndex:t,gap:n,sizes:s,totalCount:i},r,{listBoundary:a,topListHeight:l,visibleRange:c},{initialTopMostItemIndex:d,scrolledToInitialItem:u},{topListHeight:h},p,{didMount:f},{recalcInProgress:x}])=>{const g=Ye([]),v=Ye(0),w=Qt(),y=Ye(0);wt(r.topItemsIndexes,g);const b=us(Fe(Hn(f,x,Tt(c,zl),Tt(i),Tt(s),Tt(d),u,Tt(g),Tt(t),Tt(n),Tt(y),e),It(([C,k,,E,,,,,,,,I])=>{const T=I!==void 0&&I.length!==E;return C&&!k&&!T}),ut(([,,[C,k],E,I,T,A,D,W,J,O,B])=>{const L=I,{offsetTree:se,sizeTree:Q}=L,V=An(v);if(E===0)return{...rp,totalCount:E};if(C===0&&k===0)return V===0?{...rp,totalCount:E}:U1(V,T,I,W,J,B||[]);if(mn(Q))return V>0?null:jd(q$(ix(T,E),L,B),[],E,J,L,W);const H=[];if(D.length>0){const F=D[0],U=D[D.length-1];let de=0;for(const Y of qr(Q,F,U)){const X=Y.value,z=Math.max(Y.start,F),ue=Math.min(Y.end,U);for(let _e=z;_e<=ue;_e++)H.push({data:B?.[_e],index:_e,offset:de,size:X}),de+=X}}if(!A)return jd([],H,E,J,L,W);const ne=D.length>0?D[D.length-1]+1:0,he=L$(se,C,k,ne);if(he.length===0)return null;const pe=E-1,ke=ah([],F=>{for(const U of he){const de=U.value;let Y=de.offset,X=U.start;const z=de.size;if(de.offset<C){X+=Math.floor((C-de.offset+J)/(z+J));const _e=X-U.start;Y+=_e*z+_e*J}X<ne&&(Y+=(ne-X)*z,X=ne);const ue=Math.min(U.end,pe);for(let _e=X;_e<=ue&&!(Y>=k);_e++)F.push({data:B?.[_e],index:_e,offset:Y,size:z}),Y+=z+J}}),Me=Bb(O,Hl),fe=Bb(O,Bl);if(ke.length>0&&(Me>0||fe>0)){const F=ke[0],U=ke[ke.length-1];if(Me>0&&F.index>ne){const de=Math.min(Me,F.index-ne),Y=[];let X=F.offset;for(let z=F.index-1;z>=F.index-de;z--){const ue=qr(Q,z,z)[0]?.value??F.size;X-=ue+J,Y.unshift({data:B?.[z],index:z,offset:X,size:ue})}ke.unshift(...Y)}if(fe>0&&U.index<pe){const de=Math.min(fe,pe-U.index);let Y=U.offset+U.size+J;for(let X=U.index+1;X<=U.index+de;X++){const z=qr(Q,X,X)[0]?.value??U.size;ke.push({data:B?.[X],index:X,offset:Y,size:z}),Y+=z+J}}}return jd(ke,H,E,J,L,W)}),It(C=>C!==null),Dn()),rp);wt(Fe(e,It(Zg),ut(C=>C?.length)),i),wt(Fe(b,ut(C=>C.topListHeight)),h),wt(h,l),wt(Fe(b,ut(C=>[C.top,C.bottom])),a),wt(Fe(b,ut(C=>C.items)),w);const _=Rs(Fe(b,It(({items:C})=>C.length>0),$t(i,e),It(([{items:C},k])=>C[C.length-1].originalIndex===k-1),ut(([,C,k])=>[C-1,k]),Dn(zl),ut(([C])=>C))),j=Rs(Fe(b,so(200),It(({items:C,topItems:k})=>C.length>0&&C[0].originalIndex===k.length),ut(({items:C})=>C[0].index),Dn())),N=Rs(Fe(b,It(({items:C})=>C.length>0),ut(({items:C})=>{let k=0,E=C.length-1;for(;C[k].type==="group"&&k<E;)k++;for(;C[E].type==="group"&&E>k;)E--;return{endIndex:C[E].index,startIndex:C[k].index}}),Dn(G1)));return{endReached:_,initialItemCount:v,itemsRendered:w,listState:b,minOverscanItemCount:y,rangeChanged:N,startReached:j,topItemsIndexes:g,...p}},Pn(Hi,V1,ox,pc,hc,fc,Go,tx),{singleton:!0}),K1=on(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:s},{listState:i}])=>{const r=Qt(),a=us(Fe(Hn(n,e,s,t,i),ut(([l,c,d,u,h])=>l+c+d+u+h.offsetBottom+h.bottom)),0);return wt(Tt(a),r),{totalListHeight:a,totalListHeightChanged:r}},Pn(_s,br),{singleton:!0}),Y$=on(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Ye(!1),s=us(Fe(Hn(n,e,t),It(([i])=>i),ut(([,i,r])=>Math.max(0,i-r)),so(0),Dn()),0);return{alignToBottom:n,paddingTopAddition:s}},Pn(_s,K1),{singleton:!0}),q1=on(()=>({context:Ye(null)})),X$=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:s,...i},viewportBottom:r,viewportTop:a})=>t<a?{...i,align:n??"start",...s===void 0?{}:{behavior:s}}:e>r?{...i,align:n??"end",...s===void 0?{}:{behavior:s}}:null,Y1=on(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:s,fixedHeaderHeight:i,headerHeight:r,scrollingInProgress:a,scrollTop:l,viewportHeight:c},{scrollToIndex:d}])=>{const u=Qt();return wt(Fe(u,$t(t,c,n,r,i,s,l),$t(e),ut(([[h,p,f,x,g,v,w,y],b])=>{const{calculateViewLocation:_=X$,done:j,...N}=h,C=B1(h,p,x-1),k=Gl(C,p.offsetTree,b)+g+v,E=k+pi(p.sizeTree,C)[1],I=y+v,T=y+f-w,A=_({itemBottom:E,itemTop:k,locationParams:N,viewportBottom:T,viewportTop:I});return A===null?j?.():j&&ci(Fe(a,It(D=>!D),mr(An(a)?1:2)),j),A}),It(h=>h!==null)),d),{scrollIntoView:u}},Pn(Hi,_s,hc,br,zo),{singleton:!0});function Vb(e){return e===!1?!1:e==="smooth"?"smooth":"auto"}const J$=(e,t)=>typeof e=="function"?Vb(e(t)):t&&Vb(e),Z$=on(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:s},{atBottomState:i,isAtBottom:r},{scrollToIndex:a},{scrolledToInitialItem:l},{didMount:c,propsReady:d},{log:u},{scrollingInProgress:h},{context:p},{scrollIntoView:f}])=>{const x=Ye(!1),g=Qt();let v=null;function w(j){Ot(a,{align:"end",behavior:j,index:"LAST"})}un(Fe(Hn(Fe(Tt(t),mr(1)),c),$t(Tt(x),r,l,h),ut(([[j,N],C,k,E,I])=>{let T=N&&E,A="auto";return T&&(A=J$(C,k||I),T=T&&A!==!1),{followOutputBehavior:A,shouldFollow:T,totalCount:j}}),It(({shouldFollow:j})=>j)),({followOutputBehavior:j,totalCount:N})=>{v!==null&&(v(),v=null),An(n)===void 0?v=ci(e,()=>{An(u)("following output to ",{totalCount:N},Xn.DEBUG),w(j),v=null}):requestAnimationFrame(()=>{An(u)("following output to ",{totalCount:N},Xn.DEBUG),w(j)})});function y(j){const N=ci(i,C=>{j&&!C.atBottom&&C.notAtBottomBecause==="SIZE_INCREASED"&&v===null&&(An(u)("scrolling to bottom due to increased size",{},Xn.DEBUG),w("auto"))});setTimeout(N,100)}un(Fe(Hn(Tt(x),t,d),It(([j,,N])=>j!==!1&&N),Ti(({value:j},[,N])=>({refreshed:j===N,value:N}),{refreshed:!1,value:0}),It(({refreshed:j})=>j),$t(x,t)),([,j])=>{An(l)&&y(j!==!1)}),un(g,()=>{y(An(x)!==!1)}),un(Hn(Tt(x),i),([j,N])=>{j!==!1&&!N.atBottom&&N.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&w("auto")});const b=Ye(null),_=Qt();return wt(Rf(Fe(Tt(s),ut(j=>j?.length??0)),Fe(Tt(t))),_),un(Fe(Hn(Fe(_,mr(1)),c),$t(Tt(b),l,h,p),ut(([[j,N],C,k,E,I])=>N&&k&&C?.({context:I,totalCount:j,scrollingInProgress:E})),It(j=>!!j),so(0)),j=>{v!==null&&(v(),v=null),An(n)===void 0?v=ci(e,()=>{An(u)("scrolling into view",{}),Ot(f,j),v=null}):requestAnimationFrame(()=>{An(u)("scrolling into view",{}),Ot(f,j)})}),{autoscrollToBottom:g,followOutput:x,scrollIntoViewOnChange:b}},Pn(Hi,fc,hc,pc,Go,zo,_s,q1,Y1)),Q$=on(([{data:e,firstItemIndex:t,gap:n,sizes:s},{initialTopMostItemIndex:i},{initialItemCount:r,listState:a},{didMount:l}])=>(wt(Fe(l,$t(r),It(([,c])=>c!==0),$t(i,s,t,n,e),ut(([[,c],d,u,h,p,f=[]])=>U1(c,d,u,h,p,f))),a),{}),Pn(Hi,pc,br,Go),{singleton:!0}),e6=on(([{didMount:e},{scrollTo:t},{listState:n}])=>{const s=Ye(0);return un(Fe(e,$t(s),It(([,i])=>i!==0),ut(([,i])=>({top:i}))),i=>{ci(Fe(n,mr(1),It(r=>r.items.length>1)),()=>{requestAnimationFrame(()=>{Ot(t,i)})})}),{initialScrollTop:s}},Pn(Go,_s,br),{singleton:!0}),X1=on(([{scrollVelocity:e}])=>{const t=Ye(!1),n=Qt(),s=Ye(!1);return wt(Fe(e,$t(s,t,n),It(([i,r])=>r!==!1&&r!==void 0),ut(([i,r,a,l])=>{const{enter:c,exit:d}=r;if(a){if(d(i,l))return!1}else if(c(i,l))return!0;return a}),Dn()),t),un(Fe(Hn(t,e,n),$t(s)),([[i,r,a],l])=>{i&&l!==!1&&l!==void 0&&l.change&&l.change(r,a)}),{isSeeking:t,scrollSeekConfiguration:s,scrollSeekRangeChanged:n,scrollVelocity:e}},Pn(fc),{singleton:!0}),rx=on(([{scrollContainerState:e,scrollTo:t}])=>{const n=Qt(),s=Qt(),i=Qt(),r=Ye(!1),a=Ye(void 0);return wt(Fe(Hn(n,s),ut(([{scrollTop:l,viewportHeight:c},{offsetTop:d,listHeight:u}])=>({scrollHeight:u,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),wt(Fe(t,$t(s),ut(([l,{offsetTop:c}])=>({...l,top:l.top+c}))),i),{customScrollParent:a,useWindowScroll:r,windowScrollContainerState:n,windowScrollTo:i,windowViewportRect:s}},Pn(_s)),t6=on(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:s},{initialTopMostItemIndex:i},{didMount:r},{useWindowScroll:a,windowScrollContainerState:l,windowViewportRect:c}])=>{const d=Qt(),u=Ye(void 0),h=Ye(null),p=Ye(null);return wt(l,h),wt(c,p),un(Fe(d,$t(t,s,a,h,p,n)),([f,x,g,v,w,y,b])=>{const _=z$(x.sizeTree);v&&w!==null&&y!==null&&(g=w.scrollTop-y.offsetTop),g-=b,f({ranges:_,scrollTop:g})}),wt(Fe(u,It(Zg),ut(n6)),i),wt(Fe(r,$t(u),It(([,f])=>f!==void 0),Dn(),ut(([,f])=>f.ranges)),e),{getState:d,restoreStateFrom:u}},Pn(Hi,_s,pc,Go,rx));function n6(e){return{align:"start",index:0,offset:e.scrollTop}}const s6=on(([{topItemsIndexes:e}])=>{const t=Ye(0);return wt(Fe(t,It(n=>n>=0),ut(n=>Array.from({length:n}).map((s,i)=>i))),e),{topItemCount:t}},Pn(br));function J1(e){let t=!1,n;return(()=>(t||(t=!0,n=e()),n))}const i6=J1(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),o6=on(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:s},{isAtBottom:i,isScrolling:r,lastJumpDueToItemResize:a,scrollDirection:l},{listState:c},{beforeUnshiftWith:d,gap:u,shiftWithOffset:h,sizes:p},{log:f},{recalcInProgress:x}])=>{const g=Rs(Fe(c,$t(a),Ti(([,w,y,b],[{bottom:_,items:j,offsetBottom:N,totalCount:C},k])=>{const E=_+N;let I=0;return y===C&&w.length>0&&j.length>0&&(j[0].originalIndex===0&&w[0].originalIndex===0||(I=E-b,I!==0&&(I+=k))),[I,j,C,E]},[0,[],0,0]),It(([w])=>w!==0),$t(s,l,n,i,f,x),It(([,w,y,b,,,_])=>!_&&!b&&w!==0&&y===Fl),ut(([[w],,,,,y])=>(y("Upward scrolling compensation",{amount:w},Xn.DEBUG),w))));function v(w){w>0?(Ot(t,{behavior:"auto",top:-w}),Ot(e,0)):(Ot(e,0),Ot(t,{behavior:"auto",top:-w}))}return un(Fe(g,$t(e,r)),([w,y,b])=>{b&&i6()?Ot(e,y-w):v(-w)}),un(Fe(Hn(us(r,!1),e,x),It(([w,y,b])=>!w&&!b&&y!==0),ut(([w,y])=>y),so(1)),v),wt(Fe(h,ut(w=>({top:-w}))),t),un(Fe(d,$t(p,u),ut(([w,{groupIndices:y,lastSize:b,sizeTree:_},j])=>{function N(T){return T*(b+j)}if(y.length===0)return N(w);let C=0;const k=Ol(_,0);let E=0,I=0;for(;E<w;){E++,C+=k;let T=y.length===I+1?1/0:y[I+1]-y[I]-1;E+T>w&&(C-=k,T=w-E+1),E+=T,C+=N(T),I++}return C})),w=>{Ot(e,w),requestAnimationFrame(()=>{Ot(t,{top:w}),requestAnimationFrame(()=>{Ot(e,0),Ot(x,!1)})})}),{deviation:e}},Pn(_s,fc,br,Hi,zo,tx)),r6=on(([e,t,n,s,i,r,a,l,c,d,u])=>({...e,...t,...n,...s,...i,...r,...a,...l,...c,...d,...u}),Pn(ox,Q$,Go,X1,K1,e6,Y$,rx,Y1,zo,q1)),Z1=on(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:s,fixedGroupSize:i,gap:r,groupIndices:a,heightEstimates:l,itemSize:c,sizeRanges:d,sizes:u,statefulTotalCount:h,totalCount:p,trackItemSizes:f},{initialItemFinalLocationReached:x,initialTopMostItemIndex:g,scrolledToInitialItem:v},w,y,b,_,{scrollToIndex:j},N,{topItemCount:C},{groupCounts:k},E])=>{const{listState:I,minOverscanItemCount:T,topItemsIndexes:A,rangeChanged:D,...W}=_;return wt(D,E.scrollSeekRangeChanged),wt(Fe(Hn(E.windowViewportRect,w.headerHeight,w.fixedHeaderHeight),ut(([J,O,B])=>Math.max(O+B+1,J.visibleHeight))),w.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:s,fixedGroupHeight:i,gap:r,groupCounts:k,heightEstimates:l,initialItemFinalLocationReached:x,initialTopMostItemIndex:g,scrolledToInitialItem:v,sizeRanges:d,topItemCount:C,topItemsIndexes:A,totalCount:p,...b,groupIndices:a,itemSize:c,listState:I,minOverscanItemCount:T,scrollToIndex:j,statefulTotalCount:h,trackItemSizes:f,rangeChanged:D,...W,...E,...w,sizes:u,...y}},Pn(Hi,pc,_s,t6,Z$,br,hc,o6,s6,V1,r6));function a6(e,t){const n={},s={};let i=0;const r=e.length;for(;i<r;)s[e[i]]=1,i+=1;for(const a in t)Object.hasOwn(s,a)||(n[a]=t[a]);return n}const Nc=typeof document>"u"?Ce.useEffect:Ce.useLayoutEffect;function Q1(e,t,n){const s=Object.keys(t.required||{}),i=Object.keys(t.optional||{}),r=Object.keys(t.methods||{}),a=Object.keys(t.events||{}),l=Ce.createContext({});function c(v,w){v.propsReady!==void 0&&Ot(v.propsReady,!1);for(const y of s){const b=v[t.required[y]];Ot(b,w[y])}for(const y of i)if(y in w){const b=v[t.optional[y]];Ot(b,w[y])}v.propsReady!==void 0&&Ot(v.propsReady,!0)}function d(v){return r.reduce((w,y)=>(w[y]=b=>{const _=v[t.methods[y]];Ot(_,b)},w),{})}function u(v){return a.reduce((w,y)=>(w[y]=y$(v[t.events[y]]),w),{})}const h=Ce.forwardRef(function(v,w){const{children:y,...b}=v,[_]=Ce.useState(()=>ah(k$(e),C=>{c(C,b)})),[j]=Ce.useState(Eb(u,_));Nc(()=>{for(const C of a)C in b&&un(j[C],b[C]);return()=>{Object.values(j).map(Qg)}},[b,j,_]),Nc(()=>{c(_,b)}),Ce.useImperativeHandle(w,Pb(d(_)));const N=n;return o.jsx(l.Provider,{value:_,children:n===void 0?y:o.jsx(N,{...a6([...s,...i,...a],b),children:y})})}),p=v=>{const w=Ce.useContext(l);return Ce.useCallback(y=>{Ot(w[v],y)},[w,v])},f=v=>{const w=Ce.useContext(l)[v],y=Ce.useCallback(b=>un(w,b),[w]);return Ce.useSyncExternalStore(y,()=>An(w),()=>An(w))},x=v=>{const w=Ce.useContext(l)[v],[y,b]=Ce.useState(Eb(An,w));return Nc(()=>un(w,_=>{_!==y&&b(Pb(_))}),[w,y]),y},g=parseInt(Ce.version,10)>=18?f:x;return{Component:h,useEmitter:(v,w)=>{const y=Ce.useContext(l)[v];Nc(()=>un(y,w),[w,y])},useEmitterValue:g,usePublisher:p}}const eN=Ce.createContext(void 0),tN=Ce.createContext(void 0),ap="-webkit-sticky",$b="sticky",ax=J1(()=>{if(typeof document>"u")return $b;const e=document.createElement("div");return e.style.position=ap,e.style.position===ap?ap:$b}),nN=typeof document>"u"?Ce.useEffect:Ce.useLayoutEffect;function lp(e){return"self"in e}function l6(e){return"body"in e}function sN(e,t,n,s=ka,i,r){const a=Ce.useRef(null),l=Ce.useRef(null),c=Ce.useRef(null),d=Ce.useCallback(p=>{let f,x,g;const v=p.target;if(l6(v)||lp(v)){const y=lp(v)?v:v.defaultView;g=r===!0?ir(y,y.scrollX):y.scrollY,f=r===!0?y.document.documentElement.scrollWidth:y.document.documentElement.scrollHeight,x=r===!0?y.innerWidth:y.innerHeight}else g=r===!0?ir(v,v.scrollLeft):v.scrollTop,f=r===!0?v.scrollWidth:v.scrollHeight,x=r===!0?v.offsetWidth:v.offsetHeight;const w=()=>{e({scrollHeight:f,scrollTop:Math.max(g,0),viewportHeight:x})};p.suppressFlushSync===!0?w():jC.flushSync(w),l.current!==null&&(g===l.current||g<=0||g===f-x)&&(l.current=null,t(!0),c.current&&(clearTimeout(c.current),c.current=null))},[e,t,r]);Ce.useEffect(()=>{const p=i??a.current;return s(i??a.current),d({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",d,{passive:!0}),()=>{s(null),p.removeEventListener("scroll",d)}},[a,d,n,s,i]);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 x=p.behavior==="smooth";let g,v,w;lp(f)?(v=Math.max(Io(f.document.documentElement,r===!0?"width":"height"),r===!0?f.document.documentElement.scrollWidth:f.document.documentElement.scrollHeight),g=r===!0?f.innerWidth:f.innerHeight,w=r===!0?ir(f,f.scrollX):f.scrollY):(v=f[r===!0?"scrollWidth":"scrollHeight"],g=Io(f,r===!0?"width":"height"),w=r===!0?ir(f,f.scrollLeft):f.scrollTop);const y=v-g;if(p.top===void 0){f.scrollTo(p);return}const b=Math.ceil(Math.max(Math.min(y,p.top),0));if(p.top=b,W1(g,v)||b===w){e({scrollHeight:v,scrollTop:w,viewportHeight:g}),x&&t(!0);return}x?(l.current=b,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:Mb(f,b)}),f.scrollTo(p)}function h(p){r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},...p.top===void 0?{}:{left:Mb(a.current,p.top)}}),a.current.scrollBy(p)}return{scrollByCallback:h,scrollerRef:a,scrollToCallback:u}}function lx(e){return e}const c6=on(()=>{const e=Ye(l=>`Item ${l}`),t=Ye(l=>`Group ${l}`),n=Ye({}),s=Ye(lx),i=Ye("div"),r=Ye(ka),a=(l,c=null)=>us(Fe(n,ut(d=>d[l]),Dn()),c);return{components:n,computeItemKey:s,EmptyPlaceholder:a("EmptyPlaceholder"),FooterComponent:a("Footer"),GroupComponent:a("Group","div"),groupContent:t,HeaderComponent:a("Header"),HeaderFooterTag:i,ItemComponent:a("Item","div"),itemContent:e,ListComponent:a("List","div"),ScrollerComponent:a("Scroller","div"),scrollerRef:r,ScrollSeekPlaceholder:a("ScrollSeekPlaceholder"),TopItemListComponent:a("TopItemList")}}),d6=on(([e,t])=>({...e,...t}),Pn(Z1,c6)),u6=({height:e})=>o.jsx("div",{style:{height:e}}),h6={overflowAnchor:"none",position:ax(),zIndex:1},iN={overflowAnchor:"none"},p6={...iN,display:"inline-block",height:"100%"},Wb=Ce.memo(function({showTopList:e=!1}){const t=Pt("listState"),n=$s("sizeRanges"),s=Pt("useWindowScroll"),i=Pt("customScrollParent"),r=$s("windowScrollContainerState"),a=$s("scrollContainerState"),l=i||s?r:a,c=Pt("itemContent"),d=Pt("context"),u=Pt("groupContent"),h=Pt("trackItemSizes"),p=Pt("itemSize"),f=Pt("log"),x=$s("gap"),g=Pt("horizontalDirection"),{callbackRef:v}=T$(n,p,h,e?ka:l,f,x,i,g,Pt("skipAnimationFrameInResizeObserver")),[w,y]=Ce.useState(0);dx("deviation",W=>{w!==W&&y(W)});const b=Pt("EmptyPlaceholder"),_=Pt("ScrollSeekPlaceholder")??u6,j=Pt("ListComponent"),N=Pt("ItemComponent"),C=Pt("GroupComponent"),k=Pt("computeItemKey"),E=Pt("isSeeking"),I=Pt("groupIndices").length>0,T=Pt("alignToBottom"),A=Pt("initialItemFinalLocationReached"),D=e?{}:{boxSizing:"border-box",...g?{display:"inline-block",height:"100%",marginInlineStart:w===0?T?"auto":0:w,paddingInlineEnd:t.offsetBottom,paddingInlineStart:t.offsetTop,whiteSpace:"nowrap"}:{marginTop:w===0?T?"auto":0:w,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...A?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&b!==null&&b!==void 0?o.jsx(b,{...ds(b,d)}):o.jsx(j,{...ds(j,d),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:D,children:(e?t.topItems:t.items).map(W=>{const J=W.originalIndex,O=k(J+t.firstItemIndex,W.data,d);return E?m.createElement(_,{...ds(_,d),height:W.size,index:W.index,key:O,type:W.type||"item",...W.type==="group"?{}:{groupIndex:W.groupIndex}}):W.type==="group"?m.createElement(C,{...ds(C,d),"data-index":J,"data-item-index":W.index,"data-known-size":W.size,key:O,style:h6},u(W.index,d)):m.createElement(N,{...ds(N,d),...x6(N,W.data),"data-index":J,"data-item-group-index":W.groupIndex,"data-item-index":W.index,"data-known-size":W.size,key:O,style:g?p6:iN},I?c(W.index,W.groupIndex,W.data,d):c(W.index,W.data,d))})})}),f6={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},m6={outline:"none",overflowX:"auto",position:"relative"},cx=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:void 0}),oN=(e,t,n=0)=>({...cx(e),position:t?"relative":"absolute",top:t?-n:0}),g6={position:ax(),top:0,width:"100%",zIndex:1};function ds(e,t){if(typeof e!="string")return{context:t}}function x6(e,t){return{item:typeof e=="string"?void 0:t}}const v6=Ce.memo(function(){const e=Pt("HeaderComponent"),t=$s("headerHeight"),n=Pt("HeaderFooterTag"),s=vr(Ce.useMemo(()=>r=>{t(Io(r,"height"))},[t]),!0,Pt("skipAnimationFrameInResizeObserver")),i=Pt("context");return e!=null?o.jsx(n,{ref:s,children:o.jsx(e,{...ds(e,i)})}):null}),b6=Ce.memo(function(){const e=Pt("FooterComponent"),t=$s("footerHeight"),n=Pt("HeaderFooterTag"),s=vr(Ce.useMemo(()=>r=>{t(Io(r,"height"))},[t]),!0,Pt("skipAnimationFrameInResizeObserver")),i=Pt("context");return e!=null?o.jsx(n,{ref:s,children:o.jsx(e,{...ds(e,i)})}):null});function rN({useEmitter:e,useEmitterValue:t,usePublisher:n}){return Ce.memo(function({children:s,style:i,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:x}=sN(l,d,c,u,void 0,h);return e("scrollTo",x),e("scrollBy",p),o.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:f,style:{...h?m6:f6,...i},tabIndex:0,...a,...ds(c,r),children:s})})}function aN({useEmitter:e,useEmitterValue:t,usePublisher:n}){return Ce.memo(function({children:s,style:i,context:r,...a}){const l=n("windowScrollContainerState"),c=t("ScrollerComponent"),d=n("smoothScrollTargetReached"),u=t("totalListHeight"),h=t("deviation"),p=t("customScrollParent"),f=Ce.useRef(null),x=t("scrollerRef"),{scrollByCallback:g,scrollerRef:v,scrollToCallback:w}=sN(l,d,c,x,p);return nN(()=>(v.current=p??f.current?.ownerDocument.defaultView,()=>{v.current=null}),[v,p]),e("windowScrollTo",w),e("scrollBy",g),o.jsx(c,{ref:f,"data-virtuoso-scroller":!0,style:{position:"relative",...i,...u===0?void 0:{height:u+h}},...a,...ds(c,r),children:s})})}const w6=({children:e})=>{const t=Ce.useContext(eN),n=$s("viewportHeight"),s=$s("fixedItemHeight"),i=Pt("alignToBottom"),r=Pt("horizontalDirection"),a=Ce.useMemo(()=>D1(n,c=>Io(c,r?"width":"height")),[n,r]),l=vr(a,!0,Pt("skipAnimationFrameInResizeObserver"));return Ce.useEffect(()=>{t&&(n(t.viewportHeight),s(t.itemHeight))},[t,n,s]),o.jsx("div",{"data-viewport-type":"element",ref:l,style:cx(i),children:e})},y6=({children:e})=>{const t=Ce.useContext(eN),n=$s("windowViewportRect"),s=$s("fixedItemHeight"),i=Pt("customScrollParent"),r=Pt("useWindowScroll"),a=Pt("topListHeight"),l=A1(n,i,Pt("skipAnimationFrameInResizeObserver")),c=Pt("alignToBottom");return Ce.useEffect(()=>{t&&(s(t.itemHeight),n({listHeight:0,offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,s]),o.jsx("div",{"data-viewport-type":"window",ref:l,style:oN(c,r,a),children:e})},S6=({children:e})=>{const t=Pt("TopItemListComponent")??"div",n=Pt("headerHeight"),s={...g6,marginTop:`${n}px`},i=Pt("context");return o.jsx(t,{style:s,...ds(t,i),children:e})},C6=Ce.memo(function(e){const t=Pt("useWindowScroll"),n=Pt("topItemsIndexes").length>0,s=Pt("customScrollParent"),i=Pt("context");return o.jsxs(s||t?j6:_6,{...e,context:i,children:[n&&o.jsx(S6,{children:o.jsx(Wb,{showTopList:!0})}),o.jsxs(s||t?y6:w6,{children:[o.jsx(v6,{}),o.jsx(Wb,{}),o.jsx(b6,{})]})]})}),{Component:k6,useEmitter:dx,useEmitterValue:Pt,usePublisher:$s}=Q1(d6,{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"}},C6),_6=rN({useEmitter:dx,useEmitterValue:Pt,usePublisher:$s}),j6=aN({useEmitter:dx,useEmitterValue:Pt,usePublisher:$s}),N6=k6,T6=on(()=>{const e=Ye(d=>o.jsxs("td",{children:["Item $",d]})),t=Ye(null),n=Ye(d=>o.jsxs("td",{colSpan:1e3,children:["Group ",d]})),s=Ye(null),i=Ye(null),r=Ye({}),a=Ye(lx),l=Ye(ka),c=(d,u=null)=>us(Fe(r,ut(h=>h[d]),Dn()),u);return{components:r,computeItemKey:a,context:t,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:i,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")}});Pn(Z1,T6);ax();const Ub={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},I6={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Kb,floor:uu,max:cl,min:cp,round:qb}=Math;function Yb(e,t,n){return Array.from({length:t-e+1}).map((s,i)=>({data:n===null?null:n[i+e],index:i+e}))}function D6(e){return{...I6,items:e}}function Tc(e,t){return e!==void 0&&e.width===t.width&&e.height===t.height}function P6(e,t){return e!==void 0&&e.column===t.column&&e.row===t.row}const E6=on(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:s},{footerHeight:i,headerHeight:r,scrollBy:a,scrollContainerState:l,scrollTo:c,scrollTop:d,smoothScrollTargetReached:u,viewportHeight:h},p,f,{didMount:x,propsReady:g},{customScrollParent:v,useWindowScroll:w,windowScrollContainerState:y,windowScrollTo:b,windowViewportRect:_},j])=>{const N=Ye(0),C=Ye(0),k=Ye(Ub),E=Ye({height:0,width:0}),I=Ye({height:0,width:0}),T=Qt(),A=Qt(),D=Ye(0),W=Ye(null),J=Ye({column:0,row:0}),O=Qt(),B=Qt(),L=Ye(!1),se=Ye(0),Q=Ye(!0),V=Ye(!1),H=Ye(!1);un(Fe(x,$t(se),It(([fe,F])=>!Ff(F))),()=>{Ot(Q,!1)}),un(Fe(Hn(x,Q,I,E,se,V),It(([fe,F,U,de,,Y])=>fe&&!F&&U.height!==0&&de.height!==0&&!Y)),([,,,,fe])=>{if(fe===void 0){Ot(Q,!0);return}Ot(V,!0),sx(1,()=>{Ot(T,fe)}),ci(Fe(d),()=>{Ot(t,[0,0]),Ot(Q,!0)})}),wt(Fe(B,It(fe=>fe!=null&&fe.scrollTop>0),yi(0)),C),un(Fe(x,$t(B),It(([,fe])=>fe!=null)),([,fe])=>{fe&&(Ot(E,fe.viewport),Ot(I,fe.item),Ot(J,fe.gap),fe.scrollTop>0&&(Ot(L,!0),ci(Fe(d,mr(1)),F=>{Ot(L,!1)}),Ot(c,{top:fe.scrollTop})))}),wt(Fe(E,ut(({height:fe})=>fe)),h),wt(Fe(Hn(Tt(E,Tc),Tt(I,Tc),Tt(J,(fe,F)=>fe!==void 0&&fe.column===F.column&&fe.row===F.row),Tt(d)),ut(([fe,F,U,de])=>({gap:U,item:F,scrollTop:de,viewport:fe}))),O),wt(Fe(Hn(Tt(N),s,Tt(J,P6),Tt(I,Tc),Tt(E,Tc),Tt(W),Tt(C),Tt(L),Tt(Q),Tt(se)),It(([,,,,,,,fe])=>!fe),ut(([fe,[F,U],de,Y,X,z,ue,,_e,Ee])=>{const{column:Be,row:De}=de,{height:Ue,width:St}=Y,{width:Ut}=X;if(ue===0&&(fe===0||Ut===0))return Ub;if(St===0){const ft=ix(Ee,fe),mt=ft+Math.max(ue-1,0);return D6(Yb(ft,mt,z))}const tn=lN(Ut,St,Be);let Ne,Z;_e?F===0&&U===0&&ue>0?(Ne=0,Z=ue-1):(Ne=tn*uu((F+De)/(Ue+De)),Z=tn*Kb((U+De)/(Ue+De))-1,Z=cp(fe-1,cl(Z,tn-1)),Ne=cp(Z,cl(0,Ne))):(Ne=0,Z=-1);const je=Yb(Ne,Z,z),{bottom:tt,top:Et}=Xb(X,de,Y,je),zt=Kb(fe/tn),we=zt*Ue+(zt-1)*De-tt;return{bottom:tt,itemHeight:Ue,items:je,itemWidth:St,offsetBottom:we,offsetTop:Et,top:Et}})),k),wt(Fe(W,It(fe=>fe!==null),ut(fe=>fe.length)),N),wt(Fe(Hn(E,I,k,J),It(([fe,F,{items:U}])=>U.length>0&&F.height!==0&&fe.height!==0),ut(([fe,F,{items:U},de])=>{const{bottom:Y,top:X}=Xb(fe,de,F,U);return[X,Y]}),Dn(zl)),t);const ne=Ye(!1);wt(Fe(d,$t(ne),ut(([fe,F])=>F||fe!==0)),ne);const he=Rs(Fe(Hn(k,N),It(([{items:fe}])=>fe.length>0),$t(ne),It(([[fe,F],U])=>{const de=fe.items[fe.items.length-1].index===F-1;return(U||fe.bottom>0&&fe.itemHeight>0&&fe.offsetBottom===0&&fe.items.length===F)&&de}),ut(([[,fe]])=>fe-1),Dn())),pe=Rs(Fe(Tt(k),It(({items:fe})=>fe.length>0&&fe[0].index===0),yi(0),Dn())),ke=Rs(Fe(Tt(k),$t(L),It(([{items:fe},F])=>fe.length>0&&!F),ut(([{items:fe}])=>({endIndex:fe[fe.length-1].index,startIndex:fe[0].index})),Dn(G1),so(0)));wt(ke,f.scrollSeekRangeChanged),wt(Fe(T,$t(E,I,N,J),ut(([fe,F,U,de,Y])=>{const X=$1(fe),{align:z,behavior:ue,offset:_e}=X;let Ee=X.index;Ee==="LAST"&&(Ee=de-1),Ee=cl(0,Ee,cp(de-1,Ee));let Be=Hf(F,Y,U,Ee);return z==="end"?Be=qb(Be-F.height+U.height):z==="center"&&(Be=qb(Be-F.height/2+U.height/2)),_e!==void 0&&_e!==0&&(Be+=_e),{behavior:ue,top:Be}})),c);const Me=us(Fe(k,ut(fe=>fe.offsetBottom+fe.bottom)),0);return wt(Fe(_,ut(fe=>({height:fe.visibleHeight,width:fe.visibleWidth}))),E),{customScrollParent:v,data:W,deviation:D,footerHeight:i,gap:J,headerHeight:r,increaseViewportBy:e,initialItemCount:C,itemDimensions:I,overscan:n,restoreStateFrom:B,scrollBy:a,scrollContainerState:l,scrollHeight:A,scrollTo:c,scrollToIndex:T,scrollTop:d,smoothScrollTargetReached:u,totalCount:N,useWindowScroll:w,viewportDimensions:E,windowScrollContainerState:y,windowScrollTo:b,windowViewportRect:_,...f,gridState:k,horizontalDirection:H,initialTopMostItemIndex:se,totalListHeight:Me,...p,endReached:he,propsReady:g,rangeChanged:ke,startReached:pe,stateChanged:O,stateRestoreInProgress:L,...j}},Pn(ox,_s,fc,X1,Go,rx,zo));function lN(e,t,n){return cl(1,uu((e+n)/(uu(t)+n)))}function Xb(e,t,n,s){const{height:i}=n;if(i===void 0||s.length===0)return{bottom:0,top:0};const r=Hf(e,t,n,s[0].index);return{bottom:Hf(e,t,n,s[s.length-1].index)+i,top:r}}function Hf(e,t,n,s){const i=lN(e.width,n.width,t.column),r=uu(s/i),a=r*n.height+cl(0,r-1)*t.row;return a>0?a+t.row:a}const A6=on(()=>{const e=Ye(h=>`Item ${h}`),t=Ye({}),n=Ye(null),s=Ye("virtuoso-grid-item"),i=Ye("virtuoso-grid-list"),r=Ye(lx),a=Ye("div"),l=Ye(ka),c=(h,p=null)=>us(Fe(t,ut(f=>f[h]),Dn()),p),d=Ye(!1),u=Ye(!1);return wt(Tt(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:i,ListComponent:c("List","div"),readyStateChanged:d,reportReadyState:u,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),M6=on(([e,t])=>({...e,...t}),Pn(E6,A6)),R6=Ce.memo(function(){const e=Tn("gridState"),t=Tn("listClassName"),n=Tn("itemClassName"),s=Tn("itemContent"),i=Tn("computeItemKey"),r=Tn("isSeeking"),a=Ws("scrollHeight"),l=Tn("ItemComponent"),c=Tn("ListComponent"),d=Tn("ScrollSeekPlaceholder"),u=Tn("context"),h=Ws("itemDimensions"),p=Ws("gap"),f=Tn("log"),x=Tn("stateRestoreInProgress"),g=Ws("reportReadyState"),v=vr(Ce.useMemo(()=>w=>{const y=w.parentElement.parentElement.scrollHeight;a(y);const b=w.firstChild;if(b!==null){const{height:_,width:j}=b.getBoundingClientRect();h({height:_,width:j})}p({column:Jb("column-gap",getComputedStyle(w).columnGap,f),row:Jb("row-gap",getComputedStyle(w).rowGap,f)})},[a,h,p,f]),!0,!1);return nN(()=>{e.itemHeight>0&&e.itemWidth>0&&g(!0)},[e]),x?null:o.jsx(c,{className:t,ref:v,...ds(c,u),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(w=>{const y=i(w.index,w.data,u);return r?o.jsx(d,{...ds(d,u),height:e.itemHeight,index:w.index,width:e.itemWidth},y):m.createElement(l,{...ds(l,u),className:n,"data-index":w.index,key:y},s(w.index,w.data,u))})})}),L6=Ce.memo(function(){const e=Tn("HeaderComponent"),t=Ws("headerHeight"),n=Tn("headerFooterTag"),s=vr(Ce.useMemo(()=>r=>{t(Io(r,"height"))},[t]),!0,!1),i=Tn("context");return e!=null?o.jsx(n,{ref:s,children:o.jsx(e,{...ds(e,i)})}):null}),O6=Ce.memo(function(){const e=Tn("FooterComponent"),t=Ws("footerHeight"),n=Tn("headerFooterTag"),s=vr(Ce.useMemo(()=>r=>{t(Io(r,"height"))},[t]),!0,!1),i=Tn("context");return e!=null?o.jsx(n,{ref:s,children:o.jsx(e,{...ds(e,i)})}):null}),z6=({children:e})=>{const t=Ce.useContext(tN),n=Ws("itemDimensions"),s=Ws("viewportDimensions"),i=vr(Ce.useMemo(()=>r=>{s(r.getBoundingClientRect())},[s]),!0,!1);return Ce.useEffect(()=>{t&&(s({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,s,n]),o.jsx("div",{ref:i,style:cx(!1),children:e})},G6=({children:e})=>{const t=Ce.useContext(tN),n=Ws("windowViewportRect"),s=Ws("itemDimensions"),i=Tn("customScrollParent"),r=Tn("useWindowScroll"),a=A1(n,i,!1);return Ce.useEffect(()=>{t&&(s({height:t.itemHeight,width:t.itemWidth}),n({listHeight:0,offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,s]),o.jsx("div",{ref:a,style:oN(!1,r),children:e})},F6=Ce.memo(function({...e}){const t=Tn("useWindowScroll"),n=Tn("customScrollParent"),s=n||t?B6:H6,i=n||t?G6:z6,r=Tn("context");return o.jsx(s,{...e,...ds(s,r),children:o.jsxs(i,{children:[o.jsx(L6,{}),o.jsx(R6,{}),o.jsx(O6,{})]})})}),{useEmitter:cN,useEmitterValue:Tn,usePublisher:Ws}=Q1(M6,{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"}},F6),H6=rN({useEmitter:cN,useEmitterValue:Tn,usePublisher:Ws}),B6=aN({useEmitter:cN,useEmitterValue:Tn,usePublisher:Ws});function Jb(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,Xn.WARN),t==="normal"?0:parseInt(t??"0",10)}function V6({className:e}){return o.jsx("svg",{viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",className:q("size-4",e),children:o.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 $6={rows:new Set,expanded:new Set};function W6(e,t,n){const s=[],i=[],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)&&i.push(l.key),l.children.forEach((f,x)=>{r.set(f.key,{group:l.key,index:x})});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:i,children:r,next:{rows:new Set(t.map(l=>l.key)),expanded:a}}}function U6(e,t){return!e&&t>=2}const Ic=40;function K6({items:e,activeKey:t,onJump:n}){const s=xe(p=>p.chatWide),[i,r]=m.useState(null);if(!U6(s,e.length))return null;const a=Math.max(0,e.findIndex(p=>p.key===t)),l=Math.min(Math.max(0,a-Math.floor(Ic/2)),Math.max(0,e.length-Ic)),c=e.slice(l,l+Ic),d=l>0,u=l+Ic<e.length,h=(p,f)=>{const x=f?24:12;if(i===null)return x;const g=Math.abs(p-i),v=Math.max(0,16-g*6);return x+v};return o.jsx("div",{className:"group/rail absolute top-0 left-0 z-10 hidden h-full w-14 @min-[52rem]:block",children:o.jsx("div",{className:"absolute top-1/2 left-2 -translate-y-1/2 opacity-0 transition-opacity duration-200 group-hover/rail:opacity-100",onMouseLeave:()=>r(null),children:o.jsxs("div",{className:"relative flex flex-col justify-center gap-[5px]",style:{maskImage:d||u?`linear-gradient(to bottom, ${d?"transparent, black 24px":"black"}, ${u?"black calc(100% - 24px), transparent":"black"})`:void 0},children:[c.map((p,f)=>{const x=p.key===t,g=f===i;return o.jsx("button",{type:"button",onClick:()=>n(p.key),onMouseEnter:()=>r(f),className:"flex h-[7px] items-center",children:o.jsx("span",{className:q("rounded-full transition-all duration-150",x||g?"h-[3px] bg-foreground":"h-[2px] bg-muted-foreground/40"),style:{width:h(f,x)}})},p.key)}),i!==null&&c[i]&&o.jsxs("div",{className:"pointer-events-none absolute left-10 w-72 -translate-y-1/2 rounded-xl border bg-popover p-3 shadow-lg",style:{top:`${(i+.5)/c.length*100}%`},children:[o.jsx("p",{className:"line-clamp-2 text-xs font-semibold",children:c[i].question}),c[i].answer&&o.jsx("p",{className:"mt-1 line-clamp-3 text-xs text-muted-foreground",children:c[i].answer})]})]})})})}const Nd="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 dN(e){return e.content.filter(t=>t.type==="text").map(t=>t.text??"").join("").trim()}function q6(e){const t=[];for(const n of e){if(n.role!=="user"&&n.role!=="assistant")continue;const s=dN(n);s&&t.push(`${n.role==="user"?"User":"Assistant"}: ${s}`)}return t.slice(-40).join(`
21
- `)}function Y6(e){for(const t of[...e].reverse()){if(t.role!=="assistant")continue;const n=dN(t);if(n)return n}return""}function Zb(e,t){if(e!=="contextual")return Nd;const n=t.trim();return n?`${Nd}
22
-
23
- # Main conversation (background only)
24
- ${n}`:Nd}function X6(e){return e.startsWith(Nd)}function J6(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 Z6({message:e}){const{t}=te(),n={queued:t("Queued"),running:t("In progress"),completed:t("Completed"),failed:t("Failed"),canceled:t("Canceled")},s=e.kind==="routine"?d1:e.kind==="group"?oa:e.kind==="delegation-task"?da:eB,i=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"):t("Result from {{name}}",{name:e.from});return o.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:[o.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[o.jsx(s,{className:"size-3.5 shrink-0"}),o.jsx("span",{children:i}),e.kind==="delegation-result"&&e.status&&o.jsxs("span",{children:["· ",n[e.status]??e.status]})]}),o.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.text:e.kind==="delegation-results"?e.results.map((r,a)=>o.jsxs("p",{children:[o.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)=>o.jsxs("p",{children:[o.jsxs("span",{className:"font-medium",children:[r.from,":"]}),r.text]},`${a}:${r.from}`))}),e.kind==="delegation-task"&&e.context&&o.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer",children:t("Context")}),o.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words",children:e.context})]}),e.kind==="group"&&e.instruction&&o.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer",children:t("Instructions")}),o.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words",children:e.instruction})]}),e.kind==="group"&&!!e.refs?.length&&o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:e.refs.map(r=>o.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:[o.jsx(oa,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"min-w-0 truncate",children:r.title})]},r.id))}),e.kind==="group"&&e.note&&o.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&&o.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[o.jsxs("summary",{className:"cursor-pointer",children:[t("Group messages")," · ",e.group.length]}),o.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words",children:e.group.map((r,a)=>o.jsxs("p",{children:[o.jsxs("span",{className:"font-medium",children:[r.from,":"]}),r.text]},`${a}:${r.from}`))})]})]})}const uN=new Map;let Br;function Q6(e){if(Br?.revision===e)return Br.request;const t=window.electronAPI.providers.listOauth().then(s=>{const i=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&&i.set(a.key,l)}return{revision:e,emails:i}}).catch(s=>(console.error("Failed to load OAuth account metadata",s),{revision:e,emails:uN})),n={revision:e,request:t,data:void 0};return Br=n,t.then(s=>{Br===n&&(n.data=s)}),t}function e4(){const e=Ao(s=>s.snapshot.revision),[t,n]=m.useState(()=>Br?.revision===e?Br.data:void 0);return m.useEffect(()=>{let s=!1;return Q6(e).then(i=>{s||n(i)}),()=>{s=!0}},[e]),t?.revision===e?t.emails:uN}function Qb(e,t=0){let n=3735928559^t,s=1103547991^t;for(let i=0;i<e.length;i++){const r=e.charCodeAt(i);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 ux(e,t,n){return`${e}:${Qb(t)}:${Qb(n,1)}`}const t4=/(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c|$)/g,n4=/(?:\x1b\[|\x9b)[0-?]*[ -/]*(?:[@-~]|$)/g;function Oi(e){return e.replace(t4,"").replace(n4,"")}function s4(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 i4(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 o4(e){let t=0,n=0,s=0,i=0,r=0,a=0,l=0,c=0,d=0,u=0,h=0,p=0,f=null;for(const g of e){if(g.role==="user"&&(t+=1,f=null),g.role!=="assistant")continue;n+=1,g.usage&&(s+=g.usage.input,i+=g.usage.output,r+=g.usage.cacheRead,a+=g.usage.cacheWrite);const v=g.timing,w=i4(g);w!==void 0&&(l+=w);const y=s4(g);y!==void 0&&(d+=y,u+=1);const b=g.usage?.output??0;w!==void 0&&w>0&&b>0&&(h+=w,p+=b),v&&(f!==null&&(c+=Math.max(0,v.stepStartMs-f)),f=v.completedMs??null)}const x=s+r+a;return{turns:t,steps:n,llmMs:l,toolMs:c,inputTokens:x,outputTokens:i,cacheHitPercent:x===0?null:Math.round(r/x*100),ttftAvgMs:u>0?d/u:null,tokensPerSecond:h>0&&p>0?Math.round(p/(h/1e3)*10)/10:null}}function r4(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 ew=NC(e=>({byConversation:{},replace:(t,n)=>e(s=>{const i={...s.byConversation};if(n.length>0)i[t]=n;else if(i[t])delete i[t];else return s;return{byConversation:i}})})),a4={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 l4({value:e}){const t=yP(e),{t:n}=te();if(!t)return null;const s=`allow ${t.allow.toFixed(2)} · ask ${t.ask.toFixed(2)} · block ${t.block.toFixed(2)}`;return o.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:[o.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:t.verdict==="allow"?n("Auto-managed · allowed"):n("Auto-managed · denied")}),o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsx("span",{className:"font-mono",children:t.model}),o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsx("span",{className:"font-mono",children:s}),t.reason&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsxs("span",{children:[n("Reason"),": ",n(a4[t.reason])]})]})]})}function c4({ask:e,waiting:t}){const{t:n}=te(),s=e.answer!==null&&!e.options.includes(e.answer)?e.answer:null;return o.jsxs("div",{className:"space-y-1.5 px-3 py-2 text-xs",children:[o.jsx("p",{className:"whitespace-pre-wrap break-words leading-relaxed text-foreground",children:e.question}),(e.options.length>0||s!==null)&&o.jsxs("ul",{className:"space-y-0.5",children:[e.options.map(i=>o.jsx(tw,{selected:i===e.answer,text:i},i)),s!==null&&o.jsx(tw,{selected:!0,text:s,label:e.options.length>0&&!e.autoSelected?n("Custom answer"):void 0})]}),e.autoSelected&&o.jsx("p",{className:"text-muted-foreground",children:n("No answer in time; the default was selected")}),t&&e.answer===null&&o.jsx("p",{className:"text-muted-foreground",children:n("Waiting for your answer")})]})}function tw({selected:e,text:t,label:n}){const{t:s}=te(),i=e?zm:l1;return o.jsxs("li",{"data-selected":e||void 0,className:q("flex items-start gap-1.5 rounded-md px-2 py-1 leading-relaxed",e?"bg-primary/10 text-foreground":"text-muted-foreground"),children:[o.jsx(i,{className:q("mt-0.5 h-3.5 w-3.5 shrink-0",e?"text-primary":"opacity-40")}),o.jsxs("span",{className:"min-w-0 whitespace-pre-wrap break-words",children:[n&&o.jsx("span",{className:"mr-1.5 text-muted-foreground",children:n}),t]}),e&&o.jsx("span",{className:"sr-only",children:s("Selected")})]})}const ch=m.createContext(null);function Bi(){return m.useContext(ch)}const d4=new TextEncoder,u4=new TextDecoder("utf-8",{ignoreBOM:!0}),h4=/[\uD800-\uDFFF]/,Bf=1024;let Vr=new Uint8Array(Bf);function p4(){Vr.length!==Bf&&(Vr=new Uint8Array(Bf))}function ss(e){if(e.length===0)return e;if(h4.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;Vr.length<t&&(Vr=new Uint8Array(t));const{written:n}=d4.encodeInto(e,Vr);return u4.decode(Vr.subarray(0,n))}const f4=4096,m4=.5;function g4(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 i=v4(e,s);i!=null&&(t.hunkContent.splice(n,1,...i),n+=i.length-1)}x4(t,e)}}function x4(e,t){const{hunkContent:n}=e;for(let s=1;s<n.length;s++){const i=n[s],r=n[s-1];if(i.type!=="change"||i.additions>0&&i.deletions>0||r.type!=="context")continue;const a=i.additions>0,l=a?t.additionLines:t.deletionLines,c=a?i.additionLineIndex:i.deletionLineIndex,d=a?i.additions:i.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;i.additionLineIndex-=p,i.deletionLineIndex-=p;const f=i.additionLineIndex+i.additions,x=i.deletionLineIndex+i.deletions,g=n[s+1];g?.type==="context"?(g.lines+=p,g.additionLineIndex=f,g.deletionLineIndex=x):n.splice(s+1,0,{type:"context",lines:p,additionLineIndex:f,deletionLineIndex:x}),r.lines-=p,r.lines===0&&(n.splice(s-1,1),s--)}}function v4(e,t){const{deletions:n,additions:s,deletionLineIndex:i,additionLineIndex:r}=t,a=Math.min(n,s),l=Math.abs(s-n);if(a===0||l===0||a*(l+1)>f4)return null;const c=[];for(let g=0;g<n;g++)c.push(nw(e.deletionLines[i+g]??""));const d=[];for(let g=0;g<s;g++)d.push(nw(e.additionLines[r+g]??""));const u=s>n;let h=0,p=-1;for(let g=0;g<=l;g++){let v=0;for(let w=0;w<a;w++)v+=w4(c[w+(u?0:g)],d[w+(u?g:0)]);g===0?p=v+a*m4:v>p&&(p=v,h=g)}if(h===0)return null;const f=[],x=(g,v,w,y)=>{(g>0||v>0)&&f.push({type:"change",deletions:g,additions:v,deletionLineIndex:w,additionLineIndex:y})};return u?(x(0,h,i,r),x(a,a,i,r+h),x(0,s-a-h,i+a,r+h+a)):(x(h,0,i,r),x(a,a,i+h,r),x(n-a-h,0,i+h+a,r+a)),f}const b4=/\s+/g;function nw(e){return e.replace(b4,"")}function w4(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 i=0;for(;i<s&&e[i]===t[i];)i++;let r=0;for(;r<s-i&&e[e.length-1-r]===t[t.length-1-r];)r++;return(i+r)/n}function y4(e,t){try{return S4(e,t)}finally{p4()}}function S4(e,{cacheKey:t,isGitDiff:n=jP.test(e),oldFile:s,newFile:i,throwOnError:r=!1}={}){let a=0;const l=N4(e,"@@ ");let c;const d=s==null||i==null;let u=0,h=0;for(const p of l){const f=hN(p),x=f[0];if(x==null){if(r)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",p);continue}const g=_4(x);let v=0,w=0;if(g==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&&i!=null?sw(i.contents):[],deletionLines:!d&&s!=null&&i!=null?sw(s.contents):[],cacheKey:ow(t)},c.additionLines.length===1&&i?.contents===""&&(c.additionLines.length=0),c.deletionLines.length===1&&s?.contents===""&&(c.deletionLines.length=0);for(const E of f){if(E.startsWith("diff --git")){const T=E.trim().match(SP),A=T?.[1]??T?.[2],D=T?.[3]??T?.[4];if(A==null||D==null){if(r)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",E);continue}c.name=ss(D.trim()),A!==D&&(c.prevName=ss(A.trim()));continue}const I=E.startsWith("---")||E.startsWith("+++")?E.match(n?CP:kP):null;if(I!=null){const[,T,A]=I;if(T==="---"&&A!=="/dev/null"){const D=ss(A.trim());c.prevName=D,c.name=D}else T==="+++"&&A!=="/dev/null"&&(c.name=ss(A.trim()))}else if(n){if(E.startsWith("new mode ")&&(c.mode=ss(E.slice(8).trim())),E.startsWith("old mode ")&&(c.prevMode=ss(E.slice(8).trim())),E.startsWith("new file mode")&&(c.type="new",c.mode=ss(E.slice(13).trim())),E.startsWith("deleted file mode")&&(c.type="deleted",c.mode=ss(E.slice(17).trim())),E.startsWith("similarity index")&&(E.startsWith("similarity index 100%")?c.type="rename-pure":c.type="rename-changed"),E.startsWith("index ")){const[,T,A,D]=E.trim().match(_P)??[];T!=null&&(c.prevObjectId=ss(T)),A!=null&&(c.newObjectId=ss(A)),D!=null&&(c.mode=ss(D))}E.startsWith("rename from ")&&(c.prevName=ss(E.slice(12).trim())),E.startsWith("rename to ")&&(c.name=ss(E.slice(10).trim()))}}continue}let y,b;for(;f.length>0&&(f[f.length-1]===`
27
- `||f[f.length-1]==="\r"||f[f.length-1]===`\r
28
- `||f[f.length-1]==="");)f.pop();const{additionStart:_,deletionStart:j}=g;u=d?u:j-1,h=d?h:_-1;const N={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:g.additionCount,additionStart:_,additionLines:v,deletionCount:g.deletionCount,deletionStart:j,deletionLines:w,deletionLineIndex:u,additionLineIndex:h,hunkContent:[],hunkContext:ow(g.hunkContext),hunkSpecs:ss(x),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let C=0,k=0;for(let E=1;E<f.length;E++){const I=f[E];if(C>=N.additionCount&&k>=N.deletionCount&&!I.startsWith("\\")){if(r&&C4(I)&&!k4(I))throw Error("parsePatchContent: hunk has more lines than expected");break}const T=I[0];if(T!=="+"&&T!=="-"&&T!==" "&&T!=="\\"){if(r)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${T}", full line: "${I}"`),console.error("processFile: invalid rawLine:",I);continue}const A=T4(T);if(A==="addition"){if(r&&C>=N.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const D=dp(I);(y==null||y.type!=="change")&&(y=up("change",u,h),N.hunkContent.push(y)),h++,C++,d&&c.additionLines.push(D),y.additions++,v++,b="addition"}else if(A==="deletion"){if(r&&k>=N.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const D=dp(I);(y==null||y.type!=="change")&&(y=up("change",u,h),N.hunkContent.push(y)),u++,k++,d&&c.deletionLines.push(D),y.deletions++,w++,b="deletion"}else if(A==="context"){if(r&&(k>=N.deletionCount||C>=N.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const D=dp(I);(y==null||y.type!=="context")&&(y=up("context",u,h),N.hunkContent.push(y)),h++,u++,C++,k++,d&&(c.deletionLines.push(D),c.additionLines.push(D)),y.lines++,b="context"}else if(A==="metadata"&&y!=null){if(y.type==="context"?(N.noEOFCRAdditions=!0,N.noEOFCRDeletions=!0):b==="deletion"?N.noEOFCRDeletions=!0:b==="addition"&&(N.noEOFCRAdditions=!0),d&&(b==="addition"||b==="context")){const D=c.additionLines.length-1;D>=0&&(c.additionLines[D]=wl(c.additionLines[D]))}if(d&&(b==="deletion"||b==="context")){const D=c.deletionLines.length-1;D>=0&&(c.deletionLines[D]=wl(c.deletionLines[D]))}}}if(r&&(C!==N.additionCount||k!==N.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");N.additionLines=v,N.deletionLines=w,N.collapsedBefore=Math.max(ua(N.additionStart,N.additionCount)-a,0),c.hunks.push(N),a=ro(N.additionStart,N.additionCount);for(const E of N.hunkContent)E.type==="context"?(N.splitLineCount+=E.lines,N.unifiedLineCount+=E.lines):(N.splitLineCount+=Math.max(E.additions,E.deletions),N.unifiedLineCount+=E.deletions+E.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=ro(p.additionStart,p.additionCount),x=c.additionLines.length,g=Math.max(x-f,0);c.splitLineCount+=g,c.unifiedLineCount+=g}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==="")&&i!=null&&i.contents!==""?c.type="new":s!=null&&s.contents!==""&&(i==null||i.contents==="")&&(c.type="deleted")),c.type!=="rename-pure"&&c.type!=="rename-changed"&&(c.prevName=void 0),g4(c),c}}function sw(e){const t=hN(e);for(let n=0;n<t.length;n++)t[n]=ss(t[n]);return t}function hN(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const s=e.indexOf(`
29
- `,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 C4(e){const t=e[0];return t==="+"||t==="-"||t===" "}function k4(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
30
- `&&n!=="\r")return!1}return!0}function _4(e){if(!e.startsWith("@@ -"))return;let t=4;const n=Dc(e,t);if(n==null)return;const s=n.value;t=n.endIndex;let i=1;if(e[t]===","){const u=Dc(e,t+1);if(u==null)return;i=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const r=Dc(e,t);if(r==null)return;const a=r.value;t=r.endIndex;let l=1;if(e[t]===","){const u=Dc(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=j4(e.slice(d+1))),{additionCount:l,additionStart:a,deletionCount:i,deletionStart:s,hunkContext:c}}function Dc(e,t){let n=t,s=0;for(;n<e.length;n++){const i=e.charCodeAt(n)-48;if(i<0||i>9)break;s=s*10+i}if(n!==t)return{value:s,endIndex:n}}function j4(e){return e.endsWith(`\r
31
- `)?e.slice(0,-2):e.endsWith(`
32
- `)?e.slice(0,-1):e}function N4(e,t){if(e.length===0)return[""];const n=`
33
- ${t}`,s=e.startsWith(t)?0:iw(e,n,0);if(s===-1)return[e];const i=[];s>0&&i.push(e.slice(0,s));let r=s;for(;;){const a=iw(e,n,r+1);if(a===-1)break;i.push(e.slice(r,a)),r=a}return i.push(e.slice(r)),i}function iw(e,t,n){const s=e.indexOf(t,n);return s===-1?-1:s+1}function ow(e){return e==null?e:ss(e)}function T4(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function dp(e){const t=e.slice(1);return ss(t===""?`
34
- `:t)}function up(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 I4 extends NP{constructor(){super(...arguments),this.tokenize=P4}equals(t,n,s){return s.ignoreWhitespace?((!s.newlineIsToken||!t.includes(`
35
- `))&&(t=t.trim()),(!s.newlineIsToken||!n.includes(`
36
- `))&&(n=n.trim())):s.ignoreNewlineAtEof&&!s.newlineIsToken&&(t.endsWith(`
37
- `)&&(t=t.slice(0,-1)),n.endsWith(`
38
- `)&&(n=n.slice(0,-1))),super.equals(t,n,s)}}const D4=new I4;function rw(e,t,n){return D4.diff(e,t,n)}function P4(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
39
- `));const n=[],s=e.split(/(\n|\r\n)/);s[s.length-1]||s.pop();for(let i=0;i<s.length;i++){const r=s[i];i%2&&!t.newlineIsToken?n[n.length-1]+=r:n.push(r)}return n}function E4(e){for(let t=0;t<e.length;t++)if(e[t]<" "||e[t]>"~"||e[t]==='"'||e[t]==="\\")return!0;return!1}function bo(e){if(!E4(e))return e;let t='"';const n=new TextEncoder().encode(e);let s=0;for(;s<n.length;){const i=n[s];i===7?t+="\\a":i===8?t+="\\b":i===9?t+="\\t":i===10?t+="\\n":i===11?t+="\\v":i===12?t+="\\f":i===13?t+="\\r":i===34?t+='\\"':i===92?t+="\\\\":i>=32&&i<=126?t+=String.fromCharCode(i):t+="\\"+i.toString(8).padStart(3,"0"),s++}return t+='"',t}const aw={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function lw(e,t,n,s,i,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;rw(n,s,Object.assign(Object.assign({},l),{callback:h=>{const p=d(h);u(p)}}))}else return d(rw(n,s,l));function d(u){if(!u)return;u.push({value:"",lines:[]});function h(y){return y.map(function(b){return" "+b})}const p=[];let f=0,x=0,g=[],v=1,w=1;for(let y=0;y<u.length;y++){const b=u[y],_=b.lines||M4(b.value);if(b.lines=_,b.added||b.removed){if(!f){const j=u[y-1];f=v,x=w,j&&(g=c>0?h(j.lines.slice(-c)):[],f-=g.length,x-=g.length)}for(const j of _)g.push((b.added?"+":"-")+j);b.added?w+=_.length:v+=_.length}else{if(f)if(_.length<=c*2&&y<u.length-2)for(const j of h(_))g.push(j);else{const j=Math.min(_.length,c);for(const C of h(_.slice(0,j)))g.push(C);const N={oldStart:f,oldLines:v-f+j,newStart:x,newLines:w-x+j,lines:g};p.push(N),f=0,x=0,g=[]}v+=_.length,w+=_.length}}for(const y of p)for(let b=0;b<y.lines.length;b++)y.lines[b].endsWith(`
40
- `)?y.lines[b]=y.lines[b].slice(0,-1):(y.lines.splice(b+1,0,"\"),b++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:r,hunks:p}}}function Vf(e,t){var n,s,i,r,a,l;if(t||(t=aw),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=>Vf(u,t)).join(`
41
- `)}const c=[];if(e.isGit){if(t=aw,!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 "+bo(u)+" "+bo(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 "+bo(((i=e.oldFileName)!==null&&i!==void 0?i:"").replace(/^a\//,""))),c.push("rename to "+bo(((r=e.newFileName)!==null&&r!==void 0?r:"").replace(/^b\//,"")))),e.isCopy&&(c.push("copy from "+bo(((a=e.oldFileName)!==null&&a!==void 0?a:"").replace(/^a\//,""))),c.push("copy to "+bo(((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("--- "+bo(e.oldFileName)+(e.oldHeader?" "+e.oldHeader:"")),c.push("+++ "+bo(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 x of h.lines)c.push(x)}return c.join(`
42
- `)+`
43
- `}function A4(e,t,n,s,i,r,a){if(typeof a=="function"&&(a={callback:a}),a?.callback){const{callback:l}=a;lw(e,t,n,s,i,r,Object.assign(Object.assign({},a),{callback:c=>{l(c?Vf(c,a.headerOptions):void 0)}}))}else{const l=lw(e,t,n,s,i,r,a);return l?Vf(l,a?.headerOptions):void 0}}function M4(e){const t=e.endsWith(`
44
- `),n=e.split(`
45
- `).map(s=>s+`
46
- `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const R4="/dev/null";function po(e,t,n,s=!1){if(e===null&&t===null)throw new Error("parseDiffFromFile: You must pass oldFile, newFile, or both");const i=e??cw(),r=t??cw(),a=y4(A4(i.name,r.name,i.contents,r.contents,i.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:i,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 cw(){return{name:R4,contents:""}}function L4(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function O4(e){return{...e,hunks:e.hunks.map(t=>({...t,hunkContent:t.hunkContent.map(n=>({...n}))})),deletionLines:[...e.deletionLines],additionLines:[...e.additionLines]}}function $f(e){return e!==""?e.split(TP):[]}function Wf(e,t,n){const s=e==="clone"?O4(t):t;if(!s.isPartial)throw new Error("hydratePartialDiff: fileDiff must be partial");switch(s.type){case"change":case"rename-changed":return z4(s,F4(s,n),dw(s,n));case"rename-pure":{const i=dw(s,n);H4(s,n);const r=$f(i.contents);return s.isPartial=!1,s.deletionLines=r,s.additionLines=r,pN(s,null,i),s}}throw new Error(`hydratePartialDiff: ${s.type} diffs cannot be hydrated from loaded files`)}function z4(e,t,n){const s=$f(t.contents),i=$f(n.contents),{hunks:r,splitLineCount:a,unifiedLineCount:l}=G4(e.hunks,i.length);return e.hunks=r,e.splitLineCount=a,e.unifiedLineCount=l,e.isPartial=!1,e.deletionLines=s,e.additionLines=i,pN(e,t,n),e}function G4(e,t){let n=0,s=0,i=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,x=0;const g=[];for(const w of a.hunkContent){if(w.type==="context"){g.push({...w,additionLineIndex:d,deletionLineIndex:u}),d+=w.lines,u+=w.lines,f+=w.lines,x+=w.lines;continue}g.push({...w,additionLineIndex:d,deletionLineIndex:u}),d+=w.additions,u+=w.deletions,h+=w.additions,p+=w.deletions,f+=Math.max(w.additions,w.deletions),x+=w.additions+w.deletions}const v=Math.max(ua(a.additionStart,a.additionCount)-i,0);r.push({...a,collapsedBefore:v,additionLineIndex:l,deletionLineIndex:c,additionLines:h,deletionLines:p,hunkContent:g,splitLineStart:n+v,unifiedLineStart:s+v,splitLineCount:f,unifiedLineCount:x}),n+=v+f,s+=v+x,i=ro(a.additionStart,a.additionCount)}if(r.length>0){const a=r[r.length-1],l=ro(a.additionStart,a.additionCount),c=Math.max(t-l,0);n+=c,s+=c}return{hunks:r,splitLineCount:n,unifiedLineCount:s}}function F4(e,t){if(t.oldFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile`);return t.oldFile}function dw(e,t){if(t.newFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires newFile`);return t.newFile}function H4(e,t){if(t.oldFile!==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile to be null`)}function B4(e,t,n){return e.cacheKey!=null?`${e.cacheKey}:hydrated`:V4(t,n)}function pN(e,t,n){const s=B4(e,t,n);if(s==null){delete e.cacheKey;return}e.cacheKey=s}function V4(e,t){return e!=null&&t!=null?e.cacheKey!=null&&t.cacheKey!=null?`${e.cacheKey}:${t.cacheKey}`:void 0:e?.cacheKey??t?.cacheKey}var $4=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 Pc(e){return fs({tagName:"div",properties:{"data-content-buffer":"","data-buffer-size":e,style:`grid-row: span ${e};min-height:calc(${e} * 1lh)`}})}function Ec(e){return fs({tagName:"div",children:[fs({tagName:"span",children:[hd("No newline at end of file")]})],properties:{"data-no-newline":"","data-line-type":e,"data-column-content":""}})}function hp(e){return fs({tagName:"div",children:[IP({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 _r({type:e,content:t,expandIndex:n,chunked:s=!1,slotName:i,isFirstHunk:r,isLastHunk:a}){let l=0;const c=[];if(e==="metadata"&&t!=null&&c.push(fs({tagName:"div",children:[hd(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(fs({tagName:"div",children:[fs({tagName:"span",children:[hd(t)],properties:{"data-unmodified-lines":""}})],properties:{"data-separator-content":""}})),s&&n!=null&&d.push(fs({tagName:"div",children:[hd("Expand all")],properties:{role:"button","data-expand-button":"","data-expand-all-button":""}})),c.push(fs({tagName:"div",children:d,properties:{"data-separator-wrapper":"","data-separator-multi-button":l>1?"":void 0}}))}return e==="custom"&&i!=null&&c.push(fs({tagName:"slot",properties:{name:i}})),fs({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 W4(e,t){return`hunk-separator-${e}-${t}`}function U4(e){const t=e.at(-1);return t==null?0:Math.max(ro(t.additionStart,t.additionCount),ro(t.deletionStart,t.deletionCount))}function Uf(e){return e.startingLine===0&&e.totalLines===1/0&&e.bufferBefore===0&&e.bufferAfter===0}function Qi(e,t){const n=po({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 K4(e,t){const n=Math.max(e,1);let s=Array.from({length:n},(i,r)=>`${" ".repeat(r+1)}
47
- `).join("");return s===t&&(s=Array.from({length:n},(i,r)=>`\0${" ".repeat(r)}
48
- `).join("")),s}function q4(e){for(const t of e)if(t.trim().length>0)return!1;return!0}function Kf(e,t){return t.length>0&&t.length<e.deletionLines.length&&q4(t)}function hu(e,t,n){const s=e.deletionLines.join(""),i=K4(t.length,s),r=po({name:e.prevName??e.name,contents:s},{name:e.name,contents:i,lang:e.lang},n);return{hunks:r.hunks,splitLineCount:r.splitLineCount,unifiedLineCount:r.unifiedLineCount,additionLines:t,deletionLines:r.deletionLines,type:r.type}}function Td(e,t){return hu(e,[""],t)}function fN(e,t){if(e.additionLines.length===0)return Td(e,t);if(Kf(e,e.additionLines))return hu(e,e.additionLines,t);const n=e.additionLines,s=Qi(e,t);return mN(s,n),s}function Y4(e){return e.length>1&&e.at(-1)===""}function mN(e,t){if(!Y4(t))return;const n=t.length-e.additionLines.length;if(n<=0)return;const s=e.additionLines.length,i=e.hunks.at(-1);if(i!=null&&ro(i.additionStart,i.additionCount)===s){for(const r of i.hunkContent)if(r.type==="change"&&r.additions<r.deletions&&r.additionLineIndex+r.additions===s){e.additionLines=t,r.additions+=n,i.additionCount+=n,i.additionLines+=n,px(e);return}}}function X4(e,t,n){if(e.isPartial||e.deletionLines.length!==e.additionLines.length)return Wi(e,Qi(e,n));const s=Array.from(t);if(s.length===0)return Wi(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||wl(a)===wl(l))return Wi(e,Qi(e,n))}const i=J4(e,s);if(i.size===0)return Wi(e,Qi(e,n));for(const r of i)if(!Q4(e,r,n))return Wi(e,Qi(e,n));return px(e),DP(e)?Wi(e,Qi(e,n)):Wi(e,{hunks:e.hunks,splitLineCount:e.splitLineCount,unifiedLineCount:e.unifiedLineCount,type:e.type})}function Wi(e,t){return Object.assign(e,t),t}function J4(e,t){const n=new Set;for(const s of t){const i=Z4(e,s);if(i==null)return new Set;n.add(i)}return n}function Z4(e,t){for(const[n,s]of e.hunks.entries()){const i=s.additionLineIndex+s.additionCount;if(t>=s.additionLineIndex&&t<i)return n}}function Q4(e,t,n){const s=e.hunks[t];if(s==null)return!1;const i=e.deletionLines.slice(s.deletionLineIndex,s.deletionLineIndex+s.deletionCount),r=e.additionLines.slice(s.additionLineIndex,s.additionLineIndex+s.additionCount),a=po({name:e.prevName??e.name,contents:i.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:(eW(s,l),gN(e,t),!0)}function gN(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),i=e.deletionLines.at(-1);n.noEOFCRAdditions=s!=null&&s!==""&&!s.endsWith(`
49
- `),n.noEOFCRDeletions=i!=null&&i!==""&&!i.endsWith(`
50
- `)}function eW(e,t){const n=e.additionLineIndex,s=e.deletionLineIndex;e.hunkContent=t.hunkContent.map(i=>xN(i,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,hx(e)}function xN(e,t,n){return{...e,additionLineIndex:e.additionLineIndex+t,deletionLineIndex:e.deletionLineIndex+n}}function hx(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 px(e){let t=0,n=0,s=0;for(const i of e.hunks)i.collapsedBefore=Math.max(ua(i.additionStart,i.additionCount)-s,0),i.splitLineStart=t+i.collapsedBefore,i.unifiedLineStart=n+i.collapsedBefore,hx(i),t+=i.collapsedBefore+i.splitLineCount,n+=i.collapsedBefore+i.unifiedLineCount,s=ro(i.additionStart,i.additionCount);if(e.hunks.length>0){const i=e.hunks[e.hunks.length-1],r=Math.max(e.additionLines.length-ro(i.additionStart,i.additionCount),0);t+=r,n+=r}e.splitLineCount=t,e.unifiedLineCount=n}const uw=new WeakMap;function tW(e){return e.length>1&&e[e.length-1]===""?e.slice(0,-1):e}function nW(e,t){const n=Math.min(e.length,t.length);let s=0;for(;s<n&&e[s]===t[s];)s++;let i=e.length,r=t.length;for(;i>s&&r>s&&e[i-1]===t[r-1];)i--,r--;if(!(s===i&&s===r))return{start:s,deletionEnd:i,additionEnd:r}}function qf(e,t){const n=e.hunks,s=e.additionLines,i=tW(s),r=i===s?e:{...e,additionLines:i},a=uW(n,dW(r,t),e.deletionLines.length),l=fW(r,a);if(e.additionLines=i,e.hunks=l,e.editSessionDirty=!0,vW(e),mN(e,s),!!gW(n,e.hunks))return{regions:a.map(c=>c.previousSpan)}}function sW(e,t,n,s){const i=Array.from(new Set(t)).filter(c=>c>=0&&c<e.additionLines.length).sort((c,d)=>c-d);if(i.length===0)return;const{hunks:r}=e;let a,l=0;for(const c of i){for(;l<r.length;){const h=r[l];if(c<pu(h)+h.additionCount)break;l++}const d=r[l],u=d==null?void 0:pu(d);if(u==null||c<u||a!=null&&a!==l)return qf(e,n);a=l}if(a!=null){if(iW(e,i,a,s,n)){e.editSessionDirty=!0;return}return qf(e,n)}}function iW(e,t,n,s,i){if(s==null||i?.ignoreWhitespace===!0||i?.stripTrailingCr===!0)return!1;const r=oW(e),a=e.hunks[n];if(a.hunkContent.some(rW))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 oW(e){const t=uw.get(e);if(t?.lines===e.deletionLines)return t.set;const n=new Set(e.deletionLines);return uw.set(e,{lines:e.deletionLines,set:n}),n}function rW(e){return e?.type==="change"&&(e.additions===0||e.deletions===0)}function aW(e,t){const n=new Map,{regions:s}=t;for(let i=0;i<=s.length;i++){const r=s[i-1],a=s[i],l=i===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(i,{fromStart:d,fromEnd:u})}return n}function lW(e,t,n){const s=[];if(e.isPartial)return s;for(const[r,a]of e.hunks.entries()){const l=yl({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:t,hunkIndex:r,collapsedContextThreshold:n});if(l.rangeSize<=n)continue;const c=gr(a),d=c-l.rangeSize;l.fromStart>0&&s.push([d,d+l.fromStart]),l.fromEnd>0&&s.push([c-l.fromEnd,c])}const i=Sl({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:t,collapsedContextThreshold:n,errorPrefix:"captureExpansionAnchors"});if(i!=null&&i.fromStart>0&&i.rangeSize>n){const r=e.hunks[e.hunks.length-1],a=gr(r)+r.deletionCount;s.push([a,a+i.fromStart])}return s}function cW(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=gr(a);s(r,l-Math.max(a.collapsedBefore,0),l)}const i=e.hunks[e.hunks.length-1];return i!=null&&!e.isPartial&&e.deletionLines.length>0&&s(e.hunks.length,gr(i)+i.deletionCount,e.deletionLines.length),n}function Yf(e,t){return e.editSessionDirty!==!0?!1:(e.editSessionDirty=void 0,Object.assign(e,e.additionLines.length<=1&&e.additionLines.join("")===""?Qi(e,t):fN(e,t)),!0)}function dW(e,t){if(nW(e.deletionLines,e.additionLines)==null)return[];const n=po({name:e.prevName??e.name,contents:e.deletionLines.join("")},{name:e.name,contents:e.additionLines.join(""),lang:e.lang},t),s=[];let i=0,r=0;for(const a of n.hunks){const l=a.additionCount>0?a.additionLineIndex-i:a.deletionLineIndex-r;i+=l,r+=l;for(const c of a.hunkContent){if(c.type==="context"){i+=c.lines,r+=c.lines;continue}const d=xN(c,0,0);d.additions===0&&(d.additionLineIndex=i),d.deletions===0&&(d.deletionLineIndex=r),s.push(d),i+=d.additions,r+=d.deletions}}return s}function uW(e,t,n){const s=e.map((a,l)=>{const c=gr(a);return{deletionStart:c,deletionEnd:c+a.deletionCount,blocks:[],previousSpan:{firstIndex:l,lastIndex:l}}}),i=[];let r=0;for(const a of t){const l=a.deletionLineIndex,c=l+a.deletions;for(;r<s.length&&s[r].deletionEnd<l;)i.push(s[r]),r++;let d=i.length>0&&hW(l,c,i[i.length-1])?i.pop():void 0;for(;r<s.length&&s[r].deletionStart<=c;)d=pW(d,s[r]),r++;if(d==null){let u=l,h=c;if((a.deletions===0||a.additions===0)&&n>a.deletions){const p=i[i.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),i.push(d)}for(;r<s.length;)i.push(s[r]),r++;return i}function hW(e,t,n){return e<=n.deletionEnd&&t>=n.deletionStart}function pW(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 fW(e,t){const n=[];let s=0,i=0;for(const r of t){const a=r.deletionStart-s;if(a<0)throw new Error("buildRegionHunks: overlapping old-side regions");s+=a,i+=a;const l=i,c=[];for(const u of r.blocks){const h=u.deletionLineIndex-s,p=u.additionLineIndex-i;if(h<0||h!==p)throw new Error("buildRegionHunks: canonical block context mismatch");hw(c,h,i,s),s+=h,i+=p,c.push({...u}),s+=u.deletions,i+=u.additions}const d=r.deletionEnd-s;if(d<0)throw new Error("buildRegionHunks: block exceeds its old-side region");hw(c,d,i,s),s+=d,i+=d,n.push(mW(e,{additionStart:l,additionEnd:i,deletionStart:r.deletionStart,deletionEnd:r.deletionEnd},c))}if(e.deletionLines.length-s!==e.additionLines.length-i)throw new Error("buildRegionHunks: trailing context mismatch");return n}function mW(e,t,n){const s=t.additionEnd-t.additionStart,i=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:Ac(t.additionStart,s),additionCount:s,additionLines:r,additionLineIndex:fw(t.additionStart,s),deletionStart:Ac(t.deletionStart,i),deletionCount:i,deletionLines:a,deletionLineIndex:fw(t.deletionStart,i),hunkContent:n,hunkSpecs:`@@ -${Ac(t.deletionStart,i)},${i} +${Ac(t.additionStart,s)},${s} @@`,splitLineStart:0,splitLineCount:0,unifiedLineStart:0,unifiedLineCount:0,noEOFCRAdditions:!1,noEOFCRDeletions:!1};return hx(l),l}function hw(e,t,n,s){t>0&&e.push({type:"context",lines:t,additionLineIndex:n,deletionLineIndex:s})}function gW(e,t){if(e.length!==t.length)return!0;for(let n=0;n<e.length;n++){const s=e[n],i=t[n];if(gr(s)!==gr(i)||s.deletionCount!==i.deletionCount||pu(s)!==pu(i)||s.additionCount!==i.additionCount||s.splitLineCount!==i.splitLineCount||!xW(s,i))return!0}return!1}function xW(e,t){const n=pw(e),s=pw(t);for(;;){const i=n.next(),r=s.next();if(i.done===!0||r.done===!0)return i.done===r.done;if(i.value[0]!==r.value[0]||i.value[1]!==r.value[1])return!1}}function*pw(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 pu(e){return ua(e.additionStart,e.additionCount)}function gr(e){return ua(e.deletionStart,e.deletionCount)}function Ac(e,t){return t===0?e:e+1}function fw(e,t){return t===0?e-1:e}function vW(e){px(e);for(let t=0;t<e.hunks.length;t++)gN(e,t)}let bW=-1;var wW=class{options;onRenderUpdate;workerManager;__id=`diff-hunks-renderer:${++bW}`;highlighter;diff;expandedHunks=new Map;deletionAnnotations={};additionAnnotations={};computedLang="text";renderCache;editSessionActive=!1;constructor(e={theme:ki},t,n){this.options=e,this.onRenderUpdate=t,this.workerManager=n,n?.isWorkingPool()!==!0&&(this.highlighter=Ph(e.theme??ki)?PP():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,Td(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||pd(e.diff)||Lc(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);Cr(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)??EP}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:i}=this.renderCache;if(s==null)return!1;if(i.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<i.additionLines.length,x=f?i.additionLines[d]??"":"",g=wl(x);f&&(i.additionLines[d]=AP(x,p),g!==p&&(a.push(d),l.set(d,x))),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,w,y])=>v===0&&w===""?y===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:y}:{type:"element",tagName:"span",properties:{"data-char":v,style:`color:${w};`},children:[{type:"text",value:y}]})}}let c=!1;if(a.length>0)if(this.editSessionActive&&!i.isPartial){if(!n)if(i.additionLines.length<=1&&i.additionLines.join("")==="")Object.assign(i,Td(i,this.options.parseDiffOptions)),this.markEditSessionPass(i),c=!0;else if(Kf(i,i.additionLines))Object.assign(i,hu(i,i.additionLines,this.options.parseDiffOptions)),this.markEditSessionPass(i),c=!0;else{const d=sW(i,a,this.options.parseDiffOptions,l);this.applyExpansionRemap(d),c=d!=null}}else Object.assign(i,X4(i,a,this.options.parseDiffOptions));return s.baseThemeType=t,this.renderCache.isDirty=!0,c}applyExpansionRemap(e){e!=null&&(this.expandedHunks=aW(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=kW(e,s),n.code.additionLines=CW(s,t.additionLines,n.code.additionLines,e),t.additionLines.length<=1&&t.additionLines.join("")===""?(Object.assign(t,Td(t,this.options.parseDiffOptions)),n.code.additionLines[0]=Xf(0,e.getLineText(0)),this.markEditSessionPass(t)):this.editSessionActive?this.applySessionDocumentChange(t):Object.assign(t,fN(t,this.options.parseDiffOptions)),this.renderCache.isDirty=!0}applySessionDocumentChange(e){const{parseDiffOptions:t}=this.options,n=e.additionLines;if(Kf(e,n)){Object.assign(e,hu(e,n,t)),this.markEditSessionPass(e);return}this.applyExpansionRemap(qf(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=>MP(e);getOptionsWithDefaults(){const{diffIndicators:e="bars",diffStyle:t="split",disableBackground:n=!1,disableFileHeader:s=!1,disableLineNumbers:i=!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:x=!1,theme:g=ki,headerRenderMode:v="default",tokenizeMaxLineLength:w=1e3,tokenizeMaxLength:y=RP,useTokenTransformer:b=!1,useCSSClasses:_=!1}=this.options;return{diffIndicators:e,diffStyle:t,disableBackground:n,disableFileHeader:s,disableLineNumbers:i,disableVirtualizationBuffers:r,collapsed:a,expandUnchanged:l,collapsedContextThreshold:c,expansionLineCount:d,hunkSeparators:u,lineDiffType:h,maxLineDiffLength:p,overflow:f,stickyHeader:x,theme:this.workerManager?.getDiffRenderOptions().theme??g,headerRenderMode:v,tokenizeMaxLineLength:w,tokenizeMaxLength:y,useTokenTransformer:b,useCSSClasses:_}}async initializeHighlighter(){return this.highlighter=await LP(OP(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=Lc(e,this.getTokenizeMaxLength());let s=this.workerManager?.getDiffResultCache(e);s!=null&&!Cr(t,s.options)&&(s=void 0),this.renderCache??={diff:e,highlighted:!n&&!pd(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??Eh(e.name),this.initializeHighlighter())}getLocalHighlightTheme(){return this.workerManager?.getDiffRenderOptions().theme??this.options.theme??ki}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:i,lineDiffType:r,maxLineDiffLength:a}=this.getOptionsWithDefaults();return{theme:s,useTokenTransformer:this.editSessionActive||this.options.useTokenTransformer===!0,tokenizeMaxLineLength:i,lineDiffType:r,maxLineDiffLength:a}})();this.getOptionsWithDefaults();const{renderCache:n}=this;return n?.result==null?{options:t,forceHighlight:!0}:!zr(e,n.diff)||!Cr(t,n.options)?{options:t,forceHighlight:!0}:{options:t,forceHighlight:!1}}renderDiff(e=this.renderCache?.diff,t=uv){if(e==null)return;const{expandUnchanged:n,collapsedContextThreshold:s}=this.getOptionsWithDefaults();let{options:i,forceHighlight:r}=this.getRenderOptions(e);const a=this.getMatchingWorkerResultCache(e,i);a!=null&&!this.hasHighlightedRenderCache(e,i)&&(this.renderCache={diff:e,highlighted:!0,renderRange:void 0,...a},r=!1),this.renderCache??={diff:e,highlighted:!1,options:i,result:void 0,renderRange:void 0};const l=e.additionLines.length>0||e.deletionLines.length>0,c=!l||pd(e)||Lc(e,this.getTokenizeMaxLength()),d=!zr(e,this.renderCache.diff),u=!TC(this.renderCache.renderRange,t);if(!this.editSessionActive&&this.workerManager?.isWorkingPool()===!0){const h=this.renderCache.result==null&&this.renderCache.highlighted&&!c&&!d&&Uf(t);h&&(this.renderCache.highlightPending=!0),!h&&(c||this.renderCache.result==null||!this.renderCache.highlighted&&(d||u))&&(this.renderCache.diff=e,this.renderCache.options=i,this.renderCache.highlighted=!1,(this.renderCache.result==null||d||u||r)&&(this.renderCache.result=this.workerManager.getPlainDiffAST(e,t.startingLine,t.totalLines,Uf(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??Eh(e.name);const h=this.highlighter!=null&&Ph(i.theme),p=this.highlighter!=null&&hv(this.computedLang),f=!c&&p;if(this.highlighter!=null&&h&&(r||c||!this.renderCache.highlighted&&f||this.renderCache.result==null)){const{result:x,options:g}=this.renderDiffWithHighlighter(e,this.highlighter,c||!p);this.renderCache={diff:e,options:g,highlighted:f,result:x,renderRange:void 0}}(!h||!c&&!p)&&this.asyncHighlight(e).then(({result:x,options:g})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.applyHighlightResult(e,x,g,!c)})}return this.renderCache.result!=null?this.processDiffResult(this.renderCache.diff,t,this.renderCache.result):void 0}async asyncRender(e,t=uv){const{result:n}=await this.asyncHighlight(e);return this.processDiffResult(e,t,n)}createPreElement(e,t,n){const{diffIndicators:s,disableBackground:i,disableLineNumbers:r,overflow:a}=this.getOptionsWithDefaults();return zP({type:"diff",diffIndicators:s,disableBackground:i,disableLineNumbers:r,overflow:a,split:e,totalLines:t,customProperties:n})}async asyncHighlight(e){const t=Lc(e,this.getTokenizeMaxLength());this.computedLang=t?"text":e.lang??Eh(e.name);const n=this.highlighter!=null&&Ph(this.getLocalHighlightTheme()),s=t||this.highlighter!=null&&hv(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:i}=this.getOptionsWithDefaults(),r=GP(e,t,s,{forcePlainText:n,expandedHunks:n?!0:void 0,collapsedContextThreshold:i});if(this.editSessionActive&&e.additionLines.length===1&&e.additionLines[0]===""&&r.code.additionLines[0]==null){let a;if(Wr({diff:e,diffStyle:"both",expandedHunks:n?!0:void 0,collapsedContextThreshold:i,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]=Xf(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 i=this.renderCache.highlightPending===!0||!this.renderCache.highlighted||!Cr(this.renderCache.options,n)||!zr(this.renderCache.diff,e);this.renderCache={diff:e,options:n,highlighted:s,result:t,renderRange:void 0},i&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(e,t){if(this.editSessionActive)return;const n=this.workerManager?.getDiffResultCache(e);if(!(n==null||!Cr(t,n.options)))return n}hasHighlightedRenderCache(e,t){const{renderCache:n}=this;return n?.result!=null&&n.highlighted&&zr(e,n.diff)&&Cr(t,n.options)}onHighlightError(e){console.error(e)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}processDiffResult(e,t,{code:n,themeStyles:s,baseThemeType:i}){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=NW(e,this.options.loadDiffFiles!=null),x=!e.isPartial||f;let g=[],v=[],w=[];const y=[],{additionLines:b,deletionLines:_}=n,j={rowCount:0,hunkSeparators:u,additionsContentAST:g,deletionsContentAST:v,unifiedContentAST:w,unifiedGutterAST:bc(),deletionsGutterAST:bc(),additionsGutterAST:bc(),expansionLineCount:c,hunkData:y,incrementRowCount(O=1){j.rowCount+=O},pushToGutter(O,B){switch(O){case"unified":j.unifiedGutterAST.children.push(B);break;case"deletions":j.deletionsGutterAST.children.push(B);break;case"additions":j.additionsGutterAST.children.push(B);break}}},N=FP({fileDiff:e,errorPrefix:"DiffHunksRenderer.processDiffResult"}),C={size:0,side:void 0,increment(){this.size+=1},flush(){if(r!=="unified"){if(this.size<=0||this.side==null){this.side=void 0,this.size=0;return}this.side==="additions"?(j.pushToGutter("additions",si(void 0,"buffer",this.size)),g?.push(Pc(this.size))):(j.pushToGutter("deletions",si(void 0,"buffer",this.size)),v?.push(Pc(this.size))),this.size=0,this.side=void 0}}},k=(O,B,L,se,Q)=>{j.pushToGutter(O,VP(B,L,se,Q))};function E(O){C.flush(),r==="unified"?pp("unified",O,j):(pp("deletions",O,j),pp("additions",O,j))}this.pushFileLevelAnnotations(e,r,t,j),Wr({diff:e,diffStyle:r,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:l?!0:this.expandedHunks,collapsedContextThreshold:d,callback:({hunkIndex:O,hunk:B,collapsedBefore:L,collapsedAfter:se,additionLine:Q,deletionLine:V,type:H})=>{const ne=V!=null?V.splitLineIndex:Q.splitLineIndex,he=Q!=null?Q.unifiedLineIndex:V.unifiedLineIndex;r==="split"&&H!=="change"&&C.flush(),L>0&&E({hunkIndex:O,collapsedLines:L,rangeSize:Math.max(B?.collapsedBefore??0,0),hunkSpecs:B?.hunkSpecs,isFirstHunk:O===0,isLastHunk:!1,isExpandable:x});const pe=r==="unified"?he:ne,ke={type:H,hunkIndex:O,lineIndex:pe,unifiedLineIndex:he,splitLineIndex:ne,deletionLine:V,additionLine:Q};if(r==="unified"){const X=this.getUnifiedInjectedRowsForLine?.(ke);X?.before!=null&&gw(X.before,j);let z=V!=null?_[V.lineIndex]:void 0,ue=Q!=null?b[Q.lineIndex]:void 0;if(z==null&&ue==null){const Be="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(Be,{file:e.name}),new Error(Be)}const _e=H==="change"?Q!=null?"change-addition":"change-deletion":H,Ee=this.getUnifiedLineDecoration({type:H,lineType:_e,additionLineIndex:Q?.lineIndex,deletionLineIndex:V?.lineIndex});k("unified",Ee.gutterLineType,Q!=null?Q.lineNumber:V.lineNumber,`${he},${ne}`,Ee.gutterProperties),ue!=null?ue=Rc(ue,Ee.contentProperties,h&&Q!=null?{"data-line":Q.lineNumber,"data-line-index":`${he},${ne}`}:void 0):z!=null&&(z=Rc(z,Ee.contentProperties,h&&V!=null?{"data-line":V.lineNumber,"data-line-index":`${he},${ne}`}:void 0)),Mc({diffStyle:"unified",type:H,deletionLine:z,additionLine:ue,unifiedSpan:this.getAnnotations("unified",V?.lineNumber,Q?.lineNumber,O,pe),createAnnotationElement:Be=>this.createAnnotationElement(Be),context:j}),X?.after!=null&&gw(X.after,j)}else{const X=this.getSplitInjectedRowsForLine?.(ke);X?.before!=null&&xw(X.before,j,C);let z=V!=null?_[V.lineIndex]:void 0,ue=Q!=null?b[Q.lineIndex]:void 0;const _e=this.getSplitLineDecoration({side:"deletions",type:H,lineIndex:V?.lineIndex}),Ee=this.getSplitLineDecoration({side:"additions",type:H,lineIndex:Q?.lineIndex});if(z==null&&ue==null){const Ue="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(Ue,{file:e.name}),new Error(Ue)}const Be=(()=>{if(H==="change"){if(ue==null)return"additions";if(z==null)return"deletions"}})();Be!=null?(C.side!=null&&C.side!==Be&&C.flush(),C.side=Be,C.increment()):H==="change"&&C.flush();const De=this.getAnnotations("split",V?.lineNumber,Q?.lineNumber,O,pe);if(De!=null&&C.size>0&&C.flush(),V!=null){const Ue=Rc(z,_e.contentProperties,h?{"data-line":V.lineNumber,"data-line-index":`${V.unifiedLineIndex},${ne}`}:void 0);k("deletions",_e.gutterLineType,V.lineNumber,`${V.unifiedLineIndex},${ne}`,_e.gutterProperties),Ue!=null&&(z=Ue)}if(Q!=null){const Ue=Rc(ue,Ee.contentProperties,h?{"data-line":Q.lineNumber,"data-line-index":`${Q.unifiedLineIndex},${ne}`}:void 0);k("additions",Ee.gutterLineType,Q.lineNumber,`${Q.unifiedLineIndex},${ne}`,Ee.gutterProperties),Ue!=null&&(ue=Ue)}Mc({diffStyle:"split",type:H,additionLine:ue,deletionLine:z,...De,createAnnotationElement:Ue=>this.createAnnotationElement(Ue),context:j}),X?.after!=null&&xw(X.after,j,C)}const Me=r==="split"&&B!=null&&ne===B.splitLineStart+B.splitLineCount-1,fe=O===e.hunks.length-1&&B!=null&&(r==="split"?ne===B.splitLineStart+B.splitLineCount-1:he===B.unifiedLineStart+B.unifiedLineCount-1),F=Me?B.noEOFCRDeletions:!1,U=Me?B.noEOFCRAdditions:!1,de=(V?.noEOFCR??!1)||F,Y=(Q?.noEOFCR??!1)||U;if(Y||de){if(r==="split"&&C.flush(),de){const X=H==="context"||H==="context-expanded"?H:"change-deletion";r==="unified"?(j.unifiedContentAST.push(Ec(X)),j.pushToGutter("unified",si(X,"metadata",1))):(j.deletionsContentAST.push(Ec(X)),j.pushToGutter("deletions",si(X,"metadata",1)),Y||(j.pushToGutter("additions",si(void 0,"buffer",1)),j.additionsContentAST.push(Pc(1))))}if(Y){const X=H==="context"||H==="context-expanded"?H:"change-addition";r==="unified"?(j.unifiedContentAST.push(Ec(X)),j.pushToGutter("unified",si(X,"metadata",1))):(j.additionsContentAST.push(Ec(X)),j.pushToGutter("additions",si(X,"metadata",1)),de||(j.pushToGutter("deletions",si(void 0,"buffer",1)),j.deletionsContentAST.push(Pc(1))))}j.incrementRowCount(1)}u!=="simple"&&u!=="metadata"&&(se>0||fe&&f)&&E({hunkIndex:H==="context-expanded"?O:O+1,collapsedLines:fe&&f?"unknown":se,rangeSize:N,hunkSpecs:void 0,isFirstHunk:!1,isLastHunk:!0,isExpandable:x}),j.incrementRowCount(1)}}),r==="split"&&C.flush();const I=Math.max(U4(e.hunks),e.additionLines.length??0,e.deletionLines.length??0),T=t.bufferBefore>0||t.bufferAfter>0,A=!p&&e.type!=="deleted",D=!p&&e.type!=="new",W=j.rowCount>0||T;g=A&&W?g:void 0,v=D&&W?v:void 0,w=p&&W?w:void 0;const J=this.createPreElement(v!=null&&g!=null,I);return{unifiedGutterAST:p&&W?j.unifiedGutterAST.children:void 0,unifiedContentAST:w,deletionsGutterAST:D&&W?j.deletionsGutterAST.children:void 0,deletionsContentAST:v,additionsGutterAST:A&&W?j.additionsGutterAST.children:void 0,additionsContentAST:g,hunkData:y,preNode:J,themeStyles:s,baseThemeType:i,headerElement:a?void 0:this.renderHeader(this.diff),totalLines:I,rowCount:j.rowCount,bufferBefore:t.bufferBefore,bufferAfter:t.bufferAfter,css:""}}renderCodeAST(e,t){const n=e==="unified"?t.unifiedGutterAST:e==="deletions"?t.deletionsGutterAST:t.additionsGutterAST,s=e==="unified"?t.unifiedContentAST:e==="deletions"?t.deletionsContentAST:t.additionsContentAST;if(n==null||s==null)return;const i=bc(n);return i.properties.style=`grid-row: span ${t.rowCount}`,[i,HP(s,t.rowCount)]}renderFullAST(e,t=[]){const n=this.getOptionsWithDefaults().hunkSeparators==="line-info",s=this.renderCodeAST("unified",e);if(s!=null)return t.push(fs({tagName:"code",children:s,properties:{"data-code":"","data-container-size":n?"":void 0,"data-unified":""}})),{...e.preNode,children:t};const i=this.renderCodeAST("deletions",e);i!=null&&t.push(fs({tagName:"code",children:i,properties:{"data-code":"","data-container-size":n?"":void 0,"data-deletions":""}}));const r=this.renderCodeAST("additions",e);return r!=null&&t.push(fs({tagName:"code",children:r,properties:{"data-code":"","data-container-size":n?"":void 0,"data-additions":""}})),{...e.preNode,children:t}}renderFullHTML(e,t=[]){return er(this.renderFullAST(e,t))}renderPartialHTML(e,t){return t==null?er(e):er(fs({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(!IC(n))return;const i=e.type!=="new"?mw(pv(this.deletionAnnotations)):[],r=e.type!=="deleted"?mw(pv(this.additionAnnotations)):[];if(i.length===0&&r.length===0)return;const a=-1,l=-1,{createAnnotationElement:c}=this;if(t==="unified"){Mc({diffStyle:t,type:"context",unifiedSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:i.concat(r)},createAnnotationElement:c,context:s});return}Mc({diffStyle:t,type:"context",deletionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:i},additionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:r},createAnnotationElement:c,context:s})}getAnnotations(e,t,n,s,i){const r={type:"annotation",hunkIndex:s,lineIndex:i,annotations:[]};if(t!=null)for(const l of this.deletionAnnotations[t]??[])r.annotations.push(Zr(l));const a={type:"annotation",hunkIndex:s,lineIndex:i,annotations:[]};if(n!=null)for(const l of this.additionAnnotations[n]??[])(e==="unified"?r:a).annotations.push(Zr(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 BP({fileOrDiff:e,mode:t,stickyHeader:n})}};function mw(e){return e?.map(t=>Zr(t))??[]}const yW=new Intl.PluralRules("en-US");function SW(e){return`${e} unmodified line${yW.select(e)==="one"?"":"s"}`}function gw(e,t){for(const n of e)t.unifiedContentAST.push(n.content),t.pushToGutter("unified",n.gutter),t.incrementRowCount(1)}function xw(e,t,n){for(const{deletion:s,addition:i}of e){if(s==null&&i==null)continue;const r=s!=null&&i!=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)),i!=null&&(t.additionsContentAST.push(i.content),t.pushToGutter("additions",i.gutter)),r!=null&&(n.side=r,n.increment()),t.incrementRowCount(1)}}function Mc({diffStyle:e,type:t,deletionLine:n,additionLine:s,unifiedSpan:i,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),i!=null){const u=t==="change"?n!=null?"change-deletion":"change-addition":t;c.unifiedContentAST.push(l(i)),c.pushToGutter("unified",si(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",si(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",si(u,"annotation",1)),d=!0}}d&&c.incrementRowCount(1)}function pp(e,{hunkIndex:t,collapsedLines:n,rangeSize:s,hunkSpecs:i,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"){i!=null&&(c.pushToGutter(e,_r({type:"metadata",content:i,isFirstHunk:r,isLastHunk:a})),d.push(_r({type:"metadata",content:i,isFirstHunk:r,isLastHunk:a})),e!=="additions"&&c.incrementRowCount(1));return}if(c.hunkSeparators==="simple"){t>0&&(c.pushToGutter(e,_r({type:"simple",isFirstHunk:r,isLastHunk:!1})),d.push(_r({type:"simple",isFirstHunk:r,isLastHunk:!1})),e!=="additions"&&c.incrementRowCount(1));return}const u=W4(e,t),h=s>c.expansionLineCount,p=l?t:void 0,f=typeof n=="number"?SW(n):"More unchanged context may be available";c.pushToGutter(e,_r({type:c.hunkSeparators,content:f,expandIndex:p,chunked:h,slotName:u,isFirstHunk:r,isLastHunk:a})),d.push(_r({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 Rc(e,t,n){return e==null||e.type!=="element"||t==null&&n==null?e:{...e,properties:{...e.properties,...t,...n}}}function vw(e){return e.length>0&&e[e.length-1]===""?e.length-1:e.length}function CW(e,t,n,s){const i=vw(e),r=vw(t),a=Math.min(i,r);let l=0;for(;l<a&&e[l]===t[l];)l++;let c=0;for(;c<a-l&&e[i-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[i-1-u];i<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]??=Xf(u,s.getLineText(u));return d}function Xf(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 kW(e,t){const n=[],s=jW(t);for(let i=0;i<e.lineCount;i++){const r=e.getLineText(i,!0);n.push(i<e.lineCount-1&&!_W(r)?r+s:r)}return n}function _W(e){return e.endsWith(`
51
- `)||e.endsWith("\r")}function jW(e){for(const t of e){if(t.endsWith(`\r
52
- `))return`\r
53
- `;if(t.endsWith(`
54
- `))return`
55
- `;if(t.endsWith("\r"))return"\r"}return`
56
- `}function Lc(e,t){return Math.max(e.additionLines.length,e.deletionLines.length)>t}function NW(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function TW(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side&&e.metadata===t.metadata}function IW(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 Jf(e,t=300){let n;try{await Promise.race([e(),new Promise(s=>{n=setTimeout(s,t)})])}finally{n!=null&&clearTimeout(n)}}function Zf({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 DW(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:$P(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 PW(e){return e.isPartial&&(e.type==="change"||e.type==="rename-changed"||e.type==="rename-pure")}let EW=-1;var vN=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file-diff:${++EW}`;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:ki},n,s=!1){this.options=t,this.workerManager=n,this.isContainerManaged=s,this.hunksRenderer=this.createHunksRenderer(t),this.resizeManager=new WP,this.scrollSyncManager=new $4,this.interactionManager=new UP("diff",fv(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 DW(t)}createHunksRenderer(t){return new wW(this.getHunksRendererOptions(t),this.handleHighlightRender,this.workerManager)}getLineIndex=(t,n="additions")=>{const s=this.fileDiffCache;if(s==null)return;const i=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=ua(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===i){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 x=t-u;a=h+x,r=p+x;break e}else u+=f.lines,h+=f.lines,p+=f.lines;else{const x=n==="deletions"?f.deletions:f.additions;if(t<u+x){const g=t-u;r=p+(n==="additions"?f.deletions:0)+g,a=h+g;break e}else u+=x,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(fv(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&&!DC(this.appliedThemeCSS.theme,this.options.theme??ki)}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){qp(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:i,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=Zf(a,"FileDiff.hydrate"),c=l?.oldFile,d=l?.newFile;this.hydrateElements(t,n),RW(this.pre,AW({fileDiff:r,oldFile:c,newFile:d}),this.options.collapsed)||LW(this.headerElement,MW({fileDiff:r,oldFile:c,newFile:d}),this.options.disableFileHeader)?this.render({...a,fileContainer:t,lineAnnotations:i,fileDiff:r,preventEmit:!0}):this.hydrationSetup({fileDiff:r,lineAnnotations:i,...l}),s||this.emitPostRender()}hydrateElements(t,n){this.fileContainer!==t&&this.emitPostRender(!0),KP(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 i of s.children)!(i instanceof HTMLElement)||i.tagName.toLowerCase()!=="code"||("deletions"in i.dataset&&(this.codeDeletions=i),"additions"in i.dataset&&(this.codeAdditions=i),"unified"in i.dataset&&(this.codeUnified=i));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:i}){this.lineAnnotations=i??this.lineAnnotations,this.additionFile=s,this.deletionFile=n,this.fileDiff=t??(n!==void 0&&s!==void 0?po(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||!PW(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||(Wf("merge",t,n),this.setHydratedState(n),await Jf(()=>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:i=!1,lineAnnotations:r,fileContainer:a,containerWrapper:l,renderRange:c,...d}){const u=Zf(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:x="system",expandUnchanged:g=!1}=this.options,v=f?void 0:c,w=this.hasThemeChanged(),y=u!=null,b=y&&(!bw(h,this.deletionFile)||!bw(p,this.additionFile));let _=t!=null&&t!==this.fileDiff;const j=r!=null&&(r.length>0||this.lineAnnotations.length>0)?r!==this.lineAnnotations:!1;if(!f&&TC(v,this.renderRange)&&!s&&!j&&!w&&(t!=null&&t===this.fileDiff||t==null&&!b))return this.applyCachedThemeState(x);let N;t==null&&y&&(b||this.fileDiff==null)&&(N=po(u.oldFile,u.newFile,this.options.parseDiffOptions));const{renderRange:C}=this;if(this.renderRange=v,y?(this.deletionFile=h,this.additionFile=p):t!=null&&(this.deletionFile=void 0,this.additionFile=void 0),t!=null?this.fileDiff=t:N!=null&&(_=!0,this.fileDiff=N),_&&(this.cachedHeaderHTML=void 0),r!=null&&this.setLineAnnotations(r),this.fileDiff==null)return!1;this.fileDiff.editSessionDirty===!0&&this.shouldSelfHealEditSession()&&(Yf(this.fileDiff,this.options.parseDiffOptions),this.hunksRenderer.refreshHighlightedResult()),g&&this.loadFilesIfNecessary(),this.hunksRenderer.setOptions(this.getHunksRendererOptions(this.options)),this.syncInteractionOptions(),this.hunksRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:k=!1,disableFileHeader:E=!1}=this.options;if(E&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),a=this.getOrCreateFileContainer(a,l),this.applyCachedThemeState(x),f){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const I=this.hunksRenderer.renderDiff(this.fileDiff,qP);I!=null&&this.applyThemeState(a,I.themeStyles,x,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 i||this.emitPostRender(),!0}try{const I=this.getOrCreatePreNode(a);if(!(this.canPartiallyRender(s,j,b||_||w)&&this.applyPartialRender({previousRenderRange:C,renderRange:v}))){const T=this.hunksRenderer.renderDiff(this.fileDiff,v);if(T==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(a,T.themeStyles,x,T.baseThemeType),T.headerElement!=null&&this.applyHeaderToDOM(T.headerElement,a),T.additionsContentAST!=null||T.deletionsContentAST!=null||T.unifiedContentAST!=null?this.applyHunksToDOM(I,T):this.pre!=null&&(this.pre.remove(),this.pre=void 0),this.renderSeparators(T.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 i||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 i=this.mounted?"update":"mount";this.mounted=!0,s?.(n,this,i)}get fileDiffCache(){return this.hunksRenderer.diffCache??this.fileDiff}syncRenderViewToEditor(){const t=this.editor,n=this.fileContainer,s=this.fileDiffCache,i=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,i,r)})}computeEditorRenderRange(t){const n=this.fileDiffCache;if(t==null||n==null||Uf(t))return t;const{diffStyle:s="split",expandUnchanged:i=!1,collapsedContextThreshold:r=1}=this.options;let a,l;return Wr({diff:n,diffStyle:s,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:i?!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=lW(t,this.hunksRenderer.getExpandedHunksMap(),n);return Yf(t,this.options.parseDiffOptions),this.hunksRenderer.setExpandedHunksMap(cW(t,s)),this.hunksRenderer.refreshHighlightedResult(),this.escalateEditSessionRender(),!0}applyDocumentChange(t,n){this.hunksRenderer.applyDocumentChange(t);const s=this.hunksRenderer.diffCache;if(s!=null){const i=this.fileDiff?.cacheKey;i!=null&&s.cacheKey==null&&(s.cacheKey=i),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:i,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}i===!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:i=1}=this.options;return PC({fileDiff:n,lineNumber:t,expandedHunks:s?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:i})}getNearestRenderableLine(t,n){const s=this.fileDiffCache;if(s==null)return t;const{expandUnchanged:i=!1,collapsedContextThreshold:r=1}=this.options;return YP({fileDiff:s,lineNumber:t,direction:n,expandedHunks:i?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r})}revealLine(t){const n=this.fileDiffCache,{expandUnchanged:s=!1,collapsedContextThreshold:i=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]=mv(h);if(t<p){const x=yl({isPartial:n.isPartial,rangeSize:h.collapsedBefore,expandedHunks:a,hunkIndex:u,collapsedContextThreshold:i}),g=p-x.rangeSize;if(x.renderAll||t<g+x.fromStart||t>=p-x.fromEnd)return!1;const v=t-(g+x.fromStart)+1,w=p-x.fromEnd-t;return v<=w?this.expandHunk(u,"up",v+r):this.expandHunk(u,"down",w+r),!0}if(t<f)return!1}const l=Sl({fileDiff:n,hunkIndex:n.hunks.length-1,expandedHunks:a,collapsedContextThreshold:i,errorPrefix:"FileDiff.revealLine"});if(l==null||l.renderAll)return!1;const c=n.hunks[n.hunks.length-1],[,d]=mv(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(){EC(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||pd(t))return;const s=this.options.tokenizeMaxLength??1e5;Math.max(t.additionLines.length,t.deletionLines.length)>s||await n.primeDiffHighlightCache(t).catch(i=>{console.error(i)})}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:i}of this.separatorCache.values())i.remove();this.separatorCache.clear();return}const s=new Map(this.separatorCache);for(const i of t){const r=i.slotName;let a=this.separatorCache.get(r);if(a==null||!IW(i,a.hunkData)){a?.element.remove();const l=document.createElement("div");l.style.display="contents",l.slot=i.slotName;const c=n(i,this);c!=null&&l.appendChild(c),this.fileContainer.appendChild(l),a={element:l,hunkData:i},this.separatorCache.set(r,a)}s.delete(r)}for(const[i,{element:r}]of s.entries())this.separatorCache.delete(i),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,i]of this.lineAnnotations.entries()){const r=`${s}-${Zr(i)}`;let a=this.annotationCache.get(r);if(a==null||!TW(i,a.annotation)){a?.element.remove();const l=n(i);if(l==null)continue;a={element:XP(Zr(i)),annotation:i},a.element.appendChild(l),this.fileContainer.appendChild(a.element),this.annotationCache.set(r,a)}t.delete(r)}for(const[s,{element:i}]of t.entries())this.annotationCache.delete(s),i.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=JP();s.appendChild(n),this.fileContainer.appendChild(s),this.gutterUtilityContent=s}getOrCreateFileContainer(t,n){const{fileContainer:s}=this,i=t??s??document.createElement("diffs-container"),r=s!==i;return s!=null&&r&&this.editor?.__captureFocusForDOMReplacement(),r&&this.emitPostRender(!0),this.fileContainer=i,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:Yp(s)&&s.hasAttribute("data-theme-css")?(this.themeCSSStyle??=s,this.hasAdoptedThemeCSS=!0):Yp(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=ZP;const i=s.firstChild;i instanceof SVGElement&&(this.spriteSVG=i)}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,i=this.cachedHeaderHTML??er(t);if(this.cachedHeaderHTML=i,i!==this.lastRenderedHeaderHTML){const p=document.createElement("div");p.innerHTML=i;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=i}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,AC,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,QP,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(n,this.headerFilenameSuffix,eE,u),this.headerMetadata=this.upsertHeaderSlotElement(n,this.headerMetadata,tE,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,i){if(i==null){n?.remove();return}const r=n??this.createHeaderSlotElement(s);return n==null&&t.appendChild(r),this.replaceHeaderSlotContent(r,i),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??=nE(),this.unsafeCSSStyle.parentNode!==n&&n.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=sE(t),this.appliedUnsafeCSS=t)}}applyThemeState(t,n,s,i){const r=t.shadowRoot??t.attachShadow({mode:"open"}),a=i??s,l=this.options.theme??ki,c=typeof l=="string"?l:{...l},d=gv(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:i,scrollbarGutter:d};return}this.themeCSSStyle=iE({shadowRoot:r,currentNode:this.themeCSSStyle,themeCSS:cE(n,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:c,themeStyles:n,themeType:a,baseThemeType:i,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const t=this.fileContainer?.shadowRoot;t==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=oE(this.themeCSSStyle.textContent??"",gv(t)))}shouldGuardRebuildScroll(){return this.editor!=null&&rE()}applyHunksToDOM(t,n){this.shouldGuardRebuildScroll()?xv(t,()=>this.replaceCodeColumns(t,n)):this.replaceCodeColumns(t,n)}applyCodeColumnsInPlace(t,n,s){const i=this.getColumnPair(t);if(i==null)return!1;const r=wo(n[0]),a=wo(n[1]);return r==null||a==null?!1:(i.gutter.innerHTML=er(r),i.content.innerHTML=er(a),s!==this.lastRowCount&&(i.gutter.style.setProperty("grid-row",`span ${s}`),i.content.style.setProperty("grid-row",`span ${s}`)),!0)}replaceCodeColumns(t,n){const{overflow:s="scroll"}=this.options,i=(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=Ah({code:this.codeUnified,columnType:"unified",rowSpan:r,containerSize:i}),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=Ah({code:this.codeDeletions,columnType:"deletions",rowSpan:r,containerSize:i}),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=Ah({code:this.codeAdditions,columnType:"additions",rowSpan:r,containerSize:i}),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:i,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,i,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),x=Math.min(h,p);if(x<=f)return!1;const g=Math.max(0,f-d),v=Math.max(0,h-x),w=this.trimColumns({columns:c,trimStart:g,trimEnd:v,previousStart:d,overlapStart:f,overlapEnd:x,diffStyle:l});if(w<0)throw new Error("FileDiff.applyPartialRender: failed to trim to overlap");if(this.lastRowCount<w)throw new Error("FileDiff.applyPartialRender: trimmed beyond DOM row count");let y=this.lastRowCount-w;const b=(C,k)=>{if(!(k<=0||this.fileDiff==null))return this.hunksRenderer.renderDiff(this.fileDiff,{startingLine:C,totalLines:k,bufferBefore:0,bufferAfter:0})},_=b(u,Math.max(f-u,0));if(_==null&&u<f)return!1;const j=b(x,Math.max(p-x,0));if(j==null&&p>x)return!1;const N=(C,k)=>{if(C!=null){if(l==="unified"&&!Array.isArray(c))this.insertPartialHTML(l,c,C,k);else if(l==="split"&&Array.isArray(c))this.insertPartialHTML(l,c,C,k);else throw new Error("FileDiff.applyPartialRender.applyChunk: invalid chunk application");y+=C.rowCount}};return this.cleanupErrorWrapper(),N(_,"afterbegin"),N(j,"beforeend"),this.lastRowCount!==y&&(this.applyRowSpan(l,c,y),this.lastRowCount=y),!0}insertPartialHTML(t,n,s,i){if(t==="unified"&&!Array.isArray(n)){const r=this.hunksRenderer.renderCodeAST("unified",s);this.renderPartialColumn(n,r,i)}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,i),this.renderPartialColumn(n[1],a,i)}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=(i,r)=>{if(r==null)return;const a=this.hunksRenderer.renderCodeAST(i,t),l=wo(a?.[0]),c=wo(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),i=wo(s?.[0]),r=wo(s?.[1]),a=()=>{for(const[l,c]of[[n.gutter,i],[n.content,r]])c!=null&&(l.innerHTML=er(c));t.rowCount!==this.lastRowCount&&(this.applyRowSpan("unified",n,t.rowCount),this.lastRowCount=t.rowCount)};this.shouldGuardRebuildScroll()?xv(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 i=wo(n[0]),r=wo(n[1]);if(i==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],i,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],i,r,!1),t.gutter.insertAdjacentHTML(s,this.hunksRenderer.renderPartialHTML(i)),t.content.insertAdjacentHTML(s,this.hunksRenderer.renderPartialHTML(r))}mergeBuffersIfNecessary(t,n,s,i,r,a){if(!(n instanceof HTMLElement)||!(s instanceof HTMLElement))return;const l=this.getBufferSize(n.dataset);l!=null&&(a?(i.shift(),r.shift()):(i.pop(),r.pop()),this.updateBufferSize(n,l+t),this.updateBufferSize(s,l+t))}applyRowSpan(t,n,s){const i=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))i(n);else if(t==="split"&&Array.isArray(n))i(n[0]),i(n[1]);else throw new Error("dun fuuuuked up")}trimColumnRows(t,n,s){let i=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&&i>=s)&&(h.remove(),p.remove(),n>0&&(n--,n===0&&(l=!0)),r++),i++;continue}if("separator"in h.dataset&&"separator"in p.dataset){(n>0||c&&i>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in p.dataset){(n>0||c&&i>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="metadata"&&"noNewline"in p.dataset){(n>0||c&&i>=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 x=Math.min(n,f),g=f-x;g>0?(this.updateBufferSize(h,g),this.updateBufferSize(p,g),r+=x):(h.remove(),p.remove(),r+=f),n-=x,n===0&&g===0&&(l=!0)}else if(c){const x=i,g=i+f-1;if(s<=x)h.remove(),p.remove(),r+=f;else if(s<=g){const v=g-s+1,w=f-v;this.updateBufferSize(h,w),this.updateBufferSize(p,w),r+=v}}i+=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:i,previousStart:r,trimEnd:a,trimStart:l}){const c=Math.max(0,i-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 x=this.trimColumnRows(t[0],p,f),g=this.trimColumnRows(t[1],p,f);if(t[0]!=null&&t[1]!=null&&x!==g)throw new Error("FileDiff.trimColumns: split columns out of sync");return t[0]!=null?x:g}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,i){if(t==="unified")return this.getColumnPair(n);{const r=this.getColumnPair(s),a=this.getColumnPair(i);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:i},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:i,customProperties:r};aE(h,this.appliedPreAttributes)||(lE(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 i=document.createElement("div");i.dataset.errorMessage="",i.innerText=t.message,this.errorWrapper.appendChild(i);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 bw(e,t){return e==null||t==null?e==null&&t==null:MC(e,t)}function AW({fileDiff:e,oldFile:t,newFile:n}){return e!=null&&e.hunks.length>0||t!=null||n!=null}function MW({fileDiff:e,oldFile:t,newFile:n}){return e!=null||t!=null||n!=null}function RW(e,t,n=!1){return!n&&e==null&&t}function LW(e,t,n=!1){return e==null&&t&&!n}function wo(e){if(!(e==null||e.type!=="element"))return e.children??[]}function OW({fileDiff:e,metrics:t,disableFileHeader:n,hunkSeparators:s,expandUnchanged:i,expandedHunks:r,collapsedContextThreshold:a,canHydratePartialDiff:l}){let c=Mr(t,n),d=c;const u=i?!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 x=yl({isPartial:e.isPartial,rangeSize:f.collapsedBefore,expandedHunks:u,hunkIndex:p,collapsedContextThreshold:a}),g=(x.fromStart+x.fromEnd)*t.lineHeight;if(c+=g,d+=g,x.collapsedLines>0){const y=Ba({type:s,metrics:t,hunkIndex:p,hunkSpecs:f.hunkSpecs})?.totalHeight??0;c+=y,d+=y}c+=f.splitLineCount*t.lineHeight,d+=f.unifiedLineCount*t.lineHeight;const v=zW(f);c+=v.split*t.lineHeight,d+=v.unified*t.lineHeight;const w=p===h?Sl({fileDiff:e,hunkIndex:p,expandedHunks:u,collapsedContextThreshold:a,errorPrefix:"computeEstimatedDiffHeights"}):void 0;if(w!=null){const y=(w.fromStart+w.fromEnd)*t.lineHeight;if(c+=y,d+=y,w.collapsedLines>0){const b=Qo({type:s,metrics:t})?.totalHeight??0;c+=b,d+=b}}else if(p===h&&e.isPartial&&l){const y=Qo({type:s,metrics:t})?.totalHeight??0;c+=y,d+=y}}if(e.hunks.length>0){const p=RC(t);c+=p,d+=p}return{splitHeight:c,unifiedHeight:d}}function zW(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 GW(e,t)}function GW(e,t){const n=(t.deletions>0&&e.noEOFCRDeletions?1:0)+(t.additions>0&&e.noEOFCRAdditions?1:0),s=t.deletions>0&&e.noEOFCRDeletions,i=t.additions>0&&e.noEOFCRAdditions;return{split:s||i?1:0,unified:n}}const Qf=3e3;let FW=-1;var bN=class extends vN{__id=`little-virtualized-file-diff:${++FW}`;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,i=!1){super(e,s,i),this.virtualizer=t,this.metrics=Mh(n)}setMetrics(e,t=!1){const n=Mh(e);!t&&Xp(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||!dE(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=!Iu(t,e),s=n&&UW(t,e);super.setOptions(e),s&&this.resetLayoutCache({forceSimpleRecompute:!0,includeEstimatedHeights:KW(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],i=this.hasFileAnnotations(this.fileDiff);if(this.renderRange!=null&&i&&IC(this.renderRange)){const r=HW(s)??0;this.setFileAnnotationHeight(r)&&(e=!0)}else!i&&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=YW(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,x=u-p;x!==f&&(e=!0,this.cache.measuredHeightDeltaTotal+=x-f,x===0?this.cache.heightDeltas.delete(d):this.cache.heightDeltas.set(d,x))}}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 i=!zr(this.fileDiff,e),r=this.syncLineAnnotations(s);let a=n?.resetDiffLayoutCache===!0||i||r,l=i||n?.resetDiffLayoutCache===!0&&n.includeEstimatedDiffHeights;n?.metrics!=null&&(this.metrics=Mh(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:i=!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=Mr(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 Wr({diff:this.fileDiff,diffStyle:l,startingLine:h?.renderedLineIndex??0,expandedHunks:i?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:x,hunk:g,collapsedBefore:v,collapsedAfter:w,deletionLine:y,additionLine:b})=>{const _=l==="split"?b?.splitLineIndex??y?.splitLineIndex:b?.unifiedLineIndex??y?.unifiedLineIndex;if(_==null)throw new Error("VirtualizedFileDiff.getLinePosition: missing line index data");if(v>0){const N=Ba({type:c,metrics:this.metrics,hunkIndex:x,hunkSpecs:g?.hunkSpecs});if(N!=null){if(p+=N.gapBefore,d>=_-v&&d<_)return f={top:p,height:N.height},!0;p+=N.height+N.gapAfter}}const j=this.getLineHeight(_,(b?.noEOFCR??!1)||(y?.noEOFCR??!1));if(_===d)return f={top:p,height:j},!0;if(p+=j,w>0){const N=Qo({type:c,metrics:this.metrics});if(N!=null){if(d>_&&d<=_+w)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:i=1}=this.options;if(s)return;const r=this.getDiffStyle(),a=this.getHunkSeparatorType();this.approximateLayoutCheckpoints();const l=this.getLayoutCheckpointBeforeTop(e);let c=l?.top??Mr(this.metrics,t)+this.cache.fileAnnotationHeight,d;return Wr({diff:this.fileDiff,diffStyle:r,startingLine:l?.renderedLineIndex??0,expandedHunks:n?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:i,callback:({hunkIndex:u,hunk:h,collapsedBefore:p,collapsedAfter:f,deletionLine:x,additionLine:g})=>{const v=r==="split"?g?.splitLineIndex??x?.splitLineIndex:g?.unifiedLineIndex??x?.unifiedLineIndex;if(v==null)throw new Error("VirtualizedFileDiff.getNumericScrollAnchor: missing line index data");if(p>0){const y=Ba({type:a,metrics:this.metrics,hunkIndex:u,hunkSpecs:h?.hunkSpecs});y!=null&&(c+=y.totalHeight)}if(c>=e&&(x!=null?d={lineNumber:x.lineNumber,side:"deletions",top:c}:g!=null&&(d={lineNumber:g.lineNumber,side:"additions",top:c}),d!=null))return!0;const w=this.getLineHeight(v,(g?.noEOFCR??!1)||(x?.noEOFCR??!1));if(c+=w,f>0){const y=Qo({type:a,metrics:this.metrics});y!=null&&(c+=y.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:i}=t;let r=0;if(i===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=Wf("clone",e,t);if(await Jf(()=>this.primeHighlightCache(n)),!this.enabled||this.fileDiff!==e)return;this.pendingHydratedDiff={expectedDiff:e,nextDiff:n,files:t}}else{if(Wf("merge",e,t),this.setHydratedState(t),await Jf(()=>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:i}=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 i!=null&&(this.pendingHydratedDiff=void 0,i.expectedDiff===e&&(this.setHydratedState(i.files),n=i.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:i=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 PC({fileDiff:n,lineNumber:e,expandedHunks:r,collapsedContextThreshold:i})}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 i=this.virtualizer.getWindowSpecs(),r=this.computeRenderRangeFromWindow(this.fileDiff,this.top??0,i);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:i=!1,collapsed:r=!1}=this.options,a=Mr(this.metrics,i);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:i,unifiedHeight:r}=OW({fileDiff:e,metrics:this.metrics,disableFileHeader:t,hunkSeparators:this.getHunkSeparatorType(),expandUnchanged:n,expandedHunks:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:s,canHydratePartialDiff:fp(e,this.options.loadDiffFiles!=null)});this.cache.estimatedSplitHeight=i,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,...i}={}){const r=Zf(i,"VirtualizedFileDiff.render"),a=r!=null,l=r?.oldFile,c=r?.newFile,d=a&&(!Sw(l,this.deletionFile)||!Sw(c,this.additionFile));let u=t??this.fileDiff;t==null&&a&&(d||this.fileDiff==null)&&(u=po(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 x=t!=null&&t!==this.fileDiff,g=u!=null&&!zr(this.fileDiff,u),v=x||d;if(g&&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(),g&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.computeApproximateSize(!1,u));else{this.computeApproximateSize(!1,u);const j=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(j==null)throw new Error("VirtualizedFileDiff.render: simple virtualizer is not available");j.connect(e,this),this.isVisible=j.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode()&&(!v||!p))return this.fileDiff=u,r!=null&&(this.deletionFile=l,this.additionFile=c),g&&(this.cachedHeaderHTML=void 0),this.renderPlaceholder(this.height);const w=this.virtualizer.getWindowSpecs(),y=this.top??0,b=this.computeRenderRangeFromWindow(u,y,w),_=super.render({fileDiff:u,fileContainer:e,renderRange:b,lineAnnotations:s,forceRender:(h??n)||f||g,...r,...i});return this.isSimpleMode()&&_&&this.getSimpleVirtualizer()?.requestHeightReconcile(this),_}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}shouldGuardRebuildScroll(){return!1}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}getAdvancedVirtualizer(){return this.virtualizer.type==="advanced"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}getDiffStyle(){return this.options.diffStyle??"split"}getHunkSeparatorType(){return qW(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,i=e.hunks.length-1,r=fp(e,this.options.loadDiffFiles!=null),a=this.getDiffStyle(),l=this.getHunkSeparatorType(),c=n?!0:this.hunksRenderer.getExpandedHunksMap(),d=BW(this.cache.heightDeltas);let u=Mr(this.metrics,t)+this.cache.fileAnnotationHeight,h=0;const p=({rowCount:f,startLineIndex:x,preSeparatorHeight:g=0,postSeparatorHeight:v=0,metadataOffsets:w=[]})=>{if(f<=0)return;const y=h,b=h+f;let _=VW(y);for(;_<b;){const j=_-y,N=u+(j>0?g:0)+j*this.metrics.lineHeight+$W(w,j)*this.metrics.lineHeight+ww(d,x,x+j);this.cache.checkpoints.push({renderedLineIndex:_,lineIndex:x+j,top:N}),_+=Qf}u+=g+f*this.metrics.lineHeight+w.length*this.metrics.lineHeight+ww(d,x,x+f)+v,h=b};for(let f=0;f<e.hunks.length;f++){const x=e.hunks[f];if(x==null)throw new Error("VirtualizedFileDiff.approximateLayoutCheckpoints: invalid hunk index");const g=yl({isPartial:e.isPartial,rangeSize:x.collapsedBefore,expandedHunks:c,hunkIndex:f,collapsedContextThreshold:s}),v=g.collapsedLines>0?Ba({type:l,metrics:this.metrics,hunkIndex:f,hunkSpecs:x.hunkSpecs})?.totalHeight??0:0;p({rowCount:g.fromStart,startLineIndex:(a==="split"?x.splitLineStart:x.unifiedLineStart)-g.rangeSize});let w=v;p({rowCount:g.fromEnd,startLineIndex:(a==="split"?x.splitLineStart:x.unifiedLineStart)-g.fromEnd,preSeparatorHeight:w}),g.fromEnd>0&&(w=0);const y=f===i?Sl({fileDiff:e,hunkIndex:f,expandedHunks:c,collapsedContextThreshold:s,errorPrefix:"VirtualizedFileDiff"}):void 0,b=y!=null&&y.collapsedLines>0?Qo({type:l,metrics:this.metrics})?.totalHeight??0:f===i&&r?Qo({type:l,metrics:this.metrics})?.totalHeight??0:0,_=y!=null?y.fromStart+y.fromEnd:0,j=a==="split"?x.splitLineCount:x.unifiedLineCount,N=a==="split"?x.splitLineStart:x.unifiedLineStart;p({rowCount:j,startLineIndex:N,preSeparatorHeight:w,postSeparatorHeight:_===0?b:0,metadataOffsets:WW({diffStyle:a,hunk:x,rowCount:j})}),y!=null&&_>0&&p({rowCount:_,startLineIndex:N+j,postSeparatorHeight:b})}this.cache.totalLines=h}getLayoutCheckpointBeforeLineIndex(e){if(e<=0||this.cache.checkpoints.length===0)return;let t=0,n=this.cache.checkpoints.length-1,s;for(;t<=n;){const i=t+n>>1,r=this.cache.checkpoints[i];if(r==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");r.lineIndex<=e?(s=r,t=i+1):n=i-1}return s}getLayoutCheckpointBeforeTop(e,t){let n=0,s=this.cache.checkpoints.length-1,i=-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?(i=r,n=r+1):s=r-1}if(t==null)return i>=0?this.cache.checkpoints[i]:void 0;for(let r=i;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:i=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}=yl({isPartial:e.isPartial,rangeSize:u,expandedHunks:r,hunkIndex:l,collapsedContextThreshold:i});u>0&&(n+=f?u:h+p)}const a=Sl({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:r,collapsedContextThreshold:i,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:i=!1,expandUnchanged:r=!1,collapsedContextThreshold:a=1}=this.options,{hunkLineCount:l,lineHeight:c}=this.metrics,d=this.getDiffStyle(),u=this.getHunkSeparatorType(),h=fp(e,this.options.loadDiffFiles!=null),p=this.height;let f=this.getLayoutLineCount(e,d);const x=Mr(this.metrics,i),g=e.hunks.length>0?RC(this.metrics):0,{fileAnnotationHeight:v}=this.cache,w=x+v,y=Math.max(0,p-x-v-g),b=this.hasFileAnnotations(e),_=t+x,j=v>0&&b&&_<s&&_+v>n;if(t<n-p||t>s)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-x-g};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),C=Math.ceil(N/l)*l+l,k=C/l,E=k,I=[],T=(n+s)/2,A=this.getLayoutCheckpointBeforeTop(Math.max(0,n-t-C*c*2),l);let D=t+(A?.top??w),W=A?.renderedLineIndex??0,J,O,B;if(Wr({diff:e,diffStyle:d,startingLine:A?.renderedLineIndex??0,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:Me,hunk:fe,collapsedBefore:F,collapsedAfter:U,deletionLine:de,additionLine:Y})=>{const X=Y!=null?Y.splitLineIndex:de.splitLineIndex,z=Y!=null?Y.unifiedLineIndex:de.unifiedLineIndex,ue=(Y?.noEOFCR??!1)||(de?.noEOFCR??!1),_e=Me===e.hunks.length-1&&fe!=null&&(d==="split"?X===fe.splitLineStart+fe.splitLineCount-1:z===fe.unifiedLineStart+fe.unifiedLineCount-1),Ee=(F>0?Ba({type:u,metrics:this.metrics,hunkIndex:Me,hunkSpecs:fe?.hunkSpecs}):void 0)?.totalHeight??0;D+=Ee;const Be=W%l===0,De=Math.floor(W/l);if(Be&&(I[De]=D-(t+w+Ee),B!=null)){if(B<=0)return!0;B--}const Ue=this.getLineHeight(d==="split"?X:z,ue);if(D>n-Ue&&D<s&&(J??=De),O==null&&D+Ue>T&&(O=De),B==null&&D>=s&&Be&&(B=E),W++,D+=Ue,U>0||_e&&h){const St=Qo({type:u,metrics:this.metrics});St!=null&&(D<s&&D+St.totalHeight>n&&(J??=De),O==null&&D+St.totalHeight>T&&(O=De),D+=St.totalHeight)}return!1}}),J==null)if(j)J=0,O=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-x-g};O??=J;const L=Math.round(O-k/2),se=Math.max(0,Math.ceil(f/l)-k),Q=Math.max(0,Math.min(L,se)),V=Q*l,H=L<0?C+L*l:C,ne=I[Q]??0,he=V===0?0:v+ne,pe=Q+H/l,ke=pe<I.length?y-I[pe]:y-(D-t-w);return{startingLine:V,totalLines:H,bufferBefore:he,bufferAfter:Math.max(0,ke)}}};function HW(e){let t;for(const n of e){if(n==null)continue;const s=n.children[1];if(s instanceof HTMLElement)for(const i of s.children)i instanceof HTMLElement&&i.dataset.lineAnnotation===uE&&(t=Math.max(t??0,i.getBoundingClientRect().height))}return t}function BW(e){const t=Array.from(e).sort((r,a)=>r[0]-a[0]),n=[],s=[0];let i=0;for(const[r,a]of t)n.push(r),i+=a,s.push(i);return{lineIndexes:n,prefixTotals:s}}function ww({lineIndexes:e,prefixTotals:t},n,s){if(n>=s||e.length===0)return 0;const i=yw(e,n);return(t[yw(e,s)]??0)-(t[i]??0)}function yw(e,t){let n=0,s=e.length;for(;n<s;){const i=n+s>>1,r=e[i];if(r==null)throw new Error("VirtualizedFileDiff: invalid prefix index");r<t?n=i+1:s=i}return n}function VW(e){return Math.ceil(e/Qf)*Qf}function $W(e,t){let n=0;for(const s of e)s<t&&n++;return n}function WW({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 i=Math.max(s.deletions,s.additions),r=s.deletions+s.additions;if(e==="split")return i>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 UW(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 KW(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 fp(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function qW(e){return typeof e=="function"?"custom":e??"line-info"}function Sw(e,t){return e==null||t==null?e==null&&t==null:MC(e,t)}function YW(e,t){const[n,s]=e.split(",").map(Number);return t==="split"?s:n}function wN(e,t){return e==null||t==null?e===t:e.header!==t.header||e.footer!==t.footer?!1:XW(e.items,t.items)}function XW(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],i=t[n];if(s==null||i==null||s.id!==i.id||s.type!==i.type||s.element!==i.element||s.instance!==i.instance||s.version!==i.version)return!1}return!0}function JW(e,t,n){const s=document.createElement("div");return s.style.display="flow-root",e==="header"?(s.setAttribute(hE,""),t.before(s)):(s.setAttribute(pE,""),t.after(s)),n?.observe(s),s}function xi(e){const t=window.devicePixelRatio??1;return Math.round(e*t)/t}const ZW=["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"],QW=["theme","disableLineNumbers","overflow","themeType","disableFileHeader","disableVirtualizationBuffers","preferredHighlighter","useCSSClasses","useTokenTransformer","tokenizeMaxLineLength","tokenizeMaxLength","unsafeCSS","lineHoverHighlight","enableTokenInteractionsOnWhitespace","enableGutterUtility","__debugPointerEvents","enableLineSelection","controlledSelection","disableErrorHandling"],Cw=["renderCustomHeader","renderHeaderPrefix","renderHeaderFilenameSuffix","renderHeaderMetadata","renderAnnotation","renderGutterUtility","onPostRender","onGutterUtilityClick","onLineClick","onLineNumberClick","onLineEnter","onLineLeave","onTokenClick","onTokenEnter","onTokenLeave"],kw=["onLineSelected","onLineSelectionStart","onLineSelectionChange","onLineSelectionEnd"],yN=Symbol("CodeView.itemOptionsState");function _w(e,t){Object.defineProperty(e,yN,{configurable:!1,enumerable:!1,value:t})}function Ta(e){return e[yN]}function Ui(e,t,n){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get(){return n(this)}})}const e8=120,jw=1,Nw="--diffs-overflow-override",fx=12e6,SN=1e6,CN=2e6,t8=fx-CN,Tw=fx-SN;function n8(e){if(e==null)throw new Error("CodeView: createEditor is required for items with edit: true")}const s8=(()=>{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 i8=class Zi{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=_a;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:ki},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??fE}getItemTopOffset(){return this.getLayout().paddingTop+this.header.height}computeMetricsCache(t){return this.itemMetricsCache={hunkLineCount:t?.hunkLineCount??_a.hunkLineCount,lineHeight:t?.lineHeight??_a.lineHeight,diffHeaderHeight:t?.diffHeaderHeight??_a.diffHeaderHeight,hunkSeparatorHeight:t?.hunkSeparatorHeight,spacing:t?.spacing??_a.spacing,paddingTop:t?.paddingTop,paddingBottom:t?.paddingBottom},this.itemMetricsCache}getSmoothScrollSettings(){return this.options.smoothScrollSettings??mE}shouldDisablePointerEvents(){return this.options.pointerEventsOnScroll!==!0}shouldValidateItemHeights(){return gE&&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,i=t.element.getBoundingClientRect().height;s!==i&&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:i,delta:i-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:i,stickyBottom:r}=this.renderState;if(t===-1||n===-1)return;const a=this.stickyContainer.getBoundingClientRect().height;Math.abs(a-s)<jw||console.error("CodeView: sticky container height does not match computed layout",{computedStickyHeight:s,actualStickyHeight:a,delta:a-s,stickyTop:i,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),s8&&!this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Nw,"hidden"),this.codeOverflowFix=!0),this.scrollInteractionFixTimer=setTimeout(this.restoreScrollInteractions,e8)}restoreScrollInteractions=()=>{this.clearScrollInteractionTimer(),this.pointerEventsDisabled&&(this.stickyContainer.style.removeProperty("pointer-events"),this.pointerEventsDisabled=!1),this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Nw,"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 i=t==="header"?this.header:this.footer,r=t==="header"?this.options.renderCodeViewHeader:this.options.renderCodeViewFooter;if(r==null)return i.element==null||(this.resizeObserver?.unobserve(i.element),i.element.remove(),i.element=void 0,i.render=void 0,this.setHostHeight(i,0)),!1;if(i.element!=null&&r===i.render)return!1;const a=i.element??JW(t,s,this.resizeObserver);i.element=a;const l=r();return l!=null?a.replaceChildren(l):!this.isContainerManaged&&a.children.length>0&&(a.textContent=""),i.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=()=>{Zi.__STOP?(Zi.__STOP=!1,this.scrollTo({type:"position",position:Zi.__lastScrollPosition,behavior:"instant"})):(Zi.__lastScrollPosition=this.getScrollTop(),Zi.__STOP=!0)}}reset(){qp(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(LC),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))c8(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 L4()?"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 i=this.itemEditors.get(t);return i!=null&&(i.state.id=n,this.itemEditors.delete(t),this.itemEditors.set(n,i),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 i of this.items)i!==n&&s.push(i.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 i=this.items.length===0?0:this.scrollHeight+s.gap;const r=i;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,i);this.items.push(c),this.idToItem.set(c.item.id,c),this.instanceToItem.set(c.instance,c),c.height=o8(c),i+=c.height+s.gap}this.scrollHeight=i-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:i}=this;r8(n,t)&&this.invalidateElementPool(),this.options=t;const r=this.computeMetricsCache(t.itemMetrics),a=!Xp(i,r),l=!Xp(s,this.getLayout());l&&this.syncLayout();const c=a||a8(n,t);if(c){const u=this.pendingLayoutReset;this.pendingLayoutReset={metrics:a?r:u?.metrics,resetFileLayoutCache:!0,resetDiffLayoutCache:!0,includeEstimatedDiffHeights:u?.includeEstimatedDiffHeights===!0||a||l8(n,t)}}(l||c)&&(this.markLayoutDirtyFromIndex(0),this.scrollDirty=!0),Iu(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){Zi.__STOP||(t?(qp(this.computeRenderRangeAndEmit),this.computeRenderRangeAndEmit()):EC(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 i=t;i<=n;i++){const r=this.items[i];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=u8(this.getRenderedItems(),t),{element:s}=this.header,{element:i}=this.footer;if(!(n==null&&s==null&&i==null))return{items:n,header:s,footer:i}}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:i}=this;if(t.type==="diff"){const a=new bN(this.createDiffOptions(t.id),this,i,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 xE(this.createFileOptions(t.id),this,i,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&&vE(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 i=this.itemEditors.get(n),r=!1;try{if(i==null){n8(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;i={editor:l,state:a},this.itemEditors.set(n,i),r=!0}i.editor.edit(t.instance),this.attachedEditors.add(n)}catch(a){throw r&&i!=null&&(this.itemEditors.delete(n),i.editor.cleanUp()),this.releaseRenderedItem(t),a}}syncItemEditors(t){if(this.itemEditors.size===0)return;const n=[];for(const[s,i]of this.itemEditors){const r=this.idToItem.get(s),a=t?.get(s);if(a==null&&r!=null&&this.isItemInEditMode(r))continue;i.editor.cleanUp(),this.itemEditors.delete(s),this.attachedEditors.delete(s);const{lastChange:l}=i.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()),Yf(c.fileDiff)),l!=null&&n.push(a!=null||r==null?l:{...l,item:r.item})}for(const{item:s,file:i,lineAnnotations:r}of n)this.options.onItemEditComplete?.(s,i,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 QW)Ui(t,n,()=>this.options[n]);Ui(t,"stickyHeader",()=>this.options.stickyHeaders),Ui(t,"collapsed",n=>{const s=Ta(n);if(s!=null)return this.getItemOptions(s,"file")?.item.collapsed});for(const n of Cw)this.defineItemSharedCallback(t,"file",n);for(const n of kw)this.defineItemSelectionCallback(t,"file",n);return t}createDiffOptionsPrototype(){const t={};for(const n of ZW)Ui(t,n,()=>this.options[n]);Ui(t,"stickyHeader",()=>this.options.stickyHeaders),Ui(t,"hunkSeparators",()=>this.options.hunkSeparators),Ui(t,"collapsed",n=>{const s=Ta(n);if(s!=null)return this.getItemOptions(s,"diff")?.item.collapsed});for(const n of Cw)this.defineItemSharedCallback(t,"diff",n);for(const n of kw)this.defineItemSelectionCallback(t,"diff",n);return t}createFileOptions(t){const n=Object.create(this.fileOptionsPrototype);return _w(n,{id:t}),n}createDiffOptions(t){const n=Object.create(this.diffOptionsPrototype);return _w(n,{id:t}),n}updateItemOptionsId(t,n){const s=Ta(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){Ui(t,s,i=>{if(this.options[s]==null)return;const r=Ta(i);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){Ui(t,s,i=>{const r=Ta(i);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 i=t[n];if(i==null||s.item.id!==i.id||s.type!==i.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 i=t[n];if(i==null)throw new Error("CodeView.tryAppendItems: append candidate missing prefix item");this.syncItemRecord(s,i)&&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,i=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?(i.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(i.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||!i.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()>Tw}getPagedScrollHeight(){return this.shouldRebaseScroll()?Math.min(this.getScrollHeight(),fx):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=xi(this.clampPagedScrollTop(n)),i=this.clampScrollPageOffset(t-s);return s=xi(this.clampPagedScrollTop(t-i)),i=this.clampScrollPageOffset(t-s),{pagedScrollTop:s,scrollPageOffset:i}}resolvePagedScrollPosition(t){if(!this.shouldRebaseScroll())return{pagedScrollTop:this.clampPagedScrollTop(t),scrollPageOffset:0};const n=this.clampScrollPageOffset(this.scrollPageOffset),s=t-n,i=this.getMaxPagedScrollTop(),r=this.getMaxScrollPageOffset(),a=s>Tw&&n<r,l=s<SN&&n>0;return s<0||s>i||a||l?this.resolveScrollPageWindow(t,l?Math.min(t8,i):CN):{pagedScrollTop:xi(this.clampPagedScrollTop(s)),scrollPageOffset:n}}needsScrollPageUpdate(t){const n=xi(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 i=this.getRangeScrollPosition(n,t);if(i==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Iw(t.range)} for item "${t.id}"`);return}return{top:n.top+i.top,height:i.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,i=this.getItemTopOffset()+n.top,r=i+n.height,a=this.getScrollTop(),l=a+(t.type==="line"||t.type==="range"?this.getStickyHeaderOffset():0),c=a+this.getHeight();if(!(i-s<=l&&r+s>=c)){if(i-s<l)return{...t,align:"start"};if(r+s>c)return{...t,align:"end"}}}resolveScrollTargetTop(t){if(t.type==="position"){const i=this.clampScrollTop(t.position);return i!==t.position?i: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 i=this.getRangeScrollPosition(n,t);if(i==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Iw(t.range)} for item "${t.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(n.top+i.top,i.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,i=0,r=0){t+=this.getItemTopOffset();const a=this.getHeight();return s==="center"&&n+i<a?t-(a-n)/2+i:s==="end"?t-(a-n)+i:t-r-i}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,i=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(i==null||r==null)return;const a=i.top,l=a+i.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:i}=this;return i==null?s:this.computeSpringStep(i,s,n).position}computeSpringStep(t,n,s){const i=Math.max(0,s-t.lastTimestamp),{omega:r}=this.getSmoothScrollSettings(),a=Math.exp(-r*i),l=t.position-n,c=t.velocity+r*l;return{position:n+(l+c*i)*a,velocity:(c*(1-r*i)-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 i=this.scrollAnimation;if(i==null)return s;i.position+=n;const{position:r,velocity:a}=this.computeSpringStep(i,s,t);i.lastTimestamp=t,i.position=r,i.velocity=a;const{positionEpsilon:l,velocityEpsilon:c}=this.getSmoothScrollSettings();return Math.abs(s-r)<=l&&Math.abs(a)<=c?(i.position=s,i.velocity=0,this.scrollAnimation=void 0,s):i.position}computeRenderRangeAndEmit=(t=performance.now())=>{if(Zi.__STOP||this.container==null||!this.isReady())return;const n=this.getHeight(),s=this.getScrollTop();let i=s,r=this.pendingLayoutAnchor!=null,a=this.getScrollAnchor(i);if(this.layoutDirtyIndex!=null&&(this.recomputeLayout(this.layoutDirtyIndex,this.pendingLayoutReset),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,r=!0),r&&a!=null){const C=this.resolveAnchoredScrollTop(a);if(C!=null){const k=C-i;i=C,this.scrollAnimation!=null&&(this.scrollAnimation.position+=k)}}r&&(i=this.clampScrollTop(i),this.syncContainerHeight());const l=this.computeTargetScrollTopForFrame(i,t),c=!r&&(this.renderState.scrollTop===-1||Math.abs(l-this.renderState.scrollTop)>n+this.config.overscrollSize*2);c&&(a=void 0),this.windowSpecs=bE({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 C=p;C<=f;C++){const k=this.items[C];if(k==null)throw new Error(`CodeView.computeRenderRangeAndEmit: No item at index: ${C}`);k.top>u-k.height&&k.top<=h||this.releaseRenderedItem(k)}const x=this.reconcileHeaderFooterHosts();let g;const v=new Set,w=this.findFirstVisibleIndex(u),y=this.findLastVisibleIndex(h);for(let C=w;C<=y;C++){const k=this.items[C];if(k==null)throw new Error("CodeView.computeRenderRangeAndEmit: missing item");const{instance:E}=k;k.element==null?(k.element=this.acquireElement(),Ew(this.stickyContainer,k.element,g),E.virtualizedSetup(),Pw(k,k.element)&&(k.renderedOptionsRevision=this.renderOptionsRevision,v.add(k)),g=k.element):(Ew(this.stickyContainer,k.element,g),Pw(k,void 0,k.renderedOptionsRevision!==this.renderOptionsRevision)&&(k.renderedOptionsRevision=this.renderOptionsRevision,v.add(k)),g=k.element),k.item.edit===!0&&this.attachItemEditor(k)}this.renderState.firstIndex=w<=y?w:-1,this.renderState.lastIndex=y,this.flushSlotCoordinator(),this.flushManagers(v),x&&this.measureMountedHosts(),this.reconcileRenderedItems(v),this.syncContainerHeight(),this.updateStickyPositioning();const b=a!=null?this.resolveAnchoredScrollTop(a):void 0;a===this.pendingLayoutAnchor&&(this.pendingLayoutAnchor=void 0);const _=b!=null?b-i:0;let j=l,N=!1;if(this.pendingScrollTarget!=null){const C=this.advanceScrollAnimation(t,_);C!=null?(j=C,N=!0):j=i}else j=b??l;j!==d&&(this.applyScrollFix(j,d,this.windowSpecs),d=j),N&&this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),this.renderState.scrollTop=xi(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 i=this.items[n]?.instance.getAdvancedStickySpecs(t),r=this.items[s]?.instance.getAdvancedStickySpecs(t);if(!(i==null||r==null))return{stickyTop:this.getPagedLayoutTop(Math.max(i.topOffset,0)),stickyBottom:this.getPagedLayoutTop(r.topOffset+r.height)}}applyStickyPositioning({stickyTop:t,stickyBottom:n}){const s=this.getHeight(),{itemMetricsCache:i}=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()*i.lineHeight>>0)*-1,l=-Math.max(r+a,0)+s;this.stickyContainer.style.top=`${l}px`,this.stickyContainer.style.bottom=`${l+i.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 i=-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");i===-1?i=l.top:l.top!==i&&(l.top=i,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)),i+=l.instance.getVirtualizedHeight(),a<this.items.length-1&&(i+=this.getLayout().gap)}r&&i!=null&&(this.scrollDirty=!0,this.scrollHeight=i)}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=()=>{Zi.__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 i=s.borderBoxSize[0].blockSize;if(Math.abs(i-this.renderState.stickyHeight)>=jw){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 i=s.target===this.header.element?this.header:this.footer,r=s.borderBoxSize[0].blockSize;if(r!==i.height){const a=this.getScrollTop(),l=this.getScrollAnchor(a);this.setHostHeight(i,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:i}=this;if(i!=null){const u=this.idToItem.get(i.id);if(u!=null&&n.get(i.id)===u)return i;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,x=h.instance.getNumericScrollAnchor(f);if(x!=null){const g=p+x.top;return{type:"line",id:h.item.id,lineNumber:x.lineNumber,side:x.side,viewportOffset:g-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 i=n.type==="diff"?n.instance.getLinePosition(t.lineNumber,t.side):n.instance.getLinePosition(t.lineNumber);if(i==null)return;const r=s+n.top+i.top;return this.clampScrollTop(r-t.viewportOffset)}applyScrollFix(t,n,s){if(this.root==null)return;const i=xi(this.clampScrollTop(t)),r=xi(n),{scrollPageOffset:a}=this,l=xi(this.clampPagedScrollTop(r-a)),{pagedScrollTop:c,scrollPageOffset:d}=this.resolvePagedScrollPosition(i),u=c,h=a!==d;i===this.renderState.scrollTop&&i===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=i,this.scrollTop=i,this.scrollDirty=!1)}isPendingTargetSettled(t){const n=this.resolveScrollTargetTop(t);return n==null?!0:xi(this.getScrollTop())===xi(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);wN(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,i=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?(i=r,s=r-1):n=r+1}return i}findLastVisibleIndex(t){let n=0,s=this.items.length-1,i=-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?(i=r,n=r+1):s=r-1}return i}recomputeLayout(t=0,n){if(this.items.length===0){this.scrollHeight=0;return}const s=this.getLayout();let i=0;if(t>0){const r=this.items[t-1];if(r==null)throw new Error("CodeView.recomputeLayout: invalid dirty index");i=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=i,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,i,n,a.item.annotations??[])}else a.height=a.instance.prepareCodeViewItem(a.item.file,i,n,a.item.annotations??[]);i+=a.height,r<this.items.length-1&&(i+=s.gap)}i!==this.scrollHeight&&(this.scrollDirty=!0),this.scrollHeight=i}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 o8(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 r8(e,t){return!DC(e.theme??ki,t.theme??ki)||(e.themeType??"system")!==(t.themeType??"system")||e.unsafeCSS!==t.unsafeCSS}function a8(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 l8(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 c8(e){return e instanceof SVGElement?!0:Yp(e)&&(e.hasAttribute("data-core-css")||e.hasAttribute("data-theme-css")||e.hasAttribute("data-unsafe-css"))}function Iw(e){const t=Dw(e.start,e.side),n=Dw(e.end,e.endSide??e.side);return t===n?t:`${t}-${n}`}function Dw(e,t){return t==null?`${e}`:`${t==="deletions"?"D":"A"}${e}`}function Pw(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 Ew(e,t,n){if(n==null){e.firstChild!==t&&e.prepend(t);return}n.nextSibling!==t&&n.after(t)}function d8(e){return(e.annotations?.length??0)>0}function u8(e,{hasHeaderRenderers:t,hasAnnotationRenderer:n,hasGutterRenderer:s}){if(e.length===0)return;if(t||s)return e;if(!n)return;const i=[];for(const r of e)d8(r.item)&&i.push(r);return i.length>0?i:void 0}function h8({hunkIndex:e,lineIndex:t,conflictIndex:n}){return`merge-conflict-action-${e}-${t}-${n}`}function p8(e,t){const n=t.hunks[e.hunkIndex];if(n!=null)return{hunkIndex:e.hunkIndex,lineIndex:f8(n,e.startContentIndex)}}function f8(e,t){let n=e.unifiedLineStart;for(let s=0;s<t;s++){const i=e.hunkContent[s];n+=i.type==="context"?i.lines:i.deletions+i.additions}return n}function kN({fileDiff:e,actions:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:i,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderMergeConflictUtility:c,lineAnnotations:d,getHoveredLine:u,getInstance:h}){const p=n?.(e),f=s?.(e),x=i?.(e),g=r?.(e);return o.jsxs(o.Fragment,{children:[p!=null?o.jsx("div",{slot:AC,children:p}):o.jsxs(o.Fragment,{children:[f!=null&&o.jsx("div",{slot:"header-prefix",children:f}),x!=null&&o.jsx("div",{slot:"header-filename-suffix",children:x}),g!=null&&o.jsx("div",{slot:"header-metadata",children:g})]}),a!=null&&d?.map((v,w)=>o.jsx("div",{slot:Zr(v),children:a(v)},w)),t!=null&&c!=null&&h!=null&&t.map(v=>{if(v==null)return;const w=m8(v,e);return o.jsx("div",{slot:w,style:wE,children:c(v,h)},w)}),l!=null&&o.jsx("div",{slot:"gutter-utility-slot",style:yE,children:l(u)})]})}function m8(e,t){const n=p8(e,t);return n!=null?h8({hunkIndex:n.hunkIndex,lineIndex:n.lineIndex,conflictIndex:e.conflictIndex}):void 0}const Aw=typeof window>"u"?m.useEffect:m.useLayoutEffect;function Mw(e){return{instance:void 0,items:void 0,controlled:e,managedOptions:void 0,disableFlushSync:!1,slotCoordinator:void 0}}function g8(e,t){const{className:n,containerRef:s,disableWorkerPool:i=!1,editorOptions:r,initialItems:a,items:l,onItemEditChange:c,onItemEditComplete:d,onScroll:u,onSelectedLinesChange:h,options:p,renderAnnotation:f,renderCodeViewFooter:x,renderCodeViewHeader:g,renderCustomHeader:v,renderGutterUtility:w,renderHeaderFilenameSuffix:y,renderHeaderMetadata:b,renderHeaderPrefix:_,selectedLines:j,style:N}=e,C=l!==void 0,k=OC(),E=m.useContext(zC),I=m.useRef(Mw(C)),T=v!=null,A=f!=null,D=w!=null,W=T||_!=null||y!=null||b!=null,J=W||A||D,O=g!=null,B=x!=null,L=eo(F=>{h?.(F)}),se=j!==void 0,Q=eo(F=>{if(k==null)throw new Error("CodeView: EditContext is not attached");const U=k({...r,...F});if(U==null)throw new Error("CodeView: EditProvider.createEditor must return an editor instance");return U}),V=eo((F,U,de)=>{c?.(F,U,de)}),H=eo((F,U,de)=>{d?.(F,U,de)}),ne=m.useMemo(()=>w8({options:p,hasCustomHeader:T,hasGutterRenderer:D,hasCodeViewHeader:O,hasCodeViewFooter:B,onSelectedLinesChange:h!=null?L:void 0,controlledSelection:se,createEditor:k!=null?Q:void 0,onItemEditChange:c!=null?V:void 0,onItemEditComplete:d!=null?H:void 0}),[k,se,Q,V,H,L,B,O,T,D,c,d,h,p]),[he]=m.useState(()=>b8()),[,pe]=m.useState({}),ke=eo(F=>{I.current.instance!=null&&(F==null||F!==I.current.instance.getContainerElement())&&(I.current.instance.cleanUp(),he.publish(void 0),I.current=Mw(C)),F!=null&&F!==I.current.instance?.getContainerElement()&&(I.current.instance=new i8(ne,i?void 0:E,!0),I.current.instance.setup(F)),typeof s=="function"?s(F):s!=null&&(s.current=F)}),Me=eo(F=>{I.current.disableFlushSync?he.publish(F):Fs.flushSync(()=>{he.publish(F)})}),fe=m.useMemo(()=>{if(!(!W&&!A&&!D&&!O&&!B))return{hasHeaderRenderers:W,hasAnnotationRenderer:A,hasGutterRenderer:D,onSnapshotChange:Me}},[Me,A,D,W,O,B]);return Aw(()=>u!=null?I.current.instance?.subscribeToScroll(u):void 0),Aw(()=>{const{instance:F,controlled:U,items:de,managedOptions:Y,slotCoordinator:X}=I.current;if(F!=null)try{I.current.disableFlushSync=!0;let z=!1;if(Iu(ne,Y)||(I.current.managedOptions=ne,F.setOptions(ne),z=!0),U!==C){console.error("CodeView: cannot switch between controlled and uncontrolled modes. Remount with a new key instead.");return}if(C)l!==de&&(v8(de,l)?I.current.items=l:x8(de,l)?(I.current.items=l,F.addItems(l.slice(de.length))):(I.current.items=l,F.setItems(l),z=!0));else if(de==null){const Ee=a??[];I.current.items=Ee,Ee.length>0&&(F.setItems(Ee),z=!0)}j!==void 0&&F.setSelectedLines(j,{notify:!1});const ue=F.setSlotCoordinator(fe);let _e=!1;fe!==X&&((fe==null||X==null)&&(_e=!0),I.current.slotCoordinator=fe),(z||ue)&&F.render(!0),ue&&fe==null&&he.publish(void 0),_e&&pe({})}finally{I.current.disableFlushSync=!1}}),m.useImperativeHandle(t,()=>({addItems(F){const{controlled:U,instance:de}=I.current;Oc(U,"addItems"),de==null?console.error("CodeView.addItems: no valid instance to append items with",F):de.addItems(F)},getItem(F){const{instance:U}=I.current;if(U==null){console.error("CodeView.getItem: no valid instance exists",F);return}else return U.getItem(F)},removeItem(F){const{controlled:U,instance:de}=I.current;return Oc(U,"removeItem"),de==null?(console.error("CodeView.removeItem: no valid instance to remove item from",F),!1):de.removeItem(F)},updateItem(F){const{controlled:U,instance:de}=I.current;return Oc(U,"updateItem"),de==null?(console.error("CodeView.updateItem: no valid instance to update item with",F),!1):de.updateItem(F)},updateItemId(F,U){const{controlled:de,instance:Y}=I.current;return Oc(de,"updateItemId"),Y==null?(console.error("CodeView.updateItemId: no valid instance to update item id with",F,U),!1):Y.updateItemId(F,U)},scrollTo(F){const{instance:U}=I.current;U==null?console.error("CodeView.scrollTo: no valid instance to scroll with",F):U.scrollTo(F)},setSelectedLines(F){const{instance:U}=I.current;U==null?console.error("CodeView.setSelectedLines: no valid instance to update selection with",F):(U.setSelectedLines(F,{notify:!1}),L(F))},getSelectedLines(){const{instance:F}=I.current;return F==null?(console.error("CodeView.getSelectedLines: no valid instance exists"),null):F.getSelectedLines()},clearSelectedLines(){const{instance:F}=I.current;F==null?console.error("CodeView.clearSelectedLines: no valid instance to update selection with"):(F.clearSelectedLines({notify:!1}),L(null))},getEditor(F){const{instance:U}=I.current;if(U==null){console.error("CodeView.getEditor: no valid instance exists",F);return}return U.getEditor(F)},getInstance(){return I.current.instance}}),[L]),o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:ke,className:n,style:N}),(J||O||B)&&o.jsx(y8,{managedContentStore:he,renderCustomHeader:v,renderHeaderPrefix:_,renderHeaderFilenameSuffix:y,renderHeaderMetadata:b,renderAnnotation:f,renderGutterUtility:w,renderCodeViewHeader:g,renderCodeViewFooter:x})]})}const _N=m.forwardRef(g8);function x8(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 v8(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 Oc(e,t){if(e)throw new Error(`CodeView.${t} cannot be used when CodeView is controlled. Use initialItems for imperative item updates.`)}function b8(){let e;const t=new Set;return{getSnapshot(){return e},publish(n){if(!wN(e,n)){e=n;for(const s of t)s()}},subscribe(n){return t.add(n),()=>{t.delete(n)}}}}function w8({options:e,hasCustomHeader:t,hasGutterRenderer:n,hasCodeViewHeader:s,hasCodeViewFooter:i,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),i&&(u.renderCodeViewFooter=zc),u}const y8=m.memo(function({managedContentStore:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:i,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderCodeViewHeader:c,renderCodeViewFooter:d}){"use no memo";const u=eo(x=>t.subscribe(x)),h=eo(()=>t.getSnapshot()),p=m.useSyncExternalStore(u,h,h);let f="";for(const x of p?.items??[])f+=`${x.id}:${x.version}:${x.type}`;return o.jsxs(o.Fragment,{children:[m.useMemo(()=>p?.items?.map(x=>Fs.createPortal(S8({renderedItem:x,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:i,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l}),x.element,x.id)),[n,s,i,r,a,l,f]),m.useMemo(()=>c!=null&&p?.header!=null?Fs.createPortal(c(),p.header):null,[c,p?.header]),m.useMemo(()=>d!=null&&p?.footer!=null?Fs.createPortal(d(),p.footer):null,[d,p?.footer])]})});function S8({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderFilenameSuffix:s,renderHeaderMetadata:i,renderAnnotation:r,renderGutterUtility:a}){if(e.type==="diff"){const{item:l,instance:c}=e;return kN({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:i!=null?()=>i(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 SE({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:i!=null?()=>i(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 Rw=typeof window>"u"?m.useEffect:m.useLayoutEffect;function C8({fileDiff:e,options:t,editorOptions:n,lineAnnotations:s,selectedLines:i,prerenderedHTML:r,metrics:a,hasGutterRenderUtility:l,hasCustomHeader:c,disableWorkerPool:d,edit:u}){const h=CE(),p=i!==void 0,f=m.useContext(zC),x=OC(),g=m.useRef(null),v=eo(w=>{if(w!=null){if(g.current!=null)throw new Error("useFileDiffInstance: An instance should not already exist when a node is created");h!=null?g.current=new bN(mp({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),h,a,d?void 0:f,!0):g.current=new vN(mp({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),d?void 0:f,!0),g.current.hydrate({fileDiff:e,fileContainer:w,lineAnnotations:s,prerenderedHTML:r})}else{if(g.current==null)throw new Error("useFileDiffInstance: A FileDiff instance should exist when unmounting");g.current.cleanUp(),g.current=null}});return Rw(()=>{const{current:w}=g;if(w==null)return;const y=mp({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),b=y!==void 0&&!Iu(w.options,y);w.setOptions(y),w.render({forceRender:b,fileDiff:e,lineAnnotations:s}),i!==void 0&&w.setSelectedLines(i)}),Rw(()=>{if(u&&g.current!=null){if(x===void 0)throw new Error("FileDiff: EditContext is not attached");const w=x(n??{});if(w==null)throw new Error("FileDiff: EditProvider.createEditor must return an editor instance");try{return w.edit(g.current)}catch(y){throw w.cleanUp(),y}}},[u]),{ref:v,getHoveredLine:m.useCallback(()=>g.current?.getHoveredLine(),[])}}function mp({options:e,controlledSelection:t,hasCustomHeader:n,hasGutterRenderUtility:s}){return t||s||n?{...e,controlledSelection:t,renderCustomHeader:n?vv:e?.renderCustomHeader,renderGutterUtility:s?vv:e?.renderGutterUtility}:e}function k8({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:i,selectedLines:r,className:a,style:l,prerenderedHTML:c,renderAnnotation:d,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderGutterUtility:x,disableWorkerPool:g=!1,edit:v=!1}){const{ref:w,getHoveredLine:y}=C8({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:i,selectedLines:r,prerenderedHTML:c,hasGutterRenderUtility:x!=null,hasCustomHeader:u!=null,disableWorkerPool:g,edit:v});return o.jsx(LC,{ref:w,className:a,style:l,children:kE(kN({fileDiff:e,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderAnnotation:d,renderGutterUtility:x,lineAnnotations:i,getHoveredLine:y}),c)})}function _8(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 j8(e,t){const n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(s=>e[s]===t[s])}function jN(e,t){let n=e;for(let s=t.length-1;s>=0;s--){const{oldText:i,newText:r}=t[s],a=n.indexOf(r);if(a===-1)return null;n=n.slice(0,a)+i+n.slice(a+r.length)}return n}function N8(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]:[])),i={...e.snapshots};for(const[r,a]of t){const l=e.currentByPath[r],c=a.flatMap(y=>y.edits??[]),d=a.flatMap(y=>y.fileChange&&y.fileChange.truncated!==!0?[y.fileChange]:[]),u=[...a].reverse().find(y=>y.writeContent!=null)?.writeContent,h=a.find(y=>y.fileChange)?.fileChange,p=[...a].reverse().find(y=>y.fileChange||y.writeContent!=null||y.edits?.length),f=p?.fileChange?p.fileChange.truncated===!0?null:p.fileChange.newText:p?.writeContent??null,x=Object.hasOwn(i,r),g=i[r];if(!x&&h?.truncated===!0){i[r]=null,s.add(r);continue}if(x&&g===null){s.add(r);continue}let v=typeof g=="string"?g:d[0]?.oldText??null;const w=typeof l=="string"?l:f;v==null&&(c.length>0&&typeof l=="string"?v=jN(l,c):u!=null&&c.length===0&&(v="")),w==null&&p?.fileChange?.truncated===!0&&s.add(r),!(v==null||w==null)&&(v===w&&d.length===0||(i[r]=v,n.push({path:r,oldText:v,newText:w})))}return{files:n,snapshots:i,...s.size>0?{incompletePaths:[...s]}:{}}}const T8={theme:ha,diffStyle:"split",lineDiffType:"word",disableFileHeader:!0,preferredHighlighter:"shiki-js",overflow:"wrap"};function Lw({path:e,blocks:t,snapshot:n}){const{t:s}=te(),i=e.split("/").pop()||"file",[r,a]=m.useState({kind:"loading"});return m.useEffect(()=>{let l=!0;return n?(a({kind:"loading"}),Qr().then(()=>{l&&a({kind:"full",oldText:n.oldText,newText:n.newText})}).catch(()=>{l&&a({kind:"blocks"})}),()=>{l=!1}):(Promise.all([Qr(),window.electronAPI.files.read(e)]).then(([,c])=>{if(!l)return;const d=typeof c=="string"?jN(c,t):null;a(d!=null&&typeof c=="string"?{kind:"full",oldText:d,newText:c}:{kind:"blocks"})}).catch(()=>{l&&a({kind:"blocks"})}),()=>{l=!1})},[e,t,n]),r.kind==="loading"?o.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs text-muted-foreground",children:s("Loading diff…")}):o.jsx("div",{className:"border-t border-border/60 text-xs",children:r.kind==="full"?o.jsx(Ow,{name:i,oldText:r.oldText,newText:r.newText}):t.map((l,c)=>o.jsx(Ow,{name:i,oldText:l.oldText,newText:l.newText},c))})}function Ow({name:e,oldText:t,newText:n}){const s=Jl(T8),i=m.useMemo(()=>{const r=po({name:e,contents:t},{name:e,contents:n});return r.cacheKey=ux(e,t,n),r},[e,t,n]);return o.jsx(k8,{fileDiff:i,options:s})}function em({hits:e,defaultOpen:t=!1}){const{t:n}=te();return e.length===0?o.jsx("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("No results")}):o.jsx("ul",{className:"divide-y divide-border/60",children:e.map(s=>o.jsx(D8,{hit:s,defaultOpen:t},s.id))})}function I8({view:e}){const{t}=te(),n=e.written?e.deduplicated&&t("Identical memory already exists, nothing new was written"):t("Similar memories already exist, nothing was written");return o.jsxs(o.Fragment,{children:[n&&o.jsx("p",{className:"px-3 pt-2 text-xs text-muted-foreground",children:n}),e.written?o.jsx(em,{hits:[e.memory],defaultOpen:!0}):o.jsx(em,{hits:e.candidates})]})}function D8({hit:e,defaultOpen:t}){const{t:n}=te(),[s,i]=m.useState(t);return o.jsx("li",{children:o.jsxs("button",{type:"button","aria-expanded":s,onClick:r=>{const a=window.getSelection();a?.toString()&&r.currentTarget.contains(a.anchorNode)||i(l=>!l)},className:"block w-full cursor-pointer px-3 py-2 text-left transition-colors hover:bg-muted/40",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:q("min-w-0 flex-1 font-medium text-foreground text-xs",s?"break-words":"truncate"),children:e.title}),e.unitType&&o.jsx(ea,{variant:"secondary",size:"sm",children:e.unitType}),e.space&&o.jsx(ea,{variant:"outline",size:"sm",children:n(e.space==="global"?"Global":"Project")}),e.relevance!==null&&o.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",title:n("Semantic similarity"),children:e.relevance.toFixed(2)})]}),o.jsx("span",{className:q("mt-0.5 whitespace-pre-wrap break-words text-muted-foreground text-xs leading-relaxed",s?"block":"line-clamp-2"),children:e.content})]})})}const P8={"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 mx(e){return q("inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",P8[e])}function E8({label:e,onRemove:t}){return o.jsx("button",{type:"button",onClick:t,className:"rounded-sm opacity-70 transition-opacity hover:opacity-100","aria-label":e,children:o.jsx(ln,{className:"h-3 w-3"})})}function A8({recipient:e,onRemove:t}){const{t:n}=te();return o.jsxs("span",{className:q(mx("agent-type"),"mt-0.5 shrink-0"),children:[o.jsx(Zs,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:e.label}),o.jsx(E8,{label:n("Remove Agent recipient"),onRemove:t}),o.jsx("span",{className:"sr-only",children:e.typeKey})]})}const gx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function NN(e){if(!e)return null;try{const t=JSON.parse(e);return gx(t)?t:null}catch{return null}}function tm(e,t){if(!Array.isArray(e))return null;const n=[];for(const s of e){if(!gx(s)||typeof s.id!="string"||!s.id||typeof s.title!="string"||typeof s.content!="string")return null;const{spaceId:i,[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:i==="global"?"global":typeof i=="string"&&i.startsWith("proj:")?"project":null,relevance:typeof r=="number"&&Number.isFinite(r)?r:null})}return n}function M8(e){const t=NN(e);return t?tm(t.results,"relevance"):null}function R8(e,t){const n=NN(e);if(n?.status==="candidates_found"){const i=tm(n.candidates,"similarity");return i?{written:!1,candidates:i}:null}if(n?.status!=="inserted"||!gx(n.memory)||!t)return null;const s=tm([{...n.memory,content:t}],"relevance")?.[0];return s?{written:!0,deduplicated:n.deduplicated===!0,memory:s}:null}const TN=m.createContext(void 0);function mc(e){const t=m.useContext(TN);if(t===void 0&&!e)throw new Error(Zl(50));return t}const L8=600,IN=300,O8={...jE,instantType:e=>e.instantType,adaptiveOrigin:e=>e.adaptiveOrigin,closeDelay:e=>e.closeDelay};class z8 extends _E{constructor(t,n,s){const i=new DE;super(G8(t,i,n,s),F8(i),O8)}setOpen=(t,n)=>{const{inlineRectCoordsRef:s}=this.context;NE(this,t,n,{onBeforeDispatch(){const i=n.event;t&&n.reason===PE&&n.trigger&&"clientX"in i&&"clientY"in i&&s.current?.element!==n.trigger&&S1(s,n.trigger,i.clientX,i.clientY)}})}}function G8(e,t,n,s=!1){const i={...TE(),instantType:void 0,adaptiveOrigin:void 0,closeDelay:IN,...e};return i.floatingRootContext=IE(t,n,s),i}function F8(e){return{popupRef:m.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e,inlineRectCoordsRef:{current:void 0}}}function zw(e){const{open:t,defaultOpen:n=!1,onOpenChange:s,onOpenChangeComplete:i,actionsRef:r,handle:a,triggerId:l,defaultTriggerId:c=null,children:d}=e,u=ME((w,y)=>new z8({open:n,openProp:t,activeTriggerId:c,triggerIdProp:l},w,y));u.useControlledProp("openProp",t),u.useControlledProp("triggerIdProp",l),u.useContextCallback("onOpenChange",s),u.useContextCallback("onOpenChangeComplete",i);const h=u.useState("open"),p=u.useState("activeTriggerId"),f=u.useState("mounted"),x=u.useState("payload");RE(u,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:g}=LE(h,u,()=>{u.context.inlineRectCoordsRef.current=void 0});Gm(()=>{h&&p==null&&u.set("payload",void 0)},[u,p,h]),m.useImperativeHandle(r,()=>({unmount:g,close:()=>u.setOpen(!1,OE(zE))}),[g,u]);const v=h||f;return o.jsxs(TN.Provider,{value:u,children:[a&&o.jsx(GE,{handle:a,store:u}),v&&o.jsx(H8,{store:u}),typeof d=="function"?d({payload:x}):d]})}function H8({store:e}){const t=e.useState("floatingRootContext"),n=FE(t);return HE(e,{activeTriggerProps:n.reference,inactiveTriggerProps:n.trigger,popupProps:n.floating}),null}const B8=EE(function(t){return mc(!0)?o.jsx(zw,{...t}):o.jsx(AE,{children:o.jsx(zw,{...t})})}),DN=m.createContext(void 0);function V8(){const e=m.useContext(DN);if(e===void 0)throw new Error(Zl(48));return e}const $8=m.forwardRef(function(t,n){const{keepMounted:s=!1,...i}=t;return mc().useState("mounted")||s?o.jsx(DN.Provider,{value:s,children:o.jsx(BE,{ref:n,...i})}):null}),W8=VE(function(t,n){const{render:s,className:i,delay:r,closeDelay:a,id:l,payload:c,handle:d,style:u,...h}=t,p=mc(!0),x=$E(d)??p;if(!x)throw new Error(Zl(89));const g=GC(l),v=x.useState("isTriggerActive",g),w=x.useState("isOpenedByTrigger",g),y=x.useState("floatingRootContext"),b=x.context.inlineRectCoordsRef,_=m.useRef(null),j=r??L8,N=a??IN,{registerTrigger:C,isMountedByThisTrigger:k}=WE(g,_,x,{payload:c,closeDelay:N}),E=UE(y,{mouseOnly:!0,move:!1,handleClose:KE(),delay:()=>({open:j,close:N}),triggerElementRef:_,isActiveTrigger:v,isClosing:()=>x.select("transitionStatus")==="ending"}),I=qE(y,{delay:j}),T={open:w},A=x.useState("triggerProps",k),D=r$(b,w);return Ql("a",t,{state:T,ref:[n,C,_],props:[E,I.reference,A,D,{id:g},h],stateAttributesMapping:YE})}),PN=m.createContext(void 0);function U8(){const e=m.useContext(PN);if(e===void 0)throw new Error(Zl(49));return e}const K8=m.forwardRef(function(t,n){const{render:s,className:i,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:x=!1,disableAnchorTracking:g=!1,collisionAvoidance:v=XE,style:w,...y}=t,b=mc(),_=V8(),j=JE(),N=b.useState("open"),C=b.useState("mounted"),k=b.useState("floatingRootContext"),E=b.useState("instantType"),I=b.useState("transitionStatus"),T=b.useState("adaptiveOrigin"),A=b.context.inlineRectCoordsRef,D=ZE({anchor:r,floatingRootContext:k,positionMethod:a,mounted:C,side:l,sideOffset:d,align:c,alignOffset:u,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:x,disableAnchorTracking:g,keepMounted:_,nodeId:j,collisionAvoidance:v,adaptiveOrigin:T,inline:a$(A)}),W=D.update;Gm(()=>{N&&C&&W()},[N,C,W]);const J={open:N,side:D.side,align:D.align,anchorHidden:D.anchorHidden,instant:E},O=QE(t,J,{styles:D.positionerStyles,transitionStatus:I,props:y,refs:[n,b.useStateSetter("positionerElement")],hidden:!C,inert:!N});return o.jsx(PN.Provider,{value:D,children:o.jsx(eA,{id:j,children:O})})}),q8=m.forwardRef(function(t,n){const{className:s,render:i,style:r,...a}=t,l=mc(),{side:c,align:d}=U8(),u=l.useState("open"),h=l.useState("instantType"),p=l.useState("transitionStatus"),f=l.useState("popupProps"),x=l.useState("floatingRootContext"),g=l.useState("closeDelay");return tA({open:u,ref:l.context.popupRef,onComplete(){u&&l.context.onOpenChangeComplete?.(!0)}}),nA(x,{closeDelay:g}),Ql("div",t,{state:{open:u,side:c,align:d,instant:h,transitionStatus:p},ref:[n,l.context.popupRef,l.useStateSetter("popupElement")],props:[sA,f,oA(p),a],stateAttributesMapping:iA})}),xx=B8;function vx({...e}){return o.jsx(W8,{"data-slot":"preview-card-trigger",...e})}function EN({className:e,children:t,align:n="center",sideOffset:s=4,...i}){return o.jsx($8,{children:o.jsx(K8,{align:n,className:"z-50","data-slot":"preview-card-positioner",sideOffset:s,children:o.jsx(q8,{className:q("relative flex w-64 origin-(--transform-origin) text-balance rounded-lg border bg-popover bg-clip-padding p-4 text-popover-foreground text-sm shadow-lg transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",e),"data-slot":"preview-card-content",...i,children:t})})})}const Gw={mask:"text-sky-600 dark:text-sky-400",warn:"text-amber-600 dark:text-amber-400",block:"text-red-600 dark:text-red-400"},Y8={mask:Du,warn:Jr,block:FC},X8={mask:"Mask",warn:"Warn only",block:"Block"},J8={system:"System prompt",user:"Your message",tool_result:"Tool output",tool_args:"Tool arguments",assistant:"Earlier replies",tools:"Tool descriptions"};function Z8({report:e}){const{t}=te(),n=rA(e);if(!n)return null;const s=Y8[n],i=new Set(e.hits.map(r=>r.token)).size;return o.jsxs(xx,{children:[o.jsxs(vx,{render:o.jsx("span",{className:q("inline-flex shrink-0 items-center gap-0.5 text-[11px]",Gw[n]),"data-privacy-mask":n}),children:[o.jsx(s,{className:"size-3.5"}),o.jsx("span",{className:"tabular-nums",children:i})]}),o.jsxs(EN,{className:"max-h-(--available-height) w-72 flex-col overflow-y-auto overscroll-contain text-xs",children:[o.jsx("p",{className:"mb-1.5 font-medium",children:t("Privacy masking")}),o.jsx("ul",{className:"space-y-1",children:aA(e.hits).map(r=>o.jsxs("li",{className:"flex flex-wrap gap-x-2",children:[o.jsx("span",{className:Gw[r.action],children:t(X8[r.action])}),o.jsx("span",{children:r.kind}),o.jsx("span",{className:"text-muted-foreground",children:t(J8[r.where]??r.where)}),o.jsx("span",{className:"text-muted-foreground",children:r.values>1?t("{{count}} values",{count:r.values}):r.preview}),r.count>1&&o.jsxs("span",{className:"text-muted-foreground",children:["×",r.count]})]},`${r.action}-${r.kind}-${r.where}`))}),e.restored>0&&o.jsx("p",{className:"mt-1.5 text-muted-foreground",children:t("Restored {{count}} in the reply",{count:e.restored})})]})]})}const Q8=/^\[.+#[0-9A-Fa-f]{4}\]$/;function eU(e){const t=e.indexOf(`
57
- `),n=t===-1?e:e.slice(0,t);return Q8.test(n)?t===-1?"":e.slice(t+1).split(`
58
- `).map(s=>s.replace(/^\d+:/,"")).join(`
59
- `):e}const tU={theme:ha,disableFileHeader:!0,overflow:"wrap",preferredHighlighter:"shiki-js"};function Id({path:e,contents:t}){const{t:n}=te(),[s,i]=m.useState(!1),r=Jl(tU);m.useEffect(()=>{let l=!0;return Qr().then(()=>{l&&i(!0)}),()=>{l=!1}},[]);const a=m.useMemo(()=>({name:e.split("/").pop()||"file",contents:eU(t)}),[e,t]);return s?o.jsx(HC,{file:a,disableWorkerPool:!0,options:r}):o.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("Loading...")})}function nU(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 sU={compressed:"Compressed",unchanged:"Unchanged",pending:"Background task started",bypassed:"Bypassed",unavailable:"Unavailable"};function iU({value:e}){const t=TV(e),{t:n}=te();if(!t)return null;const s=nU(t);return o.jsxs("div",{className:"border-border/60 border-t text-[10px] text-muted-foreground","data-rtk-status":t.status,children:[o.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 px-3 py-1",children:[o.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:"RTK"}),o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsx("span",{children:n(sU[t.status])}),s&&o.jsxs(o.Fragment,{children:[o.jsx("span",{"aria-hidden":"true",children:"·"}),o.jsx("span",{children:n("~{{count}} tokens saved",{count:js(s.tokens)})}),s.percent!==null&&o.jsxs("span",{children:["(",s.percent,"%)"]})]})]}),o.jsxs("div",{className:"space-y-2 px-3 pb-2",children:[t.status==="pending"&&o.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)&&o.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&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:n("Input estimate")}),o.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:js(t.inputTokens)})}),o.jsx("dt",{children:n("Output estimate")}),o.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:js(t.outputTokens)})})]}),t.reason&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:n("Reason")}),o.jsx("dd",{className:"min-w-0 whitespace-pre-wrap text-foreground/80",children:t.reason})]})]})]})]})}function oU(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 rU(e,t,n=IV){const s=t-e;return s>=n?s:null}const aU={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"},lU={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."},AN=600;function cU(e){return e?.kind==="deadline"?["background","timeout"]:[]}function dU(e,t,n){const s=`\`\`\`
60
- ${t}
61
- \`\`\``;return e==="background"?n(`Rerun this command with background: true:
62
-
63
- {{command}}`,{command:s}):n(`Rerun this command with timeout: {{seconds}}:
64
-
65
- {{command}}`,{seconds:AN,command:s})}function uU(e,t,n){return t(e)?(n(),!0):!1}let dl=null,ul=null,hl=null,pl=null,fl=null;function hU(e){return dl=e,()=>{dl===e&&(dl=null)}}function pU(e){return hl=e,()=>{hl===e&&(hl=null)}}function fU(e){return ul=e,()=>{ul===e&&(ul=null)}}function wr(){return hl?(hl(),!0):!1}function Vl(e){return dl?(dl(e),!0):!1}function dh(e){return ul?(ul(e),!0):!1}function mU(e){return pl=e,()=>{pl===e&&(pl=null)}}function gU(e,t){return pl?(pl(e,t),!0):!1}function xU(e){return fl=e,()=>{fl===e&&(fl=null)}}function vU(e){return fl?(fl(e),!0):!1}function bU(){const[e,t]=m.useState(()=>Date.now());return m.useEffect(()=>{const n=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(n)},[]),e}const nm=5,Fw=2*Math.PI*nm;function wU({startedAt:e,deadlineAt:t,output:n}){const{t:s}=te(),i=bU(),r=m.useRef({output:n,at:e??Date.now()});r.current.output!==n&&(r.current={output:n,at:Date.now()});const a=oU(e,t,i),l=rU(r.current.at,i);return!a&&l===null?null:o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[10px] text-muted-foreground/70 tabular-nums",children:[l!==null&&o.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&&o.jsxs("span",{className:"flex items-center gap-0.5",title:s("Moves to background in {{seconds}}s",{seconds:Math.ceil(a.remainingMs/1e3)}),children:[o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",children:[o.jsx("circle",{cx:"6",cy:"6",r:nm,fill:"none",stroke:"currentColor",opacity:"0.25"}),o.jsx("circle",{cx:"6",cy:"6",r:nm,fill:"none",stroke:"currentColor",strokeDasharray:Fw,strokeDashoffset:Fw*(1-a.fraction),transform:"rotate(-90 6 6)"})]}),Math.ceil(a.remainingMs/1e3),"s"]})]})}function MN(e,t){return e.kind==="exit_nonzero"&&e.exitCode===void 0?t("Failed"):t(aU[e.kind],{code:e.exitCode??""})}function yU({failure:e}){const{t}=te();return o.jsx("span",{"data-shell-failure":e.kind,className:q("shrink-0 rounded px-1 text-[10px]",e.retryable?"bg-muted text-muted-foreground":"bg-destructive/10 text-destructive"),children:MN(e,t)})}function SU({failure:e,command:t}){const{t:n}=te(),[s,i]=m.useState(!1);if(!e)return null;const r=lU[e.kind],a=cU(e);return o.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:[o.jsx("span",{className:"shrink-0 font-medium",children:MN(e,n)}),r&&o.jsx("span",{className:"min-w-0 flex-1",children:n(r)}),a.map(l=>o.jsx("button",{type:"button","data-shell-rerun":l,onClick:()=>{uU(dU(l,t,n),dh,wr)},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:AN})},l)),o.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{i(!0),setTimeout(()=>i(!1),1e3)})},className:"ml-auto flex shrink-0 items-center gap-1 hover:opacity-100",title:n("Copy command"),children:[s?o.jsx(Jn,{className:"h-3 w-3"}):o.jsx(Pu,{className:"h-3 w-3"}),n("Copy command")]})]})}function CU(e){return e.startsWith("/skill:")?"skill":e==="/goal"?"goal":"command"}function kU(e){return e.startsWith("/skill:")?e.slice(7):e.replace(/^\//,"")}function fu(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 _U={skill:Ls,goal:Sa,command:x1},jU={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 RN(e,t=!1){return q("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",jU[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 bx({name:e,className:t,interactive:n=!1,trailing:s}){const i=CU(e),r=_U[i];return o.jsxs("span",{className:q(RN(i,n),t),children:[o.jsx(r,{className:"h-3 w-3"}),kU(e),s]})}function NU({icon:e,state:t}){const n=t==="running"||t==="reviewing";return o.jsxs("span",{className:q("relative flex size-[22px] shrink-0 items-center justify-center rounded-full border text-muted-foreground",n&&"border-transparent text-brand",t==="error"&&"border-destructive/40 text-destructive"),children:[o.jsx(e,{className:"size-3"}),n&&o.jsx("span",{className:"absolute -inset-px animate-spin rounded-full border-[1.5px] border-brand/20 border-t-brand"})]})}function LN({state:e}){const t=e==="running"||e==="reviewing";return o.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:t?o.jsx("span",{className:"size-2.5 animate-spin rounded-full border-[1.5px] border-border border-t-brand"}):e==="error"?o.jsx("span",{className:"size-1.5 rounded-full bg-destructive"}):o.jsx("span",{className:"size-1 rounded-full bg-current opacity-60"})})}const TU={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 IU({view:e,titles:t}){const{t:n}=te();return o.jsxs("div",{className:"space-y-2 px-3 py-2 text-sm",children:[e.kind==="report"&&e.text&&o.jsx(Ds,{text:e.text}),e.kind==="report"&&e.value&&o.jsx(Ds,{text:`\`\`\`json
66
- ${e.value}
67
- \`\`\``}),e.kind==="report"&&e.error&&o.jsx("p",{className:"whitespace-pre-wrap text-destructive",children:e.error}),e.runs.length>0&&o.jsx("ul",{className:"space-y-0.5 text-xs text-muted-foreground",children:e.runs.map(s=>o.jsx(DU,{run:s,title:t?.[s.agentId]},s.runId||s.agentId))}),e.kind==="list"&&e.runs.length===0&&o.jsx("p",{className:"text-xs text-muted-foreground",children:n("No agents")}),e.kind==="wait"&&e.timedOut&&o.jsx("p",{className:"text-xs text-muted-foreground",children:n("Timed out; unfinished agents keep running")}),e.kind==="wait"&&e.interrupted&&o.jsx("p",{className:"text-xs text-muted-foreground",children:n("Wait was interrupted")}),o.jsxs("details",{className:"text-xs text-muted-foreground",children:[o.jsx("summary",{className:"cursor-pointer hover:text-foreground",children:n("Run info")}),o.jsx("pre",{className:"mt-1 whitespace-pre-wrap font-mono",children:e.info})]}),e.head&&o.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:e.head})]})}function DU({run:e,title:t}){const{t:n}=te(),[s,i]=TU[e.status]??[null,"bg-muted-foreground"],r=e.durationMs===null?"":n("took {{duration}}",{duration:rs(e.durationMs)});return o.jsxs("li",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",i)}),t&&o.jsx("span",{className:"truncate text-foreground",children:t}),o.jsx("span",{className:"shrink-0",children:[s?n(s):e.status,r].filter(Boolean).join(" · ")})]})}const wx=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Hw=e=>typeof e=="string"&&e.trim()?e:null;function sm(e){if(!wx(e))return null;const{agentId:t,runId:n,status:s,createdAt:i,startedAt:r,finishedAt:a}=e;if(typeof t!="string"||typeof n!="string"||typeof s!="string")return null;const l=typeof r=="number"?r:i;return{agentId:t,runId:n,status:s,durationMs:typeof a=="number"&&typeof l=="number"?Math.max(0,a-l):null}}const PU=new Set(["closed","parked","creating"]);function EU(e){if(!wx(e))return null;const{agentId:t,status:n,latestRun:s}=e;return typeof t!="string"||typeof n!="string"?null:(PU.has(n)?null:sm(s))??{agentId:t,runId:"",status:n,durationMs:null}}function AU(e,t){const n=lA(t);if(!n)return null;const{head:s,value:i}=n;if(e==="report"){const l=sm(i.run);if(!l)return null;const{text:c,value:d,error:u,...h}=i;return{kind:"report",head:s,runs:[l],text:Hw(c),value:d==null?null:JSON.stringify(d,null,2),error:Hw(u),info:JSON.stringify(h,null,2)}}if(e==="list"){if(!Array.isArray(i.agents))return null;const l=i.agents.flatMap(c=>EU(c)??[]);return l.length===i.agents.length?{kind:"list",head:s,runs:l,info:JSON.stringify(i,null,2)}:null}const r=e==="wait"?i:e===void 0?i.report:null;if(!wx(r)||!Array.isArray(r.runs))return e===void 0&&i.report===void 0&&typeof i.agentId=="string"&&typeof i.runId=="string"?{kind:"receipt",head:s,runs:[],info:JSON.stringify(i,null,2)}:null;const a=r.runs.flatMap(l=>sm(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(i,null,2)}}function MU({command:e,output:t,failure:n}){const s=xe(a=>a.terminalTheme),i=xe(a=>a.terminalFontFamily),r=Eu(s)??cA;return o.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:i},children:[o.jsxs("div",{className:"whitespace-pre-wrap [overflow-wrap:anywhere]",children:[o.jsx("span",{style:{color:r.green},children:"$ "}),e]}),t&&o.jsx("pre",{className:"mt-1 whitespace-pre-wrap [overflow-wrap:anywhere]",style:{fontFamily:"inherit"},children:Oi(t)}),o.jsx(SU,{failure:n,command:e})]})}function RU(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 ON({todos:e}){return o.jsx("ul",{className:"space-y-0.5 text-xs",children:e.map(t=>o.jsxs("li",{className:"flex items-start gap-1.5",children:[t.status==="completed"?o.jsx(Jn,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):t.status==="in_progress"?o.jsx(LH,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):o.jsx(l1,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/50"}),o.jsx("span",{className:q(t.status==="completed"?"text-muted-foreground line-through":t.status==="in_progress"?"font-medium":"text-muted-foreground"),children:t.content})]},t.content))})}function zN({done:e,total:t,className:n}){return o.jsx("div",{className:q("h-0.5 overflow-hidden rounded-full bg-border",n),children:o.jsx("div",{className:"h-full rounded-full bg-brand transition-[width]",style:{width:`${t?e/t*100:0}%`}})})}const Bw=new Set;function LU({conversationId:e}){const{t}=te(),n=xe(u=>u.pinUnfinishedTodos),s=ie(u=>u.conversations[e]?.messages),i=m.useMemo(()=>n&&s?RU(s):null,[n,s]),[r,a]=m.useState(!1),[,l]=m.useState(0);if(!i||Bw.has(i.id))return null;const c=i.todos.filter(u=>u.status==="completed").length,d=i.todos.find(u=>u.status==="in_progress")??i.todos.find(u=>u.status==="pending");return o.jsxs("div",{"data-enso":"todo",className:"mb-1.5 rounded-xl border bg-card px-3 py-1.5 text-xs shadow-xs",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.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:[o.jsx(BC,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"shrink-0 font-medium",children:t("Todos")}),o.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums",children:[c,"/",i.todos.length]}),!r&&d&&o.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",title:d.content,children:d.content}),r?o.jsx($n,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"}):o.jsx(kn,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"})]}),o.jsx("button",{type:"button",title:t("Hide until the todo list updates"),onClick:()=>{Bw.add(i.id),l(u=>u+1)},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]}),r&&o.jsxs("div",{className:"mt-1.5 max-h-48 overflow-y-auto pb-0.5",children:[o.jsx(zN,{done:c,total:i.todos.length,className:"mb-2"}),o.jsx(ON,{todos:i.todos})]})]})}async function OU(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 i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return new Blob([s],{type:t[1]})}async function zU(e){const t=await OU(e);let n=t;if(t.type!=="image/png"){const s=await createImageBitmap(t),i=new OffscreenCanvas(s.width,s.height);i.getContext("2d")?.drawImage(s,0,0),s.close(),n=await i.convertToBlob({type:"image/png"})}await navigator.clipboard.write([new ClipboardItem({"image/png":n})])}function GN({src:e,className:t,frameClassName:n,onError:s}){const{t:i}=te(),[r,a]=m.useState(!1);VC(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=()=>{zU(e).then(()=>We({type:"success",title:i("Image copied")}),c=>We({type:"error",title:i("Could not copy image"),description:c instanceof Error?c.message:String(c)}))};return o.jsxs(o.Fragment,{children:[o.jsxs(ao,{children:[o.jsx(lo,{render:o.jsx("button",{type:"button",onClick:()=>a(!0),className:q("cursor-zoom-in",n),children:o.jsx("img",{src:e,alt:"",className:t,onError:s})}),onContextMenu:c=>c.stopPropagation()}),o.jsx(co,{className:"min-w-36",children:o.jsx(Ht,{closeOnClick:!0,onClick:l,children:i("Copy image")})})]}),r&&o.jsx("button",{type:"button",onClick:()=>a(!1),className:q("fixed inset-0 flex cursor-zoom-out items-center justify-center bg-black/75"),style:{zIndex:yn.NESTED_MODAL_BACKDROP},"data-enso-float":"",children:o.jsx("img",{src:e,alt:"",className:"max-h-[92vh] max-w-[92vw] rounded-lg object-contain"})})]})}const GU=(e,t)=>e===t||!!e&&!!t&&e.runMs===t.runMs&&e.turnMs===t.turnMs&&e.ttftMs===t.ttftMs&&e.tps===t.tps;function FU(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((i,r)=>i===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"&&GU(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.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(`
68
- `)===s.ask?.options.join(`
69
- `)&&n.ask?.answer===s.ask?.answer&&n.ask?.autoSelected===s.ask?.autoSelected&&n.subagentOp===s.subagentOp&&JSON.stringify(n.subagentTitles)===JSON.stringify(s.subagentTitles)&&n.waiting===s.waiting&&n.pluginArtifacts===s.pluginArtifacts&&n.shellFailure===s.shellFailure;case"tool-group":return s.kind==="tool-group"&&n.expanded===s.expanded&&n.count===s.count&&n.stats.commands===s.stats.commands&&n.stats.reads===s.stats.reads&&n.stats.searches===s.stats.searches&&n.stats.others===s.stats.others&&n.exploring===s.exploring&&n.activity?.thinking===s.activity?.thinking&&n.activity?.workedMs===s.activity?.workedMs&&n.explore?.goal===s.explore?.goal&&n.explore?.report===s.explore?.report&&n.explore?.steps===s.explore?.steps;case"error":return s.kind==="error"&&n.text===s.text;case"task-note":return s.kind==="task-note"&&n.detail===s.detail;case"compaction":case"compaction-notice":return(s.kind==="compaction"||s.kind==="compaction-notice")&&n.kind===s.kind&&n.summary===s.summary&&n.tokensBefore===s.tokensBefore&&n.verified===s.verified;case"compaction-progress":return s.kind==="compaction-progress"&&n.state===s.state;case"session-custom":return s.kind==="session-custom"&&n.entry===s.entry;case"divider":return s.kind==="divider"&&n.text===s.text;case"plugin-message":return s.kind==="plugin-message"&&n.text===s.text&&n.pluginId===s.pluginId}}const HU=/^<(agent-notification|goal-continuation|coworker-hired|coworker-dismissed|background-task-update)>\n?([\s\S]*?)\n?<\/\1>\s*$/,FN=/^<role>\n?([\s\S]*?)\n?<\/role>\s*/,BU=/^<workspace-migrated>\n?([\s\S]*?)\n?<\/workspace-migrated>\s*/;function VU({note:e}){const{t}=te(),n=/(?:moved to|main working tree): (.+)$/m.exec(e)?.[1]?.trim(),s=e.includes("main working tree");return o.jsxs("div",{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:[o.jsx(Ni,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.jsxs("span",{className:"min-w-0",children:[t(s?"Workspace fell back to the main working tree":"Workspace moved to an isolated worktree"),n&&o.jsx("span",{className:"ml-1.5 break-all font-mono text-[11px] opacity-80",children:n})]})]})}function $U({note:e}){const{t}=te();return o.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:[o.jsx(da,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.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 WU({note:e}){const{t}=te(),n=e==="on";return o.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:[n?o.jsx(DA,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):o.jsx(kV,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.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 UU({tag:e,body:t}){const[n,s]=m.useState(!1),i=t.trim(),r=i.indexOf(`
70
- `),a=r>0,l=e.startsWith("coworker-")||e==="agent-notification"?Zs:Eo;return o.jsxs("div",{className:"w-full rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[o.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:[o.jsx(l,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:q("min-w-0 flex-1",a?"truncate":"whitespace-pre-wrap"),children:a?i.slice(0,r):i}),a&&o.jsx(kn,{className:q("mt-0.5 h-3 w-3 shrink-0 transition-transform",n&&"rotate-90")})]}),a&&n&&o.jsx("pre",{className:"mt-1.5 max-h-80 overflow-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-words",children:i.slice(r+1)})]})}const HN=/^<message-from-main-agent>\n?([\s\S]*?)\n?<\/message-from-main-agent>\s*$/;function KU(e){const t=FN.exec(e);return HN.test(t?e.slice(t[0].length):e)}const BN=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function qU({name:e,content:t}){const{t:n}=te();return o.jsxs(gn,{children:[o.jsxs(AA,{className:RN("skill",!0),children:[o.jsx(Ls,{className:"h-3 w-3"}),e]}),o.jsxs(xn,{className:"max-w-lg",children:[o.jsx(vn,{children:o.jsxs(bn,{className:"text-base",children:[n("Skill")," · ",e]})}),o.jsx(Rn,{className:"max-h-[50vh] text-sm",children:o.jsx(Ds,{text:t})})]})]})}function VN({chip:e,extra:t}){return o.jsxs("div",{className:"max-w-[80%] rounded-2xl rounded-br-md bg-muted px-4 py-2.5 text-sm",children:[e,t?o.jsx("span",{className:"ml-1.5 align-middle whitespace-pre-wrap",children:t}):null]})}function YU({text:e}){const t=BN.exec(e);if(!t)return null;const[,n,,s,i]=t;return o.jsx(VN,{chip:o.jsx(qU,{name:n,content:s}),extra:i?.trim()})}function XU({text:e}){const t=fu(e);return t.slash?o.jsx(VN,{chip:o.jsx(bx,{name:t.slash}),extra:t.rest.trim()}):null}function JU({preset:e}){const{t}=te();return o.jsxs("div",{className:"min-w-64 max-w-[80%] overflow-hidden rounded-2xl rounded-br-md bg-muted text-sm",children:[o.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2.5",children:[o.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-info/15 text-info",children:o.jsx(Hm,{className:"h-4 w-4"})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("Workflow preset")}),o.jsx("p",{className:"truncate font-medium",title:e.id,children:e.name||e.id})]})]}),e.args.length>0&&o.jsx("dl",{className:"space-y-1 border-t border-border/60 px-3.5 py-2 text-xs",children:e.args.map(([n,s])=>o.jsxs("div",{className:"flex gap-2",children:[o.jsx("dt",{className:"shrink-0 font-mono text-muted-foreground",children:n}),o.jsx("dd",{className:"min-w-0 whitespace-pre-wrap break-words",children:s})]},n))})]})}function ml({kind:e,label:t,title:n}){const s=e==="file"?go:e==="chat"?Lo:m1;return o.jsxs("span",{className:q(mx(e),"mx-0.5 max-w-52 rounded-md px-1.5 align-middle leading-4"),title:n,children:[o.jsx(s,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:t})]})}function Ia({text:e,searchQuery:t="",activeNth:n=-1}){const s=WV(e),i={n:0};return o.jsx("span",{className:"whitespace-pre-wrap",children:s.map((r,a)=>r.type==="file"?o.jsx(KC,{path:r.path,children:o.jsx(ml,{kind:"file",label:ih(r.path),title:r.path})},a):r.type==="chat"?o.jsx(ml,{kind:"chat",label:r.label,title:r.sessionFile},a):r.type==="ui-element"?o.jsx(ml,{kind:"ui-element",label:r.label,title:`${r.path}${r.text?` · ${r.text}`:""}`},a):o.jsx("span",{children:t.trim()?PA(r.text,t,n,i):r.text},a))})}function ZU({files:e,chats:t}){return o.jsxs("span",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[e.map(n=>o.jsx(KC,{path:n,children:o.jsx(ml,{kind:"file",label:ih(n),title:n})},`f:${n}`)),t.map(n=>o.jsx(ml,{kind:"chat",label:n.label,title:n.sessionFile},`c:${n.sessionFile}`))]})}const Wa="max-w-[82%] rounded-[10px] bg-muted px-3.5 py-[9px] text-[14.5px] leading-[1.6]";function Ua({text:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=te(),i=Bi(),r=!!(i?.speaker||i?.botSession),a=r?wA(e):null;if(a)return o.jsx(Z6,{message:a});const l=r?yA(e):e;if(l!==e)return o.jsx(Ua,{text:l,searchQuery:t,activeNth:n});const c=r?SA(e):null;if(c?.refs.length)return o.jsxs("div",{className:"flex w-full flex-col items-end gap-1.5",children:[c.body&&o.jsx(Ua,{text:c.body,searchQuery:t,activeNth:n}),o.jsx("div",{className:"flex flex-wrap justify-end gap-1.5",children:c.refs.map(j=>o.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:[o.jsx(oa,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"min-w-0 truncate",children:j.title})]},j.id))})]});const d=CA(e);if(d.note){const j=d.rest.trim();return o.jsxs("div",{className:"flex w-full flex-col items-end gap-1.5",children:[o.jsx($U,{note:d.note}),j&&o.jsx(Ua,{text:j,searchQuery:t,activeNth:n})]})}const u=kA(e);if(u.note){const j=u.rest.trim();return o.jsxs("div",{className:"flex w-full flex-col items-end gap-1.5",children:[o.jsx(WU,{note:u.note}),j&&o.jsx(Ua,{text:j,searchQuery:t,activeNth:n})]})}const h=_A(e);if(h?.kind==="approved")return o.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:[o.jsx(c1,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.jsxs("span",{className:"min-w-0",children:[s("Plan approved, executing"),o.jsx("span",{className:"ml-1.5 text-foreground",children:h.title})]})]});if(h?.kind==="feedback")return o.jsxs("div",{className:q(Wa,"whitespace-pre-wrap"),children:[o.jsxs("p",{className:"mb-1 flex items-center gap-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:[o.jsx(da,{className:"h-3 w-3"}),s("Plan feedback")]}),o.jsx(Ia,{text:h.feedback,searchQuery:t,activeNth:n})]});const p=jA(e);if(p)return o.jsx(JU,{preset:p});const f=JV(e);if(f.files.length>0||f.chats.length>0){const j=fu(f.body);return o.jsxs("div",{className:Wa,children:[j.slash?o.jsxs(o.Fragment,{children:[o.jsx(bx,{name:j.slash}),j.rest.trim()?o.jsx("span",{className:"ml-1.5 align-middle",children:o.jsx(Ia,{text:j.rest.trim(),searchQuery:t,activeNth:n})}):null]}):o.jsx(Ia,{text:f.body,searchQuery:t,activeNth:n}),o.jsx(ZU,{files:f.files,chats:f.chats})]})}if(BN.test(e))return o.jsx(YU,{text:e});if(fu(e).slash)return o.jsx(XU,{text:e});const g=BU.exec(e);if(g){const j=e.slice(g[0].length).trim();return o.jsxs("div",{className:"flex w-full flex-col items-end gap-1.5",children:[o.jsx(VU,{note:g[1]}),j&&o.jsx("div",{className:q(Wa,"whitespace-pre-wrap"),children:o.jsx(Ia,{text:j,searchQuery:t,activeNth:n})})]})}const v=HU.exec(e);if(v)return o.jsx(UU,{tag:v[1],body:v[2]});const w=FN.exec(e),y=w?e.slice(w[0].length):e,b=HN.exec(y),_=b?b[1]:y;return o.jsxs("div",{className:q(b?"max-w-[80%] rounded-2xl rounded-bl-md border border-blue-500/20 bg-blue-500/8 px-4 py-2.5 text-sm":q(Wa,"whitespace-pre-wrap")),children:[b&&o.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:[o.jsx(Zs,{className:"h-3 w-3"}),s("From main agent")]}),w?.[1]&&!X6(w[1])&&o.jsxs("div",{className:"mb-2 rounded-md bg-background/60 px-2.5 py-1.5 text-xs text-muted-foreground",children:[o.jsx("span",{className:"font-semibold",children:s("Role")})," · ",w[1]]}),b?o.jsx(Ds,{text:_,searchQuery:t,activeNth:n}):o.jsx(Ia,{text:_,searchQuery:t,activeNth:n})]})}function Vw(e){return e.kind==="tool-group"||e.kind==="thinking"||e.kind==="tool"&&$C(e)}const uh="text-[color:var(--subtle-foreground,var(--muted-foreground))]";function QU({model:e,at:t,privacyMask:n}){const s=Bi()?.speaker,i=[e,typeof t=="number"?hh(t):null].filter(Boolean).join(" · ");return!s&&!i&&!n?null:o.jsxs("div",{className:"mb-2 flex h-6 min-w-0 items-center gap-2 text-xs select-none",children:[s&&(s.image?o.jsx("img",{src:s.image,alt:"",draggable:!1,className:"size-[22px] shrink-0 rounded-full object-cover",style:{backgroundColor:s.color}}):o.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&&o.jsx("span",{className:"shrink-0 truncate text-[13px] font-semibold text-foreground",children:s.name}),i&&o.jsx("span",{className:q("min-w-0 truncate text-[11.5px]",uh),children:i}),n&&o.jsx(Z8,{report:n})]})}const e7=m.memo(function({item:t,onToggleGroup:n,onToggleTurn:s}){const i=dA(),r=i.query,a=i.activeKey===t.key?i.activeNth:-1;switch(t.kind){case"user":{const l=t.text?KU(t.text):!1,c=t.collapsed===!0;return o.jsxs("div",{"data-enso":"message-user",className:q("group/user flex flex-col gap-1.5",l?"items-start":"items-end"),children:[t.images.map((d,u)=>o.jsx(GN,{src:`data:${d.mimeType};base64,${d.data}`,className:"max-h-48 max-w-full rounded-lg border object-contain"},u)),t.text&&o.jsx(Ua,{text:t.text,searchQuery:r,activeNth:a}),c?o.jsx(l7,{turnKey:t.key,timestamp:t.timestamp,turnDurationMs:t.turnDurationMs,onToggle:s}):o.jsx(c7,{turnKey:t.key,messageIndex:Number(t.key),timestamp:t.timestamp,deliveryState:t.deliveryState,canCollapse:t.canCollapse,onToggleTurn:s})]})}case"text":return o.jsx(d7,{item:t,searchQuery:r,activeNth:a});case"thinking":return o.jsx(p7,{itemKey:t.key,text:t.text,streaming:t.streaming,durationMs:t.durationMs,startedAt:t.startedAt});case"tool":return o.jsxs(o.Fragment,{children:[o.jsx(uA,{name:t.name,output:t.output,state:t.state}),o.jsx(y7,{item:t}),t.pluginArtifacts?o.jsx(hA,{artifacts:t.pluginArtifacts}):null]});case"tool-group":return o.jsx(x7,{item:t,onToggle:n});case"error":return o.jsxs("div",{className:"flex items-start gap-2 text-sm text-destructive",children:[o.jsx(ur,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.jsx("p",{className:"min-w-0 flex-1 whitespace-pre-wrap",children:t.text}),o.jsx(WN,{})]});case"task-note":return o.jsx(f7,{item:t});case"compaction":case"compaction-notice":return o.jsx(g7,{item:t});case"compaction-progress":return o.jsx(m7,{state:t.state});case"session-custom":return o.jsx(s7,{entry:t.entry});case"plugin-message":return o.jsx(n7,{item:t});case"divider":return o.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground",children:[o.jsx("span",{className:"h-px flex-1 bg-border"}),t.text,o.jsx("span",{className:"h-px flex-1 bg-border"})]})}},FU),$w=e=>{if(typeof e=="string")return e;if(e===void 0)return"—";try{return JSON.stringify(e)}catch{return String(e)}};function t7({entry:e}){const{t}=te(),n=e4(),s=n.get(e.accountKey),i=e.previousAccountKey?n.get(e.previousAccountKey):void 0,r=e.previousAccountKey?i&&s?t("ChatGPT account switched: {{previous}} → {{current}}",{previous:i,current:s}):t("ChatGPT account switched"):s?t("ChatGPT account selected: {{account}}",{account:s}):t("ChatGPT account selected");return o.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:[o.jsx(Mo,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),o.jsx("p",{className:"min-w-0 break-words text-muted-foreground",children:r})]})}function n7({item:e}){const{t}=te();return o.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:[o.jsxs("p",{className:"mb-1 flex items-center gap-1.5 text-muted-foreground",children:[o.jsx(Fm,{pluginId:e.pluginId,className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{children:t("From plugin {{name}}",{name:e.pluginName})}),o.jsx("span",{className:"font-mono opacity-70",children:e.pluginId})]}),o.jsx("p",{className:"whitespace-pre-wrap break-words text-foreground",children:e.text})]})}function s7({entry:e}){const{t}=te();if(e.kind==="oauth-account-selected")return o.jsx(t7,{entry:e});if(e.kind==="agent-dispatch")return o.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:[o.jsx(Zs,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),o.jsx("span",{className:"text-muted-foreground",children:t("Dispatched to")}),o.jsx("span",{className:"font-medium",children:e.child.instanceName})]});if(e.kind==="agent-completed")return o.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:[o.jsx(Jn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"}),o.jsxs("div",{className:"min-w-0",children:[o.jsxs("p",{className:"font-medium",children:[e.child.instanceName," · ",t("Completed")]}),e.receiptSummary&&o.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:e.receiptSummary})]})]});if(e.kind==="agent-failed")return o.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:[o.jsx(ur,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive"}),o.jsxs("div",{className:"min-w-0",children:[o.jsxs("p",{className:"font-medium",children:[e.child.instanceName," · ",t("Failed")]}),o.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:e.message})]})]});const n=e.receipt,s=n.outcome==="succeeded";return o.jsx("div",{className:q("rounded-md border px-2.5 py-2 text-xs",s?"border-emerald-500/20 bg-emerald-500/5":n.outcome==="failed"?"border-destructive/20 bg-destructive/5":"border-amber-500/20 bg-amber-500/5"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[s?o.jsx(Jn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"}):o.jsx(ur,{className:q("mt-0.5 h-3.5 w-3.5 shrink-0",n.outcome==="failed"?"text-destructive":"text-amber-500")}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("p",{className:"font-medium",children:[n.subject.label," · ",t(n.outcome)]}),o.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:n.summary}),n.changes&&n.changes.length>0&&o.jsx("dl",{className:"mt-2 space-y-1 border-t border-border/50 pt-2",children:n.changes.map(i=>o.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[o.jsx("dt",{className:"truncate text-muted-foreground",children:i.field}),o.jsxs("dd",{className:"text-right font-mono",children:[$w(i.previous)," → ",$w(i.value)]})]},i.field))})]})]})})}function Is(e){const t=e.activeId?e.conversations[e.activeId]:null;return t?t.activeTabId?e.conversations[t.activeTabId]??t:t:null}const $N=()=>()=>{};function WN(){const{t:e}=te(),t=Bi(),n=t?.botControls,s=ie(l=>{if(t&&(!t.canRetry||t.botControls))return!1;const c=Is(l);return!!(c?.started&&!c.spawning&&c.status!=="running")}),i=()=>{if(!n||!t?.canRetry)return!1;const l=n.projection();return!!(l&&l.status!=="running")},r=m.useSyncExternalStore(n?.subscribe??$N,i,i);return(n?r:s)?o.jsxs("button",{type:"button",title:e("Retry"),onClick:()=>{if(n)return n.retry();const l=Is(ie.getState());l&&ie.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:[o.jsx(Mo,{className:"h-3 w-3"}),e("Retry")]}):null}function i7(e,t){return EA(Is(e),t)}const yx="flex items-center gap-1 text-[11px] text-muted-foreground transition-opacity hover:text-foreground";function o7({messageIndex:e}){const{t}=te(),n=Bi();return ie(i=>TA(Is(i),n))?o.jsxs("button",{type:"button",className:yx,title:t("Keep this session and start a parallel one from here"),onClick:()=>{const i=ie.getState(),r=Is(i);if(!r)return;const a=IA(r,e);a!==null&&i.forkFromMessage(r.id,a)},children:[o.jsx(Ni,{className:"h-3 w-3"}),t("Conversation branch")]}):null}function r7({messageIndex:e}){const{t}=te(),n=Bi(),s=ie(r=>Is(r)?.id),i=ie(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 NA(l)?l.deliveryId:void 0});return!s||!i?null:o.jsxs("button",{type:"button",title:t("Withdraw message"),onClick:()=>ie.getState().withdrawMessage(s,{kind:"delivery",id:i}),className:"inline-flex items-center gap-1 hover:text-foreground",children:[o.jsx(ra,{className:"h-3 w-3"}),t("Withdraw message")]})}function a7({messageIndex:e}){const{t}=te(),[n,s]=m.useState(!1),[i,r]=m.useState(null),a=Bi(),l=a?.botControls,c=ie(g=>{if(a?.botControls)return!1;const v=Is(g);return i7(g,a)&&!!(v&&wc(v.id,v.id,v,e))}),d=()=>{if(!l||!a?.canRewind||!a.sessionId)return null;const g=l.projection();return!g||g.status==="running"?null:wc(a.sessionId,a.sessionId,g,e)?.entryId??null},u=m.useSyncExternalStore(l?.subscribe??$N,d,d);if(!(l?u!==null:c))return null;const p=g=>{if(l&&a?.sessionId&&u){r({restoreFiles:g,conversationId:a.sessionId,entryId:u});return}const v=Is(ie.getState());if(!v)return;const w=wc(v.id,v.id,v,e);w&&r({restoreFiles:g,conversationId:v.id,entryId:w.entryId})},f=(g,v,w)=>{if(l)return l.rewind(w,g);const y=ie.getState(),b=Is(y),_=wc(v,b?.id,y.conversations[v],e,w);_&&y.rewind(_.conversationId,_.entryId,g)},x=[{icon:ra,label:t("Conversation only"),desc:t("Rewind to this message"),restoreFiles:!1,action:()=>p(!1)},{icon:Lo,label:t("Conversation + files"),desc:t("Rewind and restore files to before this turn"),restoreFiles:!0,action:()=>p(!0)}];return o.jsxs(Pi,{open:n,onOpenChange:s,children:[o.jsxs(Ei,{className:yx,title:t("Rewind to this message"),children:[o.jsx(ra,{className:"h-3 w-3"}),t("Rewind")]}),o.jsx(Ai,{side:"bottom",align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",children:x.map(g=>o.jsxs("button",{type:"button",onClick:()=>{s(!1),g.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:[o.jsx(g.icon,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block",children:g.label}),o.jsx("span",{className:"block text-xs text-muted-foreground",children:g.desc})]})]},g.label))}),o.jsx(hs,{open:i!==null,onOpenChange:g=>{g||r(null)},title:t("Rewind to this message?"),description:i?.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:()=>{i&&f(i.restoreFiles,i.conversationId,i.entryId)}})]})}function l7({turnKey:e,timestamp:t,turnDurationMs:n,onToggle:s}){const{t:i}=te();return o.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground/80 select-none",children:[o.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:i("Expand"),children:[o.jsx(kn,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{children:i("Expand")})]}),typeof t=="number"&&o.jsx("span",{children:hh(t)}),n!==void 0&&o.jsxs("span",{children:["· ",i("took {{duration}}",{duration:rs(n)})]})]})}function c7({turnKey:e,messageIndex:t,timestamp:n,canCollapse:s,deliveryState:i,onToggleTurn:r}){const{t:a}=te(),l=xe(c=>c.autoCollapseTurns);return o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/75 select-none",children:[o.jsx(a7,{messageIndex:t}),o.jsx(r7,{messageIndex:t}),i&&o.jsx("span",{children:a(i==="rejected"?"Not sent":"Delivery unconfirmed")}),l&&s&&r&&o.jsxs("button",{type:"button",onClick:()=>r(e,!0),className:q(yx,"cursor-pointer opacity-0 group-hover/user:opacity-100"),title:a("Collapse"),children:[o.jsx($n,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{children:a("Collapse")})]}),typeof n=="number"&&o.jsx("span",{children:hh(n)})]})}function d7({item:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=te(),i=Bi(),r=e.perf?h7(e.perf,s,e.turnDurationMs!==void 0):"",a=ie(c=>Is(c)?.id??null),l={text:e.text,messageIndex:Number(e.key.split("-")[0]),sessionId:i?i.sessionId:a};return o.jsxs("div",{"data-enso":"message-assistant",className:"group text-[14.5px]",children:[o.jsx(Ds,{text:e.text,streaming:e.streaming,searchQuery:t,activeNth:n,leaf:{messageIndex:l.messageIndex,sessionId:l.sessionId}}),e.turnEnd&&!e.streaming&&i?.turnFooter?.(Number(e.key.split("-")[0])),!e.streaming&&o.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:[o.jsx(bv,{position:"left",...l}),o.jsx(u7,{text:e.text}),o.jsx(bv,{position:"right",...l}),e.turnEnd&&o.jsx(o7,{messageIndex:Number(e.key.split("-")[0])}),e.timestamp&&!e.turnEnd&&o.jsx("span",{children:hh(e.timestamp)}),e.turnDurationMs!==void 0&&o.jsxs("span",{children:[e.timestamp&&!e.turnEnd&&"· ",s("took {{duration}}",{duration:rs(e.turnDurationMs)})]}),r&&o.jsxs("span",{children:["· ",r]})]})]})}function u7({text:e}){const{t}=te(),[n,s]=m.useState(!1);return o.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?o.jsx(Jn,{className:"h-3 w-3"}):o.jsx(Pu,{className:"h-3 w-3"})})}const Ww=e=>String(e).padStart(2,"0"),hh=e=>{const t=new Date(e);return`${Ww(t.getHours())}:${Ww(t.getMinutes())}`},Uw=e=>{const t=e/1e3;return t<10?String(Math.round(t*10)/10):String(Math.round(t))};function h7(e,t,n=!1){const s=[];return(!n||e.turnMs!==void 0)&&s.push(`${Uw(e.runMs)}s`),e.ttftMs!==void 0&&s.push(`TTFT ${Uw(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:rs(e.turnMs)})),s.join(" · ")}function p7({itemKey:e,text:t,streaming:n,durationMs:s,startedAt:i}){const{t:r}=te(),a=xe(u=>u.expandLiveReasoning),[l,c]=m.useState(null),d=bA(l,n,a);return o.jsxs("div",{"data-enso":"thinking",children:[o.jsxs("button",{type:"button",onClick:()=>c(!d),className:q("flex min-h-6 items-center gap-2 text-[13px] transition-colors hover:text-foreground",uh),children:[o.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:o.jsx(pA,{className:q("size-3",n&&"animate-pulse text-brand")})}),n?o.jsx("span",{className:"t-shimmer","data-text":r("Thinking…"),children:r("Thinking…")}):s!==null?o.jsx("span",{children:r("Thought for {{duration}}",{duration:rs(s)})}):o.jsx("span",{children:r("Thought process")}),n&&o.jsx(UN,{itemKey:e,since:i}),o.jsx(kn,{className:q("h-3 w-3 transition-transform",d&&"rotate-90")})]}),d&&o.jsx(fA,{text:t,streaming:n,itemKey:e})]})}function f7({item:e}){const{t}=te(),[n,s]=m.useState(!1),[i,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 (\/.+?\.log) for the complete log|Full log: (\/\S+?\.log))/.exec(e.detail)?.slice(1).find(Boolean)??null;return m.useEffect(()=>{!n||!c||i!==void 0||window.electronAPI.files.read(c).then(d=>{r(typeof d=="string"?d:null)}).catch(()=>r(null))},[n,c,i]),o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>s(d=>!d),className:"flex w-full items-center gap-3",title:e.detail,children:[o.jsx("span",{className:"h-px flex-1 bg-border"}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[o.jsx(Jn,{className:"h-3 w-3 text-green-600 dark:text-green-500"}),l,o.jsx(kn,{className:q("h-3 w-3 transition-transform",n&&"rotate-90")})]}),o.jsx("span",{className:"h-px flex-1 bg-border"})]}),n&&o.jsxs("div",{className:"mt-1.5 rounded-lg border border-border/60 bg-muted/20",children:[o.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}),o.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?i===void 0?t("Loading…"):Oi(i??t("(log unavailable)")):t("(no log available)")})]})]})}function m7({state:e}){const{t}=te();return o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[o.jsx(Vt,{className:"h-3 w-3 animate-spin"}),o.jsx("span",{children:t(e==="queued"?"Compacts after this turn":"Compacting…")})]})}function g7({item:e}){const{t}=te(),[n,s]=m.useState(!1),i=e.kind==="compaction",r=e.tokensBefore===null?null:js(e.tokensBefore),a=e.memory?r===null?t("Memory context compacted"):t("Memory context compacted ({{tokens}} tokens before)",{tokens:r}):e.verified?r===null?t("Verified context compacted"):t("Verified context compacted ({{tokens}} tokens before)",{tokens:r}):r===null?t("Context compacted"):t("Context compacted ({{tokens}} tokens before)",{tokens:r});return o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>s(l=>!l),className:q("flex items-center gap-3",i&&"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(i?"Messages above are no longer in the model context; only this summary is.":"Latest compaction summary — expand to read what the model kept."),children:[i&&o.jsx("span",{className:"h-px flex-1 bg-border"}),o.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[o.jsx(qB,{className:"h-3 w-3"}),a,o.jsx(kn,{className:q("h-3 w-3 transition-transform",n&&"rotate-90")})]}),i&&o.jsx("span",{className:"h-px flex-1 bg-border"})]}),n&&o.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 x7({item:e,onToggle:t}){const{t:n}=te(),s=xe(p=>p.compactReadOnlyTools),i=[];e.stats.commands>0&&i.push(n("ran {{count}} commands",{count:e.stats.commands})),e.stats.reads>0&&i.push(n("read {{count}} files",{count:e.stats.reads})),e.stats.searches>0&&i.push(n("searched {{count}} times",{count:e.stats.searches})),e.stats.others>0&&i.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=c?aa("explore_fold",n):a?a.workedMs>0?n("Worked for {{duration}}",{duration:rs(a.workedMs)}):n("Activity"):s?e.exploring?n("Exploring"):n("Explored"):n("{{count}} tool calls",{count:e.count}),u=c?[c.goal,n("{{count}} tool calls",{count:e.count})].filter(Boolean):a?l:s?r:i,h=o.jsxs("button",{type:"button",onClick:()=>{c?.steps&&t?.(wv(e.key)),t?.(e.key)},title:c?.goal,"data-explore-head":c?"":void 0,"data-enso":"tool-row",className:q("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",uh),children:[o.jsx(LN,{state:e.exploring?"running":"ok"}),e.exploring?o.jsx("span",{className:"t-shimmer shrink-0 font-medium","data-text":d,children:d}):o.jsx("span",{className:"shrink-0 text-muted-foreground group-hover/step:text-foreground",children:d}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.join(" · ")}),o.jsx(kn,{className:q("h-3 w-3 shrink-0 transition-transform",e.expanded&&"rotate-90")})]});return!c||!e.expanded?h:o.jsxs(o.Fragment,{children:[h,o.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&&o.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[o.jsx("div",{className:"mb-0.5 text-[11px] text-muted-foreground",children:n("Goal")}),o.jsx("p",{className:"whitespace-pre-wrap",children:c.goal})]}),c.report&&o.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[o.jsx("div",{className:"mb-0.5 text-[11px] text-muted-foreground",children:n("Result")}),o.jsx(Ds,{text:c.report})]}),o.jsxs("button",{type:"button",onClick:()=>t?.(wv(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:[o.jsx(kn,{className:q("h-3 w-3 shrink-0 transition-transform",c.steps&&"rotate-90")}),o.jsx("span",{children:c.steps?n("Hide process"):n("Show process")}),o.jsxs("span",{children:["· ",n("{{count}} tool calls",{count:e.count})]})]})]})]})}function Da({children:e,className:t,follow:n}){const s=m.useRef(null),i=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=i.current;if(!p)return;const f=new ResizeObserver(h);return f.observe(p),()=>f.disconnect()},[h]),m.useEffect(()=>()=>cancelAnimationFrame(d.current),[]),o.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 g=l.current;if(g!==null&&f.scrollTop>=g-2){l.current=null,h();return}u()},className:q("max-h-96 overflow-auto [overflow-anchor:none]",t),children:o.jsx("div",{ref:i,children:e})})}function v7(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??""}catch{return String(e)}}function b7({source:e,output:t,view:n}){const s=n?.status==="completed"?v7(n.value):n?.error??t;return o.jsxs("div",{className:"space-y-1 px-3 py-1",children:[e?o.jsx(yv,{code:e,language:"javascript"}):null,n&&n.calls.length>0?o.jsx("div",{className:"flex flex-wrap gap-1",children:[...new Map(n.calls.map(i=>[i.name,i])).keys()].map(i=>{const r=n.calls.filter(c=>c.name===i),a=r.find(c=>!c.ok),l=`${i} ×${r.length}`;return o.jsx("span",{className:q("rounded-md border px-1.5 py-0.5 font-mono text-[10px]",a?"border-destructive/40 text-destructive":"text-muted-foreground"),title:r.map(c=>c.summary).filter(Boolean).join(`
71
- `),children:a?`${l} · ${a.error??"error"}`:l},i)})}):null,s?n?.status==="completed"&&typeof n.value!="string"?o.jsx(yv,{code:s,language:"json"}):o.jsx("pre",{className:"font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:Oi(s)}):null]})}function w7({path:e,fallback:t}){const[n,s]=m.useState(!1);return n?t:o.jsx("div",{"data-slot":"read-image",className:"w-full min-w-0 px-3 py-3",children:o.jsx(GN,{src:Kp(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 y7({item:e}){const{t}=te(),n=Bi(),s=xe(I=>I.compactReadOnlyTools),i=xe(I=>I.expandLiveEdits),r=s&&e.name!=="bash"&&$C(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=j1[e.name],f=WC(e.name),x=e.subagentOp?[t(h$[e.subagentOp]),e.summary].filter(Boolean).join(" · "):e.summary,g=e.nestedPending&&e.state==="running"?`${x} · ${e.nestedPending} pending`:d?.calls.length&&e.state!=="error"?mA(d.calls):x,v=!!(e.output||e.source||u||e.ask),w=e.state==="running"&&e.waiting==="subagent"&&!n,y=a||l||c||v||w||h,b=i&&(a||l||h)&&e.state==="running",[_,j]=m.useState(b),N=_&&e.name==="memory_search"?M8(e.output):null,C=_&&e.name==="memory_capture"?R8(e.output,e.memoryContent):null,k=_&&e.name==="subagent"&&e.state!=="error"?AU(e.subagentOp,e.output):null,E=m.useRef(c);return m.useEffect(()=>{const I=gA(e,E.current);E.current=c,(b||i&&I)&&j(!0)},[b,i,c,e]),e.todos?o.jsx(k7,{todos:e.todos}):e.name.startsWith("goal_")?o.jsx(S7,{item:e}):e.plan&&e.state!=="error"?o.jsx(C7,{plan:e.plan}):o.jsxs("div",{"data-enso":"tool-row","data-tool-style":r?"compact":"full",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsxs("button",{type:"button",disabled:!y,onClick:()=>j(I=>!I),className:q("group/step flex min-h-6 min-w-0 flex-1 items-center gap-2 text-left text-[13px]",uh,y&&"cursor-pointer"),children:[o.jsx(LN,{state:e.state}),o.jsx("span",{className:"shrink-0 text-muted-foreground transition-colors group-hover/step:text-foreground",children:p?t(p):f?.tool??e.name}),o.jsx("span",{className:q("min-w-0 flex-1 truncate font-mono text-[12px]",e.state==="error"?"text-destructive":"text-muted-foreground"),children:e.state==="error"&&e.output?x&&e.name==="apply_patch"&&c?`${g} · ${Yw(e.output)}`:Yw(e.output):x?g:null}),e.backgroundTaskId&&o.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",title:e.backgroundTaskId,children:t("Moved to background")}),e.shellFailure&&e.state!=="running"&&o.jsx(yU,{failure:e.shellFailure}),e.state==="reviewing"?o.jsx("span",{className:"t-shimmer shrink-0 text-[11px]","data-text":t("Assistant reviewing…"),children:t("Assistant reviewing…")}):e.state==="running"&&e.startedAt!==null?o.jsxs(o.Fragment,{children:[e.callId&&(e.name==="bash"||e.name==="powershell")&&o.jsx(D7,{callId:e.callId,startedAt:e.startedAt,output:e.output??""}),o.jsx(UN,{itemKey:e.key,since:e.startedAt??void 0})]}):(e.agentMeta||e.durationMs!==null)&&o.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?rs(e.durationMs):null].filter(Boolean).join(" · ")}),y&&o.jsx(kn,{className:q("h-3 w-3 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] group-hover/step:opacity-100",_&&"rotate-90 opacity-100")})]}),e.state==="running"&&e.callId&&!n&&o.jsx(_7,{callId:e.callId,waiting:!!e.waiting}),(a||l||c)&&(e.state==="ok"||c)&&o.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:()=>UC(),children:o.jsx(Ug,{className:"h-3 w-3"})})]}),_&&y&&o.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&&o.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]}),w&&o.jsx(I7,{agentIds:e.subagentTitles?Object.keys(e.subagentTitles):void 0}),a&&e.edits&&o.jsx(Da,{follow:e.state==="running",children:o.jsx(Lw,{path:e.summary,blocks:e.edits})}),c&&e.fileChanges&&o.jsx(Da,{follow:e.state==="running",children:e.fileChanges.map((I,T)=>o.jsxs("div",{children:[o.jsxs("div",{className:q("flex items-center gap-2 border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",(T>0||a)&&"border-t"),children:[o.jsx("span",{className:"uppercase",children:I.type}),o.jsx("span",{className:"min-w-0 flex-1 truncate",title:I.path,children:I.path}),I.truncated&&o.jsx("span",{children:t("Truncated preview")})]}),o.jsx(Lw,{path:I.path,blocks:[I],snapshot:I})]},`${I.type}:${ux(I.path,I.oldText,I.newText)}`))}),xA(e)&&o.jsx(Da,{follow:!1,className:"border-t border-border/60",children:o.jsx("pre",{className:"px-3 py-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:Oi(e.output??"")})}),l&&e.writeContent&&o.jsx(Da,{follow:e.state==="running",className:q((a||c)&&"border-t border-border/60"),children:o.jsx(Id,{path:e.summary,contents:e.writeContent})}),!a&&!l&&!c&&(v||h)&&o.jsxs(Da,{follow:e.state==="running",children:[vA(e.name)?o.jsx(b7,{source:e.source,output:e.output,view:d}):e.name==="bash"||e.name==="powershell"?o.jsx(MU,{command:e.summary,output:e.output??"",failure:e.shellFailure}):e.name==="read"&&h&&e.imagePath?o.jsx(w7,{path:e.imagePath,fallback:o.jsx(Id,{path:e.summary,contents:e.output??""})},e.imagePath):e.name==="read"?o.jsx(Id,{path:e.summary,contents:e.output??""}):e.name==="subagent"&&e.state!=="error"&&!u&&!k?o.jsx("div",{className:"px-3 py-2 text-sm",children:o.jsx(Ds,{text:e.output??""})}):N?o.jsx(em,{hits:N}):C?o.jsx(I8,{view:C}):o.jsxs(o.Fragment,{children:[e.ask&&o.jsx(c4,{ask:e.ask,waiting:e.state==="running"}),u&&o.jsx("div",{className:"px-3 py-2 text-sm",children:o.jsx(Ds,{text:u})}),k?o.jsx(IU,{view:k,titles:e.subagentTitles}):e.output&&o.jsx("pre",{className:"px-3 py-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:Oi(e.output)})]}),o.jsx(iU,{value:e.rtk}),o.jsx(l4,{value:e.approvalReview})]})]})]})}function S7({item:e}){const{t}=te(),n=e.name.replace("goal_",""),s=t(n==="complete"?"Goal completed":n==="blocked"?"Goal blocked":"Goal waiting");return o.jsxs("div",{className:q("flex items-start gap-2 rounded-lg border px-3 py-2 text-sm",n==="complete"&&"border-green-500/50 bg-green-500/5",n==="blocked"&&"border-destructive/50 bg-destructive/5",n==="wait"&&"border-amber-500/50 bg-amber-500/5"),children:[o.jsx(Sa,{className:q("mt-0.5 h-4 w-4 shrink-0",n==="complete"&&"text-green-600 dark:text-green-500",n==="blocked"&&"text-destructive",n==="wait"&&"text-amber-500")}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"font-medium",children:s}),e.summary&&o.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground text-xs",children:e.summary})]})]})}function C7({plan:e}){const{t}=te(),[n,s]=m.useState(!1);return o.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 px-3 py-2",children:[o.jsxs("button",{type:"button",onClick:()=>s(i=>!i),className:"flex w-full min-w-0 items-center gap-2 text-left text-xs",children:[o.jsx(da,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"shrink-0 font-medium text-muted-foreground",children:t("Plan")}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:e.title}),o.jsx(kn,{className:q("h-3 w-3 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")})]}),n&&o.jsx("div",{className:"mt-2 border-border/60 border-t pt-2 text-sm",children:o.jsx(Ds,{text:e.text})})]})}function k7({todos:e}){const{t}=te(),n=e.filter(s=>s.status==="completed").length;return o.jsxs("div",{"data-enso":"todo",className:"rounded-lg border bg-card px-3 py-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[o.jsx(BC,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"font-medium text-foreground",children:t("Todos")}),o.jsxs("span",{className:"ml-auto tabular-nums",children:[n,"/",e.length]})]}),o.jsx(zN,{done:n,total:e.length,className:"mt-1.5 mb-2"}),o.jsx(ON,{todos:e})]})}const Kw=new Map;function _7({callId:e,waiting:t}){const{t:n}=te(),s=ie(c=>Is(c)?.id??""),[i,r]=m.useState(!1);if(m.useEffect(()=>{if(!i)return;const c=setTimeout(()=>r(!1),5e3);return()=>clearTimeout(c)},[i]),!s)return null;const a=n(t?i?"Stopping wait…":"Stop waiting":i?"Moving to background…":"Move to background"),l=t?aV:kH;return o.jsxs("button",{type:"button",disabled:i,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:[o.jsx(l,{className:"h-3 w-3"}),a]})}const j7=5e3,N7=[];function T7(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 I7({agentIds:e}){const{t}=te(),n=ie(l=>Is(l)?.id??""),s=ew(l=>l.byConversation[n]??N7),[i,r]=m.useState(!1);if(m.useEffect(()=>{if(!n)return;let l=!0;const c=p=>{l&&(ew.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,j7);return()=>{l=!1,clearInterval(h),u()}},[n]),!i)return null;const a=e?.length?s.filter(l=>e.includes(l.agentId)):s;return o.jsxs("div",{className:"border-b border-border/60 px-3 py-2 text-xs",children:[a.length===0?o.jsx("div",{className:"text-muted-foreground",children:t("No running subagents")}):a.map(l=>o.jsxs("div",{className:"py-0.5",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"max-w-[40%] shrink-0 truncate font-medium",children:l.title??l.agentId.slice(0,8)}),o.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:T7(l,t)}),o.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:rs(l.elapsedMs)})]}),l.text&&o.jsx("div",{className:"line-clamp-2 break-words pl-2 text-[11px] text-muted-foreground/80",children:l.text.replace(/\s+/g," ")})]},l.runId)),o.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 UN({itemKey:e,since:t}){const n=Bi(),s=ie(c=>Is(c)?.id??""),i=n?n.sessionId??"":s,r=m.useRef(null);if(r.current===null){const c=`${i}:${e}`;r.current=t??Kw.get(c)??Date.now(),t===void 0&&Kw.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)},[]),o.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:rs(Date.now()-a)})}function D7({callId:e,startedAt:t,output:n}){const s=Bi(),i=ie(r=>s?void 0:Is(r)?.toolDeadlineAt?.[e]);return o.jsx(wU,{startedAt:t,deadlineAt:i,output:n})}function qw(e){return e.kind==="tool-group"?!0:e.kind==="tool"&&!e.todos&&!e.name.startsWith("goal_")}const Yw=e=>Oi(e.split(`
72
- `,1)[0]??""),P7=100;function E7(e,t,n,s,i=P7){if(s||!n)return{hiddenSince:t,delayMs:null};const r=t??e;return{hiddenSince:r,delayMs:Math.max(0,i-(e-r))}}const A7=1e6;function M7(e,t,n=A7){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((i,r)=>[i,r]));for(let i=0;i<e.keys.length;i++){const r=s.get(e.keys[i]);if(r===void 0)continue;const a=e.index+i-r;return{anchor:{keys:t,index:a},firstItemIndex:a,remount:!1}}return{anchor:{keys:t,index:n},firstItemIndex:n,remount:!0}}function R7(e,t){return t}const L7=new Set(["text","thinking","tool","tool-group"]),O7=[{icon:ZH,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:a1,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:qC,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:Lo,title:"Summarize recent changes",hint:"A digest based on git log",prompt:"Summarize the recent changes in this repository based on git log."}];function z7({onPick:e}){const{t}=te();return o.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:O7.map(({icon:n,title:s,hint:i,prompt:r})=>o.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:[o.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-lg bg-brand/8 text-brand dark:bg-brand/14",children:o.jsx(n,{className:"size-3.5"})}),o.jsxs("span",{className:"min-w-0",children:[o.jsx("span",{className:"block text-[13px] font-medium",children:t(s)}),o.jsx("span",{className:"block text-xs text-muted-foreground",children:t(i)})]})]},s))})}const fi="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",Xw=1e3;function Jw({className:e,children:t}){const[n,s]=m.useState(!1);return m.useEffect(()=>{const i=requestAnimationFrame(()=>s(!0));return()=>cancelAnimationFrame(i)},[]),o.jsx("div",{className:q("t-stagger",n&&"is-shown",e),children:t})}const Zw=40,G7={index:"LAST",align:"end"},F7={top:600,bottom:600},H7=e=>e?"auto":!1;function B7({style:e,...t}){const n=e?.visibility==="hidden",[s,i]=m.useState(!1),r=m.useRef(null);return m.useEffect(()=>{const a=E7(Date.now(),r.current,n,s);if(r.current=a.hiddenSince,a.delayMs===null)return;const l=window.setTimeout(()=>i(!0),a.delayMs);return()=>window.clearTimeout(l)},[n,s]),o.jsx("div",{...t,style:n&&s?{...e,visibility:"visible"}:e})}function ph({ref:e,items:t,busy:n,loading:s=!1,running:i,runStartedAt:r,lastOutputAt:a,error:l,emptyTitle:c,emptyDescription:d,onSuggestion:u,onRetryResume:h,virtualize:p=!0,onStartReached:f,historyLoading:x=!1,hasOlder:g,olderCursor:v,searchQuery:w="",activeHit:y=null}){const{t:b}=te(),_=m.useRef(null),[j,N]=m.useState(!0),[C,k]=m.useState(!1),E=m.useRef(!0),I=m.useRef(null),T=m.useRef(0),A=m.useRef(0),D=m.useRef(null),W=m.useRef(!1),J=m.useRef(!1),O=m.useRef(0),[B,L]=m.useState(null),se=m.useRef(0),Q=m.useCallback(ge=>{cancelAnimationFrame(se.current),se.current=requestAnimationFrame(()=>L(ge()))},[]);m.useEffect(()=>()=>cancelAnimationFrame(se.current),[]);const[V,H]=m.useState(new Set),ne=m.useCallback(ge=>{H($e=>{const it=new Set($e);return it.has(ge)?it.delete(ge):it.add(ge),it})},[]),[he,pe]=m.useState(new Map),ke=xe(ge=>ge.autoCollapseTurns),Me=xe(ge=>ge.collapseCompletedActivity),fe=xe(ge=>ge.compactReadOnlyTools),F=m.useMemo(()=>MA(t,i,V,{compact:fe,autoCollapseCompletedTurns:ke,collapseCompletedActivity:Me,turnOverrides:he}),[t,i,V,fe,ke,Me,he]),U=m.useRef({state:$6,collapse:new Map,reveal:new Map}),de=m.useMemo(()=>{const ge=U.current,$e=Mt=>I.current?.querySelector(`[data-nav-key="${CSS.escape(Mt)}"]`),it=W6(ge.state,F,(Mt,Gt)=>{const sn=$e(Mt)?.getBoundingClientRect().top,wn=$e(Gt)?.getBoundingClientRect().bottom;return sn===void 0||wn===void 0?0:wn-sn}),xt=Date.now();ge.state=it.next;for(const{key:Mt,...Gt}of it.collapses)ge.collapse.set(Mt,{at:xt,...Gt});for(const Mt of it.expands)ge.reveal.set(Mt,xt);return it.children},[F]),Y=m.useRef(null),X=m.useRef(0),z=m.useRef(null),ue=M7(Y.current,F.map(ge=>ge.key));Y.current=ue.anchor,ue.remount&&(X.current+=1,z.current=null);const _e=ue.firstItemIndex,Ee=m.useCallback((ge,$e)=>{pe(it=>it.get(ge)===$e?it:new Map(it).set(ge,$e))},[]),Be=m.useMemo(()=>{const ge=[];for(let $e=0;$e<t.length;$e++){const it=t[$e];if(it.kind!=="user")continue;let xt="";for(let Mt=$e+1;Mt<t.length;Mt++){const Gt=t[Mt];if(Gt.kind==="user")break;if(Gt.kind==="text"){xt=Gt.text;break}}ge.push({key:it.key,question:it.text||"[image]",answer:xt})}return ge},[t]),De=m.useCallback(()=>{const ge=I.current;ge&&ge.scrollHeight-ge.scrollTop-ge.clientHeight>2&&(W.current=!0,ge.scrollTop=ge.scrollHeight)},[]),Ue=m.useCallback(()=>{cancelAnimationFrame(T.current);const ge=Date.now()+1200;let $e=null;const it=()=>{cancelAnimationFrame(T.current),W.current=!1,$e?.removeEventListener("touchstart",it),$e?.removeEventListener("wheel",it)},xt=()=>{if(J.current){it();return}!$e&&I.current&&($e=I.current,$e.addEventListener("touchstart",it,{passive:!0,once:!0}),$e.addEventListener("wheel",it,{passive:!0,once:!0})),De(),E.current=!0,N(!0),Date.now()<ge?T.current=requestAnimationFrame(xt):it()};xt(),N(!0),E.current=!0},[De]);m.useEffect(()=>()=>{cancelAnimationFrame(T.current),cancelAnimationFrame(A.current),window.clearTimeout(O.current)},[]);const St=()=>{J.current=!0,window.clearTimeout(O.current)},Ut=()=>{window.clearTimeout(O.current),O.current=window.setTimeout(()=>{J.current=!1},400)},tn=()=>{St(),Ut()},Ne=()=>{cancelAnimationFrame(T.current),cancelAnimationFrame(A.current),W.current=!1,E.current=!1,N(!1)},Z=m.useCallback(ge=>{if(D.current?.disconnect(),D.current=null,!ge)return;const $e=new ResizeObserver(()=>{if(!E.current&&!W.current)return;cancelAnimationFrame(A.current);let it=8;const xt=()=>{De();const Mt=I.current;(Mt?Mt.scrollHeight-Mt.scrollTop-Mt.clientHeight:0)<=2||(--it>0?A.current=requestAnimationFrame(xt):Ue())};xt()});$e.observe(ge),D.current=$e,Ue()},[De,Ue]);m.useEffect(()=>()=>D.current?.disconnect(),[]);const je=ge=>F.findIndex($e=>$e.key===ge||$e.kind==="tool-group"&&KN($e,ge)),tt=ge=>{if(!p){I.current?.querySelector(`[data-nav-key="${CSS.escape(ge)}"]`)?.scrollIntoView({block:"center"});return}const $e=je(ge);$e>=0&&_.current?.scrollToIndex({index:R7(_e,$e),align:"center"})},Et=m.useRef(null),zt=ge=>{if(Ne(),je(ge)>=0){Et.current=null,tt(ge);return}let $e=null,it=!1;for(const xt of t)if(xt.kind==="user"&&($e=xt.key),xt.key===ge){it=!0;break}!it||!$e||(Et.current=ge,Ee($e,!1))};m.useLayoutEffect(()=>{const ge=Et.current;!ge||je(ge)<0||(Et.current=null,tt(ge))},[F]),m.useImperativeHandle(e,()=>({scrollToBottom:Ue,pinToBottom:De,isAtBottom:()=>E.current,getScroller:()=>p?null:I.current,scrollToKey:zt}));const we=m.useRef(!1),ft=`${v}:${_e}`,mt=m.useRef(ft);mt.current!==ft&&(mt.current=ft,we.current=!1);const ze=()=>{!f||we.current||(we.current=!0,f())};m.useEffect(()=>{p&&!x&&z.current===_e&&ze()},[v,x]);const Ct=m.useMemo(()=>({query:w,activeKey:y?.key??"",activeNth:y?.nth??-1}),[w,y?.key,y?.nth]),K=(ge,$e)=>{const it=F[$e+1];if(it!==void 0&&qw(ge)&&qw(it))return"pb-0";if(!fe)return"pb-4";const xt=it!==void 0&&Vw(it);return Vw(ge)?xt?"pb-1":"pb-2":ge.kind==="text"&&xt?"pb-1":"pb-4"},be=(ge,$e)=>{const it=F[$e-1],xt=it?.kind==="user"&&!it.collapsed&&L7.has(ge.kind)?it:void 0,Mt=Date.now(),Gt=U.current.collapse.get(ge.key),sn=Gt&&Mt-Gt.at<Xw?Gt:void 0,wn=de.get(ge.key),On=wn&&U.current.reveal.get(wn.group),rn=wn&&On!==void 0&&Mt-On<Xw;return o.jsxs("div",{"data-nav-key":ge.key,"data-fold-collapse":sn?sn.pair?"pair":"toggle":void 0,style:sn?{"--fold-from":`${sn.height}px`}:rn?{"--fold-i":wn.index}:void 0,className:q(fi,K(ge,$e),rn&&"t-fold-reveal","[overflow-wrap:anywhere]"),children:[xt&&o.jsx(QU,{model:xt.replyModel,at:xt.replyAt,privacyMask:xt.replyPrivacyMask}),o.jsx(K7,{itemKey:ge.key,children:o.jsx(e7,{item:ge,onToggleGroup:ne,onToggleTurn:Ee})})]},ge.key)},Re=m.useRef(!1);g===!0&&(Re.current=!0);const Ve=RA(t.length>0,x,g,Re.current,!p&&C);m.useLayoutEffect(()=>{if(p){k(!1);return}const ge=I.current;k(!!ge&&LA(g===!0,x,ge.scrollHeight,ge.clientHeight))},[p,g,x,_e,F.length,t.length]);const Ke=()=>o.jsx(V7,{chrome:Ve,onLoadMore:Ve==="more"?ze:void 0}),nt=()=>o.jsxs("div",{className:q(fi,"pb-6 [overflow-wrap:anywhere]"),children:[n&&o.jsxs("div",{className:"flex min-h-[26px] items-center gap-2 text-[13px]",children:[o.jsx($7,{}),o.jsx("span",{className:"t-shimmer","data-text":b(s?"Loading…":"Working…"),children:b(s?"Loading…":"Working…")}),!s&&(a??r)!==void 0&&o.jsx(U7,{since:a??r})]}),l&&o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("p",{className:"min-w-0 flex-1 text-sm text-destructive whitespace-pre-wrap",children:b(l)}),o.jsx(WN,{}),h&&o.jsx(le,{size:"sm",variant:"outline",onClick:h,children:b("Retry resume")})]})]});return o.jsx(OA.Provider,{value:Ct,children:o.jsxs("div",{"data-enso":"timeline",className:"@container relative min-h-0 flex-1",onWheel:tn,onKeyDown:tn,onTouchStart:St,onTouchEnd:Ut,onPointerDown:ge=>{ge.target===I.current&&(St(),window.addEventListener("pointerup",Ut,{once:!0}))},children:[o.jsx(K6,{items:Be,activeKey:B,onJump:zt}),t.length===0&&!n?o.jsxs(Jw,{className:"flex h-full flex-col items-center justify-center gap-2 overflow-y-auto px-4 text-center",children:[o.jsx("span",{className:"t-stagger-line t-stagger-line--1 mb-3",children:o.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:o.jsx(V6,{className:"size-6"})})}),o.jsx("p",{className:"t-stagger-line t-stagger-line--1 text-[22px] font-semibold tracking-tight",children:c}),l?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"t-stagger-line t-stagger-line--2 max-w-md text-sm text-destructive whitespace-pre-wrap",children:b(l)}),h&&o.jsx(le,{size:"sm",variant:"outline",onClick:h,children:b("Retry resume")})]}):o.jsxs(o.Fragment,{children:[d!==""&&o.jsx("p",{className:"t-stagger-line t-stagger-line--2 text-sm text-muted-foreground",children:d??b("Ask the agent…")}),u&&o.jsx("div",{className:"t-stagger-line t-stagger-line--3 mt-5 w-full",children:o.jsx(z7,{onPick:u})})]})]}):t.length===0&&l?o.jsxs(Jw,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[o.jsx("p",{className:"t-stagger-line t-stagger-line--1 max-w-md text-sm text-destructive whitespace-pre-wrap",children:b(l)}),h&&o.jsx(le,{size:"sm",variant:"outline",onClick:h,children:b("Retry resume")})]}):t.length===0?o.jsxs("div",{"data-timeline-loading":"",className:"flex h-full flex-col items-center justify-center gap-2.5 text-center",children:[o.jsx(Vt,{className:"h-5 w-5 animate-spin text-muted-foreground"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:b("Preparing session…")})]}):p?o.jsx(N6,{ref:_,data:F,defaultItemHeight:80,computeItemKey:(ge,$e)=>$e.key,firstItemIndex:_e,startReached:ze,followOutput:H7,atBottomThreshold:Zw,atBottomStateChange:ge=>{if(!ge&&E.current&&!J.current){Ue();return}N(ge),E.current=ge},increaseViewportBy:F7,initialTopMostItemIndex:G7,rangeChanged:({startIndex:ge})=>{z.current=ge,ge>_e+4&&(we.current=!1),Q(()=>{const $e=Math.max(0,ge-_e);let it=null;for(let xt=0;xt<=Math.min($e+1,F.length-1);xt++)F[xt]?.kind==="user"&&(it=F[xt].key);return it})},scrollerRef:ge=>{I.current=ge instanceof HTMLElement?ge:null},className:"h-full select-text",components:{List:B7,Header:Ke,Footer:nt},itemContent:(ge,$e)=>be($e,ge-_e)},X.current):o.jsx("div",{ref:ge=>{I.current=ge},onScroll:ge=>{const $e=ge.currentTarget;if(W.current){W.current=!1,E.current=!0,N(!0);return}if(!J.current){E.current&&De();return}const it=$e.scrollHeight-$e.scrollTop-$e.clientHeight<=Zw;it!==E.current&&(E.current=it,N(it)),f&&($e.scrollTop<80&&!we.current?(we.current=!0,f()):$e.scrollTop>240&&(we.current=!1))},className:"h-full select-text overflow-y-auto [overflow-anchor:none]",children:o.jsxs("div",{ref:Z,children:[Ke(),F.map((ge,$e)=>be(ge,$e)),nt()]})}),!j&&t.length>0&&o.jsxs("button",{type:"button",onClick:Ue,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:[o.jsx(th,{className:"h-3 w-3"}),b("Scroll to bottom")]})]})})}function KN(e,t){return e.children.some(n=>n.key===t||n.kind==="tool-group"&&KN(n,t))}function V7({chrome:e,onLoadMore:t}){const{t:n}=te();return e==="none"?o.jsx("div",{className:"h-6"}):o.jsx("div",{className:q(fi,"flex items-center justify-center gap-2 py-3"),children:e==="loading"?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}),o.jsx("p",{className:"text-xs text-muted-foreground",children:n("Loading earlier messages…")})]}):e==="more"?o.jsx("button",{type:"button",className:"text-xs text-muted-foreground underline-offset-2 hover:underline",onClick:t,children:n("Load earlier messages")}):o.jsx("p",{className:"text-xs text-muted-foreground",children:n("Beginning of conversation")})})}function $7(){return o.jsxs("span",{className:"relative flex size-[22px] shrink-0 items-center justify-center",children:[o.jsx("span",{className:"absolute size-2 animate-ping rounded-full bg-brand/50"}),o.jsx("span",{className:"relative size-2 rounded-full bg-brand"})]})}const W7=e=>{const t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},U7=m.memo(function({since:t}){const[,n]=m.useState(0);return m.useEffect(()=>{const s=setInterval(()=>n(i=>i+1),1e3);return()=>clearInterval(s)},[]),o.jsx("span",{className:"font-mono text-[11px] text-muted-foreground tabular-nums",children:W7(Date.now()-t)})});class K7 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?o.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 Yr={type:"spring",stiffness:400,damping:30},mu={type:"tween",duration:.22,ease:[.2,0,0,1]},gp={initial:{height:0,opacity:0},animate:{height:"auto",opacity:1,transition:mu},exit:{height:0,opacity:0,transition:mu}};function q7(e){return e.resizing?!0:e.previousConversationId!==void 0&&e.conversationId!==void 0&&e.previousConversationId!==e.conversationId}function qN(e){return e.skip?{duration:0}:e.cover||e.targetW===0?mu:Yr}const YN=e=>{const t=window.electronAPI.speech,n=crypto.randomUUID(),s=t.onPartial(r=>{r.sessionId===n&&e(r.text,r.correcting===!0)});let i=!1;return{push:r=>{i||t.pushAudio(n,r)},finish:()=>(i=!0,t.finishSession(n).finally(s)),cancel:()=>{i||(i=!0,s(),t.cancelSession(n))}}},Y7={ts:ja,tsx:ja,js:ja,jsx:ja,mjs:ja,json:Bm,html:qH,css:Sv,scss:Sv,md:go,sh:Jp,bash:Jp,yml:ai,yaml:ai,toml:ai},X7={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 gc(e,t,n=!1){if(t)return n?Qs:uc;const s=e.split(".").pop()?.toLowerCase()??"";return Y7[s]??pB}function xc(e,t){if(t)return"text-amber-500";const n=e.split(".").pop()?.toLowerCase()??"";return X7[n]??"text-muted-foreground"}const J7={artifacts:[],media:[]},xp=new Map,vp=new Map,Z7=new Set(["image","markdown","html","text"]),Q7=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`;function e9(e){const t=JSON.stringify(e),[n,s]=m.useState(()=>xp.get(t)??J7);return m.useEffect(()=>{if(xp.has(t))return;let i=!0;return window.electronAPI.bots.artifacts.list(JSON.parse(t)).then(r=>{if(!i||!r.ok)return;const a={artifacts:r.artifacts,media:r.media??[]};(a.artifacts.length>0||a.media.length>0)&&xp.set(t,a),s(a)}).catch(()=>{}),()=>{i=!1}},[t]),n}function t9(e){const{t}=te();return(n,s)=>{window.electronAPI.bots.artifacts.open({...e,rel:n.rel,action:s}).then(i=>{i.ok||We({type:"error",title:i.error==="not-openable"?t("This file type is only shown in Finder"):t("Could not open the file")})})}}function gu({target:e}){const{artifacts:t,media:n}=e9(e);return o.jsxs(o.Fragment,{children:[n.length>0&&o.jsx(s9,{target:e,media:n}),t.length>0&&o.jsx(r9,{target:e,artifacts:t})]})}function n9(){const{t:e}=te();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 XN(e,t,n){const s=JSON.stringify(e),i=t&&n==="thumb"?vp.get(t):void 0,[r,a]=m.useState(i?{ok:!0,kind:"image",dataUrl:i}:null);return m.useEffect(()=>{const l=t&&n==="thumb"?vp.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"&&vp.set(t,d.dataUrl),c&&a(d)}).catch(()=>c&&a({ok:!1,error:"unavailable"})),()=>{c=!1}},[s,t,n]),r}function s9({target:e,media:t}){const{t:n}=te(),s=n9(),[i,r]=m.useState(null),a=t.some(l=>l.ok&&l.source==="desktop");return o.jsxs("div",{className:"mt-2","data-bot-media":"",children:[o.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map((l,c)=>l.ok?o.jsx(i9,{target:e,item:l,label:s(l),onOpen:()=>r(l)},l.mediaId):o.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:[o.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[o.jsx(h1,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"truncate",children:l.name??s(l)})]}),o.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&&o.jsx("p",{className:"mt-1 text-warning text-xs",children:n("Desktop screenshots may capture sensitive content from other windows.")}),o.jsx(o9,{target:e,item:i,label:i?s(i):"",onClose:()=>r(null)})]})}function i9({target:e,item:t,label:n,onOpen:s}){const i=XN(e,t.mediaId,"thumb"),r=t.caption??t.name??n;return o.jsxs("button",{type:"button",title:r,onClick:s,className:"relative h-24 w-36 overflow-hidden rounded-lg border bg-muted",children:[i?.ok&&i.kind==="image"?o.jsx("img",{src:i.dataUrl,alt:r,className:"h-full w-full object-cover"}):i?o.jsx(h1,{className:"m-auto h-4 w-4 text-muted-foreground"}):o.jsx(Vt,{className:"m-auto h-4 w-4 animate-spin text-muted-foreground"}),n&&o.jsx("span",{className:q("absolute top-1 left-1 rounded px-1 text-[10px] leading-4",t.source==="desktop"?"bg-warning text-warning-foreground":"bg-black/60 text-white"),children:n}),(t.caption||t.name)&&o.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 o9({target:e,item:t,label:n,onClose:s}){const{t:i}=te(),r=XN(e,t?.mediaId??null,"full"),a=t?.caption??t?.name??n;return o.jsx(gn,{open:t!==null,onOpenChange:l=>!l&&s(),children:o.jsxs(xn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[o.jsx(vn,{children:o.jsxs(bn,{className:"flex min-w-0 items-center gap-2 pr-8",children:[o.jsx("span",{className:"truncate",children:a}),o.jsx("span",{className:"shrink-0 font-normal text-muted-foreground text-xs",children:n})]})}),t?.source==="desktop"&&o.jsx("p",{className:"text-warning text-xs",children:i("Desktop screenshots may capture sensitive content from other windows.")}),t?.source==="file"&&o.jsx("p",{className:"text-muted-foreground text-xs",children:i("Copied into this chat: later edits or deletion of the original do not change it. Deleted together with the chat.")}),o.jsx(JN,{name:a,content:r})]})})}function r9({target:e,artifacts:t}){const{t:n}=te(),s=t9(e),[i,r]=m.useState(null);return o.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5","data-bot-artifacts":"",children:[t.map(a=>{const l=gc(a.name,!1),c=Z7.has(a.kind)||a.kind==="pdf";return o.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:[o.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:[o.jsx(l,{className:q("h-3.5 w-3.5 shrink-0",xc(a.name,!1))}),o.jsx("span",{className:"truncate",children:a.name}),o.jsx("span",{className:"shrink-0 text-muted-foreground",children:Q7(a.size)})]}),o.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:o.jsx(Qs,{className:"h-3.5 w-3.5"})}),o.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:o.jsx(YC,{className:"h-3.5 w-3.5"})})]},a.rel)}),o.jsx(a9,{target:e,artifact:i,onOpen:s,onClose:()=>r(null)})]})}function a9({target:e,artifact:t,onOpen:n,onClose:s}){const{t:i}=te(),[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]),o.jsx(gn,{open:t!==null,onOpenChange:d=>!d&&s(),children:o.jsxs(xn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[o.jsx(vn,{children:o.jsxs(bn,{className:"flex min-w-0 items-center gap-2 pr-8",children:[o.jsx("span",{className:"truncate",children:t?.name}),o.jsx("span",{className:"truncate font-normal text-muted-foreground text-xs",children:t?.rel}),o.jsx("span",{className:"flex-1"}),t&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",title:i("Show in Finder"),onClick:()=>n(t,"reveal"),className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:o.jsx(Qs,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",title:i("Open with default app"),onClick:()=>n(t,"open"),className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:o.jsx(YC,{className:"h-4 w-4"})})]})]})}),o.jsx(JN,{name:t?.name??"",content:r})]})})}function JN({name:e,content:t}){const{t:n}=te();return o.jsxs("div",{className:"min-h-0 flex-1 select-text overflow-auto border-t","data-bot-artifact-preview":"",children:[!t&&o.jsx("div",{className:"flex justify-center p-6 text-muted-foreground",children:o.jsx(Vt,{className:"h-4 w-4 animate-spin"})}),t&&!t.ok&&o.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"&&o.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"&&o.jsx("div",{className:"px-6 py-4 text-sm",children:o.jsx(Ds,{text:t.text})}),t?.ok&&t.kind==="html"&&o.jsx("iframe",{title:e,sandbox:"",srcDoc:t.text,className:"h-full w-full bg-white"}),t?.ok&&t.kind==="text"&&o.jsx("div",{className:"p-2 text-xs",children:o.jsx(Id,{path:e,contents:t.text})})]})}const l9=(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,Qw=(e,t)=>t.some(n=>l9(e,n)),c9=new Set(["dialog-popup","dialog-viewport","dialog-backdrop","alert-dialog-popup","alert-dialog-viewport","alert-dialog-backdrop"]);function d9(e){if(e.getAttribute("data-enso-float")!==null)return!0;const t=e.getAttribute("data-slot");return t?c9.has(t)||t.endsWith("-popup")||t.endsWith("-positioner"):!1}function ey(e,t){const n=[];for(const s of Array.from(e.querySelectorAll("*"))){if(!d9(s))continue;const i=s.getBoundingClientRect();i.width>0&&i.height>0&&n.push({x:i.left,y:i.top,width:i.width,height:i.height})}return n}const u9={tabId:null,url:"",title:"",favicon:null,loading:!1,canGoBack:!1,canGoForward:!1,locked:!1,devtoolsOpen:!1,designMode:!1,holder:null},bp=(e,t)=>e===t||e!==null&&t!==null&&e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height&&e.radius===t.radius,ty=80,h9=.42;function ny(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=p9(e,t.bottom);return s>0?{...n,radius:s}:n}function p9(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 f9(){const{t:e}=te();return o.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-muted-foreground text-sm",children:[o.jsx(uo,{className:"h-6 w-6"}),o.jsx("p",{children:e("The built-in browser is not available in full view. Check it on the computer.")})]})}function ZN(e){return window.electronAPI.remote?o.jsx(f9,{}):o.jsx(m9,{...e})}function m9({conversationId:e,panelApi:t,active:n}){const{t:s}=te(),i=ie(L=>zA(L.conversations,e)),r=pn(L=>L.uiByConversation[i]?.open??!1),a=ie(L=>L.activeId===i),l=n??(r&&a),[c,d]=m.useState(u9),[u,h]=m.useState(""),[p,f]=m.useState(!1),[x,g]=m.useState(null),[v,w]=m.useState(h9),y=m.useRef(null),b=m.useRef(null),_=m.useRef(null),j=m.useRef(void 0),N=m.useRef(!1),C=m.useRef(void 0),k=m.useRef(!1),E=m.useRef(!1);E.current=c.locked;const I=m.useRef(!1);I.current=c.devtoolsOpen;const T=(c.url.startsWith("http")||c.url.startsWith("file:"))&&!c.loading,A=m.useRef(!1);A.current=T;const D=m.useRef(null),W=t.id;m.useEffect(()=>window.electronAPI.browser.onState(L=>{L.tabId===W&&d(L.state)}),[W]),m.useEffect(()=>window.electronAPI.browser.onDesignMode(L=>{if(L.tabId!==W||L.type==="cancelled")return;let se=!1;if(L.type==="annotated")se=L.image?vU(L.image):!1;else{const Q=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ui-${Date.now()}`;se=gU({kind:"ui-element",id:Q,label:L.payload.label||L.payload.tag||"element",path:L.payload.path||L.payload.tag||"element",text:L.payload.text||L.payload.label||L.payload.tag||"element",imageId:`img-${Q}`},L.image)}se?wr():We({type:"warning",title:s("No Composer for this selection")})}),[W,s]),m.useEffect(()=>{if(!c.designMode)return;const L=se=>{se.key==="Escape"&&(se.preventDefault(),window.electronAPI.browser.setDesignMode(W,!1).then(d))};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[c.designMode,W]),m.useEffect(()=>{p||h(c.url)},[c.url,p]),m.useEffect(()=>{const L=c.title.trim()||s("Browser");t.setTitle(L),t.updateParameters({...t.getParameters(),favicon:c.favicon})},[t,c.title,c.favicon,s]),m.useEffect(()=>{let L=0,se=!1;document.getElementById("root"),XC();const Q=()=>{if(se)return;const V=l&&t.isActive&&t.isVisible&&document.visibilityState==="visible",H=V?ny(y.current):null,ne=H!==null&&(E.current||Qw(H,ey(document)));(j.current===void 0||!bp(j.current,H)||ne!==N.current)&&(j.current=H,N.current=ne,window.electronAPI.browser.setViewport(W,e,H,ne).then(d));const he=A.current?H:null;bp(D.current,he)||(D.current=he,pn.getState().setBrowserHole(`${W}:guest`,he));const pe=V&&I.current?ny(b.current):null,ke=pe!==null&&Qw(pe,ey(document));(C.current===void 0||!bp(C.current,pe)||ke!==k.current)&&(pn.getState().setBrowserHole(`${W}:devtools`,pe),C.current=pe,k.current=ke,window.electronAPI.browser.setDevToolsViewport(W,e,pe,ke).then(d)),L=requestAnimationFrame(Q)};return L=requestAnimationFrame(Q),()=>{se=!0,cancelAnimationFrame(L);const{setBrowserHole:V}=pn.getState();V(`${W}:guest`,null),V(`${W}:devtools`,null),D.current=null,j.current!==null&&(j.current=null,window.electronAPI.browser.setViewport(W,e,null)),C.current!==null&&(C.current=null,window.electronAPI.browser.setDevToolsViewport(W,e,null))}},[e,W,t,l]);const J=async()=>{f(!1);const L=u.trim();if(!L)return;const se=await window.electronAPI.browser.navigate(W,e,L);g(se.ok?null:se.error??s("Navigation failed"))},O=L=>{const se=y.current,Q=b.current;if(!se||!Q)return;L.currentTarget.setPointerCapture(L.pointerId);const V=L.clientY,H=se.getBoundingClientRect().height,ne=Q.getBoundingClientRect().height,he=H+ne,pe=Me=>{const fe=Math.min(he-ty,Math.max(ty,ne-(Me.clientY-V)));w(fe/he)},ke=()=>{window.removeEventListener("pointermove",pe),window.removeEventListener("pointerup",ke)};window.addEventListener("pointermove",pe),window.addEventListener("pointerup",ke)},B="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 o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b bg-background px-2",children:[o.jsx("button",{type:"button",className:B,disabled:c.locked||!c.canGoBack,onClick:()=>{window.electronAPI.browser.goBack(W)},"aria-label":s("Back"),children:o.jsx(Au,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",className:B,disabled:c.locked||!c.canGoForward,onClick:()=>{window.electronAPI.browser.goForward(W)},"aria-label":s("Forward"),children:o.jsx(GA,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",className:B,disabled:c.locked||!c.tabId,onClick:()=>{window.electronAPI.browser.reload(W)},"aria-label":s("Reload"),children:o.jsx(CC,{className:q("h-3.5 w-3.5",c.loading&&"animate-spin")})}),o.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-md border bg-background px-2 py-0.5 text-xs focus-within:border-ring",onSubmit:L=>{L.preventDefault(),J()},children:[o.jsx(uo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),o.jsx("input",{value:u,onChange:L=>h(L.target.value),onFocus:L=>{f(!0),L.target.select()},onBlur:()=>f(!1),placeholder:s("Enter a URL"),spellCheck:!1,disabled:c.locked,className:"min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground disabled:opacity-60"})]}),o.jsx("button",{type:"button",className:q(B,c.designMode&&"bg-muted text-foreground"),disabled:!c.tabId||c.locked||c.devtoolsOpen,onClick:()=>{window.electronAPI.browser.setDesignMode(W,!c.designMode).then(d)},"aria-label":s("Toggle Design Mode"),"aria-pressed":c.designMode,children:o.jsx(m1,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",className:q(B,c.devtoolsOpen&&"bg-muted text-foreground"),disabled:!c.tabId,onClick:()=>{window.electronAPI.browser.setDevTools(W,!c.devtoolsOpen).then(d)},"aria-label":s("Toggle Developer Tools"),"aria-pressed":c.devtoolsOpen,children:o.jsx(a1,{className:"h-3.5 w-3.5"})}),c.locked&&o.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:[o.jsx(wb,{className:"h-3 w-3"}),s("Enso is in control")]})]}),x&&o.jsx("div",{className:"border-b bg-destructive/10 px-3 py-1 text-xs text-destructive",children:x}),o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col","data-slot":"browser-native-stack",children:[o.jsxs("div",{ref:y,className:q("relative min-h-0",c.devtoolsOpen?"shrink-0":"flex-1",T?"bg-transparent":"bg-background"),style:c.devtoolsOpen?{flex:`${1-v} 1 0`}:void 0,children:[!c.url.startsWith("http")&&o.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-center text-sm text-muted-foreground",children:[o.jsx(uo,{className:"h-6 w-6 opacity-40"}),o.jsx("p",{children:s("Enter a URL above, or let the agent open a page with browser_navigate.")})]}),c.locked&&o.jsxs("div",{className:"group absolute inset-0 z-10 flex cursor-default items-center justify-center",children:[o.jsx("div",{className:"absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/40"}),o.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:[o.jsx(wb,{className:"h-3.5 w-3.5"}),s("Take control")]})]})]}),c.devtoolsOpen&&o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:_,className:"h-1.5 shrink-0 cursor-row-resize bg-border hover:bg-ring",onPointerDown:O}),o.jsx("div",{ref:b,className:"min-h-0 bg-transparent",style:{flex:`${v} 1 0`}})]})]})]})}function g9({chatId:e,visible:t}){const{t:n}=te(),s=re(p=>p.browserTabs[e]),i=re(p=>p.browserTitles),r=re(p=>p.browserHolders),{openBrowserTab:a,selectBrowserTab:l,closeBrowserTab:c,setBrowserTitle:d}=re.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 o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[o.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],x=i[p]||n("Browser");return o.jsxs("div",{className:q("flex h-6 min-w-0 max-w-44 shrink items-center rounded-md text-xs",p===u?"bg-brand/10 text-foreground dark:bg-brand/15":"text-muted-foreground hover:bg-muted/60 hover:text-foreground"),children:[o.jsxs("button",{type:"button",title:f?`${x}
73
- ${n("{{name}} is using this tab",{name:f.name})}`:x,onClick:()=>l(e,p),className:"flex h-full min-w-0 items-center gap-1.5 pl-2",children:[o.jsx(uo,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:x}),f&&o.jsxs("span",{className:"max-w-16 shrink-0 truncate text-muted-foreground",children:["· ",f.name]})]}),o.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:o.jsx(ln,{className:"h-3 w-3"})})]},p)}),o.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:o.jsx(ps,{className:"h-3.5 w-3.5"})})]}),h&&o.jsx(ZN,{conversationId:FA(e),panelApi:h,active:t},h.id)]})}const x9=[[0,59],[0,23],[1,31],[1,12],[0,7]],Xo=6e4,v9=60*Xo,b9=5e4;function wp(e,t,n){if(!/^\d+$/u.test(e))return;const s=Number(e);return s>=t&&s<=n?s:void 0}function w9(e,t,n){const s=new Set;for(const i of e.split(",")){const[r,a,l]=i.split("/");if(l!==void 0)return;const c=a===void 0?1:wp(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=wp(h,t,n),u=p===void 0?a===void 0?d:n:wp(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((i,r)=>i-r)}function fh(e){const t=e.trim().split(/\s+/u);if(t.length!==5)return;const n=t.map((c,d)=>w9(c,...x9[d]));if(n.some(c=>c===void 0))return;const[s,i,r,a,l]=n;return{source:t.join(" "),minute:s,hour:i,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 y9(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 S9(e,t){let n=Math.floor(t/Xo)*Xo+Xo;for(let s=0;s<b9;s+=1){const i=new Date(n);let r;if(!e.month.includes(i.getMonth()+1))r=new Date(i.getFullYear(),i.getMonth()+1,1).getTime();else if(!y9(e,i))r=new Date(i.getFullYear(),i.getMonth(),i.getDate()+1).getTime();else if(!e.hour.includes(i.getHours()))r=n-i.getMinutes()*Xo+v9;else if(!e.minute.includes(i.getMinutes()))r=n+Xo;else return n;n=Math.max(r,n+Xo)}}const yp=e=>String(e).padStart(2,"0"),C9=["日","一","二","三","四","五","六"],k9=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Sx(e,t){const n=typeof e=="string"?fh(e):e;if(!n)return String(e);const[s,i,r,a,l]=n.source.split(" "),c=t==="zh";if(a!=="*")return n.source;const d=/^\*\/(\d+)$/u.exec(s);if(i==="*"&&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=yp(n.minute[0]);return c?`每小时 ${h} 分`:`Every hour at :${h}`}return n.source}if(!/^\d+$/u.test(s)||!/^\d+$/u.test(i))return n.source;const u=`${yp(n.hour[0])}:${yp(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=>C9[p]).join("、")} ${u}`:`Every ${h.map(p=>k9[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 _9=/[A-Za-z0-9._%+-]/,sy=/[A-Za-z0-9_-]/,j9=/```[\s\S]*?(?:```|$)|`[^`\n]*`/g;function QN(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 N9(e,t){if(typeof e!="string")return{ids:[],all:!1};const n=e.normalize("NFC").replace(j9,a=>" ".repeat(a.length)),s=[...t.map(a=>({key:Ld(a.name),id:a.id})),...JC.map(a=>({key:Ld(a),id:null}))].sort((a,l)=>l.key.length-a.key.length),i=[];let r=!1;for(let a=n.indexOf("@");a!==-1;a=n.indexOf("@",a+1)){if(a>0&&_9.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&&sy.test(c.at(-1)??"")&&sy.test(u))});l&&(l.id===null?r=!0:i.includes(l.id)||i.push(l.id))}return{ids:i,all:r}}function T9(e,t){const n=QN(t),{ids:s,all:i}=N9(e,n);return i?{ids:[...new Set(n.map(r=>r.id))],all:i}:{ids:s,all:i}}function I9(e,t){const n=Ld(typeof e=="string"?e.replace(/^@/,""):"");return QN(t).filter(s=>Ld(s.name).startsWith(n))}function im(e,t){return/(?:^|\s)\$([^\s$]*)$/.exec(e.slice(0,t))?.[1]??null}function eT(e){const t=new Set,n=[];for(const s of e){const i=s.name.trim().toLowerCase();!i||t.has(i)||(t.add(i),n.push(s))}return n}function D9(e,t,n){const s=n??t;if(s===null)return[];const i=s.toLowerCase();return eT(e.filter(r=>n!==null?r.name.startsWith("/skill:")&&r.name.slice(7).toLowerCase().includes(i):r.name.toLowerCase().includes(i))).slice(0,10)}const P9=500,E9=72,gl=28;function tT({phase:e,heldMs:t,cancelZone:n}){return e!=="recording"&&e!=="starting"?"none":n?"cancel":e==="starting"||t<P9?"too-short":"finish"}function iy(e,t){return e-t>=E9}function mh(e,t){const n=[...e,t].slice(-gl);return n.length<gl?[...new Array(gl-n.length).fill(0),...n]:n}const A9=300,M9=12,R9=-50,L9=3;function nT(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 O9(){let e=Number.POSITIVE_INFINITY;return t=>{const n=t.length/Od*1e3,s=nT(t);return e=Math.min(s,e+L9*n/1e3),s>Math.max(e+M9,R9)}}function z9(e){if(e===Od)return r=>r;const t=e/Od;let n=new Float32Array(0),s=0,i=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(i*t),h=Math.floor((i+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),i++}const d=Math.floor(i*t);return n=a.slice(d-s),s=d,Float32Array.from(c)}}function G9(e){return Math.min(1,Math.max(0,(nT(e)+55)/45))}const F9=2e3;function H9(e=F9){const t=O9();let n=0,s=0;return i=>{const r=i.length/Od*1e3;return t(i)?(n+=r,s=0):s+=r,n>=A9&&s>=e}}class sT extends Error{}let oi=null;function om(){return(!oi||oi.state==="closed")&&(oi=new AudioContext),oi.state!=="running"&&oi.resume().catch(()=>{}),oi}async function B9(){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 oy(){const e=oi;oi=null,e?.close().catch(()=>{})}const Sp={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};async function V9(e){const t=navigator.mediaDevices;if(!e||e===HA)return t.getUserMedia({audio:Sp});try{return await t.getUserMedia({audio:{...Sp,deviceId:{exact:e}}})}catch(n){const s=n instanceof Error?n.name:"";if(s==="NotAllowedError"||s==="SecurityError")throw n;return t.getUserMedia({audio:Sp})}}const $9=5e3;async function W9(e,t={}){const n=!t.context,s=t.context??new AudioContext,i=t.context!=null&&t.context===oi,r=s.resume(),a=()=>{!n&&!i||(oi===s&&(oi=null),s.close().catch(()=>{}))};let l;try{l=await V9(t.deviceId),await Promise.race([r,new Promise((b,_)=>setTimeout(()=>_(new Error("audio context stayed suspended")),3e3))])}catch(b){for(const _ of l?.getTracks()??[])_.stop();throw a(),b}const c=l.getTracks();if(s.state==="closed"){for(const b of c)b.stop();throw new Error("audio context closed")}const d=s.createMediaStreamSource(l),u=s.createScriptProcessor(4096,1,1),h=z9(s.sampleRate);let p=0,f=()=>{};const x=new Promise(b=>{f=b}),g=setTimeout(f,$9),v=()=>{clearTimeout(g),f()};u.onaudioprocess=b=>{const _=b.inputBuffer.getChannelData(0);for(let N=0;N<_.length;N++)p=Math.max(p,Math.abs(_[N]));p>0&&v(),t.onLevel?.(G9(_));const j=h(new Float32Array(_));j.length>0&&e(j)},d.connect(u),u.connect(s.destination);let w=!1;const y=()=>{if(!w){w=!0,v(),u.onaudioprocess=null,u.disconnect(),d.disconnect();for(const b of c)b.stop();a()}};return{live:x,cancel:y,stop:async()=>{if(y(),p===0)throw new sT("silent recording")}}}const iT="Microphone access denied. Allow it in system settings.",U9={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 oT(e){const t=e?.name;return t==="NotFoundError"||t==="OverconstrainedError"?"No microphone found.":t==="NotAllowedError"||t==="SecurityError"?iT:"Voice input failed."}function rT({startSession:e,requestMicAccess:t,onText:n}){const{t:s}=te(),[i,r]=m.useState("idle"),[a,l]=m.useState(0),[c,d]=m.useState(null),[u,h]=m.useState(""),[p,f]=m.useState(!1),x=m.useRef(null),g=m.useRef(null),v=m.useRef(async()=>{}),w=m.useRef(0);m.useEffect(()=>()=>{w.current++,x.current?.cancel(),g.current?.cancel()},[]),m.useEffect(()=>{if(!c)return;const j=setTimeout(()=>d(null),4e3);return()=>clearTimeout(j)},[c]);const y=m.useCallback(()=>{w.current++,x.current?.cancel(),g.current?.cancel(),x.current=null,g.current=null,h(""),f(!1),r("idle")},[]),b=m.useCallback(async()=>{const j=x.current,N=g.current;if(!(!j||!N)){x.current=null,r("transcribing");try{await j.stop();const C=await N.finish();C.ok?C.text?n(C.text):d(s("No speech detected.")):d(s(U9[C.error]))}catch(C){N.cancel(),d(s(C instanceof sT?iT:"Voice input failed."))}finally{g.current=null,h(""),f(!1),r("idle")}}},[n,s]);return v.current=b,m.useEffect(()=>{if(i!=="recording")return;const j=setInterval(()=>l(N=>N+1),1e3);return()=>clearInterval(j)},[i]),m.useEffect(()=>{i==="recording"&&a>=BA&&b()},[a,b,i]),{phase:i,elapsed:a,error:c,setError:d,partial:u,correcting:p,start:async({autoStop:j=!1,...N}={})=>{if(d(null),!navigator.mediaDevices?.getUserMedia){d(s("Voice input needs a secure (HTTPS) connection."));return}const C=++w.current;h(""),f(!1),l(0),r("starting");let k=null;try{if(t&&!await t())throw new DOMException("microphone denied","NotAllowedError");if(C!==w.current)return;const E=e((A,D)=>{g.current===E&&(h(A),f(D))});k=E,g.current=E;const I=j?H9():null,T=await W9(A=>{E.push(A),I?.(A)&&g.current===E&&v.current()},N);if(C!==w.current){T.cancel();return}if(x.current=T,await T.live,C!==w.current)return;r("recording")}catch(E){if(C!==w.current)return;k?.cancel(),g.current=null,r("idle"),d(s(oT(E)))}},finish:b,cancel:y}}const K9=6,ry=8,q9=448;function Y9(e,t){const n=Math.min(q9,t.width*.8);return{left:Math.max(ry,Math.min(e.left,t.width-ry-n)),bottom:t.height-e.top+K9,maxWidth:n}}const ay=120,aT=12,X9=Array.from({length:aT},(e,t)=>`bar-${t}`),ly=mh([],0),J9=300;function cy(e){const t=e.getBoundingClientRect();return Y9(t,{width:window.innerWidth,height:window.innerHeight})}function lT({anchor:e,status:t,children:n}){const[s,i]=m.useState(()=>cy(e));return m.useLayoutEffect(()=>{let r=0;const a=()=>{const l=cy(e);i(c=>c.left===l.left&&c.bottom===l.bottom&&c.maxWidth===l.maxWidth?c:l),r=requestAnimationFrame(a)};return a(),()=>cancelAnimationFrame(r)},[e]),Fs.createPortal(o.jsx("p",{role:t?"status":void 0,"aria-live":"polite","data-testid":t?void 0:"voice-partial",style:{position:"fixed",...s,zIndex:yn.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 rm="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 cT({startSession:e,requestMicAccess:t,disabled:n,holdBinding:s,holdScope:i,onText:r}){const{t:a}=te(),{phase:l,elapsed:c,error:d,setError:u,partial:h,correcting:p,start:f,finish:x,cancel:g}=rT({startSession:e,requestMicAccess:t,onText:r}),v=m.useRef(null),[w,y]=m.useState(ly),b=xe(k=>k.voiceInputDevice),_=(k=!1)=>(y(ly),f({autoStop:k,deviceId:b,onLevel:E=>y(I=>mh(I,E))})),j=m.useRef({phase:l,start:_,finish:x,cancel:g});j.current={phase:l,start:_,finish:x,cancel:g},m.useEffect(()=>{if(!s||n)return;let k=null,E;const I=()=>{clearTimeout(E),E=void 0},T=()=>{E!==void 0&&(I(),s==="space"&&document.execCommand("insertText",!1," "))},A=()=>{if(I(),k===null)return;const J=j.current,O=tT({phase:J.phase,heldMs:performance.now()-k,cancelZone:!1});k=null,O==="finish"?J.finish():O!=="none"&&J.cancel(),O==="too-short"&&u(a("Speech was too short."))},D=J=>{if(J.isComposing||J.keyCode===229)return;if(Cl(J,{allowBare:!0})!==s){T();return}const O=i.current;if(!O||!(J.target instanceof Node)||!O.contains(J.target))return;const B=k===null&&E===void 0;B&&(J.repeat||j.current.phase!=="idle")||(J.preventDefault(),k!==null&&J.stopPropagation(),B&&(E=setTimeout(()=>{E=void 0,k=performance.now(),j.current.start()},J9)))},W=J=>{k===null&&!E||!VA(s,J)||(J.preventDefault(),T(),A())};return window.addEventListener("keydown",D,!0),window.addEventListener("keyup",W,!0),window.addEventListener("blur",A),()=>{window.removeEventListener("keydown",D,!0),window.removeEventListener("keyup",W,!0),window.removeEventListener("blur",A),I(),k!==null&&j.current.cancel()}},[n,s,i,u,a]),m.useEffect(()=>{if(l!=="recording")return;const k=E=>{E.key==="Escape"&&(E.preventDefault(),E.stopPropagation(),g())};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[g,l]);const N=h.length>ay?`…${h.slice(-ay)}`:h,C=l==="transcribing"?a(p?"Correcting…":"Transcribing…"):null;return o.jsxs("div",{ref:v,className:"relative flex shrink-0 items-center",children:[l==="recording"?o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",onClick:()=>{x()},"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:[o.jsx("span",{"aria-hidden":!0,className:"flex h-3.5 items-center gap-[2px]",children:X9.map((k,E)=>o.jsx("span",{className:"w-[2px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:3+w[gl-aT+E]*11}},k))}),o.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(c/60),":",String(c%60).padStart(2,"0")]}),o.jsx(Mu,{className:"h-3 w-3 fill-current"})]}),o.jsx("button",{type:"button",onClick:g,"aria-label":a("Cancel recording"),title:`${a("Cancel recording")} (Esc)`,className:rm,children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]}):o.jsx("button",{type:"button",disabled:n||l!=="idle",onClick:()=>{_(!0)},"aria-label":C??a("Voice input"),title:C??(s?`${a("Voice input")} · ${a("Hold {{key}} to talk",{key:Mi(s)})}`:a("Voice input")),className:rm,children:l==="idle"?o.jsx(ZC,{className:"h-3.5 w-3.5"}):o.jsx(ar,{className:"h-3.5 w-3.5"})}),v.current&&(d||h)?o.jsx(lT,{anchor:v.current,status:!!d,children:d??(p?o.jsxs("span",{className:"flex items-start gap-1.5",children:[o.jsx(ar,{"aria-hidden":!0,className:"mt-0.5 size-3 shrink-0"}),o.jsxs("span",{children:[o.jsxs("span",{className:"text-muted-foreground",children:[a("Correcting…")," "]}),N]})]}):N)}):null]})}const dT=["agents","members","chats"];function Z9(e){return[...dT.flatMap(t=>e[t].map(n=>({candidate:n,group:t}))),...e.files.map(t=>({candidate:t,group:"files"}))]}function uT(e,t){const n=dT.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"}))]:Z9(e).map(s=>({type:"item",candidate:s.candidate,group:s.group}))}const Q9=20;function eK(e,t,n){return e.filter(s=>s.id!==n&&!s.parentId&&!!s.sessionFile).sort((s,i)=>{const r=s.projectId===t?0:1,a=i.projectId===t?0:1;return r!==a?r-a:i.createdAt-s.createdAt}).slice(0,Q9).map(s=>({kind:"chat",id:s.id,label:s.title.split(`
74
- `)[0].trim()||"Untitled chat",sessionFile:s.sessionFile}))}function tK(e){return e.map(t=>({...t,kind:"agent-type",id:t.typeKey,label:t.displayName}))}function nK(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 sK(e,t,n,s=[]){const i=e.trim().toLocaleLowerCase(),r=i?t.filter(c=>`${c.label}
75
- ${c.description}
76
- ${c.source}
77
- ${c.typeKey}`.toLocaleLowerCase().includes(i)):[...t],a=i?n.filter(c=>`${c.label}
78
- ${c.relativePath}`.toLocaleLowerCase().includes(i)):[...n],l=i?s.filter(c=>c.label.toLocaleLowerCase().includes(i)):[...s];return{agents:r.filter(c=>c.source!=="bot"),members:r.filter(c=>c.source==="bot"),files:a,chats:l}}function hT(e,t,n=[],s={}){const[i,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=QC(p);h||r(f?tK(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(nK(f))}).catch(()=>{h||l([])})},150);return()=>{h=!0,window.clearTimeout(p)}},[e,t,d]),m.useMemo(()=>t===null?{agents:[],members:[],files:[],chats:[]}:sK(t,i,a,n),[i,a,n,t])}const dy={bot:"Mention a member",all:"Mention a member",chat:"Reference a chat",file:"Files",skill:"Skills"},iK=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 oK({chatId:e,placeholder:t,members:n,chatOptions:s=[],skills:i=[],running:r,disabled:a=!1,toolbar:l,hint:c,voice:d,requestMicAccess:u,onSend:h,onStop:p}){const{t:f}=te(),x=m.useRef(null),g=m.useRef(null),v=m.useRef(null),w=m.useRef(!1),[y,b]=m.useState(()=>Cv(localStorage,e)),[_,j]=m.useState([]),[N,C]=m.useState(null),[k,E]=m.useState(0),[I,T]=m.useState(!1),A=xe(Y=>Y.keybindings),{"voice-hold":D,"send-message":W}=Ii(A),{text:J}=y,O=Y=>b(X=>({...X,...Y}));m.useEffect(()=>{g.current?.focus()},[]),m.useEffect(()=>{$A(localStorage,e,y)},[e,y]),m.useEffect(()=>WA(Y=>{Y===e&&b(Cv(localStorage,Y))}),[e]),m.useLayoutEffect(()=>{const Y=g.current;Y&&(Y.style.height="auto",Y.style.height=`${Math.min(Y.scrollHeight,220)}px`)},[J]);const B=m.useCallback(Y=>window.electronAPI.bots.searchFiles({chatId:e,query:Y}).then(X=>X.ok?X.files:[]),[e]),L=hT(void 0,N?.kind==="at"?N.query:null,[],{searchFiles:B,agents:!1}).files,se=(()=>{if(!N)return[];const Y=N.query.toLowerCase();if(N.kind==="skill")return i.filter(z=>z.name.toLowerCase().includes(Y)).slice(0,10).map(z=>({kind:"skill",skill:z}));const X=n?I9(N.query,n).map(z=>({kind:"bot",bot:z})):[];return n&&JC.some(z=>z.startsWith(Y))&&X.push({kind:"all"}),y.chats.length<UA&&X.push(...s.filter(z=>!y.chats.includes(z.id)&&z.title.toLowerCase().includes(Y)).slice(0,6).map(z=>({kind:"chat",chat:z}))),X.push(...L.slice(0,8).map(z=>({kind:"file",path:z.relativePath,name:z.label}))),X})(),Q=(Y,X)=>{const z=i.length?im(Y,X):null;if(z!==null){C({kind:"skill",start:X-z.length-1,query:z}),E(0);return}const ue=/(^|[^A-Za-z0-9._%+-])@([^\s@]*)$/u.exec(Y.slice(0,X));if(!ue)return C(null);C({kind:"at",start:X-ue[2].length-1,query:ue[2]}),E(0)},V=Y=>{if(!N)return;const X=g.current,z=X?.selectionStart??J.length,ue=J.slice(0,N.start),_e=J.slice(z);let Ee="";const Be={};Y.kind==="bot"||Y.kind==="all"?Ee=`@${Y.kind==="all"?f("everyone"):Y.bot.name} `:Y.kind==="file"?(Ee=`@${Y.path} `,Be.files=[...new Set([...y.files,Y.path])]):Y.kind==="chat"?Be.chats=[...y.chats,Y.chat.id]:Be.skill=Y.skill.id,O({...Be,text:ue+Ee+_e}),C(null);const De=ue.length+Ee.length;requestAnimationFrame(()=>{X?.focus(),X?.setSelectionRange(De,De)})},H=Y=>{const X=g.current,z=X?.selectionStart??J.length,ue=X?.selectionEnd??J.length;O({text:J.slice(0,z)+Y+J.slice(ue)}),requestAnimationFrame(()=>{X?.focus(),X?.setSelectionRange(z+Y.length,z+Y.length)})},ne=Y=>{for(const X of Y){if(!X.type.startsWith("image/"))continue;const z=new FileReader;z.onload=()=>{const ue=z.result;j(_e=>[..._e,{data:ue.slice(ue.indexOf(",")+1),mimeType:X.type}])},z.readAsDataURL(X)}},he=Y=>{const X=g.current,z=X?.selectionStart??J.length,ue=X?.selectionEnd??J.length;window.electronAPI.bots.savePastedText({chatId:e,text:Y}).catch(()=>({ok:!1,error:"unavailable"})).then(_e=>{const Ee=_e.ok?`@${_e.path} `:Y;b(Be=>({...Be,text:Be.text.slice(0,z)+Ee+Be.text.slice(ue)})),requestAnimationFrame(()=>{X?.focus(),X?.setSelectionRange(z+Ee.length,z+Ee.length)})})},pe=new Map(s.map(Y=>[Y.id,Y])),ke=y.skill?i.find(Y=>Y.id===y.skill||Y.name===y.skill):void 0,Me=ke&&n?n.filter(Y=>T9(J,n).ids.includes(Y.id)&&!ke.owners.includes(Y.id)):[],fe=!a&&!I&&(J.trim().length>0||_.length>0||y.chats.length>0||!!y.skill),F=async()=>{if(!fe)return;const Y=y,X=_,z=Y.text.trim();b(KA),j([]),C(null),T(!0);try{await h({text:z,images:X,files:Y.files.filter(_e=>z.includes(`@${_e}`)),chats:Y.chats,...Y.skill?{skill:ke?.id??Y.skill}:{}})||(b(_e=>_e.text||_e.chats.length||_e.skill?_e:Y),j(_e=>_e.length?_e:X))}finally{T(!1)}},U=Y=>{const X=Y.nativeEvent.isComposing||w.current;if(N&&se.length>0&&!X){if(Y.key==="ArrowDown"||Y.key==="ArrowUp"){Y.preventDefault();const z=Y.key==="ArrowDown"?1:-1;E(ue=>(ue+z+se.length)%se.length);return}if(Y.key==="Enter"||Y.key==="Tab"){Y.preventDefault(),V(se[Math.min(k,se.length-1)]);return}if(Y.key==="Escape"){Y.preventDefault(),C(null);return}}!X&&tk(Y,W)&&(Y.preventDefault(),F())},de=Y=>(n??[]).filter(X=>Y.includes(X.id)).map(X=>X.name).join(", ");return o.jsxs("div",{ref:x,"data-slot":"composer",className:"relative rounded-2xl border bg-background shadow-float",onDragOver:Y=>Y.preventDefault(),onDrop:Y=>{Y.preventDefault(),ne([...Y.dataTransfer.files])},children:[N&&se.length>0&&o.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:se.map((Y,X)=>{const z=dy[Y.kind],ue=X===0||dy[se[X-1].kind]!==z;return o.jsxs("div",{children:[ue&&o.jsx("div",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:f(z)}),o.jsx("button",{type:"button",onMouseDown:_e=>{_e.preventDefault(),V(Y)},onMouseEnter:()=>E(X),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",X===k&&"bg-muted"),children:o.jsx(rK,{item:Y,ownerNames:de,grouped:!!n})})]},iK(Y))})}),(y.chats.length>0||y.skill)&&o.jsxs("div",{className:"flex flex-wrap gap-1.5 px-3 pt-3",children:[y.skill&&o.jsx(uy,{icon:o.jsx(Ls,{className:"h-3 w-3"}),label:ke?.name??y.skill,tone:"skill",onRemove:()=>O({skill:void 0})}),y.chats.map(Y=>o.jsx(uy,{icon:o.jsx(oa,{className:"h-3 w-3"}),label:pe.get(Y)?.title??f("Unavailable chat"),onRemove:()=>O({chats:y.chats.filter(X=>X!==Y)})},Y))]}),Me.length>0&&o.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(Y=>Y.name).join(", ")})}),_.length>0&&o.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:_.map((Y,X)=>o.jsxs("div",{className:"group relative h-14 w-14 overflow-hidden rounded-lg border",children:[o.jsx("img",{src:`data:${Y.mimeType};base64,${Y.data}`,alt:"",className:"h-full w-full object-cover"}),o.jsx("button",{type:"button","aria-label":f("Remove"),onClick:()=>j(z=>z.filter((ue,_e)=>_e!==X)),className:"absolute top-0.5 right-0.5 hidden rounded-full bg-background/90 p-0.5 group-hover:block",children:o.jsx(ln,{className:"h-3 w-3"})})]},X))}),o.jsx("textarea",{ref:g,value:J,rows:1,disabled:a,placeholder:t,onChange:Y=>{O({text:Y.target.value}),Q(Y.target.value,Y.target.selectionStart)},onSelect:Y=>Q(Y.currentTarget.value,Y.currentTarget.selectionStart),onBlur:()=>C(null),onKeyDown:U,onCompositionStart:()=>{w.current=!0},onCompositionEnd:()=>{w.current=!1},onPaste:Y=>{const X=[...Y.clipboardData.files].filter(z=>z.type.startsWith("image/"));if(X.length===0){const z=Y.clipboardData.getData("text/plain");if(!ek(z))return;Y.preventDefault(),he(z);return}Y.preventDefault(),ne(X)},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"}),o.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 pb-2",children:[o.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:o.jsx(Kg,{className:"h-4 w-4"})}),o.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:Y=>{ne([...Y.target.files??[]]),Y.target.value=""}}),d&&o.jsx(cT,{startSession:d,requestMicAccess:u,disabled:a,holdBinding:D||void 0,holdScope:x,onText:H}),l,o.jsx("div",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",children:c}),r&&p&&!fe?o.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:o.jsx(Mu,{className:"h-3 w-3 fill-current"})}):o.jsx("button",{type:"button",disabled:!fe,onClick:()=>{F()},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:o.jsx(nh,{className:"h-4 w-4"})})]})]})}function rK({item:e,ownerNames:t,grouped:n}){const{t:s}=te();switch(e.kind){case"all":return o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"grid h-6 w-6 place-items-center rounded-full bg-muted text-[11px]",children:"@"}),o.jsx("span",{children:s("everyone")})]});case"bot":return o.jsxs(o.Fragment,{children:[o.jsx(Jt,{bot:e.bot,size:"sm"}),o.jsx("span",{className:"min-w-0 truncate",children:e.bot.name}),o.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:e.bot.title})]});case"chat":return o.jsxs(o.Fragment,{children:[o.jsx(oa,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"min-w-0 truncate",children:e.chat.title}),o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:e.chat.kind==="group"?s("Group chat"):s("Direct chat")})]});case"file":return o.jsxs(o.Fragment,{children:[o.jsx(go,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"shrink-0",children:e.name}),o.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:e.path})]});case"skill":return o.jsxs(o.Fragment,{children:[o.jsx(Ls,{className:"h-4 w-4 shrink-0 text-info"}),o.jsx("span",{className:"shrink-0",children:e.skill.name}),o.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:n?t(e.skill.owners):e.skill.description})]})}}function uy({icon:e,label:t,tone:n,onRemove:s}){const{t:i}=te();return o.jsxs("span",{className:q("inline-flex h-6 max-w-56 items-center gap-1 rounded-md px-1.5 text-xs",n==="skill"?"bg-info/15 text-info":"bg-muted text-foreground"),children:[e,o.jsx("span",{className:"min-w-0 truncate",children:t}),o.jsx("button",{type:"button","aria-label":i("Remove"),onClick:s,className:"rounded opacity-70 hover:opacity-100",children:o.jsx(ln,{className:"h-3 w-3"})})]})}const aK={thinking:"Thinking",typing:"Writing reply",tool:"Calling tools",retrying:"Retrying"},hy={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"},lK={running:"Running",done:"Done",error:"Error",denied:"Denied",timeout:"Timed out · denied"},cK={running:"text-primary",done:"text-success",error:"text-destructive",denied:"text-warning",timeout:"text-warning"},dK=e=>e<1e4?`${(Math.max(0,e)/1e3).toFixed(1)}s`:ho(e);function pT({conversationId:e,leading:t,trailing:n,className:s}){const{t:i}=te(),r=re(p=>e?p.sessions[e]:void 0),a=re(p=>e?p.queue.find(f=>f.conversationId===e):void 0),l=m.useMemo(()=>qA(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"?i(aK[l.state]):i(a?.reason&&Object.hasOwn(hy,a.reason)?hy[a.reason]:"Queued"):null;return o.jsxs("div",{className:q("min-w-0 text-muted-foreground text-xs",s),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[t,h&&o.jsx("span",{className:"truncate",children:h}),c&&l?.startedAt!==void 0&&o.jsx("span",{className:"shrink-0 tabular-nums",children:ho(d-l.startedAt)}),n]}),l&&l.steps.length>0&&o.jsxs("div",{className:"mt-1 flex flex-col gap-0.5",children:[l.more>0&&o.jsxs("span",{children:["+",l.more]}),l.steps.map(p=>{const f=p.durationMs??(p.startedAt!==void 0?d-p.startedAt:void 0);return o.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:"shrink-0 font-medium text-foreground",children:aa(p.name,i)}),p.detail&&o.jsx("span",{className:"truncate font-mono",children:p.detail}),o.jsx("span",{className:q("shrink-0",cK[p.status]),children:i(p.status==="timeout"&&p.name==="ask_user"?"Timed out · no answer":lK[p.status])}),f!==void 0&&o.jsx("span",{className:"shrink-0 tabular-nums",children:dK(f)})]},p.id)})]})]})}const uK=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});function gh({state:e,interrupted:t}){const{t:n}=te(),s=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",i={queued:n("Queued"),running:n("In progress"),completed:n("Completed"),failed:n(t?"Interrupted":"Failed"),canceled:n("Canceled"),blocked:n("Stuck run")};return o.jsx("span",{className:q("rounded px-1.5 text-[11px]",s),children:i[e]??e})}function fT({check:e,className:t}){const{t:n}=te();return o.jsxs("div",{className:q("flex min-w-0 items-center gap-1.5 text-muted-foreground text-xs",t),children:[o.jsx("span",{className:"shrink-0",children:n("Acceptance check")}),o.jsx("code",{className:"min-w-0 truncate rounded bg-muted px-1",title:e.text,children:e.text}),e.passed!==void 0&&o.jsx("span",{className:q("shrink-0 rounded px-1.5 text-[11px]",e.passed?"bg-success/15 text-success":"bg-destructive/15 text-destructive"),children:e.passed?n("Passed"):n("Not passed")})]})}function vc(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 hK(e,t){window.electronAPI.bots.cancelDelegation(e).then(n=>{n.ok||We({type:"error",title:t("Cancel failed"),description:n.error}),re.getState().refreshDelegations()})}function xl(e,t,n){window.electronAPI.bots.retryDelegation(e,n).then(s=>{s.ok?s.warning&&We({type:"warning",title:s.warning}):We({type:"error",title:t("Retry failed"),description:s.error}),re.getState().refreshDelegations()})}function xh(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 vh({record:e,entry:t,retried:n,append:s,taskSeq:i,bots:r,onOpenConversation:a}){const{t:l}=te(),c=e?.state??t?.state??"queued",d=xh(!s&&kl(c)),u=r.get(e?.parentBotId??t?.from??""),h=r.get(e?.targetBotId??t?.to??""),p=XA(s?"completed":c),f=YA(e),x=!s&&f&&kl(c),g=!s&&c==="blocked"?e?.blocked:void 0,v=re(I=>g&&e?.taskId?I.delegations.some(T=>T.taskId===e.taskId&&T.createdAt>e.createdAt):!1),w=re(I=>I.openTask),y=!!t?.taskId&&!s,[b,_]=m.useState(!y),j=s?void 0:e?c==="completed"?e.result:c==="blocked"?void 0:vc(e,l):t?.summary,N=l("{{from}} → {{to}} · Delegation",{from:u?.name??l("Deleted member"),to:h?.name??l("Deleted member")}),C=o.jsxs(o.Fragment,{children:[y&&o.jsx(kn,{"aria-hidden":!0,className:q("size-3.5 shrink-0 transition-transform",b&&"rotate-90")}),o.jsx(Jt,{bot:u,size:"xs"}),o.jsx("span",{className:"text-foreground",children:u?.name??l("Deleted member")}),o.jsx("span",{children:"→"}),o.jsx(Jt,{bot:h,size:"xs",presence:f?.state}),o.jsx("span",{className:"text-foreground",children:h?.name??l("Deleted member")}),o.jsxs("span",{children:["· ",l("Delegation")]}),s?o.jsx("span",{className:"rounded bg-info/15 px-1.5 text-[11px] text-info",children:i===void 0?l("Merged into the current run"):l("Merged into the current run of #{{n}}",{n:i})}):x?o.jsx(nk,{info:f}):o.jsx(gh,{state:c,interrupted:e?.failure==="interrupted"}),e&&!s&&o.jsx("span",{children:ho((e.finishedAt??d)-e.createdAt)}),o.jsx("span",{className:"flex-1"}),o.jsx("span",{children:uK(s?.at??t?.at??e?.createdAt??d)})]}),k="flex flex-wrap items-center gap-1.5 whitespace-nowrap text-muted-foreground text-xs",E=s?.text??e?.task;return o.jsxs("div",{"data-slot":"bot-card",className:"max-w-lg rounded-xl border bg-card px-3 py-2.5",children:[y?o.jsx("button",{type:"button","aria-expanded":b,"aria-label":l(b?"Collapse delegation result":"Expand delegation result"),className:q(k,"w-full rounded text-left hover:text-foreground"),onClick:()=>_(I=>!I),children:C}):o.jsx("div",{className:k,children:C}),!b&&E&&o.jsx("div",{className:"mt-1 truncate text-muted-foreground text-xs",children:E}),b&&E&&o.jsx("div",{className:"mt-1.5 line-clamp-3 text-sm",children:E}),b&&o.jsxs(o.Fragment,{children:[e?.check&&!s&&o.jsx(fT,{check:e.check,className:"mt-1.5"}),j&&o.jsx("div",{className:"mt-1.5 line-clamp-4 whitespace-pre-wrap text-muted-foreground text-xs",children:j}),g&&e&&o.jsxs("div",{className:"mt-1.5 rounded-md bg-warning/10 px-2 py-1 text-xs",children:[o.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap",children:l("Blocked · needs: {{need}}",{need:g.need})}),o.jsx("div",{className:"text-muted-foreground",children:v?l("Answered; the work continues"):g.waitFor==="parent"?l("Waiting for {{name}} to reply",{name:u?.name??l("Deleted member")}):l("Waiting for your reply")})]}),e&&o.jsxs("div",{className:"mt-2 flex justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>a(e.childConversationId,N),children:l("View process")}),g&&!v&&e.chatId&&e.taskId&&o.jsx(le,{size:"xs",variant:"outline",onClick:()=>e.chatId&&e.taskId&&w(e.chatId,e.taskId),children:l("Reply")}),p.cancel&&o.jsx(le,{size:"xs",variant:"outline",onClick:()=>hK(e.id,l),children:l("Cancel")}),p.retry&&!n&&o.jsx(le,{size:"xs",variant:"outline",onClick:()=>xl(e.id,l),children:l("Retry")}),p.resumeOrRestart&&!n&&o.jsxs(o.Fragment,{children:[o.jsx(le,{size:"xs",variant:"outline",onClick:()=>xl(e.id,l,"resume"),children:l("Continue")}),o.jsx(le,{size:"xs",variant:"outline",onClick:()=>xl(e.id,l,"restart"),children:l("Start over")})]})]})]})]})}function mT(e){const t=re(d=>d.chats.find(u=>u.id===e)),n=re(d=>d.sessions),s=re(d=>d.queue),i=re(d=>d.silences),r=re(d=>d.delegations),a=re(d=>d.browserHolders),l=re(d=>d.browserTabs[t?.parentId??e]?.tabs),c=re(d=>ZA(d.timelines[e]?.entries??[]));return m.useMemo(()=>({chat:t??{id:e,sessions:{}},delegations:r,sessions:n,queue:s,silences:i,clearedAt:c,holders:a,tabIds:l??[]}),[t,e,r,n,s,i,c,a,l])}function pK(e,t){const n=mT(e);return m.useMemo(()=>JA(t,n),[t,n])}function fK(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 gT(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 Pa({label:e,children:t}){return o.jsxs("div",{className:"flex gap-2",children:[o.jsx("span",{className:"w-12 shrink-0 text-muted-foreground",children:e}),o.jsx("span",{className:"min-w-0 flex-1 break-words",children:t})]})}function xT({info:e,bot:t}){const{t:n}=te(),s=re(c=>e.delegation?c.bots.find(d=>d.id===e.delegation?.parentBotId):void 0),i=e.delegation,r=fK(e,n),a=re(c=>e.browserTab?c.browserTitles[e.browserTab]||n("Browser"):void 0),l=e.wait&&"conversationId"in e.wait?e.wait.conversationId:void 0;return o.jsxs(EN,{align:"start",className:"w-72 flex-col gap-1.5 p-3 text-xs",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-semibold text-sm",children:t?.name??n("Deleted member")}),o.jsx(nk,{info:e})]}),e.state==="idle"?o.jsx("div",{className:"text-muted-foreground",children:n("Nothing in progress")}):o.jsxs(o.Fragment,{children:[i&&o.jsxs(o.Fragment,{children:[o.jsx(Pa,{label:n("Task"),children:o.jsx("span",{className:"line-clamp-2",children:i.task})}),o.jsx(Pa,{label:n("From"),children:s?.name??n("Deleted member")}),o.jsx(Pa,{label:n("Time"),children:ho((i.finishedAt??Date.now())-i.createdAt)})]}),r&&o.jsx(Pa,{label:n("Waiting on"),children:r}),a&&o.jsx(Pa,{label:n("Browser"),children:o.jsx("span",{className:"line-clamp-1",children:a})}),e.quietSince!==void 0&&o.jsx("div",{className:"text-muted-foreground",children:n("Still running, no output for {{time}}",{time:ho(Date.now()-e.quietSince)})}),i&&e.state==="stuck"&&i.state==="failed"&&o.jsx("div",{className:"text-muted-foreground",children:vc(i,n)}),i&&e.state==="done"&&i.result&&o.jsx("div",{className:"line-clamp-3 text-muted-foreground",children:i.result}),l&&o.jsx(le,{size:"xs",className:"mt-1 self-start",onClick:()=>gT(l),children:n("Go handle it")})]})]})}function vT({chatId:e,botId:t,bot:n,size:s="sm"}){const{t:i}=te(),r=pK(e,t);return o.jsxs(xx,{children:[o.jsxs(vx,{render:o.jsx("span",{className:"relative inline-flex shrink-0"}),children:[o.jsx(Jt,{bot:n,size:s,presence:r.state}),o.jsx("span",{className:"sr-only",children:Zp(r,i)})]}),o.jsx(xT,{info:r,bot:n})]})}function mK({chatId:e,memberIds:t,bots:n,onOpenLive:s}){const{t:i}=te(),r=mT(e),a=m.useMemo(()=>QA(t,r),[t,r]);return a.length===0?null:o.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??i("Deleted member"),h=eM(c),p=tM(c);return o.jsxs(xx,{children:[o.jsxs(vx,{render:o.jsx("button",{type:"button",onClick:()=>p?.kind==="pending"?gT(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:[o.jsx(Jt,{bot:d,size:"xs",presence:c.state}),h?o.jsx("span",{className:"max-w-56 truncate pr-1.5",children:[u,Zp(c,i),h].join(" · ")}):o.jsx("span",{className:"sr-only",children:`${u} · ${Zp(c,i)}`})]}),o.jsx(xT,{info:c,bot:d})]},l)})})}const bT=[137,80,78,71,13,10,26,10];function la(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}let Gc=null;function gK(e){if(!Gc){Gc=new Uint32Array(256);for(let n=0;n<256;n+=1){let s=n;for(let i=0;i<8;i+=1)s=s&1?3988292384^s>>>1:s>>>1;Gc[n]=s>>>0}}let t=4294967295;for(const n of e)t=Gc[(t^n)&255]^t>>>8;return(t^4294967295)>>>0}function wT(e){return bT.every((t,n)=>e[n]===t)?"png":e[0]===255&&e[1]===216&&e[2]===255?"jpeg":la(e.subarray(0,4))==="RIFF"&&la(e.subarray(8,12))==="WEBP"?"webp":null}function yT(e){if(wT(e)!=="png")return null;const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=[];for(let s=8;s+12<=e.length;){const i=t.getUint32(s),r=s+12+i;if(r>e.length)return null;const a=la(e.subarray(s+4,s+8));if(n.push({type:a,data:e.subarray(s+8,s+8+i),raw:e.subarray(s,r)}),s=r,a==="IEND")return n}return null}const ST=e=>{if(e.type!=="tEXt")return null;const t=e.data.indexOf(0);return t>0?la(e.data.subarray(0,t)):null};function py(e,t){const n=yT(e)?.find(s=>ST(s)===t);return n?la(n.data.subarray(t.length+1)):null}function fy(e,t){const n=new Uint8Array(12+t.length),s=new DataView(n.buffer);s.setUint32(0,t.length);for(let i=0;i<4;i+=1)n[4+i]=e.charCodeAt(i);return n.set(t,8),s.setUint32(8+t.length,gK(n.subarray(4,8+t.length))),n}function xK(e,t,n,s=[]){const i=yT(e);if(!i)return null;const r=new Set([t,...s]),a=i.filter(h=>{const p=ST(h);return h.type!=="IEND"&&!(p&&r.has(p))}),l=Uint8Array.from(`${t}\0${n}`,h=>h.charCodeAt(0)&255),c=[Uint8Array.from(bT),...a.map(h=>h.raw),fy("tEXt",l),fy("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 vK(e){return btoa(la(new TextEncoder().encode(e)))}function bK(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 wK(e){return{budgetCost:e?.dailyCostUsd!==void 0?String(e.dailyCostUsd):"",budgetTokens:e?.dailyTokens!==void 0?String(e.dailyTokens):""}}function CT(e){const t={},n=e.budgetCost.trim();if(n){const i=Number(n);if(!Number.isFinite(i)||i<=0)return{ok:!1};t.dailyCostUsd=i}const s=e.budgetTokens.trim();if(s){const i=Number(s);if(!Number.isSafeInteger(i)||i<=0)return{ok:!1};t.dailyTokens=i}return{ok:!0,budget:Object.keys(t).length>0?t:null}}function yK(e){return{delegationTimeout:e.delegationTimeoutMinutes!==void 0?String(e.delegationTimeoutMinutes):"",maxTurnTokens:e.maxTokensPerTurn!==void 0?String(e.maxTokensPerTurn):""}}function Cx(e){const t=e.delegationTimeout.trim()?Number(e.delegationTimeout):null,n=e.maxTurnTokens.trim()?Number(e.maxTurnTokens):null;return t!==null&&!nM(t)||n!==null&&!sM(n)?{ok:!1}:{ok:!0,delegationTimeoutMinutes:t,maxTokensPerTurn:n}}function my(e){return[...e.normalize("NFC").trim().replace(/\s+/gu,"_").replace(/[^\p{L}\p{N}_-]/gu,"").replace(/_+/gu,"_").replace(/^_+|_+$/gu,"")].slice(0,oM).join("")}const ko=e=>typeof e=="string"?e.trim():"",Cp=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function gy(e){const t=e.split(`
79
- `).find(s=>s.trim())??"",n=/^.*?[.!?。!?](?=\s|$)/u.exec(t.trim());return(n?n[0]:t.trim()).slice(0,80)}function SK(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 CK(e){return{...typeof e.title=="string"?{title:e.title.trim()}:{},...ko(e.scope)?{scope:ko(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}:{},...iM.includes(e.approvalMode)?{approvalMode:e.approvalMode}:{},...typeof e.memory=="boolean"?{memoryEnabled:e.memory}:{}}}function kK(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=Cp(n.data)?n.data:n,i=ko(s.name);if(!i)return{ok:!1,error:"not-a-card"};const r=Cp(s.extensions)?s.extensions.enso:void 0;if(Cp(r)){const d=typeof s.description=="string"?s.description:"";return{ok:!0,draft:{name:my(i),title:"",scope:gy(d),persona:d,...CK(r)}}}const a=d=>d.replace(/\{\{char\}\}/giu,i).replace(/\{\{user\}\}/giu,"the user"),l=a(ko(s.description)),c=[l,ko(s.personality)&&`Personality: ${a(ko(s.personality))}`,ko(s.scenario)&&`Scenario: ${a(ko(s.scenario))}`].filter(Boolean);return{ok:!0,draft:{name:my(i),title:"",scope:gy(l),persona:c.join(`
80
-
81
- `)}}}const jr=256,xy=4;function kT({hasImage:e,nested:t=!1,disabled:n=!1,onPick:s,onRemove:i}){const{t:r}=te(),a=m.useRef(null),[l,c]=m.useState(null);return o.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.jsxs(le,{size:"xs",variant:"outline",disabled:n,onClick:()=>a.current?.click(),children:[o.jsx(Kg,{}),r("Upload avatar")]}),e&&o.jsxs(le,{size:"xs",variant:"ghost",disabled:n,onClick:i,children:[o.jsx(ln,{}),r("Remove avatar")]}),o.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&&rM(u).then(c,()=>We({type:"error",title:r("This image cannot be used as an avatar.")}))}}),o.jsx(_K,{source:l,nested:t,onCancel:()=>c(null),onDone:d=>{c(null),s(d)}})]})}function _K({source:e,nested:t=!1,onCancel:n,onDone:s}){const{t:i}=te(),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?jr/Math.min(l.w,l.h)*v:1,p=v=>{if(!l)return v;const w=h(v.zoom),y=(l.w*w-jr)/2,b=(l.h*w-jr)/2;return{zoom:v.zoom,x:Math.max(-y,Math.min(y,v.x)),y:Math.max(-b,Math.min(b,v.y))}},f=v=>u(w=>p({...w,zoom:Math.max(1,Math.min(xy,v))})),x=()=>{const v=r.current;if(!v||!l)return;const w=h(d.zoom),y=jr/w;s(lM(v,l.w/2-y/2-d.x/w,l.h/2-y/2-d.y/w,y))},g=h(d.zoom);return o.jsx(gn,{open:e!==null,onOpenChange:v=>!v&&n(),children:o.jsxs(xn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:i("Crop avatar")}),o.jsx(Os,{children:i("Drag to move, scroll to zoom.")})]}),o.jsxs(Rn,{className:"flex flex-col items-center gap-4",children:[o.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:jr,height:jr},onPointerDown:v=>{v.currentTarget.setPointerCapture(v.pointerId),a.current={id:v.pointerId,x:v.clientX,y:v.clientY}},onPointerMove:v=>{const w=a.current;!w||w.id!==v.pointerId||(a.current={...w,x:v.clientX,y:v.clientY},u(y=>p({...y,x:y.x+v.clientX-w.x,y:y.y+v.clientY-w.y})))},onPointerUp:()=>{a.current=null},onWheel:v=>f(d.zoom*(v.deltaY<0?1.1:1/1.1)),children:[e&&o.jsx("img",{ref:r,src:e,alt:"",draggable:!1,onLoad:v=>c({w:v.currentTarget.naturalWidth,h:v.currentTarget.naturalHeight}),onError:()=>{We({type:"error",title:i("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*g,height:l.h*g,transform:`translate(-50%, -50%) translate(${d.x}px, ${d.y}px)`}:{visibility:"hidden"}}),o.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"})]}),o.jsx(aM,{min:1,max:xy,step:.01,value:d.zoom,"aria-label":i("Zoom"),onValueChange:v=>f(Array.isArray(v)?v[0]:v)})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:n,children:i("Cancel")}),o.jsx(le,{size:"sm",disabled:!l,onClick:x,children:i("Use this avatar")})]})]})})}const jK=["tools","approvalMode","skillIds","mcpServerIds","canDelegateTo","acceptFrom"],NK=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every(n=>t.includes(n)):e===t;function vy(e,t){return jK.flatMap(n=>{const s=t[n];return!s||NK(e[n],s.value)?[]:[{field:n,from:e[n],to:s.value,reason:s.reason}]})}function TK(e,t,n){const s={...e};for(const i of t)n.includes(i.field)&&Object.assign(s,{[i.field]:i.to});return s}const _T={tools:"all",approvalMode:"auto-edits",skillIds:[],mcpServerIds:[],canDelegateTo:"any",acceptFrom:"any",memoryEnabled:!0,budgetCost:"",budgetTokens:"",delegationTimeout:"",maxTurnTokens:""};function jT({value:e,onChange:t,profile:n,botId:s,zIndex:i}){const{t:r}=te(),l=re(c=>c.bots).filter(c=>c.id!==s&&!c.archivedAt);return o.jsxs("div",{className:"space-y-4",children:[o.jsx(IK,{value:e,onApply:t,profile:n,botId:s}),o.jsxs("div",{children:[o.jsx(Bt,{children:r("Tools")}),o.jsx(Vm,{value:e.tools,options:[{value:"all",label:r("All tools")},{value:"readonly",label:r("Read-only")}],onChange:c=>t({tools:c})})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:r("Approval mode")}),o.jsx(sk,{value:e.approvalMode,onChange:c=>t({approvalMode:c}),zIndex:i})]}),o.jsx(NT,{value:e,onChange:t}),o.jsx(by,{label:r("Can delegate to"),value:e.canDelegateTo,bots:l,onChange:c=>t({canDelegateTo:c})}),o.jsx(by,{label:r("Accepts delegation from"),value:e.acceptFrom,bots:l,onChange:c=>t({acceptFrom:c})}),o.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[o.jsx("span",{children:r("Long-term memory")}),o.jsx(_i,{checked:e.memoryEnabled,onCheckedChange:c=>t({memoryEnabled:c})})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:r("Daily budget")}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsx(Wt,{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})}),o.jsx(Wt,{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})})]}),o.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.")})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:r("Per-turn token limit")}),o.jsx(Wt,{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})}),o.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.")})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:r("Delegation time limit (minutes)")}),o.jsx(Wt,{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})}),o.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 bh(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 IK({value:e,onApply:t,profile:n,botId:s}){const{t:i,locale:r}=te(),[a,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState([]),p=c?vy(e,c):[],f=async()=>{if(![n.name,n.title,n.scope,n.persona].some(g=>g.trim())){We({type:"warning",title:i("Fill in a name, title or responsibilities first.")});return}l(!0);try{const g=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(!g.ok){We({type:"error",title:bh(g,i),...g.detail?{description:g.detail}:{}});return}if(vy(e,g.suggestion).length===0){We({type:"info",title:i("Current abilities already match the suggestion.")});return}h([]),d(g.suggestion)}finally{l(!1)}},x=()=>{const g=p.map(w=>w.field).filter(w=>!u.includes(w)),v=TK(e,p,g);t(Object.fromEntries(g.map(w=>[w,v[w]]))),d(null)};return o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:i("Let a model suggest abilities from the name, title, responsibilities and persona.")}),o.jsxs(le,{size:"xs",variant:"outline",disabled:a,onClick:()=>{f()},children:[a?o.jsx(Vt,{className:"animate-spin"}):o.jsx(Ls,{}),i("Auto-configure abilities")]})]}),c&&p.length>0&&o.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/40 p-2.5",children:[o.jsx("p",{className:"font-medium text-xs",children:i("Suggested changes")}),p.map(g=>o.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[o.jsx(ec,{className:"mt-0.5",checked:!u.includes(g.field),onCheckedChange:v=>h(w=>v?w.filter(y=>y!==g.field):[...w,g.field])}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-1.5",children:[o.jsx("span",{className:"font-medium",children:DK(g.field,i)}),o.jsx(PK,{change:g})]}),g.reason&&o.jsx("p",{className:"text-muted-foreground",children:g.reason})]})]},g.field)),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(le,{size:"xs",variant:"outline",onClick:()=>d(null),children:i("Cancel")}),o.jsx(le,{size:"xs",disabled:p.every(g=>u.includes(g.field)),onClick:x,children:i("Apply")})]})]})]})}function DK(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 PK({change:e}){const{t}=te(),n=xe(p=>p.skills),s=xe(p=>p.mcpServers),i=re(p=>p.bots),r=(p,f)=>o.jsxs("span",{className:"text-muted-foreground",children:[p," → ",o.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(_l[f].labelKey);return r(p(e.from),p(e.to))}const a=e.field==="skillIds"?n:e.field==="mcpServerIds"?s:i,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 o.jsxs("span",{className:"space-x-1.5",children:[u.map(p=>o.jsxs("span",{className:"text-success",children:["+",l(p)]},`+${p}`)),h.map(p=>o.jsx("span",{className:"text-destructive line-through",children:l(p)},`-${p}`))]})}function NT({value:e,onChange:t}){const{t:n}=te(),s=xe(a=>a.skills),i=xe(a=>a.mcpServers),r=(a,l)=>a.includes(l)?a.filter(c=>c!==l):[...a,l];return o.jsxs(o.Fragment,{children:[o.jsx(kv,{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:jv(e.skillIds,a,l)}),placeholder:n("Filter skills..."),renderDetail:a=>o.jsx(_v,{rows:[[n("Source"),a.source],[n("Path"),a.path],[n("Description"),a.description]]})}),o.jsx(kv,{title:n("MCP Servers"),emptyText:n("No MCP servers yet"),items:i,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:jv(e.mcpServerIds,a,l)}),placeholder:n("Filter MCP servers..."),renderDetail:a=>o.jsx(_v,{rows:[[n("Source"),a.source],["Transport",a.transport],["URL",a.url]]})})]})}function by({label:e,value:t,bots:n,onChange:s}){const{t:i}=te();return o.jsxs("div",{children:[o.jsx(Bt,{children:e}),o.jsx(Vm,{value:t==="any"?"any":"some",options:[{value:"any",label:i("All members")},{value:"some",label:i("Selected members")}],onChange:r=>s(r==="any"?"any":[])}),t!=="any"&&o.jsxs("div",{className:"mt-1.5 space-y-1",children:[n.length===0&&o.jsx("p",{className:"text-muted-foreground text-xs",children:i("No other members")}),n.map(r=>o.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[o.jsx(ec,{checked:t.includes(r.id),onCheckedChange:a=>s(a?[...t,r.id]:t.filter(l=>l!==r.id))}),o.jsx(Jt,{bot:r,size:"xs"}),r.name]},r.id))]})]})}function EK({bot:e}){const{t}=te(),n=re(r=>r.usage?.bots[e.id]);if(m.useEffect(()=>{re.getState().refreshUsage()},[]),!n)return null;const s=[[t("Today"),n.today],[t("Last 7 days"),n.week],[t("Last 30 days"),n.month]],i=e.budget;return o.jsxs("div",{"data-slot":"bot-card",className:"rounded-lg border bg-card p-3",children:[o.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.map(([r,a])=>o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-muted-foreground text-xs",children:r}),o.jsx("div",{className:"truncate font-medium text-sm tabular-nums",children:Rh(a.tokens)}),o.jsx("div",{className:"truncate text-muted-foreground text-xs tabular-nums",children:Lh(a.cost)})]},r))}),i&&o.jsxs("div",{className:n.exhausted?"mt-2 text-destructive text-xs":"mt-2 text-muted-foreground text-xs",children:[[i.dailyTokens!==void 0&&`${Rh(n.today.tokens)} / ${Rh(i.dailyTokens)} tokens`,i.dailyCostUsd!==void 0&&`${Lh(n.today.cost??0)} / ${Lh(i.dailyCostUsd)}`].filter(Boolean).join(" · "),n.exhausted&&` · ${t("Today's budget is used up")}`]})]})}function TT({spaceId:e,emptyText:t}){const[n,s]=m.useState(null),i=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),i(),window.electronAPI.memory.onChanged(()=>{i()})),[i]),n===null?o.jsx(Vt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):n.length===0?o.jsx("p",{className:"text-muted-foreground text-xs",children:t}):o.jsx("div",{className:"space-y-1.5",children:n.map(r=>o.jsx(AK,{item:r,onDeleted:()=>s(a=>a?.filter(l=>l.id!==r.id)??null)},r.id))})}function AK({item:e,onDeleted:t}){const{t:n}=te(),[s,i]=m.useState(null),[r,a]=m.useState(!1),l=async()=>{a(!0);const d=await window.electronAPI.memory.detail(e.id);a(!1),d?i({title:d.title,content:d.content}):We({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?i(null):We({type:"error",title:n("Save failed"),description:d.error})};return s?o.jsxs("div",{"data-slot":"bot-card",className:"space-y-1.5 rounded-lg border bg-card px-2.5 py-2",children:[o.jsx(Wt,{size:"sm",value:s.title,placeholder:n("Memory title"),onChange:d=>i({...s,title:d.target.value})}),o.jsx(Ys,{rows:5,value:s.content,placeholder:n("Memory content"),onChange:d=>i({...s,content:d.target.value})}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",disabled:r,onClick:()=>i(null),children:n("Cancel")}),o.jsxs(le,{size:"xs",disabled:r||!s.content.trim(),onClick:()=>{c()},children:[r&&o.jsx(Vt,{className:"animate-spin"}),n("Save")]})]})]}):o.jsxs("div",{"data-slot":"bot-card",className:"group flex items-start gap-2 rounded-lg border bg-card px-2.5 py-2",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"truncate font-medium text-xs",children:e.title}),o.jsx("div",{className:"line-clamp-3 text-muted-foreground text-xs",children:e.contentSummary})]}),o.jsxs("div",{className:"flex shrink-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100",children:[o.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?o.jsx(Vt,{className:"h-3.5 w-3.5 animate-spin"}):o.jsx(Xs,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",title:n("Delete"),"aria-label":n("Delete"),onClick:()=>{window.electronAPI.memory.delete(e.id).then(d=>{d.ok?t():We({type:"error",title:d.error??n("Delete failed")})})},className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive",children:o.jsx(di,{className:"h-3.5 w-3.5"})})]})]})}function IT({target:e,emptyText:t}){const{t:n}=te(),s="botId"in e?e.botId:void 0,i="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 x=await window.electronAPI.bots.notes.get(s?{botId:s}:{chatId:i??""});x.ok&&a(x.notes)},[s,i]);m.useEffect(()=>(a(null),c(null),p(),window.electronAPI.bots.onEvent(x=>{x.kind!=="notes"||h.current||(s?!x.chatId:x.chatId===i)&&p()})),[p,s,i]);const f=async()=>{if(!r||l===null)return;u(!0);const x=await window.electronAPI.bots.notes.save({...s?{botId:s}:{chatId:i??""},content:l,version:r.version});if(u(!1),x.ok){a(x.notes),c(null);return}We({type:"error",title:x.error==="conflict"?n("Notes were updated elsewhere; reloaded the latest version"):n("Save failed")}),x.error==="conflict"&&(c(null),p())};return r?l!==null?o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Ys,{rows:8,value:l,maxLength:r.maxChars,onChange:x=>c(x.target.value)}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsxs("span",{className:"mr-auto text-muted-foreground text-xs",children:[l.length," / ",r.maxChars]}),o.jsx(le,{size:"xs",variant:"ghost",disabled:d,onClick:()=>c(null),children:n("Cancel")}),o.jsx(le,{size:"xs",disabled:d,onClick:()=>{f()},children:n("Save")})]})]}):o.jsxs("div",{className:"group space-y-1.5",children:[r.content?o.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}):o.jsx("p",{className:"text-muted-foreground text-xs",children:t}),o.jsx(le,{size:"xs",variant:"outline",onClick:()=>c(r.content),children:n("Edit notes")})]}):o.jsx(Vt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}function DT({value:e,onApply:t}){const{t:n,locale:s}=te(),[i,r]=m.useState(!1),a=async()=>{if(!e.name.trim()||!e.title.trim()){We({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){We({type:"error",title:bh(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}:{}}),We({type:"success",title:n(d?"Persona and responsibilities generated":"Persona generated"),timeout:1e4,actions:[{label:n("Undo"),onClick:()=>t(u)}]})}finally{r(!1)}};return o.jsxs(le,{size:"xs",variant:"ghost",className:"-my-1 h-6 text-muted-foreground",disabled:i,onClick:()=>{a()},children:[i?o.jsx(Vt,{className:"animate-spin"}):o.jsx(Ls,{}),n("Generate with AI")]})}function wy(e){const t=fh(e);if(!t)return;const[n,s,i,r,a]=t.source.split(" ");if(!/^\d+$/u.test(n)||!/^\d+$/u.test(s)||i!=="*"||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 MK(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 i=[...new Set(e.days)].filter(a=>Number.isInteger(a)&&a>=0&&a<=6);if(t==="weekly"&&!i.length)return;const r=t==="daily"?"*":t==="weekdays"?"1-5":i.sort().join(",");return`${s} ${n} * * ${r}`}function RK(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 LK(e){return e.status==="review"&&!!(e.delegationId&&e.assigneeBotId)}function OK(e,t){return e.filter(n=>n.chatId===t).sort((n,s)=>n.createdAt-s.createdAt)}const Fc=e=>e.finishedAt??e.createdAt;function zK(e,t){const n=e.filter(s=>s.chatId===t);return{active:n.filter(s=>kl(s.state)).sort((s,i)=>s.createdAt-i.createdAt),completed:n.filter(s=>s.state==="completed").sort((s,i)=>Fc(i)-Fc(s)),failed:n.filter(s=>["failed","canceled","blocked"].includes(s.state)).sort((s,i)=>Fc(i)-Fc(s))}}function GK(e,t,n){const s=new Map(t.map(i=>[i.id,i]));return[...e].sort((i,r)=>i.createdAt-r.createdAt).map(i=>({run:i,record:s.get(i.id),time:i.state==="queued"&&i.startedAt===void 0?{queued:!0,ms:n-i.createdAt}:{queued:!1,ms:(i.finishedAt??n)-(i.startedAt??i.createdAt)}}))}function FK(e,t){const n=cM(e);if(!n)return;const s=t.find(r=>r.id===e.delegationId);if(n.reason==="failed"){const r=ik(e);return{reason:"failed",...s?{record:s}:{},since:r?.finishedAt??s?.finishedAt??e.updatedAt}}const i=(e.blockedStreak?.[e.assigneeBotId??""]??0)>=dM;return{reason:"need",need:n.need||s?.blocked?.need||"",waitFor:!i&&s?.blocked?.waitFor==="parent"?s.parentBotId:"human",...i?{humanOnly:!0}:{},since:s?.finishedAt??s?.blocked?.at??e.updatedAt}}const HK=["0 9 * * *","0 9 * * 1-5","0 9 * * 1","0 * * * *"];function BK(e,t,n){const s=fh(e);if(s)return{source:s.source,description:Sx(s,t),next:S9(s,n)}}function VK(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 $K(e){return e.title.trim()?e.prompt.trim()?fh(e.schedule)?e.chatId?null:"chat":"schedule":"prompt":"title"}function xu(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 ca("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?ca(n,t):t("This routine is blocked. Fix the problem and enable it again.");default:return e}}function ca(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 PT(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 kx(){const{t:e}=te(),[t,n]=m.useState(!1),s=async(r,a,l)=>{n(!0);try{const c=await a();c.ok?l&&We({type:"success",title:l}):We({type:"error",title:r,description:xu(c.error,e,c.reason)})}finally{n(!1)}},i=window.electronAPI.bots.routines;return{busy:t,review:(r,a)=>s(e("Routine not saved"),()=>i.review({botId:r.botId,id:r.id,approve:a})),resume:r=>s(e("Routine not saved"),async()=>{const a=await i.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"),()=>i.runNow({botId:r.botId,id:r.id,dryRun:a}),e(a?"Dry run started":"Routine started"))}}function ET({routine:e}){const{t,locale:n}=te(),s=re(r=>r.bots),i=e.doneBy?s.find(r=>r.id===e.doneBy):void 0;return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mt-2 font-medium text-sm",children:e.title}),o.jsxs("div",{className:"mt-0.5 text-muted-foreground text-xs",children:[Sx(e.schedule,n),e.doneBy?` · ${t("Done by {{name}}",{name:i?.name??t("Deleted member")})}`:""]}),o.jsx("div",{className:"mt-1 line-clamp-3 whitespace-pre-wrap text-xs",children:e.prompt})]})}function WK({alert:e}){const{t}=te(),n=re(p=>p.bots),s=re(p=>p.chats),i=re(p=>p.setView),{busy:r,review:a,resume:l,run:c}=kx(),{routine:d}=e,u=n.find(p=>p.id===d.botId),h=s.find(p=>p.id===d.chatId);return o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[o.jsx(Jt,{bot:u,size:"sm"}),o.jsx("span",{className:"text-foreground",children:u?.name??t("Deleted member")}),h?.kind==="group"&&o.jsxs("span",{children:["· ",bs(h,n,t)]}),o.jsx(_x,{routine:d})]}),o.jsx(ET,{routine:d}),e.kind==="blocked"&&o.jsx("div",{className:"mt-1 text-destructive text-xs",children:ca(d.blockedReason,t)}),o.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[h&&o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>i({kind:"chat",chatId:h.id}),children:t("Go to chat")}),e.kind==="approval"?o.jsxs(o.Fragment,{children:[o.jsx(le,{size:"xs",variant:"outline",disabled:r,onClick:()=>c(d,!0),children:t("Dry run")}),o.jsx(le,{size:"xs",variant:"outline",disabled:r,onClick:()=>a(d,!1),children:t("Reject")}),o.jsx(le,{size:"xs",disabled:r,onClick:()=>a(d,!0),children:t("Approve")})]}):o.jsx(le,{size:"xs",disabled:r,onClick:()=>l(d),children:t("Enable again")})]})]})}function _x({routine:e}){const{t}=te(),[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 o.jsx("span",{className:q("rounded px-1.5 text-[11px]",s),children:n})}function UK({text:e,target:t}){const{t:n}=te(),s=re(l=>l.routines.find(c=>c.id===t.id&&c.botId===t.botId)),{busy:i,review:r,run:a}=kx();return o.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:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[o.jsx("span",{className:"min-w-0 flex-1",children:e}),s?o.jsx(_x,{routine:s}):o.jsx("span",{className:"text-[11px]",children:n("Routine removed")})]}),s&&o.jsx(ET,{routine:s}),s?.status==="draft"&&o.jsxs("div",{className:"mt-2 flex justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",disabled:i,onClick:()=>a(s,!0),children:n("Dry run")}),o.jsx(le,{size:"xs",variant:"outline",disabled:i,onClick:()=>r(s,!1),children:n("Reject")}),o.jsx(le,{size:"xs",disabled:i,onClick:()=>r(s,!0),children:n("Approve")})]})]})}const jx=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function AT(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 KK(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 qK(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 MT({botId:e,chatId:t}){const{t:n,locale:s}=te(),i=re(b=>b.chats),r=re(b=>b.bots),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(null),[p,f]=m.useState(null),x=kx(),g=m.useCallback(async()=>{const b=await window.electronAPI.bots.routines.list(e?{botId:e}:{}).catch(()=>null),_=b?.ok?b.routines:[];l(t?OK(_,t):_)},[e,t]);m.useEffect(()=>(l(null),g(),window.electronAPI.bots.onEvent(b=>{b.kind==="routine"&&g()})),[g]);const v=async(b,_)=>{const{id:j,title:N,prompt:C,schedule:k}=b,E=await window.electronAPI.bots.routines.save({botId:b.botId,id:j,title:N,prompt:C,schedule:k,chatId:b.chatId,enabled:_});E.ok?E.routine.status==="blocked"&&We({type:"error",title:n("Routine blocked"),description:ca(E.routine.blockedReason,n)}):We({type:"error",title:n("Routine not saved"),description:xu(E.error,n)}),g()},w=async b=>{h(null);const _=await window.electronAPI.bots.routines.remove({botId:b.botId,id:b.id});_.ok||We({type:"error",title:n("Routine not deleted"),description:xu(_.error,n)}),g()};if(a===null)return o.jsx(Vt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const y=b=>r.find(_=>_.id===b)?.name??n("Deleted member");return o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs(le,{size:"xs",variant:"outline",onClick:()=>d("new"),children:[o.jsx(ps,{}),n("New routine")]}),a.length===0&&o.jsx("p",{className:"text-muted-foreground text-xs",children:n("No routines yet")}),a.map(b=>{const _=i.find(k=>k.id===b.chatId),j=b.status==="draft",N=uM(b)&&(b.status==="enabled"||b.status==="paused"),C=_?n("Posts to {{chat}}",{chat:bs(_,r,n)}):n("Target chat missing");return o.jsxs("div",{"data-slot":"bot-card",className:q("rounded-lg border bg-card px-2.5 py-2 text-xs",b.status==="paused"&&"opacity-70"),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:b.title}),o.jsx(_x,{routine:b}),!j&&o.jsx(_i,{checked:b.status==="enabled",onCheckedChange:k=>{v(b,k)},title:b.status==="enabled"?n("Enabled"):n("Paused")})]}),o.jsx("div",{className:"mt-0.5 text-muted-foreground",children:[t?y(b.botId):"",Sx(b.schedule,s),b.doneBy?n("Done by {{name}}",{name:y(b.doneBy)}):"",t?"":C].filter(Boolean).join(" · ")}),b.proposedBy&&j&&o.jsx("div",{className:"mt-0.5 text-warning",children:n("Proposed by {{name}}, waiting for your approval",{name:y(b.proposedBy)})}),b.status==="blocked"&&o.jsx("div",{className:"mt-0.5 text-destructive",children:ca(b.blockedReason,n)}),o.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-2 text-muted-foreground",children:[o.jsx("span",{children:b.lastRunAt?n("Last run {{time}} · {{result}}",{time:jx(b.lastRunAt),result:PT(b.lastResult,n)}):n("Never run")}),b.missed?o.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-warning",children:n("Missed {{n}} times",{n:b.missed})}):null,!b.catchUp&&o.jsx("span",{children:n("No catch-up")})]}),o.jsxs("div",{className:"mt-1.5 flex flex-wrap justify-end gap-1",children:[j?o.jsxs(o.Fragment,{children:[o.jsx(le,{size:"xs",variant:"ghost",disabled:x.busy,onClick:()=>{x.review(b,!1)},children:n("Reject")}),o.jsx(le,{size:"xs",disabled:x.busy,onClick:()=>{x.review(b,!0)},children:n("Approve")})]}):o.jsxs(le,{size:"xs",variant:"ghost",disabled:!N||x.busy,onClick:()=>{x.run(b,!1)},children:[o.jsx($m,{}),n("Run now")]}),o.jsxs(le,{size:"xs",variant:"ghost",disabled:x.busy,title:n("Run once without affecting the schedule"),onClick:()=>{x.run(b,!0)},children:[o.jsx(qC,{}),n("Dry run")]}),o.jsxs(le,{size:"xs",variant:p===b.id?"secondary":"ghost",onClick:()=>f(p===b.id?null:b.id),children:[o.jsx(Lo,{}),n("History")]}),o.jsxs(le,{size:"xs",variant:"ghost",onClick:()=>d(b),children:[o.jsx(Xs,{}),n("Edit")]}),o.jsxs(le,{size:"xs",variant:"ghost",onClick:()=>h(b),children:[o.jsx(di,{}),n("Delete")]})]}),p===b.id&&o.jsx(YK,{routine:b})]},b.id)}),c&&o.jsx(ZK,{botId:e,chatId:t,routine:c==="new"?void 0:c,onClose:b=>{d(null),b&&g()}}),o.jsx(hs,{open:u!==null,onOpenChange:b=>!b&&h(null),title:n('Delete routine "{{title}}"?',{title:u?.title??""}),description:n("It will no longer run. This cannot be undone."),confirmLabel:n("Delete"),onConfirm:()=>u&&void w(u)})]})}function YK({routine:e}){const{t}=te(),n=re(l=>l.setView),[s,i]=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&&i(u.ok?u.runs:[])).catch(()=>l&&i([]))};c();const d=window.electronAPI.bots.onEvent(u=>{u.kind==="routine"&&c()});return()=>{l=!1,d()}},[r,a]),s===null?o.jsx(Vt,{className:"mt-2 h-3.5 w-3.5 animate-spin"}):s.length===0?o.jsx("p",{className:"mt-2 text-muted-foreground",children:t("No runs yet")}):o.jsx("ul",{className:"mt-2 space-y-1 border-t pt-2",children:s.map(l=>o.jsxs("li",{className:"flex flex-wrap items-center gap-x-2 text-muted-foreground",children:[o.jsx("span",{className:"tabular-nums",children:jx(l.startedAt)}),o.jsx("span",{children:KK(l.trigger,t)}),o.jsxs("span",{className:q(l.result==="ok"&&"text-success",(l.result==="error"||l.result==="blocked"||l.result==="budget")&&"text-destructive"),children:[PT(l.result,t),qK(l)]}),l.conversationId&&o.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>n({kind:"chat",chatId:l.chatId}),children:t("Open chat")}),l.error&&o.jsx("span",{className:"w-full truncate text-destructive",title:l.error,children:l.result==="blocked"?ca(l.error,t):l.error})]},l.runId))})}const XK=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],yy=e=>String(e).padStart(2,"0");function JK({value:e,onChange:t}){const{t:n,locale:s}=te(),i=wy(e),[r,a]=m.useState(!i),[l,c]=m.useState(i??{kind:"daily",days:[1],hour:9,minute:0}),d=BK(e,s,Date.now()),u=f=>{c(f);const x=MK(f);x&&t(x)},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=wy(e);f?c(f):u(l),a(!1)};return o.jsxs("div",{children:[o.jsx(Bt,{hint:r?n("cron: minute hour day month weekday, local time"):void 0,action:o.jsx(le,{size:"xs",variant:"ghost",onClick:p,children:n(r?"Simple":"Advanced (cron)")}),children:n("Schedule")}),r?o.jsx(Wt,{className:"font-mono",value:e,placeholder:"0 9 * * 1-5",onChange:f=>t(f.target.value)}):o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs(ms,{items:h,value:l.kind,onValueChange:f=>u({...l,kind:f,days:l.days.length?l.days:[1]}),children:[o.jsx(gs,{className:"w-32",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:h.map(f=>o.jsx(ts,{value:f.value,children:f.label},f.value))})]}),l.kind==="weekly"&&XK.map((f,x)=>{const g=l.days.includes(x);return o.jsx(le,{size:"xs",variant:g?"default":"outline",onClick:()=>{const v=g?l.days.filter(w=>w!==x):[...l.days,x].sort();v.length&&u({...l,days:v})},children:n(f)},f)}),o.jsx(Wt,{type:"time",className:"w-28",value:`${yy(l.hour)}:${yy(l.minute)}`,onChange:f=>{const[x,g]=f.target.value.split(":").map(Number);Number.isInteger(x)&&Number.isInteger(g)&&u({...l,hour:x,minute:g})}})]}),o.jsx("p",{className:q("mt-1 text-xs",d?"text-muted-foreground":"text-destructive"),children:d?`${d.description} · ${d.next?n("Next run {{time}}",{time:jx(d.next)}):n("Never runs")}`:AT("schedule",n)})]})}function ZK({botId:e,chatId:t,routine:n,onClose:s}){const{t:i}=te(),r=re(B=>B.chats),a=re(B=>B.bots),l=m.useMemo(()=>(r.find(L=>L.id===t)?.members??[]).flatMap(L=>{const se=a.find(Q=>Q.id===L&&Q.archivedAt===void 0);return se?[se]:[]}),[r,a,t]),[c,d]=m.useState(n?.botId??e??l[0]?.id??""),u=m.useMemo(()=>VK(r,c),[r,c]),[h,p]=m.useState(n?.title??""),[f,x]=m.useState(n?.prompt??""),[g,v]=m.useState(n?.schedule??HK[0]),[w,y]=m.useState(n?.chatId??t??u[0]?.id??""),[b,_]=m.useState(n?.doneBy??""),[j,N]=m.useState(n?.catchUp??!0),[C,k]=m.useState(null),[E,I]=m.useState(!1),T=B=>{const L=r.find(se=>se.id===B);return L?`${bs(L,a,i)} · ${L.kind==="group"?i("Group chat"):i("Private chat")}`:i("Target chat missing")},A=u.some(B=>B.id===w)||!w?u.map(B=>B.id):[w,...u.map(B=>B.id)],D=m.useMemo(()=>(r.find(L=>L.id===w)?.members??[]).flatMap(L=>{const se=a.find(Q=>Q.id===L&&Q.archivedAt===void 0);return se&&se.id!==c?[se]:[]}),[r,a,w,c]),W=[{value:"",label:i("The member itself")},...D.map(B=>({value:B.id,label:B.name}))],J=D.some(B=>B.id===b)?b:"",O=async()=>{if(!c)return k(i("Choose a member."));const B=$K({title:h,prompt:f,schedule:g,chatId:w});if(B)return k(AT(B,i));I(!0),k(null);try{const L=await window.electronAPI.bots.routines.save({botId:c,title:h,prompt:f,schedule:g,chatId:w,catchUp:j,doneBy:J||null,...n?{id:n.id,enabled:n.status!=="paused"}:{}});L.ok?s(!0):k(xu(L.error,i))}finally{I(!1)}};return o.jsx(gn,{open:!0,onOpenChange:B=>!B&&s(!1),children:o.jsxs(xn,{className:"max-h-[85vh] max-w-lg",children:[o.jsx(vn,{children:o.jsx(bn,{children:i(n?"Edit routine":"New routine")})}),o.jsxs(Rn,{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx(Bt,{children:i("Routine title")}),o.jsx(Wt,{value:h,onChange:B=>p(B.target.value)})]}),o.jsxs("div",{children:[o.jsx(Bt,{hint:i("Sent to the member as the task each time it runs"),children:i("Prompt")}),o.jsx(Ys,{rows:4,value:f,onChange:B=>x(B.target.value)})]}),o.jsx(JK,{value:g,onChange:v}),t?o.jsxs("div",{children:[o.jsx(Bt,{children:i("Member")}),o.jsxs(ms,{items:l.map(B=>({value:B.id,label:B.name})),value:c,disabled:!!n,onValueChange:B=>d(B),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:l.map(B=>o.jsx(ts,{value:B.id,children:B.name},B.id))})]})]}):o.jsxs("div",{children:[o.jsx(Bt,{children:i("Target chat")}),A.length===0?o.jsx("p",{className:"text-muted-foreground text-xs",children:i("This member is not in any chat yet. Start a private chat first.")}):o.jsxs(ms,{items:A.map(B=>({value:B,label:T(B)})),value:w,onValueChange:B=>y(B),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:A.map(B=>o.jsx(ts,{value:B,children:T(B)},B))})]})]}),D.length>0&&o.jsxs("div",{children:[o.jsx(Bt,{hint:i("Another member of the target chat runs it, as a delegation"),children:i("Done by")}),o.jsxs(ms,{items:W,value:J,onValueChange:B=>_(B),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:W.map(B=>o.jsx(ts,{value:B.value,children:B.label},B.value||"self"))})]})]}),o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(Bt,{hint:i("If the app was closed at the scheduled time, run the latest missed one once on startup"),children:i("Catch up missed runs")}),o.jsx(_i,{checked:j,onCheckedChange:N})]}),C&&o.jsx("p",{className:"text-destructive text-sm",children:C})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:()=>s(!1),children:i("Cancel")}),o.jsxs(le,{size:"sm",disabled:E,onClick:()=>{O()},children:[E&&o.jsx(Vt,{className:"animate-spin"}),i("Save")]})]})]})})}function kp(e,t){return{name:e.name,title:e.title,scope:e.scope,persona:t,color:e.avatar.color,engine:e.engine??null,tools:e.tools,approvalMode:e.approvalMode,skillIds:e.skillIds,mcpServerIds:e.mcpServerIds,canDelegateTo:e.delegation.canDelegateTo,acceptFrom:e.delegation.acceptFrom,memoryEnabled:e.memory.enabled,...wK(e.budget),...yK(e)}}function QK(e){const t=CT(e),n=Cx(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 eq(e,t){const n=zd(e),s=n?await fetch(n).then(r=>r.blob()).then(lk).catch(()=>null):null,i=xK(hM(s??await pM(e.name,e.avatar.color)),"chara",vK(JSON.stringify(SK(e,t))),["ccv3"]);if(!i)throw new Error("png");fM(new Blob([new Uint8Array(i)],{type:"image/png"}),`${e.name}.png`)}function tq({botId:e,chat:t,onOpenHistory:n}){const{t:s}=te(),i=re(T=>T.bots.find(A=>A.id===e)),r=re(T=>T.bots),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(!1),[p,f]=m.useState(!1),[x,g]=m.useState(!1),[v,w]=m.useState(null),y=m.useCallback(async()=>{const T=await window.electronAPI.bots.get(e);T.ok&&(re.getState().upsertBot(T.bot),l(T.persona),d(kp(T.bot,T.persona)),h(!1))},[e]);m.useEffect(()=>{l(null),d(null),y()},[y]);const b=m.useMemo(()=>i&&a!==null?kp(i,a):null,[i,a]),_=u&&!!(c&&b&&JSON.stringify(c)!==JSON.stringify(b));if(m.useEffect(()=>{!u&&b&&d(b)},[i?.version]),!i||!c)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Vt,{className:"h-4 w-4 animate-spin text-muted-foreground"})});const j=T=>{d(A=>A&&{...A,...T}),h(!0)},N=Wm(c.name,r,s,i.id),C=async T=>{g(!0);try{await ak(i.id,T)||We({type:"error",title:s("Avatar update failed")})}finally{g(!1)}},k=()=>{eq(i,a??"").then(()=>We({type:"success",title:s('Persona embedded in the PNG. Restore it in a new member via "Import character card".')})).catch(()=>We({type:"error",title:s("Export failed")}))},E=async()=>{const T=QK(c);if(!T){We({type:"error",title:Cx(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 A=await window.electronAPI.bots.update({botId:i.id,expectedVersion:i.version,draft:T});if(A.ok){re.getState().upsertBot(A.bot),l(c.persona),d(kp(A.bot,c.persona)),h(!1);return}We({type:"error",title:Ja(A.reason,A.error,s),...A.reason==="conflict"?{actions:[{label:s("Refresh"),onClick:()=>{y()}}]}:{}})}finally{f(!1)}},I=async()=>{const T=v;if(w(null),T==="archive"){const D=await window.electronAPI.bots.archive(i.id,!0);D.ok?re.getState().upsertBot(D.bot):We({type:"error",title:Ja(D.reason,D.error,s)});return}const A=await window.electronAPI.bots.remove(i.id);if(A.ok){re.getState().setView(null),await Promise.all([re.getState().refreshCatalog(),re.getState().refreshChats()]);return}if(A.reason==="boss"){const D=re.getState().chats,W=(A.chatIds??[]).map(J=>D.find(O=>O.id===J)).filter(J=>!!J).map(J=>bs(J,r,s));We({type:"warning",title:s("{{name}} owns group chats",{name:i.name}),description:s("Choose another owner in {{groups}} first.",{groups:W.join("、")})});return}We({type:"error",title:Ja(A.reason,A.error,s)})};return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[o.jsxs("div",{className:"flex items-center gap-3 px-4 pt-4",children:[o.jsx(Jt,{bot:{id:i.id,name:c.name||i.name,avatar:{...i.avatar,color:c.color}},size:"lg"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate font-semibold text-base",children:i.name}),o.jsx("div",{className:"truncate text-muted-foreground text-sm",children:i.title}),o.jsxs("div",{className:"mt-1 flex flex-wrap gap-1.5",children:[o.jsxs(Qp,{children:[o.jsxs(ef,{render:o.jsx(le,{size:"xs",variant:"outline",onClick:k}),children:[o.jsx(Xl,{}),s("Export character card")]}),o.jsx(tf,{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".')})]}),o.jsx(kT,{hasImage:!!i.avatar.image,disabled:x,onPick:T=>{C(T)},onRemove:()=>{C(null)}})]})]})]}),o.jsxs(Ru,{defaultValue:"profile",className:"mt-3 flex min-h-0 flex-1 flex-col",children:[o.jsxs(Lu,{variant:"underline",className:"shrink-0 px-2",children:[o.jsx(Ns,{value:"profile",children:s("Profile")}),o.jsx(Ns,{value:"abilities",children:s("Abilities")}),o.jsx(Ns,{value:"memory",children:s("Memory")}),o.jsx(Ns,{value:"routines",children:s("Routines")}),o.jsx(Ns,{value:"history",children:s("History")})]}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-3",children:[o.jsxs(no,{value:"profile",className:"space-y-3",children:[o.jsx(EK,{bot:i}),o.jsxs("div",{children:[o.jsx(Bt,{hint:s("Used for @ in groups; must be unique"),children:s("Name")}),o.jsx(Wt,{value:c.name,onChange:T=>j({name:T.target.value})}),N&&o.jsx("p",{className:"mt-1 text-destructive text-xs",children:N})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:s("Title")}),o.jsx(Wt,{value:c.title,onChange:T=>j({title:T.target.value})})]}),o.jsxs("div",{children:[o.jsx(Bt,{hint:s("Used for routing and the delegation directory"),children:s("Responsibilities")}),o.jsx(Ys,{rows:2,value:c.scope,onChange:T=>j({scope:T.target.value})})]}),o.jsxs("div",{children:[o.jsx(Bt,{action:o.jsx(DT,{value:c,onApply:j}),children:s("Persona")}),o.jsx(Ys,{rows:8,value:c.persona,onChange:T=>j({persona:T.target.value})})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:s("Avatar color")}),o.jsx(ok,{value:c.color,onChange:T=>j({color:T})})]}),o.jsxs("div",{className:"flex gap-2 border-t pt-3",children:[o.jsxs(le,{size:"xs",variant:"outline",onClick:()=>w("archive"),children:[o.jsx(ji,{}),s("Archive member")]}),o.jsxs(le,{size:"xs",variant:"destructive-outline",onClick:()=>w("delete"),children:[o.jsx(di,{}),s("Delete permanently")]})]})]}),o.jsxs(no,{value:"abilities",className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx(Bt,{children:s("Model")}),o.jsx(rk,{engine:c.engine,onChange:T=>j({engine:T})})]}),o.jsx(jT,{value:c,onChange:j,profile:c,botId:i.id})]}),o.jsxs(no,{value:"memory",children:[o.jsxs("div",{className:"mb-4",children:[o.jsx(Bt,{hint:s("Injected into every new conversation"),children:s("Core notes")}),o.jsx(IT,{target:{botId:i.id},emptyText:s("No notes yet. Key preferences and facts are summarized here automatically after memories are organized.")})]}),o.jsx(TT,{spaceId:`bot:${i.id}`,emptyText:s("No memories yet")})]}),o.jsx(no,{value:"routines",children:o.jsx(MT,{botId:i.id})}),o.jsx(no,{value:"history",children:o.jsx(nq,{chat:t,botId:i.id,onOpen:T=>n(T,i.name)})})]})]}),_&&o.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t bg-muted/50 px-4 py-2.5",children:[o.jsx(le,{size:"sm",variant:"outline",onClick:()=>{b&&d(b),h(!1)},children:s("Discard")}),o.jsxs(le,{size:"sm",disabled:p||!!N,onClick:()=>{E()},children:[p&&o.jsx(Vt,{className:"animate-spin"}),s("Save")]})]}),o.jsx(hs,{open:v!==null,onOpenChange:T=>!T&&w(null),title:v==="delete"?s("Delete {{name}}?",{name:i.name}):s("Archive {{name}}?",{name:i.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 nq({chat:e,botId:t,onOpen:n}){const{t:s}=te(),[i,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]),i===null?o.jsx(Vt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):i.length===0?o.jsx("p",{className:"text-muted-foreground text-xs",children:s("No conversations yet")}):o.jsx("div",{className:"space-y-1",children:i.map((a,l)=>o.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:[o.jsx("span",{children:s("Conversation {{n}}",{n:i.length-l})}),o.jsx("span",{className:"text-muted-foreground",children:a.current?s("Current"):s("Read-only")})]},a.conversationId))})}function vu(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 RT(e,t,n,s){const i=await window.electronAPI.bots.tasks.reply({chatId:e,id:t,text:n}),r=re.getState();return r.refreshTasks(e),r.refreshDelegations(),r.refreshInbox(),i.ok||We({type:"error",title:s("Reply not sent"),description:vu(i.error,s)}),i.ok}function Nx({placeholder:e,onSend:t,className:n}){const{t:s}=te(),[i,r]=m.useState(""),[a,l]=m.useState(!1),c=Ii(xe(u=>u.keybindings))["send-message"],d=async()=>{const u=i.trim();if(!(!u||a)){l(!0);try{await t(u)&&r("")}finally{l(!1)}}};return o.jsxs("div",{className:q("mt-1.5 flex items-end gap-1",n),children:[o.jsx(Ys,{value:i,rows:1,size:"sm",maxLength:Um,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&&tk(u,c)&&(u.preventDefault(),d())}}),o.jsx(le,{size:"icon-sm",variant:i.trim()?"default":"ghost","aria-label":s("Send reply"),disabled:!i.trim()||a,onClick:()=>{d()},children:a?o.jsx(Vt,{className:"animate-spin"}):o.jsx(Jg,{})})]})}function LT(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 OT=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),zT=(e,t)=>e.ok===void 0?t("Processing"):e.ok?t("Delivered"):t("Not delivered");function sq({appends:e}){const{t}=te();return o.jsx("ul",{className:"mt-0.5 ml-6 space-y-0.5",children:e.map(n=>o.jsxs("li",{className:"flex items-center gap-1.5 text-muted-foreground",children:[o.jsx("span",{className:"shrink-0 tabular-nums",children:OT(n.at)}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",title:n.text,children:n.text}),o.jsx("span",{className:q("shrink-0 rounded px-1.5 text-[11px]",n.ok===void 0?"bg-info/15 text-info":n.ok?"bg-success/15 text-success":"bg-destructive/15 text-destructive"),children:zT(n,t)})]},n.deliveryId))})}function iq({runs:e,bots:t,onOpenConversation:n}){const{t:s}=te(),i=re(f=>f.delegations),r=xh(e.some(f=>kl(f.state))),[a,l]=m.useState(!1),[c,d]=m.useState(null),u=GK(e,i,r),h=a?u:u.slice(-5),p=f=>t.get(f)?.name??s("Deleted member");return o.jsxs("section",{className:"mt-1.5 border-t pt-1.5",children:[o.jsxs("h5",{className:"mb-1 text-[11px] text-muted-foreground",children:[s("Run history")," · ",u.length]}),o.jsx("ul",{className:"space-y-1",children:h.map(({run:f,record:x,time:g})=>{const v=f.state==="failed"?vc(x??f,s):void 0,w=x?.appends??[];return o.jsxs("li",{className:q(f.nested&&"ml-3 border-l pl-2"),children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-muted-foreground",children:[o.jsx(Jt,{bot:t.get(f.botId),size:"xs"}),o.jsx("span",{className:"text-foreground",children:p(f.botId)}),o.jsxs("span",{children:["· ",f.nested?s("Sub-delegation"):LT(f.trigger,s)]}),g.queued?o.jsx("span",{className:"rounded bg-info/15 px-1.5 text-[11px] text-info",children:s("Queued {{time}}",{time:ho(g.ms)})}):o.jsxs(o.Fragment,{children:[o.jsx(gh,{state:f.state,interrupted:f.failure==="interrupted"}),o.jsx("span",{children:ho(g.ms)})]}),f.appends&&o.jsx("button",{type:"button","aria-expanded":c===f.id,disabled:!w.length,title:w.map(y=>`${OT(y.at)} ${y.text} · ${zT(y,s)}`).join(`
82
- `),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})}),o.jsx("span",{className:"flex-1"}),x&&o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>n(x.childConversationId,s("{{from}} → {{to}} · Delegation",{from:p(x.parentBotId),to:p(x.targetBotId)})),children:s("View process")})]}),c===f.id&&w.length>0&&o.jsx(sq,{appends:w}),v&&o.jsx("div",{className:"mt-0.5 line-clamp-2 whitespace-pre-wrap text-destructive",children:v})]},f.id)})}),u.length>h.length&&o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>l(!0),children:s("Show all ({{n}})",{n:u.length})})]})}const am=5,oq=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function to({title:e,count:t,limit:n,children:s}){const{t:i}=te(),[r,a]=m.useState(!1),l=n&&!r?Math.min(n,t):t;return o.jsxs("section",{className:"mt-4 first:mt-0",children:[o.jsxs("h4",{className:"mb-1.5 font-medium text-[11px] text-muted-foreground uppercase tracking-wide",children:[e," · ",t]}),o.jsx("div",{className:"space-y-1.5",children:s(l)}),t>l&&o.jsx(le,{size:"xs",variant:"ghost",className:"mt-1",onClick:()=>a(!0),children:i("Show all ({{n}})",{n:t})})]})}function rq({chat:e,onOpenConversation:t}){const{t:n}=te(),s=re(k=>k.tasks[e.id]),i=re(k=>k.bots),r=re(k=>k.delegations),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(null),p=re(k=>k.taskFocus),[f,x]=m.useState(null),g=m.useRef(null),v=xh(!!s?.some(k=>k.status==="blocked")),w=m.useMemo(()=>new Map(i.map(k=>[k.id,k])),[i]),y=e.members.flatMap(k=>{const E=w.get(k);return E&&E.archivedAt===void 0?[E]:[]});m.useEffect(()=>{re.getState().refreshTasks(e.id)},[e.id]),m.useEffect(()=>{!p||p.chatId!==e.id||!s||(re.getState().clearTaskFocus(p.nonce),s.some(k=>k.id===p.taskId)&&(x(p.taskId),requestAnimationFrame(()=>g.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(()=>x(null),2e3);return()=>clearTimeout(k)},[f]);const b=async(k,E)=>{const I=await k();I.ok||We({type:"error",title:E,description:vu(I.error??"",n)}),re.getState().refreshTasks(e.id)},_=window.electronAPI.bots.tasks,j=k=>({chatId:e.id,id:k.id});if(!s)return o.jsx(Vt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const N=RK(s),C=k=>o.jsx(aq,{task:k,bots:w,members:y,onOpenConversation:t,block:FK(k,r),now:v,highlighted:f===k.id,onEdit:()=>l(k),onAssign:E=>{b(()=>_.assign({...j(k),botId:E}),n("Task not assigned"))},onComplete:()=>{b(()=>_.complete(j(k)),n("Task not updated"))},onAccept:()=>{b(()=>_.review({...j(k),accept:!0}),n("Task not updated"))},onReturn:E=>h({task:k,rework:E}),onCancel:()=>{b(()=>_.cancel(j(k)),n("Task not updated"))},onDelete:()=>d(k),onReply:E=>RT(e.id,k.id,E,n)},k.id);return o.jsxs("div",{ref:g,children:[o.jsxs(le,{size:"xs",variant:"outline",className:"mb-3",onClick:()=>l("new"),children:[o.jsx(ps,{}),n("New task")]}),s.length===0&&o.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&&o.jsx(to,{title:n("To do"),count:N.todo.length,children:()=>N.todo.map(C)}),N.doing.length>0&&o.jsx(to,{title:n("Doing"),count:N.doing.length,children:()=>N.doing.map(C)}),N.blocked.length>0&&o.jsx(to,{title:n("Stuck tasks"),count:N.blocked.length,children:()=>N.blocked.map(C)}),N.review.length>0&&o.jsx(to,{title:n("Awaiting review"),count:N.review.length,children:()=>N.review.map(C)}),N.done.length>0&&o.jsx(to,{title:n("Completed"),count:N.done.length,limit:am,children:k=>N.done.slice(0,k).map(C)}),N.canceled.length>0&&o.jsx(to,{title:n("Canceled"),count:N.canceled.length,limit:0,children:k=>N.canceled.slice(0,k).map(C)}),a&&o.jsx(dq,{chatId:e.id,task:a==="new"?void 0:a,onClose:k=>{l(null),k&&re.getState().refreshTasks(e.id)}}),u&&o.jsx(cq,{task:u.task,assignee:w.get(u.task.assigneeBotId??"")?.name??n("Deleted member"),rework:u.rework,onClose:()=>h(null),onReturn:k=>_.review({...j(u.task),accept:!1,reason:k,...u.rework?{rework:!0}:{}}).then(E=>(E.ok&&(h(null),re.getState().refreshTasks(e.id)),E.ok?null:vu(E.error,n)))}),o.jsx(hs,{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&&b(()=>_.remove(j(k)),n("Task not deleted"))}})]})}function aq({task:e,bots:t,members:n,onOpenConversation:s,onEdit:i,onAssign:r,onComplete:a,onAccept:l,onReturn:c,onCancel:d,onDelete:u,onReply:h,block:p,now:f,highlighted:x}){const{t:g}=te(),v=e.status==="todo"||e.status==="doing"||e.status==="blocked",w=e.status==="review",y=ik(e),b=e.assigneeBotId?t.get(e.assigneeBotId):void 0,_=e.createdBy==="human"?g("You"):t.get(e.createdBy)?.name??g("Deleted member");return o.jsxs("div",{"data-slot":"bot-card","data-task-id":e.id,className:q("group rounded-lg border bg-card px-2.5 py-2 text-xs transition-shadow",!v&&!w&&"opacity-75",x&&"ring-2 ring-brand/60"),children:[o.jsxs("div",{className:"flex items-start gap-1.5",children:[o.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["#",e.seq]}),o.jsx("span",{className:"min-w-0 flex-1 break-words font-medium text-sm",children:e.title}),o.jsxs(zi,{children:[o.jsx(Gi,{className:"rounded p-1 text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 data-popup-open:opacity-100",children:o.jsx(sh,{className:"h-3.5 w-3.5"})}),o.jsxs(Fi,{align:"end",children:[o.jsxs(dn,{onClick:i,children:[o.jsx(Xs,{}),g("Edit")]}),v&&(!e.delegationId||e.status==="blocked"||y)&&n.length>0&&o.jsxs(dk,{children:[o.jsxs(uk,{children:[o.jsx(Ml,{}),e.assigneeBotId?g("Reassign to"):g("Assign to")]}),o.jsx(hk,{children:n.map(j=>o.jsxs(dn,{disabled:j.id===e.assigneeBotId,onClick:()=>r(j.id),children:[o.jsx(Jt,{bot:j,size:"xs"}),j.name]},j.id))})]}),v&&!y&&o.jsxs(dn,{onClick:a,children:[o.jsx(Jn,{}),g("Mark done")]}),(v||w)&&o.jsxs(dn,{onClick:d,children:[o.jsx(ln,{}),g("Cancel task")]}),o.jsx(pa,{}),o.jsxs(dn,{variant:"destructive",onClick:u,children:[o.jsx(di,{}),g("Delete")]})]})]})]}),e.detail&&o.jsx("div",{className:"mt-1 line-clamp-3 whitespace-pre-wrap text-muted-foreground",children:e.detail}),e.result&&o.jsx("div",{className:q("mt-1 rounded px-1.5 py-1 text-foreground",e.status!=="done"&&e.check?.passed===!1?"bg-destructive/10":"bg-success/10"),children:o.jsx("div",{className:"line-clamp-3 whitespace-pre-wrap",children:e.result})}),e.returnReason&&o.jsx("div",{className:"mt-1 rounded bg-warning/10 px-1.5 py-1 text-foreground",children:o.jsx("div",{className:"line-clamp-3 whitespace-pre-wrap",children:g("Returned: {{reason}}",{reason:e.returnReason})})}),p&&o.jsx(lq,{block:p,now:f,assignee:b,bots:t,members:n,assigneeBotId:e.assigneeBotId,onRetry:()=>y&&xl(y.id,g),onAssign:r,onCancel:d,onReply:h}),!p&&(w||e.status==="doing"&&e.delegationId)&&o.jsx(Nx,{placeholder:g(w?"Comment…":"Add to the current run…"),onSend:h}),e.check&&o.jsx(fT,{check:e.check,className:"mt-1"}),w&&o.jsxs("div",{className:"mt-1.5 flex gap-1.5",children:[o.jsxs(le,{size:"xs",onClick:l,children:[o.jsx(Jn,{}),g("Accept result")]}),o.jsxs(le,{size:"xs",variant:"outline",onClick:()=>c(!1),children:[o.jsx(ra,{}),g("Return")]}),LK(e)&&o.jsxs(le,{size:"xs",variant:"outline",onClick:()=>c(!0),children:[o.jsx(Km,{}),g("Return for rework")]})]}),o.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-muted-foreground",children:[b||e.assigneeBotId?o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(Jt,{bot:b,size:"xs"}),b?.name??g("Deleted member")]}):o.jsx("span",{children:g("Unassigned")}),e.delegationId&&o.jsxs("span",{children:["· ",g("Delegation")]}),o.jsx("span",{className:"flex-1"}),o.jsx("span",{title:g("Created by {{name}}",{name:_}),children:oq(e.updatedAt)})]}),e.runs&&e.runs.length>0&&o.jsx(iq,{runs:e.runs,bots:t,onOpenConversation:s})]})}function lq({block:e,now:t,assignee:n,assigneeBotId:s,bots:i,members:r,onRetry:a,onAssign:l,onCancel:c,onReply:d}){const{t:u}=te(),h=n?.name??u("Deleted member"),p=u("Stuck for {{time}}",{time:ho(t-e.since)});if(e.reason==="need"){const x=e.waitFor==="human"?u("Waiting for your reply"):u("Waiting for {{name}} to reply",{name:i.get(e.waitFor)?.name??u("Deleted member")});return o.jsxs("div",{className:"mt-1.5 rounded-md border border-warning/30 bg-warning/10 px-2 py-1.5 text-foreground",children:[o.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:u("Blocked · needs: {{need}}",{need:e.need})}),o.jsxs("div",{className:"mt-0.5 text-muted-foreground",children:[x," · ",p]}),e.humanOnly&&o.jsx("div",{className:"mt-0.5 text-muted-foreground",children:u("Stuck several times in a row; only you can answer now.")}),o.jsx(Nx,{placeholder:u("Answer {{name}}; they continue after your reply…",{name:h}),onSend:d})]})}const f=e.record?.state==="failed"&&vc(e.record,u)||u("Failed");return o.jsxs("div",{className:"mt-1.5 rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-foreground",children:[o.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:u("Blocked · run failed: {{reason}}",{reason:f})}),o.jsxs("div",{className:"mt-0.5 text-muted-foreground",children:[u("Waiting for you to handle it")," · ",p]}),o.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[o.jsxs(le,{size:"xs",variant:"outline",onClick:a,children:[o.jsx(qm,{}),u("Retry")]}),r.length>0&&o.jsxs(zi,{children:[o.jsxs(Gi,{render:o.jsx(le,{size:"xs",variant:"outline"}),children:[o.jsx(Ml,{}),u("Reassign")]}),o.jsx(Fi,{align:"start",children:r.map(x=>o.jsxs(dn,{disabled:x.id===s,onClick:()=>l(x.id),children:[o.jsx(Jt,{bot:x,size:"xs"}),x.name]},x.id))})]}),o.jsxs(le,{size:"xs",variant:"outline",onClick:c,children:[o.jsx(ln,{}),u("Cancel task")]})]})]})}function cq({task:e,assignee:t,rework:n,onClose:s,onReturn:i}){const{t:r}=te(),[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 i(a.trim()))}finally{h(!1)}};return o.jsx(gn,{open:!0,onOpenChange:f=>!f&&s(),children:o.jsxs(xn,{className:"max-w-lg",children:[o.jsx(vn,{children:o.jsx(bn,{children:n?r("Return task #{{n}} for rework",{n:e.seq}):r("Return task #{{n}}",{n:e.seq})})}),o.jsxs(Rn,{className:"space-y-2",children:[o.jsx(Bt,{children:r("Reason for returning")}),o.jsx(Ys,{rows:4,autoFocus:!0,value:a,maxLength:Um,onChange:f=>l(f.target.value)}),o.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&&o.jsx("p",{className:"text-destructive text-sm",children:c})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:s,children:r("Cancel")}),o.jsxs(le,{size:"sm",disabled:u,onClick:()=>{p()},children:[u&&o.jsx(Vt,{className:"animate-spin"}),r(n?"Return for rework":"Return")]})]})]})})}function dq({chatId:e,task:t,onClose:n}){const{t:s}=te(),[i,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),x=async()=>{if(!i.trim())return h(s("Enter a title."));f(!0);try{const g=await window.electronAPI.bots.tasks.save({chatId:e,title:i.trim(),detail:a.trim(),check:c.trim(),...t?{id:t.id}:{}});g.ok?n(!0):h(vu(g.error,s))}finally{f(!1)}};return o.jsx(gn,{open:!0,onOpenChange:g=>!g&&n(!1),children:o.jsxs(xn,{className:"max-w-lg",children:[o.jsx(vn,{children:o.jsx(bn,{children:t?s("Edit task #{{n}}",{n:t.seq}):s("New task")})}),o.jsxs(Rn,{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx(Bt,{children:s("Task title")}),o.jsx(Wt,{value:i,maxLength:mM,onChange:g=>r(g.target.value)})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:s("Details")}),o.jsx(Ys,{rows:4,value:a,maxLength:Um,onChange:g=>l(g.target.value)})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:s("Acceptance check (optional)")}),o.jsx(Wt,{value:c,maxLength:gM,onChange:g=>d(g.target.value)}),o.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&&o.jsx("p",{className:"text-destructive text-sm",children:u})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),o.jsxs(le,{size:"sm",disabled:p,onClick:()=>{x()},children:[p&&o.jsx(Vt,{className:"animate-spin"}),s("Save")]})]})]})})}function uq({chat:e,onOpenConversation:t}){const{t:n}=te(),s=re(c=>c.delegations),i=re(c=>c.bots),r=m.useMemo(()=>new Map(i.map(c=>[c.id,c])),[i]),a=m.useMemo(()=>zK(s,e.id),[s,e.id]),l=c=>o.jsx(vh,{record:c,retried:ck(c,s),bots:r,onOpenConversation:t},c.id);return!a.active.length&&!a.completed.length&&!a.failed.length?o.jsx("p",{className:"text-muted-foreground text-xs",children:n("No delegations in this group yet")}):o.jsxs("div",{children:[a.active.length>0&&o.jsx(to,{title:n("In progress"),count:a.active.length,children:()=>a.active.map(l)}),a.completed.length>0&&o.jsx(to,{title:n("Completed"),count:a.completed.length,limit:am,children:c=>a.completed.slice(0,c).map(l)}),a.failed.length>0&&o.jsx(to,{title:n("Failed · interrupted · canceled"),count:a.failed.length,limit:am,children:c=>a.failed.slice(0,c).map(l)})]})}const hq=(e,t)=>e.workspace.kind===t.kind&&(t.kind!=="project"||e.workspace.kind==="project"&&e.workspace.projectId===t.projectId);function GT({chat:e,className:t}){const{t:n}=te(),s=xe(f=>f.projects),i=re(f=>f.bots),r=re(f=>f.upsertChat),[a,l]=m.useState(!1),[c,d]=m.useState(null),u=pk(e,s,i,n),h=[e.kind==="direct"?{input:{kind:"member-home"},label:n("Member's own workspace")}:{input:{kind:"chat-home"},label:n("Standalone workspace")},...Ou(s).map(f=>({input:{kind:"project",projectId:f.id},label:f.alias||f.name}))],p=async f=>{const x=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,workspace:f});x.ok?r(x.chat):We({type:"error",title:Cs(x.error,n)})};return o.jsxs(o.Fragment,{children:[o.jsxs(Pi,{open:a,onOpenChange:l,children:[o.jsxs(Ei,{className:q("flex h-7 min-w-0 max-w-56 @max-[28rem]:max-w-32 @max-[21rem]:max-w-24 items-center gap-1.5 whitespace-nowrap rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground",t),title:n("Workspace"),children:[o.jsx(uc,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"truncate",children:u}),o.jsx($n,{className:"h-3 w-3 shrink-0 opacity-60"})]}),o.jsxs(Ai,{side:"bottom",align:"end",className:"w-64 [&_[data-slot=popover-viewport]]:p-1",children:[o.jsxs("button",{type:"button",onClick:()=>{l(!1),window.electronAPI.bots.openWorkspace({chatId:e.id}).then(f=>{f.ok||We({type:"error",title:Cs(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:[o.jsx(Qs,{className:"h-3.5 w-3.5 shrink-0"}),n("Open folder")]}),o.jsx("div",{className:"my-1 border-t"}),o.jsx("div",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:n("Change workspace")}),o.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map(f=>{const x=hq(e,f.input);return o.jsxs("button",{type:"button",onClick:()=>{l(!1),x||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:[o.jsx("span",{className:"min-w-0 flex-1 truncate",children:f.label}),x&&o.jsx(Jn,{className:"h-3.5 w-3.5 shrink-0 text-brand"})]},f.input.kind==="project"?f.input.projectId:f.input.kind)})})]})]}),o.jsx(hs,{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 $o({title:e,children:t}){return o.jsxs("section",{className:"mt-5",children:[o.jsx("h4",{className:"mb-1.5 font-medium text-[11px] text-muted-foreground uppercase tracking-wide",children:e}),t]})}function _p({label:e,value:t}){return o.jsxs("div",{className:"flex justify-between gap-3 border-b border-dashed py-1.5 text-xs",children:[o.jsx("span",{className:"shrink-0 text-muted-foreground",children:e}),o.jsx("span",{className:"min-w-0 truncate text-right",children:t})]})}async function FT(e,t){const n={};for(const s of e.members){const i=await window.electronAPI.bots.get(s);if(!i.ok)return null;n[s]=i.persona}return wM(e,t,n,new Date().toISOString())}async function pq(e,t){const n=await FT(e,t);if(!n)return!1;const s=URL.createObjectURL(new Blob([JSON.stringify(n,null,2)],{type:"application/json"})),i=document.createElement("a");return i.href=s,i.download=`${e.title||"team"}.team.json`,i.click(),URL.revokeObjectURL(s),!0}async function fq(e,t){const n=await FT(e,t),s=n&&xM(vM(n.team));return s?bM(i=>({...i,teams:yM(i.teams,s,crypto.randomUUID())})):!1}function mq({chat:e,thread:t=e,onOpenConversation:n}){const{t:s}=te(),i=re(D=>D.bots),r=re(D=>D.runtime[t.id]),a=re(D=>D.upsertChat),l=re(D=>D.openDirect),c=xe(D=>D.projects),d=m.useMemo(()=>new Map(i.map(D=>[D.id,D])),[i]),[u,h]=m.useState(e.title),[p,f]=m.useState(String(e.routing.maxHops)),[x,g]=m.useState(String(e.routing.maxTurnsPerBot)),[v,w]=m.useState(!1),[y,b]=m.useState("info"),_=re(D=>D.taskFocus);m.useEffect(()=>{_?.chatId===e.id&&b("board")},[_,e.id]),m.useEffect(()=>{h(e.title),f(String(e.routing.maxHops)),g(String(e.routing.maxTurnsPerBot))},[e.title,e.routing.maxHops,e.routing.maxTurnsPerBot]);const j=async D=>{const W=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,...D});W.ok?a(W.chat):(We({type:"error",title:Cs(W.error,s)}),re.getState().refreshChats())},N=e.members.map(D=>({id:D,bot:d.get(D)})),C=e.routing.muted??[],k=i.filter(D=>!D.archivedAt&&!e.members.includes(D.id)),E=D=>D?d.get(D)?.name??"?":"—",I=e.workspace.kind==="project"?c.find(D=>e.workspace.kind==="project"&&D.id===e.workspace.projectId):void 0,T=p!==String(e.routing.maxHops)||x!==String(e.routing.maxTurnsPerBot),A=[{value:"boss",label:s("Group owner replies")},{value:"smart",label:s("Smart pick")}];return o.jsxs(Ru,{value:y,onValueChange:D=>b(String(D)),className:"flex min-h-0 flex-1 flex-col",children:[o.jsxs(Lu,{variant:"underline",className:"shrink-0 px-2 pt-2",children:[o.jsx(Ns,{value:"info",children:s("Group info")}),o.jsx(Ns,{value:"board",children:s("Task board")}),o.jsx(Ns,{value:"delegations",children:s("Delegations")}),o.jsx(Ns,{value:"routines",children:s("Routines")})]}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:[o.jsx(no,{value:"board",children:o.jsx(rq,{chat:e,onOpenConversation:n})}),o.jsx(no,{value:"delegations",children:o.jsx(uq,{chat:t,onOpenConversation:n})}),o.jsx(no,{value:"routines",children:o.jsx(MT,{chatId:e.id})}),o.jsxs(no,{value:"info",children:[o.jsx(Wt,{className:"mt-2",value:u,placeholder:s("Group name"),onChange:D=>h(D.target.value),onBlur:()=>u.trim()!==e.title&&void j({title:u.trim()}),onKeyDown:D=>D.key==="Enter"&&D.currentTarget.blur()}),o.jsxs($o,{title:s("Members"),children:[N.map(({id:D,bot:W})=>o.jsxs("div",{className:"group flex items-center gap-2 rounded-lg py-1.5",children:[o.jsxs("button",{type:"button",onClick:()=>{l(D)},className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[o.jsx(vT,{chatId:t.id,botId:D,bot:W}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[o.jsx("span",{className:"truncate",children:W?.name??s("Deleted member")}),e.bossBotId===D&&o.jsx("span",{className:"shrink-0 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:s("Owner")}),C.includes(D)&&o.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:[o.jsx(vb,{className:"h-2.5 w-2.5"}),s("Muted")]})]}),o.jsx("div",{className:"truncate text-muted-foreground text-xs",children:W?.scope||W?.title})]})]}),o.jsxs(zi,{children:[o.jsx(Gi,{className:"rounded p-1 text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 data-popup-open:opacity-100",children:o.jsx(sh,{className:"h-3.5 w-3.5"})}),o.jsxs(Fi,{align:"end",children:[o.jsxs(dn,{disabled:e.bossBotId===D,onClick:()=>{j({bossBotId:D})},children:[o.jsx(fk,{}),s("Make owner")]}),o.jsxs(dn,{disabled:e.bossBotId===D,onClick:()=>{j({routing:{muted:C.includes(D)?C.filter(J=>J!==D):[...C,D]}})},children:[o.jsx(vb,{}),C.includes(D)?s("Unmute"):s("Mute")]}),o.jsxs(dn,{disabled:e.bossBotId===D||e.members.length<=2,onClick:()=>{j({members:e.members.filter(J=>J!==D)})},children:[o.jsx(yV,{}),s("Remove from group")]})]})]})]},D)),o.jsxs(Pi,{open:v,onOpenChange:w,children:[o.jsxs(Ei,{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:[o.jsx(ps,{className:"h-3.5 w-3.5"}),s("Add member")]}),o.jsx(Ai,{side:"bottom",align:"start",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:k.map(D=>o.jsxs("button",{type:"button",onClick:()=>{w(!1),j({members:[...e.members,D.id]})},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted",children:[o.jsx(Jt,{bot:D,size:"sm"}),o.jsx("span",{className:"min-w-0 truncate",children:D.name})]},D.id))})]})]}),o.jsxs($o,{title:s("Reply queue"),children:[o.jsx(_p,{label:s("Current"),value:r?.current?`${E(r.current)}(${s("relay {{n}}/{{max}}",{n:r.hops,max:e.routing.maxHops})})`:r?.routing?s("Choosing who replies…"):"—"}),o.jsx(_p,{label:s("Waiting"),value:r?.queue.length?r.queue.map(D=>E(D)).join("、"):"—"}),o.jsx(_p,{label:s("Per-member limit"),value:s("{{n}} replies",{n:e.routing.maxTurnsPerBot})})]}),o.jsx($o,{title:s("Workspace"),children:o.jsxs("div",{"data-slot":"bot-card",className:"rounded-lg border bg-card px-2.5 py-2",children:[o.jsx(GT,{chat:e,className:"w-full max-w-none"}),o.jsxs("p",{className:"mt-1.5 text-muted-foreground text-xs",children:[I?`${I.path} · `:"",s("Shared by all members")]})]})}),o.jsxs($o,{title:s("Routing limits"),children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:s("Without @")}),o.jsxs(ms,{items:A,value:e.routing.mode,onValueChange:D=>{D!==e.routing.mode&&j({routing:{mode:D}})},children:[o.jsx(gs,{size:"sm",className:"w-40",children:o.jsx(xs,{})}),o.jsx(vs,{children:A.map(D=>o.jsx(ts,{value:D.value,children:D.label},D.value))})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("label",{className:"space-y-1",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:s("@ relay limit")}),o.jsx(Wt,{type:"number",min:1,max:20,value:p,onChange:D=>f(D.target.value)})]}),o.jsxs("label",{className:"space-y-1",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:s("Replies per member")}),o.jsx(Wt,{type:"number",min:1,max:10,value:x,onChange:D=>g(D.target.value)})]})]}),T&&o.jsx(le,{size:"xs",className:"mt-2",onClick:()=>{j({routing:{maxHops:Math.round(Number(p))||e.routing.maxHops,maxTurnsPerBot:Math.round(Number(x))||e.routing.maxTurnsPerBot}})},children:s("Save")})]}),o.jsx($o,{title:s("Group notes"),children:o.jsx(IT,{target:{chatId:e.id},emptyText:s("No group notes yet. Group conventions and decisions are summarized here automatically after memories are organized.")})}),o.jsx($o,{title:s("Group memory"),children:o.jsx(TT,{spaceId:`chat:${e.id}`,emptyText:s("No group memories yet")})}),o.jsxs($o,{title:s("Team"),children:[o.jsxs(le,{size:"xs",variant:"outline",onClick:()=>{pq(e,i).then(D=>D||We({type:"error",title:s("Export failed")}))},children:[o.jsx(Xl,{}),s("Export team")]}),o.jsxs(le,{size:"xs",variant:"outline",className:"ml-1.5",onClick:()=>{fq(e,i).then(D=>We(D?{type:"success",title:s("Saved as team template")}:{type:"error",title:s("Could not save as team template")}))},children:[o.jsx(PH,{}),s("Save as team template")]}),o.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 gq(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[i,r]of n)r===s.retryOf&&n.delete(i);return new Set(n.values())}function xq(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 vq(e,t){const n=String(t),s=`${n}-`;return e.find(i=>i.key===n||i.key.startsWith(s))?.key}function bq(e){return e.earliest===void 0?"wait":e.target>=e.earliest?"scroll":e.loading?"wait":e.hasOlder?"load":"give-up"}function wq(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 yq(e,t){const n=[];let s=0;for(const[i,r]of t)i<s||r<=i||r>e.length||(i>s&&n.push({text:e.slice(s,i),match:!1}),n.push({text:e.slice(i,r),match:!0}),s=r);return s<e.length&&n.push({text:e.slice(s),match:!1}),n}function Sq({chatId:e,bots:t}){const{t:n}=te(),s=re(a=>a.queue),[i,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 o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[o.jsxs("span",{children:[l," · ",n("Queued")]}),a.canInterject&&o.jsx(le,{size:"sm",variant:"ghost",disabled:i!==null,onClick:async()=>{if(a.deliveryId){r(a.deliveryId);try{const c=await window.electronAPI.bots.interjectQueued(e,a.deliveryId);c.ok||We({type:"error",title:c.error})}catch{We({type:"error",title:n("Failed to send")})}finally{r(null)}}},children:n("Insert into {{name}}’s current task",{name:l})})]},a.deliveryId)})}const Cq=(e,t)=>t?e.find(n=>n.conversationId===t):void 0,kq=(e,t)=>Math.max(0,Math.floor((t-e)/1e3));function HT({since:e}){const{t}=te(),[n,s]=m.useState(()=>Date.now());return m.useEffect(()=>{const i=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(i)},[]),o.jsx(o.Fragment,{children:t("Quiet for {{n}}s",{n:kq(e,n)})})}function BT({conversationId:e,className:t}){const n=re(s=>Cq(s.silences,e)?.since);return n===void 0?null:o.jsx("span",{className:t??"shrink-0 text-warning",children:o.jsx(HT,{since:n})})}const Dd=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),_q={smart:"Smart pick","smart:build":"Smart pick · build","smart:answer":"Smart pick · answer","smart:discuss":"Smart pick · discuss",summary:"Owner summary"};function jq({chat:e,bots:t,timeline:n,runtime:s,delegations:i,focus:r,onFocusDone:a,onLoadOlder:l,onLoadNewer:c,onLoadAround:d,onJumpLatest:u,onOpenConversation:h,onOpenLive:p}){const{t:f}=te(),x=m.useRef(null),g=m.useRef(!0),v=m.useRef(h);v.current=h;const w=m.useCallback((X,z)=>v.current(X,z),[]),y=m.useRef(null),b=m.useRef(!1),_=n?.entries??[],j=gq(_,e.epochSeq??0),N=n?.history,C=e.epochSeq??0,[k,E]=m.useState(!1);m.useEffect(()=>E(!1),[e.id,C]);const I=C>0&&!k&&!N,T=m.useMemo(()=>I?_.filter(X=>X.seq>=C):_,[_,I,C]),A=m.useMemo(()=>_M(T),[T]),D=()=>{I&&n?.hasOlder&&!n.loading&&!_.some(X=>X.seq<C)&&(he(),l()),E(I)},W=m.useMemo(()=>{const X=new Map;if(!N)for(const z of A)z.kind==="entry"&&z.entry.kind==="bot"&&!z.continued&&X.set(z.entry.botId,z.entry.id);return new Set(X.values())},[A,N]),J=m.useMemo(()=>new Map(i.map(X=>[X.id,{record:X,retried:ck(X,i)}])),[i]),O=m.useMemo(()=>i.filter(X=>X.state==="queued"||X.state==="running").sort((X,z)=>X.createdAt-z.createdAt),[i]),B=m.useMemo(()=>jM(T,NM(O)),[T,O]),L=re(X=>X.tasks[e.id]),se=O.some(X=>X.appends?.length);m.useEffect(()=>{se&&!L&&re.getState().refreshTasks(e.id)},[se,L,e.id]);const Q=({key:X,record:z,append:ue})=>o.jsx(vh,{record:z,append:ue,taskSeq:ue&&L?.find(_e=>_e.id===z.taskId)?.seq,bots:t,onOpenConversation:h},X),V=s?.current?t.get(s.current):void 0,H=s?.current?e.sessions[s.current]?.conversationId:void 0,ne=re(X=>H?X.sessions[H]?.messages.length:void 0);m.useLayoutEffect(()=>{const X=x.current;X&&(X.scrollTop=X.scrollHeight),g.current=!0},[e.id]);const he=()=>{const X=x.current;if(!X)return;const z=X.getBoundingClientRect().top;for(const ue of X.querySelectorAll("[data-seq]")){const _e=ue.getBoundingClientRect();if(!(_e.bottom<=z)){y.current={seq:Number(ue.dataset.seq),top:_e.top-z};return}}};m.useLayoutEffect(()=>{const X=x.current;if(!X)return;const z=y.current;!n?.loading&&!n?.loadingNewer&&(y.current=null);const _e=b.current&&!N;b.current=!!N;const Ee=z&&X.querySelector(`[data-seq="${z.seq}"]`);if(z&&Ee){X.scrollTop+=Ee.getBoundingClientRect().top-X.getBoundingClientRect().top-z.top;return}_e&&(g.current=!0),g.current&&!N&&(X.scrollTop=X.scrollHeight)},[T,N,n?.loading,n?.loadingNewer,O.length,V?.id,ne,s?.routing]);const pe=()=>{const X=x.current;if(!X||!n)return;const z=X.scrollHeight-X.scrollTop-X.clientHeight;g.current=z<40,y.current&&he(),!(T.length===0||I&&(_[0]?.seq??0)<=C)&&(X.scrollTop<80&&n.hasOlder&&!n.loading&&(he(),l()),z<80&&N&&!n.loadingNewer&&(he(),c()))},[ke,Me]=m.useState(null),fe=m.useRef(null),[F,U]=m.useState(null);m.useLayoutEffect(()=>{if(!r||fe.current===r.nonce)return;if(I&&r.seq<C){E(!0);return}const X=T[0]?.seq,z=T.at(-1)?.seq,ue=F?.nonce===r.nonce?F:null,_e=wq({target:r.seq,range:n?X===void 0||z===void 0?null:[X,z]:void 0,loading:!!(ue&&!ue.done),jumped:!!ue?.done});if(_e!=="wait"){if(_e==="jump"){const Ee=r.nonce;g.current=!1,y.current=null,U({nonce:Ee,done:!1}),d(r.seq).finally(()=>U(Be=>Be?.nonce===Ee?{nonce:Ee,done:!0}:Be));return}fe.current=r.nonce,a?.(r.nonce),_e==="scroll"&&(g.current=!1,y.current=null,Me(r.seq),x.current?.querySelector(`[data-seq="${r.seq}"]`)?.scrollIntoView({block:"center"}))}},[r,T,n===void 0,F,I]),m.useEffect(()=>{if(ke===null)return;const X=window.setTimeout(()=>Me(null),2500);return()=>window.clearTimeout(X)},[ke]);const de=()=>{g.current=!0,y.current=null,u()},Y=N&&n?n.lastSeq-N.sinceSeq:0;return o.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[o.jsx("div",{ref:x,onScroll:pe,className:"min-h-0 flex-1 select-text overflow-y-auto",children:o.jsx("div",{className:"@container",children:o.jsxs("div",{className:q(fi,"flex flex-col gap-3 py-4"),children:[n?.loading&&o.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:o.jsx(Vt,{className:"h-4 w-4 animate-spin"})}),n&&!n.hasOlder&&!I&&T.length>0&&o.jsx("div",{className:"text-center text-[11px] text-muted-foreground",children:f("Beginning of the chat")}),!n&&o.jsx("div",{className:"flex justify-center py-6 text-muted-foreground",children:o.jsx(Vt,{className:"h-4 w-4 animate-spin"})}),n&&T.length===0&&o.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.")}),B.head.map(Q),A.map(X=>X.kind==="day"?o.jsx("div",{className:"py-1 text-center text-[11px] text-muted-foreground",children:new Date(X.at).toLocaleDateString()},X.key):o.jsxs(m.Fragment,{children:[C>0&&!N&&X.entry.seq===C&&o.jsxs("button",{type:"button",onClick:D,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:[I?o.jsx(kn,{className:"h-3.5 w-3.5"}):o.jsx($n,{className:"h-3.5 w-3.5"}),I?f("Earlier conversation · {{n}} messages",{n:C-1}):f("Collapse earlier conversation")]}),o.jsx("div",{"data-seq":X.entry.seq,className:q("-mx-2 flex flex-col rounded-lg px-2 transition-colors duration-500",ke===X.entry.seq&&"bg-brand/10"),children:o.jsx(Nq,{chatId:e.id,entry:X.entry,continued:X.continued,latest:W.has(X.entry.id),retryable:j.has(X.entry.id)&&e.archivedAt===void 0,retryBusy:!!(s?.current||s?.routing),bots:t,records:J,onOpenConversation:w})}),B.after.get(X.entry.id)?.map(Q)]},X.key)),n?.loadingNewer&&o.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:o.jsx(Vt,{className:"h-4 w-4 animate-spin"})}),!N&&!V&&s?.routing&&o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[o.jsx(Sy,{}),f("Choosing who replies…")]}),!N&&o.jsx(Sq,{chatId:e.id,bots:t}),!N&&V&&o.jsxs("button",{type:"button",disabled:!H,title:f("View live"),onClick:()=>H&&p(H,V.id),className:"-mx-2 flex gap-2.5 rounded-lg px-2 py-1 text-left hover:bg-muted/60 disabled:pointer-events-none",children:[o.jsx(Jt,{bot:V,size:"sm",busy:!0}),o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"text-muted-foreground text-xs",children:[o.jsx("span",{className:"mr-1.5 font-semibold text-foreground",children:V.name}),f("Replying")]}),o.jsx(pT,{conversationId:H,leading:o.jsx(Sy,{}),trailing:o.jsxs(o.Fragment,{children:[o.jsx(BT,{conversationId:H}),H&&o.jsx("span",{className:"shrink-0 underline-offset-2 hover:underline",children:f("View live")})]})})]})]})]})})}),N&&o.jsxs("button",{type:"button",onClick:de,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:[o.jsx(th,{className:"h-3 w-3"}),Y>0?f("Back to latest · {{n}} new",{n:Y}):f("Back to latest")]})]})}function Sy(){return o.jsx("span",{className:"flex gap-0.5",children:[0,1,2].map(e=>o.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground",style:{animationDelay:`${e*.2}s`}},e))})}const Nq=m.memo(function({chatId:t,entry:n,continued:s,latest:i,bots:r,records:a,onOpenConversation:l,retryable:c,retryBusy:d}){const{t:u}=te(),[h,p]=m.useState(!1),f=async()=>{if(!h){p(!0);try{const x=await window.electronAPI.bots.retry(t,n.id);x.ok||We({type:"error",title:u("Retry failed"),description:Cs(x.error,u)})}catch{We({type:"error",title:u("Retry failed")})}finally{p(!1)}}};switch(n.kind){case"system":return n.newConversation?o.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground text-xs",children:[o.jsx("div",{className:"h-px flex-1 bg-border"}),u("New conversation")," · ",Dd(n.at),o.jsx("div",{className:"h-px flex-1 bg-border"})]}):n.routine?o.jsx(UK,{text:n.text,target:n.routine}):o.jsxs("div",{"data-slot":"bot-notice",className:"self-center rounded-full bg-muted px-2.5 py-0.5 text-center text-muted-foreground text-xs",children:[n.text,c&&o.jsx(le,{size:"xs",variant:"outline",className:"ml-2",disabled:d||h,onClick:f,children:u("Retry")})]});case"human":return o.jsxs("div",{className:"flex w-full flex-col items-end",children:[n.text&&o.jsx("div",{className:q(Wa,"whitespace-pre-wrap break-words"),children:o.jsx(Pd,{text:n.text,bots:r})}),n.images?.length?o.jsx(gu,{target:{chatId:t,entryId:n.id}}):null,(n.refs?.skill||n.refs?.chats?.length)&&o.jsx(Pq,{refs:n.refs}),!s&&o.jsx("span",{className:"mt-0.5 text-[11px] text-muted-foreground",children:Dd(n.at)})]});case"progress":return o.jsx(Iq,{chatId:t,entry:n,bots:r,failed:a.get(n.delegationId)?.record.state==="failed"});case"delegation":return o.jsx(vh,{record:a.get(n.delegationId)?.record,retried:a.get(n.delegationId)?.retried,entry:n,bots:r,onOpenConversation:l});case"bot":{const x=r.get(n.botId);return o.jsxs("div",{className:q("flex w-full gap-2.5",s&&"-mt-1.5"),children:[s?o.jsx("span",{className:"w-6 shrink-0"}):i?o.jsx(vT,{chatId:t,botId:n.botId,bot:x}):o.jsx(Jt,{bot:x,size:"sm"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[!s&&o.jsxs("div",{className:"mb-0.5 text-muted-foreground text-xs",children:[o.jsx("span",{className:"mr-1.5 font-semibold text-foreground",children:x?.name??u("Deleted member")}),x?.title?`${x.title} · `:"",Dd(n.at),n.model&&o.jsx("span",{className:"ml-1.5 rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10px]",children:n.model}),n.routedBy&&o.jsx("span",{title:u(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:u(_q[n.routedBy])})]}),o.jsx("div",{className:"text-sm",children:o.jsx(Ds,{text:n.text})}),o.jsx(gu,{target:{chatId:t,entryId:n.id}}),o.jsx(Dq,{entry:n,onOpen:()=>l(n.conversationId,x?.name??"")})]})]})}}}),Tq={started:{icon:zH,className:"border-brand/50 text-brand"},blocked:{icon:ur,className:"border-warning/60 text-warning"},failed:{icon:SM,className:"border-destructive/60 text-destructive"},delivered:{icon:zm,className:"border-success/60 text-success"}};function Iq({chatId:e,entry:t,bots:n,failed:s}){const{t:i}=te(),r=re(u=>u.openTask),a=n.get(t.botId),l=Tq[t.phase==="blocked"&&s?"failed":t.phase],c=l.icon,d=xq(t.text,t.taskSeq);return o.jsxs("div",{"data-slot":"bot-progress","data-phase":t.phase,className:"flex w-full gap-2.5",children:[o.jsx(Jt,{bot:a,size:"sm"}),o.jsxs("div",{className:q("flex min-w-0 max-w-lg items-start gap-1.5 rounded-md border-l-2 bg-muted/50 px-2 py-1 text-xs",l.className),children:[o.jsx(c,{"aria-hidden":!0,className:"mt-px size-3.5 shrink-0"}),o.jsxs("div",{className:"line-clamp-2 min-w-0 break-words text-muted-foreground",children:[o.jsx("span",{className:"font-medium text-foreground",children:a?.name??i("Deleted member")})," ",d?o.jsxs(o.Fragment,{children:[o.jsx(Pd,{text:d[0],bots:n}),o.jsx("button",{type:"button","aria-label":i("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]}),o.jsx(Pd,{text:d[2],bots:n})]}):o.jsx(Pd,{text:t.text,bots:n})]}),o.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:Dd(t.at)})]})]})}function Pd({text:e,bots:t}){const n=m.useMemo(()=>{const s=[...t.values()].map(a=>a.name).sort((a,l)=>l.length-a.length),i=s.map(a=>a.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")),r=s.length?new RegExp(`(@(?:${i.join("|")}|所有人|everyone|all))`,"giu"):null;return SC(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 o.jsx(o.Fragment,{children:n.map((s,i)=>typeof s=="string"?s:s.type==="file"?o.jsxs("span",{className:q(mx("file"),"mx-0.5 leading-4"),title:s.path,children:[o.jsx(go,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:mk})]},i):o.jsx("span",{className:"font-medium underline underline-offset-2",children:s.part},i))})}function Dq({entry:e,onOpen:t}){const{t:n}=te(),[s,i]=m.useState(!1),[r,a]=m.useState(null);m.useEffect(()=>{if(!s||r)return;let c=!0;const d=h=>{const p=CM(h,e.text);if(c){if(!p)return a({error:n("No process recorded.")});a({steps:kM(h.slice(p.start,p.end)),exact:p.exact})}},u=re.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?$n:kn;return o.jsxs("div",{className:"mt-1",children:[o.jsxs("button",{type:"button",onClick:()=>i(c=>!c),className:"flex items-center gap-1 text-muted-foreground text-xs hover:text-foreground",children:[o.jsx(l,{className:"h-3 w-3"}),n("View process"),r&&"steps"in r&&` · ${n("{{n}} steps",{n:r.steps.length})}`]}),s&&o.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&&o.jsx(Vt,{className:"h-3.5 w-3.5 animate-spin"}),r&&"error"in r&&o.jsx("span",{children:r.error}),r&&"steps"in r&&o.jsxs(o.Fragment,{children:[!r.exact&&o.jsx("div",{className:"mb-1 font-sans italic",children:n("Could not locate this reply; showing the latest turn.")}),r.steps.length===0&&o.jsx("div",{className:"font-sans",children:n("No tool calls in this turn.")}),r.steps.map(c=>o.jsxs("div",{className:q("truncate",c.error&&"text-destructive"),children:[c.error?"✗":"·"," ",aa(c.name,n),c.detail&&o.jsxs("span",{className:"text-foreground/80",children:[" ",c.detail]})]},c.id))]}),o.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 Pq({refs:e}){const{t}=te(),n=re(a=>a.chats),s=re(a=>a.bots),i=xe(a=>a.skills),r="inline-flex h-6 max-w-56 items-center gap-1 rounded-md px-1.5 text-xs";return o.jsxs("div",{className:"mt-1 flex flex-wrap justify-end gap-1.5",children:[e.skill&&o.jsxs("span",{className:q(r,"bg-info/15 text-info"),children:[o.jsx(Ls,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"min-w-0 truncate",children:i.find(a=>a.id===e.skill)?.name??e.skill})]}),e.chats?.map(a=>{const l=n.find(c=>c.id===a);return o.jsxs("span",{className:q(r,"bg-muted"),title:t("Referenced chat"),children:[o.jsx(oa,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"min-w-0 truncate",children:l?bs(l,s,t):t("Unavailable chat")})]},a)})]})}function wh({retry:e,onCancel:t}){const{t:n}=te(),[s,i]=m.useState(()=>Date.now());m.useEffect(()=>{const a=setInterval(()=>i(Date.now()),500);return()=>clearInterval(a)},[]);const r=Math.max(0,Math.ceil((e.at+e.delayMs-s)/1e3));return o.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:[o.jsx(Mo,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-amber-500 [animation-duration:2s]"}),o.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}),o.jsxs("span",{className:"text-muted-foreground",children:[" · ",r>0?n("retrying in {{seconds}}s",{seconds:r}):n("retrying…")," — ",e.error]})]}),t&&o.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:o.jsx(ln,{className:"h-3.5 w-3.5"})})]})}function VT(e){const{t}=te(),n=re(r=>r.delegations),s=e?TM(n,e):[],i=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:LT(r.trigger,t)})})),[i,t])}const Eq=2500;function $T({focus:e,timelineRef:t,items:n,baseIndex:s,hasMessages:i,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=bq({target:e.messageIndex,earliest:i?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"?vq(n,e.messageIndex):void 0;p&&(window.setTimeout(()=>t.current?.scrollToKey(p),60),d({key:p,query:e.query}))},[e,n,s,i,r,a,l,t]),m.useEffect(()=>{if(!c)return;const h=window.setTimeout(()=>d(null),Eq);return()=>window.clearTimeout(h)},[c]),{searchQuery:c?.query??"",activeHit:c?{key:c.key,nth:0}:null}}function WT({conversationId:e,speaker:t,emptyTitle:n,emptyDescription:s,className:i,focus:r,onFocusDone:a,turnFooter:l,controls:c,runDividers:d}){const u=re(N=>N.sessions[e]),h=re(N=>!!N.sessionHistoryLoading[e]),p=m.useRef(null),f=u?.status==="running",x=m.useMemo(()=>u?hr(u.messages,f,u.customEntries,void 0,{historyBaseIndex:u.historyBaseIndex,toolOutputs:u.toolOutputs,pendingApprovals:u.pendingApprovals,toolStartedAt:u.toolStartedAt,runDividers:d}):[],[u,f,d]);m.useEffect(()=>{p.current?.isAtBottom()&&p.current.pinToBottom()},[x]);const g=m.useMemo(()=>()=>{re.getState().loadOlderSession(e)},[e]),v=$T({focus:r,timelineRef:p,items:x,baseIndex:u?.historyBaseIndex??0,hasMessages:(u?.messages.length??0)>0,loading:h,loadOlder:g,onDone:a}),{name:w,color:y,image:b}=t,_=m.useMemo(()=>({sessionId:e,canRewind:!!c,canRetry:!!c,canFork:!1,speaker:{name:w,color:y,image:b},turnFooter:l,...c?{botControls:c}:{}}),[e,w,y,b,l,c]),j=(u?.historyBaseIndex??0)>0;return o.jsx(ch.Provider,{value:_,children:o.jsxs("div",{className:q("@container flex min-h-0 flex-1 flex-col",i),children:[o.jsx(ph,{ref:p,items:x,busy:f,loading:!1,running:f,runStartedAt:u?.runStartedAt,lastOutputAt:u?.lastOutputAt,error:u?.status==="failed"?u.error:void 0,emptyTitle:n,emptyDescription:s,historyLoading:h,hasOlder:j,olderCursor:u?.historyBaseIndex,onStartReached:j?()=>{re.getState().loadOlderSession(e)}:void 0,searchQuery:v.searchQuery,activeHit:v.activeHit},e),u?.retry&&o.jsx("div",{className:fi,children:o.jsx(wh,{retry:u.retry})})]})})}function Aq({conversationId:e,title:t,speaker:n,emptyTitle:s,emptyDescription:i,footer:r,onClose:a}){const l=VT(e);return o.jsx(gn,{open:e!==null,onOpenChange:c=>!c&&a(),children:o.jsxs(xn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[o.jsx(vn,{children:o.jsx(bn,{children:t})}),e&&o.jsx(WT,{className:"border-t",conversationId:e,speaker:n,emptyTitle:s??t,emptyDescription:i,runDividers:l}),r&&o.jsx("div",{className:fi,children:r})]})})}function Tx({conversationId:e,title:t,speaker:n,focus:s,turnFooter:i,read:r,botSession:a=!0,onClose:l}){const{t:c}=te(),[d,u]=m.useState(null),[h,p]=m.useState(),[f,x]=m.useState(!1),g=m.useRef(!1),v=m.useRef(null),w=m.useCallback(T=>r?r(T):window.electronAPI.bots.sessionHistory({conversationId:e??"",...T!==void 0?{beforeIndex:T}:{}}),[e,r]);m.useEffect(()=>{if(u(null),p(void 0),!e)return;let T=!0;return w().then(A=>{T&&(A.ok?u({messages:A.messages,baseIndex:A.baseIndex}):p(A.code==="not-found"?c("This conversation has no history yet."):A.error))}),()=>{T=!1}},[e,w,c]);const y=m.useCallback(async()=>{if(!(!e||!d||d.baseIndex<=0||g.current)){g.current=!0,x(!0);try{const T=await w(d.baseIndex);T.ok&&T.baseIndex+T.messages.length===d.baseIndex&&u({messages:[...T.messages,...d.messages],baseIndex:T.baseIndex})}finally{g.current=!1,x(!1)}}},[e,w,d]),b=VT(e),_=m.useMemo(()=>d?hr(d.messages,!1,[],void 0,{historyBaseIndex:d.baseIndex,runDividers:b}):[],[d,b]),j=m.useCallback(()=>{y()},[y]),N=$T({focus:s,timelineRef:v,items:_,baseIndex:d?.baseIndex??0,hasMessages:!!d?.messages.length,loading:f||d===null,loadOlder:j}),C=n?.name,k=n?.color,E=n?.image,I=m.useMemo(()=>({sessionId:e,canRewind:!1,canRetry:!1,botSession:a,speaker:C&&k?{name:C,color:k,image:E}:void 0,turnFooter:i}),[a,e,C,k,E,i]);return o.jsx(gn,{open:e!==null,onOpenChange:T=>!T&&l(),children:o.jsxs(xn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[o.jsx(vn,{children:o.jsx(bn,{children:t})}),o.jsx(ch.Provider,{value:I,children:o.jsx("div",{className:"@container flex min-h-0 flex-1 flex-col border-t",children:h?o.jsx("p",{className:"p-6 text-muted-foreground text-sm",children:h}):o.jsx(ph,{ref:v,items:_,busy:d===null,loading:d===null,running:!1,emptyTitle:t,hasOlder:!!(d&&d.baseIndex>0),historyLoading:f,olderCursor:d?.baseIndex,onStartReached:d&&d.baseIndex>0?()=>{y()}:void 0,searchQuery:N.searchQuery,activeHit:N.activeHit})})})]})})}function Do(e,t,n=Date.now()){const s=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),i=e-n,r=Math.abs(i);return r<6e4?s.format(0,"second"):r<36e5?s.format(Math.trunc(i/6e4),"minute"):r<864e5?s.format(Math.trunc(i/36e5),"hour"):r<30*864e5?s.format(Math.trunc(i/864e5),"day"):r<365*864e5?s.format(Math.trunc(i/(30*864e5)),"month"):s.format(Math.trunc(i/(365*864e5)),"year")}const lm="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 Mq({group:e,thread:t}){const{t:n}=te(),s=re(k=>k.chats),i=re(k=>k.sessions),r=re(k=>k.timelines),a=re(k=>k.queue),l=re(k=>k.reads),c=re(k=>k.bots),[d,u]=m.useState(!1),[h,p]=m.useState(null),[f,x]=m.useState(null),g=e.archivedAt!==void 0,v=m.useMemo(()=>Object.fromEntries(c.map(k=>[k.id,k.name])),[c]),w=k=>k.threadTitle??(k.parentId?n("New topic"):n("Main topic")),y=l$(s,e).map(k=>{const E=Ym(k,{sessions:i,timeline:r[k.id],queue:a,names:v});return{id:k.id,title:w(k),preview:E.preview,activityAt:Math.max(E.activityAt,k.createdAt),unread:k.id!==t.id&&Va(E.marker,l[E.key]),running:E.running,canRename:!g,canDelete:!!k.parentId}}),b=k1(y,{currentId:t.id,rootId:e.id}),_=y.length-b.length,j=k=>re.getState().openThread(e.id,k),N=async()=>{await re.getState().createThread(e.id)||We({type:"error",title:n("Could not create topic")})},C=async k=>{const E=await window.electronAPI.bots.deleteThread(k);E.ok||We({type:"error",title:Cs(E.error,n)}),re.getState().refreshChats()};return o.jsxs(o.Fragment,{children:[o.jsxs(zi,{children:[o.jsxs(Gi,{className:q(lm,"max-w-56 @max-[28rem]:max-w-32 @max-[21rem]:max-w-24"),children:[o.jsx("span",{className:"truncate",children:w(t)}),y.some(k=>k.unread)&&o.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-info"}),o.jsx($n,{className:"h-3.5 w-3.5 shrink-0"})]}),o.jsxs(Fi,{align:"end",className:"w-72",children:[o.jsxs(Xm,{children:[o.jsx(Jm,{children:n("Topics")}),b.map(k=>o.jsxs(dn,{onClick:()=>j(k.id),children:[o.jsx(Jn,{className:q(k.id!==t.id&&"invisible")}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:k.title}),o.jsx(Ix,{entry:k})]},k.id))]}),o.jsx(pa,{}),_>0&&o.jsxs(dn,{onClick:()=>u(!0),children:[o.jsx(Yg,{}),n("All topics ({{n}})",{n:y.length})]}),o.jsxs(dn,{disabled:g,onClick:()=>{N()},children:[o.jsx(fr,{}),n("New topic")]}),o.jsxs(dn,{disabled:g,onClick:()=>p({id:t.id,title:w(t)}),children:[o.jsx(Xs,{}),n("Rename topic")]}),t.parentId&&o.jsxs(dn,{variant:"destructive",onClick:()=>x(t.id),children:[o.jsx(di,{}),n("Delete topic")]})]})]}),o.jsxs("button",{type:"button",disabled:g,onClick:()=>{N()},className:q(lm,"shrink-0"),title:n("New topic"),"aria-label":n("New topic"),children:[o.jsx(fr,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New topic")})]}),d&&o.jsx(UT,{heading:n("Topics"),placeholder:n("Search topics..."),empty:n("No matching topics"),filters:!0,entries:y,currentId:t.id,onClose:()=>u(!1),onOpen:k=>{j(k),u(!1)},onRename:k=>p({id:k.id,title:k.title}),onDelete:k=>x(k.id)}),o.jsx(hs,{open:f!==null,onOpenChange:k=>!k&&x(null),title:n("Delete this topic?"),description:n("Its messages and member sessions are removed; replies in progress are stopped. Group notes, memory and the task board stay."),confirmLabel:n("Delete"),onConfirm:()=>f&&void C(f),zIndexLevel:d?"nested":"base"}),h!==null&&o.jsx(Rq,{initial:h.title,nested:d,onClose:()=>p(null),onSave:async k=>{const E=await window.electronAPI.bots.renameThread(h.id,k);if(!E.ok){We({type:"error",title:Cs(E.error,n)});return}re.getState().upsertChat(E.chat),p(null)}})]})}function Ix({entry:e}){const{locale:t}=te();return o.jsxs(o.Fragment,{children:[e.running&&o.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-warning"}),e.unread&&o.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-info"}),o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Do(e.activityAt,t)})]})}function UT({heading:e,placeholder:t,empty:n,filters:s=!1,entries:i,currentId:r,onClose:a,onOpen:l,onRename:c,onDelete:d}){const{t:u}=te(),[h,p]=m.useState(""),[f,x]=m.useState("all"),g=Db(i,h,f),v=y=>Db(i,"",y).length,w="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 o.jsx(gn,{open:!0,onOpenChange:y=>!y&&a(),children:o.jsxs(xn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[o.jsxs(vn,{children:[o.jsxs(bn,{className:"flex items-baseline gap-2",children:[e,o.jsx("span",{className:"font-sans text-muted-foreground text-sm tabular-nums",children:i.length})]}),o.jsxs(zu,{"data-size":"sm",className:"mt-1",children:[o.jsx(Gu,{children:o.jsx(Js,{})}),o.jsx(Fu,{autoFocus:!0,value:h,placeholder:t,onChange:y=>p(y.target.value)})]}),s&&o.jsx(Ru,{value:f,onValueChange:y=>x(y),children:o.jsxs(Lu,{children:[o.jsx(Ns,{value:"all",children:u("All")}),o.jsxs(Ns,{value:"unread",children:[u("Unread"),v("unread")>0&&o.jsx("span",{className:"tabular-nums",children:v("unread")})]}),o.jsxs(Ns,{value:"running",children:[u("In progress"),v("running")>0&&o.jsx("span",{className:"tabular-nums",children:v("running")})]})]})})]}),o.jsxs(Rn,{className:"flex flex-col gap-y-0.5 border-t pt-3!",children:[g.length===0&&o.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:n}),g.map(y=>o.jsxs("div",{className:"group flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted/60",children:[o.jsxs("button",{type:"button",onClick:()=>l(y.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[o.jsx(Jn,{className:q("h-3.5 w-3.5 shrink-0",y.id!==r&&"invisible")}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate text-sm",children:y.title}),y.preview&&o.jsx("span",{className:"block truncate text-muted-foreground text-xs",children:y.preview})]}),o.jsx(Ix,{entry:y})]}),c&&y.canRename&&o.jsx("button",{type:"button",className:w,onClick:()=>c(y),title:u("Rename topic"),"aria-label":u("Rename topic"),children:o.jsx(Xs,{className:"h-3.5 w-3.5"})}),d&&y.canDelete?o.jsx("button",{type:"button",className:q(w,"hover:text-destructive"),onClick:()=>d(y),title:u("Delete topic"),"aria-label":u("Delete topic"),children:o.jsx(di,{className:"h-3.5 w-3.5"})}):d?o.jsx("span",{className:"w-5.5 shrink-0","aria-hidden":!0}):null]},y.id))]})]})})}function Rq({initial:e,nested:t,onClose:n,onSave:s}){const{t:i}=te(),[r,a]=m.useState(e),l=()=>{r.trim()&&s(r.trim())};return o.jsx(gn,{open:!0,onOpenChange:c=>!c&&n(),children:o.jsxs(xn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[o.jsx(vn,{children:o.jsx(bn,{children:i("Rename topic")})}),o.jsx(Rn,{children:o.jsx(Wt,{value:r,autoFocus:!0,maxLength:80,onChange:c=>a(c.target.value),onKeyDown:c=>c.key==="Enter"&&l()})}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:n,children:i("Cancel")}),o.jsx(le,{size:"sm",disabled:!r.trim(),onClick:l,children:i("Save")})]})]})})}function Lq({chat:e,botId:t,running:n,onView:s}){const{t:i}=te(),[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(b=>{b.ok&&a(b.sessions.filter(_=>_.botId===t))})},[e.id,t]);m.useEffect(p,[p,h,n]);const f=r.map(b=>{const _=b.conversationId===h;return{id:b.conversationId,title:b.title??i(_?"New conversation":"Untitled conversation"),preview:_||b.resumable?"":i("Workspace changed; view only"),activityAt:b.activityAt??(_?Date.now():0),unread:!1,running:_&&n,resumable:b.resumable}}),x=k1(f,{currentId:h??"",rootId:h??""}),g=f.length-x.length,v=f.find(b=>b.id===h)?.title??i("New conversation"),w=async b=>{const _=await window.electronAPI.bots.switchSession(e.id,b);_.ok||We({type:"error",title:Cs(_.error,i)}),await re.getState().refreshChats(),p()},y=b=>{const _=f.find(j=>j.id===b);!_||b===h||(_.resumable?n?u(b):w(b):s(b,_.title))};return f.length<2?null:o.jsxs(o.Fragment,{children:[o.jsxs(zi,{onOpenChange:b=>b&&p(),children:[o.jsxs(Gi,{className:q(lm,"max-w-56"),children:[o.jsx("span",{className:"truncate",children:v}),o.jsx($n,{className:"h-3.5 w-3.5 shrink-0"})]}),o.jsxs(Fi,{align:"end",className:"w-72",children:[o.jsxs(Xm,{children:[o.jsx(Jm,{children:i("Conversations")}),x.map(b=>o.jsxs(dn,{onClick:()=>y(b.id),children:[o.jsx(Jn,{className:q(b.id!==h&&"invisible")}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:b.title}),!b.resumable&&b.id!==h&&o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:i("Read-only")}),o.jsx(Ix,{entry:b})]},b.id))]}),g>0&&o.jsxs(o.Fragment,{children:[o.jsx(pa,{}),o.jsxs(dn,{onClick:()=>c(!0),children:[o.jsx(Yg,{}),i("All conversations ({{n}})",{n:f.length})]})]})]})]}),l&&o.jsx(UT,{heading:i("Conversations"),placeholder:i("Search conversations..."),empty:i("No matching conversations"),entries:f,currentId:h??"",onClose:()=>c(!1),onOpen:b=>{c(!1),y(b)}}),o.jsx(hs,{open:d!==null,onOpenChange:b=>!b&&u(null),title:i("Switch conversation?"),description:i("The reply in progress will be stopped."),confirmLabel:i("Switch"),onConfirm:()=>d&&void w(d)})]})}function KT(e){const{t}=te(),n=ma(),s=xe(c=>c.virtualModels);if(!e?.engine)return t("Default model");const{providerId:i,modelId:r}=e.engine,a=yk(s,e.engine);return a?a.name:n.find(c=>c.id===i)?.models.find(c=>c.id===r)?.label??r}function Oq({chat:e,group:t=e}){const{t:n}=te(),s=re(we=>we.bots),i=re(we=>we.chats),r=re(we=>we.sessions),a=re(we=>we.queue),l=re(we=>we.delegations),c=re(we=>we.timelines[e.id]),d=re(we=>we.runtime[e.id]),u=re(we=>we.markRead),h=re(we=>we.panelOpen),p=re(we=>we.panelTab),f=re(we=>we.browserTabs[t.id]?.tabs.length??0),x=re(we=>we.panelWidth),g=xe(we=>we.skills),v=xe(we=>we.voiceInputEnabled),w=xe(we=>we.voiceModel),{status:y}=gk(v),b=v&&y?.state!=="unsupported"&&y?.models.find(we=>we.id===w)?.state==="ready",[_,j]=m.useState(!1),[N,C]=m.useState(0),k=fa(),E=m.useRef(null);m.useEffect(()=>{const we=E.current?.parentElement;if(!we)return;const ft=()=>C(we.clientWidth);ft();const mt=new ResizeObserver(ft);return mt.observe(we),()=>mt.disconnect()},[]);const I=k?N:wk(x,N),T=h?I:0,A=m.useCallback(we=>{const ft=E.current?.parentElement;ft&&re.getState().nudgePanelWidth(-we,ft.clientWidth)},[]),[D,W]=m.useState(null),[J,O]=m.useState(),[B,L]=m.useState(null),se=re(we=>we.focus?.chatId===e.id?we.focus:null),Q=re(we=>we.clearFocus),V=m.useMemo(()=>new Map(s.map(we=>[we.id,we])),[s]),H=m.useMemo(()=>Object.fromEntries(s.map(we=>[we.id,we.name])),[s]),ne=e.members.map(we=>V.get(we)).filter(we=>!!we),he=ne.map(we=>`${we.id}:${we.skillIds.join(",")}`).join("|"),pe=m.useMemo(()=>g.flatMap(we=>{const ft=ne.filter(mt=>mt.skillIds.includes(we.id)).map(mt=>mt.id);return ft.length?[{id:we.id,name:we.name,description:we.description,owners:ft}]:[]}),[g,he]),ke=m.useMemo(()=>i.filter(we=>we.id!==t.id&&!we.parentId&&we.archivedAt===void 0).map(we=>({id:we.id,title:bs(we,s,n),kind:we.kind})),[i,t.id,s,n]),Me=Ym(e,{sessions:r,timeline:c,queue:a,names:H}),fe=re(we=>we.reads[Me.key]),F=e.kind==="group"?IM(c,fe):Me.marker,U=m.useMemo(()=>l.filter(we=>we.chatId===e.id),[l,e.id]),de=m.useMemo(()=>xk(r,vk(i,l),e.id),[r,i,l,e.id]),X=D?(we=>{const ft=U.find(Ct=>Ct.childConversationId===we);if(ft)return V.get(ft.targetBotId);const mt=Object.entries(e.sessions).find(([,Ct])=>Ct.conversationId===we)?.[0],ze=c?.entries.find(Ct=>Ct.kind==="bot"&&Ct.conversationId===we);return V.get(mt??(ze?.kind==="bot"?ze.botId:e.kind==="direct"?e.members[0]:""))})(D.id):void 0,z=B?V.get(B.botId):void 0,ue=B?de.filter(we=>we.conversationId===B.id):[],_e=B?.title??z?.name??n("Deleted member"),Ee=B&&l.find(we=>we.childConversationId===B.id)?.state==="queued",Be=m.useCallback((we,ft)=>{const mt=DM(re.getState().delegations,we);mt?(re.getState().sessions[we]||re.getState().trackSession(we),L({id:we,botId:mt.botId,title:ft})):W({id:we,title:ft})},[]);m.useEffect(()=>{u(Me.key,F)},[u,Me.key,F]),m.useEffect(()=>{if(e.kind==="group"){const we=re.getState();we.timelines[e.id]?.history&&we.focus?.chatId!==e.id?we.jumpLatest(e.id):we.loadLatest(e.id),re.getState().refreshRuntime(e.id)}},[e.id,e.kind]);const De=e.kind==="direct"?ne[0]:void 0,Ue=De?e.sessions[De.id]?.conversationId:void 0,St=se?.locator,Ut=se&&St?.kind==="session"&&St.conversationId===Ue?{messageIndex:St.messageIndex,query:se.query,nonce:se.nonce}:void 0,tn=se&&St?.kind==="timeline"?{seq:St.seq,query:se.query,nonce:se.nonce}:void 0;m.useEffect(()=>{se?.locator.kind==="session"&&se.locator.conversationId!==Ue&&(W({id:se.locator.conversationId,title:n("History")}),O({messageIndex:se.locator.messageIndex,query:se.query,nonce:se.nonce}),Q(se.nonce))},[se,Ue,Q,n]);const Ne=D?.id,Z=m.useCallback(we=>e.kind==="direct"&&Ne?o.jsx(gu,{target:{chatId:e.id,conversationId:Ne,messageIndex:we}}):null,[e.id,e.kind,Ne]),je=e.archivedAt!==void 0,tt=d?.current?V.get(d.current):void 0,Et=(()=>{if(je)return n("This chat is archived. Restore it before sending.");if(e.kind==="group"){const we=e.routing.mode==="smart"?n("Without @, the best-fit member is picked to reply"):n("Without @, the group owner replies");return tt?`${we} · ${n("{{name}} is replying; new messages are routed after they finish",{name:tt.name})}`:we}return Me.running&&De?n("{{name}} is working; your message joins the current turn",{name:De.name}):null})(),zt=async({text:we,images:ft,...mt})=>{const ze=await re.getState().send(e.id,we,ft,mt);return ze.ok?(ze.queued&&We({type:"info",title:n("Queued until a session slot frees up")}),re.getState().timelines[e.id]?.history&&re.getState().jumpLatest(e.id),!0):(We({type:"error",title:n("Message not sent"),description:Cs(ze.error,n)}),!1)};return o.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1",children:[o.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[o.jsxs("header",{className:"@container flex h-[52px] shrink-0 items-center gap-2.5 border-b px-4",children:[De?o.jsx(Jt,{bot:De,busy:Me.running}):o.jsx(Za,{bots:ne,busy:Me.running}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate font-semibold text-sm",children:bs(e,s,n)}),o.jsx("div",{className:"truncate text-muted-foreground text-xs",children:De?o.jsx(Gq,{bot:De,running:Me.running,queued:Me.queued,conversationId:e.sessions[De.id]?.conversationId}):n("{{n}} members · Owner {{name}}",{n:ne.length,name:V.get(e.bossBotId??"")?.name??"—"})})]}),o.jsx("div",{className:"flex-1"}),o.jsx(GT,{chat:t}),De?o.jsxs(o.Fragment,{children:[o.jsx(Lq,{chat:e,botId:De.id,running:Me.running,onView:(we,ft)=>W({id:we,title:ft})}),o.jsxs("button",{type:"button",disabled:je,onClick:()=>{window.electronAPI.bots.newSession(e.id).then(we=>{we.ok?re.getState().refreshChats():We({type:"error",title:Cs(we.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:[o.jsx(fr,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New conversation")})]})]}):o.jsx(Mq,{group:t,thread:e})]}),De?o.jsxs(o.Fragment,{children:[o.jsx(zq,{items:PM(U,e.id),bots:V,onOpenConversation:Be}),o.jsx(Hq,{chat:e,bot:De,focus:Ut,onFocusDone:Q})]}):o.jsx(jq,{chat:e,bots:V,timeline:c,runtime:d,delegations:U,focus:tn,onFocusDone:Q,onLoadOlder:()=>{re.getState().loadOlder(e.id)},onLoadNewer:()=>{re.getState().loadNewer(e.id)},onLoadAround:we=>re.getState().loadAround(e.id,we),onJumpLatest:()=>{re.getState().jumpLatest(e.id)},onOpenConversation:Be,onOpenLive:(we,ft)=>L({id:we,botId:ft,title:V.get(ft)?.name??n("Deleted member")})}),o.jsx("div",{className:"@container pt-1",children:o.jsxs("div",{className:q(fi,"pb-4"),children:[De&&(Me.running||Me.queued)&&o.jsx(pT,{conversationId:e.sessions[De.id]?.conversationId,className:"mb-2 rounded-lg border bg-muted/30 px-3 py-2"}),o.jsx(Cy,{items:de,bots:V,showNames:e.kind==="group"}),e.kind==="group"&&o.jsx(mK,{chatId:e.id,memberIds:e.members,bots:V,onOpenLive:(we,ft)=>L({id:we,botId:ft,title:V.get(ft)?.name??n("Deleted member")})}),o.jsx(oK,{chatId:e.id,placeholder:De?n("Message {{name}}…",{name:De.name}):n("@ a member, or just say it…"),members:e.kind==="group"?ne:void 0,chatOptions:ke,skills:pe,voice:b?YN:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,running:Me.running||!!(d?.current||d?.routing),disabled:je,hint:Et,toolbar:De?o.jsx(Fq,{bot:De}):null,onSend:zt,onStop:()=>{re.getState().stop(e.id)}},e.id)]})})]}),h&&!k&&o.jsx(cu,{onResize:A,onResizingChange:j}),o.jsx(Es.aside,{ref:E,initial:!1,animate:{width:T},style:k?void 0:{maxWidth:`max(0px, calc(100% - ${bk+Qm}px))`},transition:qN({skip:_,cover:k,targetW:T}),className:q("flex min-h-0 shrink-0 flex-col overflow-hidden bg-background",k?"absolute inset-y-0 right-0 z-10":"relative"),children:o.jsxs("div",{className:q("flex h-full min-h-0 flex-col",!h&&"invisible"),style:{width:I},children:[o.jsx("div",{className:"flex h-10 shrink-0 items-center gap-1 border-b px-2",children:["info","browser"].map(we=>o.jsxs("button",{type:"button",onClick:()=>re.getState().setPanelTab(we),className:q("flex h-7 items-center gap-1.5 rounded-md px-2.5 text-xs transition-colors",p===we?"bg-brand/10 font-medium text-foreground dark:bg-brand/15":"text-muted-foreground hover:text-foreground"),children:[we==="info"?o.jsx(Zm,{className:"h-3.5 w-3.5"}):o.jsx(uo,{className:"h-3.5 w-3.5"}),n(we==="info"?De?"Member":"Group info":"Browser"),we==="browser"&&f>0&&o.jsx("span",{className:"text-muted-foreground tabular-nums",children:f})]},we))}),p==="browser"?o.jsx(g9,{chatId:t.id,visible:h}):De?o.jsx(tq,{botId:De.id,chat:e,onOpenHistory:Be}):o.jsx(mq,{chat:t,thread:e,onOpenConversation:Be})]})}),o.jsx(Tx,{conversationId:D?.id??null,title:D?.title??"",speaker:X?{name:X.name,color:X.avatar.color,image:zd(X)}:void 0,focus:J,turnFooter:Z,onClose:()=>{W(null),O(void 0)}}),o.jsx(Aq,{conversationId:B?.id??null,title:_e,speaker:{name:z?.name??_e,color:z?.avatar.color??"#64748b",image:z?zd(z):void 0},emptyTitle:Ee?n("Queued and has not started yet"):void 0,emptyDescription:Ee?"":void 0,footer:z&&ue.length>0?o.jsx(Cy,{items:ue,bots:V,showNames:!1}):void 0,onClose:()=>L(null)})]})}function zq({items:e,bots:t,onOpenConversation:n}){const{t:s}=te();return e.length===0?null:o.jsx("div",{className:"shrink-0 border-b bg-muted/30",children:o.jsxs("div",{className:q(fi,"py-2"),children:[o.jsx("div",{className:"mb-1.5 text-muted-foreground text-xs",children:s("Delegations in progress · {{n}}",{n:e.length})}),o.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto",children:e.map(i=>o.jsx(vh,{record:i,bots:t,onOpenConversation:n},i.id))})]})})}function Gq({bot:e,running:t,queued:n,conversationId:s}){const{t:i}=te(),r=KT(e),a=i(t?"Working":n?"Queued":"Idle");return o.jsxs(o.Fragment,{children:[[e.title,r,a].filter(Boolean).join(" · "),t&&o.jsx(BT,{conversationId:s,className:"ml-1.5 text-warning"})]})}function Fq({bot:e}){const{t}=te(),n=KT(e),s=_l[e.approvalMode];return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex h-6 min-w-0 items-center gap-1 rounded-md px-1.5 text-muted-foreground text-xs",children:[o.jsx(Ls,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"max-w-32 truncate",children:n})]}),o.jsxs("span",{className:"flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 text-muted-foreground text-xs",children:[o.jsx(Du,{className:"h-3 w-3"}),t(s.labelKey)]})]})}function Hq({chat:e,bot:t,focus:n,onFocusDone:s}){const{t:i}=te(),r=e.sessions[t.id]?.conversationId,a=e.archivedAt!==void 0,l=m.useMemo(()=>{if(a||!r)return;const d=u=>{u.ok||We({type:"error",title:Cs(u.error??"unavailable",i)})};return{subscribe:re.subscribe,projection:()=>re.getState().sessions[r],rewind:(u,h)=>{re.getState().rewind(e.id,u,h).then(d)},retry:()=>{re.getState().retry(e.id).then(d)}}},[e.id,r,a,i]),c=m.useCallback(d=>r?o.jsx(gu,{target:{chatId:e.id,conversationId:r,messageIndex:d}}):null,[e.id,r]);return r?o.jsx(WT,{conversationId:r,speaker:{name:t.name,color:t.avatar.color,image:zd(t)},emptyTitle:i("Say hi to {{name}}",{name:t.name}),focus:n,onFocusDone:s,turnFooter:c,controls:l}):o.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 px-6 text-center",children:[o.jsx(Jt,{bot:t,size:"lg"}),o.jsx("p",{className:"font-medium text-lg",children:t.name}),o.jsx("p",{className:"max-w-sm text-muted-foreground text-sm",children:t.scope||t.title})]})}function Cy({items:e,bots:t,showNames:n}){const{t:s}=te(),i=new Map;for(const r of e)i.set(r.conversationId,[...i.get(r.conversationId)??[],r]);return o.jsx(o.Fragment,{children:[...i.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 o.jsxs("div",{"data-pending-conversation":r,children:[(n||c)&&o.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-muted-foreground text-xs",children:[o.jsx(Jt,{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})]}),o.jsx(Rl,{approvals:u,onRespond:(p,f)=>{window.electronAPI.agent.respondApproval(r,p,f)}}),o.jsx(oh,{asks:h,onAnswer:(p,f)=>{window.electronAPI.agent.respondAsk(r,p,f)}})]},r)})})}function Bq(e,t){const n={pending:[],budgets:[],routines:[],silences:[],interrupted:[],blocked:[],count:0};for(const s of EM(e)){const i={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,...i});else if(s.kind==="ask"&&s.ask&&s.conversationId)n.pending.push({kind:"ask",conversationId:s.conversationId,request:s.ask,...i});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 Vq({write:e,bot:t,chatName:n}){const{t:s}=te(),i=AM(u=>u.review),[r,a]=m.useState(!1),[l,c]=m.useState(null),d=u=>{a(!0),c(null),i(e.id,u).then(h=>{h.ok||c(h.error??s("Failed"))}).finally(()=>a(!1))};return o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[o.jsx(Jt,{bot:t,size:"sm"}),o.jsx("span",{className:"text-foreground",children:t?.name??s("Deleted member")}),n&&o.jsxs("span",{children:["· ",n]}),o.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-[11px] text-warning",children:s("Memory write")}),o.jsxs("span",{children:["→ ",e.spaceLabel]}),e.redacted&&o.jsxs("span",{children:["· ",s("Secrets redacted")]})]}),e.title&&o.jsx("div",{className:"mt-2 font-medium text-sm",children:e.title}),o.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&&o.jsx("div",{className:"mt-1 text-destructive text-xs",children:l}),o.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"outline",disabled:r,onClick:()=>d("reject"),children:s("Reject")}),o.jsx(le,{size:"xs",disabled:r,onClick:()=>d("approve"),children:s("Approve")})]})]})}function $q(){const{t:e}=te(),t=re(p=>p.inbox),n=re(p=>p.chats),s=re(p=>p.bots),i=re(p=>p.delegations),r=re(p=>p.routines),[a,l]=m.useState(null),c=m.useMemo(()=>Bq(t,{routines:r,delegations:i}),[t,r,i]),d=MM(),u=m.useMemo(()=>new Map(s.map(p=>[p.id,p])),[s]),h=p=>{const f=n.find(x=>x.id===p);return f?bs(f,s,e):""};return o.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[o.jsxs("header",{className:"flex h-[52px] shrink-0 items-center gap-2.5 border-b px-4",children:[o.jsx("div",{className:"font-semibold text-sm",children:e("Inbox")}),o.jsx("div",{className:"text-muted-foreground text-xs",children:e("Everything members are waiting on you for")})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:o.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&&o.jsxs("div",{className:"flex flex-col items-center gap-2 py-16 text-muted-foreground",children:[o.jsx(qg,{className:"h-6 w-6"}),o.jsx("p",{className:"text-sm",children:e("Nothing needs your attention")})]}),c.pending.map(p=>o.jsx(Yq,{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=>o.jsx(Uq,{item:p,bot:u.get(p.botId??"")},p.key)),d.map(p=>o.jsx(Vq,{write:p,bot:p.botId?u.get(p.botId):void 0,chatName:h(p.chatId)},p.id)),c.routines.map(p=>o.jsx(WK,{alert:p},p.routine.id)),c.silences.map(p=>o.jsx(Wq,{item:p,bot:u.get(p.botId??""),chatName:h(p.chatId)},p.key)),c.blocked.length>0&&o.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Stuck delegated tasks")}),c.blocked.map(({item:p,record:f})=>o.jsx(Kq,{inboxKey:p.key,record:f,bots:u,chatName:h(f.chatId)},p.key)),c.interrupted.length>0&&o.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Interrupted delegations")}),c.interrupted.map(({item:p,record:f})=>o.jsx(qq,{inboxKey:p.key,record:f,bots:u,chatName:h(f.chatId),onOpen:x=>l({id:f.childConversationId,title:x,bot:u.get(f.targetBotId)})},p.key))]})}),o.jsx(Tx,{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 Wq({item:e,bot:t,chatName:n}){const{t:s}=te(),i=re(l=>l.setView),r=re(l=>l.dismissInbox),a=t?.name??s("Deleted member");return o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[o.jsx(Jt,{bot:t,size:"sm",busy:!0}),o.jsx("span",{className:"text-foreground",children:a}),n&&o.jsxs("span",{children:["· ",n]}),e.delegationId&&o.jsxs("span",{children:["· ",s("Delegation")]}),o.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-[11px] text-warning",children:o.jsx(HT,{since:e.since??e.createdAt})})]}),o.jsx("div",{className:"mt-2 text-sm",children:s("{{name}} is still running but has produced no output for a while",{name:a})}),o.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>{r(e.key)},children:s("Dismiss")}),e.chatId&&o.jsx(le,{size:"xs",variant:"outline",onClick:()=>e.chatId&&i({kind:"chat",chatId:e.chatId}),children:s("Go to chat")})]})]})}function Uq({item:e,bot:t}){const{t:n}=te(),s=re(a=>a.dismissInbox),i=re(a=>a.openDirect),r=t?.name??n("Deleted member");return o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[o.jsx(Jt,{bot:t,size:"sm"}),o.jsx("span",{className:"text-foreground",children:r}),o.jsx("span",{className:"rounded bg-destructive/15 px-1.5 text-[11px] text-destructive",children:n("Budget")})]}),o.jsx("div",{className:"mt-2 text-sm",children:n("{{name}}'s budget for today is used up",{name:r})}),o.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.")}),o.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>{s(e.key)},children:n("Dismiss")}),t&&o.jsx(le,{size:"xs",variant:"outline",onClick:()=>{i(t.id)},children:n("Go to chat")})]})]})}function Kq({inboxKey:e,record:t,bots:n,chatName:s}){const{t:i}=te(),r=re(x=>x.openTask),a=re(x=>x.dismissInbox),l=xh(!0),c=n.get(t.targetBotId),d=c?.name??i("Deleted member"),u=t.finishedAt??t.blocked?.at??t.createdAt,h=t.blocked?.waitFor==="parent"?i("Waiting for {{name}} to reply",{name:n.get(t.parentBotId)?.name??i("Deleted member")}):i("Waiting for your reply"),{chatId:p,taskId:f}=t;return o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-xs",children:[o.jsx(Jt,{bot:c,size:"xs"}),o.jsx("span",{className:"text-foreground",children:d}),s&&o.jsxs("span",{children:["· ",s]}),o.jsx(gh,{state:t.state}),o.jsx("span",{className:"flex-1"}),o.jsx("span",{children:i("Stuck for {{time}}",{time:ho(l-u)})})]}),o.jsx("div",{className:"mt-2 line-clamp-2 text-muted-foreground text-sm",children:t.task}),o.jsxs("div",{className:"mt-2 rounded-md border border-warning/30 bg-warning/10 px-2 py-1.5 text-xs",children:[o.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:i("Blocked · needs: {{need}}",{need:t.blocked?.need??""})}),o.jsx("div",{className:"mt-0.5 text-muted-foreground",children:h}),p&&f&&o.jsx(Nx,{placeholder:i("Answer {{name}}; they continue after your reply…",{name:d}),onSend:x=>RT(p,f,x,i)})]}),o.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>{a(e)},children:i("Dismiss")}),p&&f&&o.jsx(le,{size:"xs",variant:"outline",onClick:()=>r(p,f),children:i("Open task card")})]})]})}function qq({inboxKey:e,record:t,bots:n,chatName:s,onOpen:i}){const{t:r}=te(),a=re(p=>p.setView),l=re(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 o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-xs",children:[o.jsx(Jt,{bot:c,size:"xs"}),o.jsx("span",{className:"text-foreground",children:u}),o.jsx("span",{children:"→"}),o.jsx(Jt,{bot:d,size:"xs"}),o.jsx("span",{className:"text-foreground",children:h}),o.jsxs("span",{children:["· ",r("Delegation")]}),s&&o.jsxs("span",{children:["· ",s]}),o.jsx(gh,{state:t.state,interrupted:!0})]}),o.jsx("div",{className:"mt-2 line-clamp-3 text-sm",children:t.task}),o.jsx("div",{className:"mt-1 text-muted-foreground text-xs",children:vc(t,r)}),o.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>{l(e)},children:r("Dismiss")}),t.chatId&&o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>t.chatId&&a({kind:"chat",chatId:t.chatId}),children:r("Go to chat")}),o.jsx(le,{size:"xs",variant:"outline",onClick:()=>i(r("{{from}} → {{to}} · Delegation",{from:u,to:h})),children:r("View conversation")}),o.jsx(le,{size:"xs",onClick:()=>xl(t.id,r),children:r("Retry")})]})]})}function Yq({item:e,bot:t,owner:n,chatName:s}){const{t:i}=te(),r=re(x=>x.setView),[a,l]=m.useState(""),[c,d]=m.useState(!1),u=x=>{d(!0),x.finally(()=>d(!1))},h=x=>u(window.electronAPI.agent.respondApproval(e.conversationId,e.request.requestId,x)),p=x=>x.trim()&&u(window.electronAPI.agent.respondAsk(e.conversationId,e.request.requestId,x.trim())),f=e.kind==="approval"&&e.request.phase==="reviewing";return o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[o.jsx(Jt,{bot:t,size:"sm"}),o.jsx("span",{className:"text-foreground",children:e.delegation?i("{{name}} on behalf of {{owner}}",{name:t?.name??i("Deleted member"),owner:n?.name??i("Deleted member")}):t?.name??i("Deleted member")}),s&&o.jsxs("span",{children:["· ",s]}),o.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"?i("Approval"):i("Question")}),e.kind==="approval"&&e.request.protected&&o.jsx("span",{className:"rounded bg-destructive/15 px-1.5 text-[11px] text-destructive",children:_1(e.request.protected,i)})]}),e.kind==="approval"?o.jsxs("div",{className:"mt-2 text-sm",children:[aa(e.request.tool,i),o.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})]}):o.jsx("div",{className:"mt-2 whitespace-pre-wrap text-sm",children:e.request.question}),o.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[o.jsx(le,{size:"xs",variant:"ghost",onClick:()=>r({kind:"chat",chatId:e.chatId}),children:i("Go to chat")}),e.kind==="approval"?f?o.jsx("span",{className:"text-muted-foreground text-xs",children:i("Assistant reviewing…")}):o.jsxs(o.Fragment,{children:[o.jsx(le,{size:"xs",variant:"outline",disabled:c,onClick:()=>h("deny"),children:i("Deny")}),!e.request.protected&&o.jsx(le,{size:"xs",variant:"outline",disabled:c,onClick:()=>h("allowSession"),children:i("Always allow in this session")}),o.jsx(le,{size:"xs",disabled:c,onClick:()=>h("allow"),children:i("Allow")})]}):o.jsxs(o.Fragment,{children:[e.request.options?.map(x=>o.jsx(le,{size:"xs",variant:"outline",disabled:c,onClick:()=>p(x),children:x},x)),o.jsx(Wt,{className:"h-7 w-48",value:a,placeholder:i("Custom answer…"),onChange:x=>l(x.target.value),onKeyDown:x=>x.key==="Enter"&&p(a)}),o.jsx(le,{size:"xs",disabled:c||!a.trim(),onClick:()=>p(a),children:i("Reply")})]})]})]})}function Xq(e){const{openOnInputClick:t=!1,value:n,defaultValue:s,onValueChange:i,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,x]=m.useState("");m.useEffect(()=>{u&&x("")},[n,u]);let g;c&&f!==""?g=f:u?g=n??"":g=h;const v=RM({locale:l.locale}),w=m.useMemo(()=>l.filter!==void 0?l.filter:v.contains,[l.filter,v]),y=String(u?n:h).trim(),b=m.useMemo(()=>r!=="both"?d?null:w:w===null?null:(N,C,k)=>w(N,y,k),[w,r,y,d]);function _(N,C){x(""),u||p(N),i?.(N,C)}function j(N,C){e.onItemHighlighted?.(N,C),C.reason!==OM&&x(c&&N!=null?zM(N,a):"")}return o.jsx(LM,{...l,itemToStringLabel:a,openOnInputClick:t,selectionMode:"none",fillInputOnItemPress:!0,filter:b,autoComplete:r,inputValue:g,defaultInputValue:s,onInputValueChange:_,onItemHighlighted:j})}const Jq=GM,Zq="⁠",Qq=200;function eY(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 tY(){const e=FM(),t=m.useRef(null);return m.useEffect(()=>{if(HM)return;const n=t.current;if(n==null)return;const s=eY(n);if(s==null)return;const i=s.data,r=`${i}${Zq}`;return s.nodeValue=r,e.start(Qq,()=>{s.nodeValue===r&&(s.nodeValue=i)}),()=>{e.clear(),s.nodeValue===r&&(s.nodeValue=i)}},[t,e]),t}const qT=m.createContext(void 0);function nY(){const e=m.useContext(qT);if(e===void 0)throw new Error(Zl(18));return e}const sY=m.forwardRef(function(t,n){const{render:s,className:i,style:r,items:a,...l}=t,[c,d]=m.useState(),u=m.useMemo(()=>({labelId:c,setLabelId:d,items:a}),[c,d,a]),h=Ql("div",t,{ref:n,props:[{role:"group","aria-labelledby":c},l]}),p=o.jsx(qT.Provider,{value:u,children:h});return a?o.jsx(BM,{items:a,children:p}):p}),iY=m.forwardRef(function(t,n){const{render:s,className:i,style:r,id:a,...l}=t,{setLabelId:c}=nY(),d=GC(a);return Gm(()=>(c(d),()=>{c(h=>h===d?void 0:h)}),[d,c]),Ql("div",t,{ref:n,props:[{id:d},l]})}),oY=VM,rY=m.forwardRef(function(t,n){const{render:s,className:i,style:r,children:a,...l}=t,{filteredItems:c}=$M(),d=WM(),u=tY(),h=c.length===0?a:null;return Ql("div",t,{ref:[n,d.state.emptyRef,u],props:[{children:h,role:"status","aria-live":"polite","aria-atomic":!0},l]})}),Dx=Xq,jp=new WeakMap;function Nr(e,t){const n=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(e));return Number.isFinite(n)?n:t}function cm(e){if(e.classList.contains("is-clearing"))return;const t=e.querySelector("input"),n=e.querySelector(".t-clear-mirror");if(!t||!n)return;const s=t.value.length>0;e.classList.toggle("has-value",s),n.textContent=s?t.value.replace(/ /g," "):""}function aY(e){const t=e.closest(".t-clear"),n=t?.querySelector("input"),s=t?.querySelector(".t-clear-mirror"),i=t?.querySelector(".t-clear-placeholder");if(!t||!n||!s||!i||!n.value)return;const r=jp.get(t);if(r!==void 0&&window.clearTimeout(r),s.textContent=n.value.replace(/ /g," "),i.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=Nr("--clear-dur",1e3),c=Nr("--clear-out-dur",400),d=Nr("--clear-in-dur",400),u=Nr("--clear-out-fly",12),h=Nr("--clear-in-fly",12),p=Nr("--clear-blur",2),f=a.getPropertyValue("--clear-out-ease").trim()||"ease-out",x=a.getPropertyValue("--clear-in-ease").trim()||"ease-out",g=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=i.animate([{transform:`translateY(-${h}px)`,opacity:.9,filter:`blur(${p}px)`},{transform:"translateY(0)",opacity:1,filter:"blur(0)"}],{duration:d,easing:x,fill:"forwards"}),w=window.setTimeout(()=>{g.cancel(),v.cancel(),t.classList.remove("is-clearing"),s.textContent="",jp.delete(t),cm(t)},Math.max(l,c,d));jp.set(t,w)}function Px({className:e,showTrigger:t=!1,showClear:n=!1,startAddon:s,size:i,...r}){const a=i??"default",l=m.useRef(null);return m.useLayoutEffect(()=>{l.current&&cm(l.current)},[r.value]),o.jsxs("div",{ref:l,className:"t-clear autocomplete-clear-dissolve relative w-full",onInput:c=>cm(c.currentTarget),children:[s&&o.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}),o.jsx(UM,{className:q(s&&"data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7.5)-1px)] *:data-[slot=autocomplete-input]:ps-[calc(--spacing(8.5)-1px)] sm:data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7)-1px)] sm:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(8)-1px)]",a==="sm"?"has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-6.5":"has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-7",e),"data-slot":"autocomplete-input",render:o.jsx(Wt,{size:a}),...r}),o.jsx("div",{"aria-hidden":"true",className:q("t-clear-mirror px-[calc(--spacing(3)-1px)] text-base sm:text-sm",a==="sm"&&"px-[calc(--spacing(2.5)-1px)]",s&&(a==="sm"?"ps-[calc(--spacing(7.5)-1px)] sm:ps-[calc(--spacing(7)-1px)]":"ps-[calc(--spacing(8.5)-1px)] sm:ps-[calc(--spacing(8)-1px)]"))}),o.jsx("div",{"aria-hidden":"true",className:q("t-clear-placeholder px-[calc(--spacing(3)-1px)] text-base text-muted-foreground/72 opacity-0 sm:text-sm",a==="sm"&&"px-[calc(--spacing(2.5)-1px)]",s&&(a==="sm"?"ps-[calc(--spacing(7.5)-1px)] sm:ps-[calc(--spacing(7)-1px)]":"ps-[calc(--spacing(8.5)-1px)] sm:ps-[calc(--spacing(8)-1px)]")),children:r.placeholder}),o.jsx("div",{"aria-hidden":"true",className:"t-clear-glow"}),t&&o.jsx(uY,{className:q("-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",a==="sm"?"end-0":"end-0.5"),children:o.jsx(Sk,{})}),n&&o.jsx(dY,{className:q("-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",a==="sm"?"end-0":"end-0.5"),children:o.jsx(ln,{})})]})}function YT({className:e,children:t,sideOffset:n=4,zIndex:s,...i}){return o.jsx(KM,{children:o.jsx(qM,{className:"z-[55] select-none",style:s?{zIndex:s}:void 0,"data-slot":"autocomplete-positioner",sideOffset:n,children:o.jsx("span",{className:q("relative flex max-h-full origin-(--transform-origin) rounded-lg border bg-popover bg-clip-padding transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-lg has-data-starting-style:scale-98 has-data-starting-style:opacity-0 dark:not-in-data-[slot=group]:bg-clip-border",e),children:o.jsx(YM,{className:"flex max-h-[min(var(--available-height),23rem)] w-(--anchor-width) max-w-(--available-width) flex-col","data-slot":"autocomplete-popup",...i,children:t})})})})}function Ex({className:e,children:t,...n}){return o.jsx(oY,{className:q("flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",e),"data-slot":"autocomplete-item",...n,children:t})}function lY({className:e,...t}){return o.jsx(sY,{className:q("[[role=group]+&]:mt-1.5",e),"data-slot":"autocomplete-group",...t})}function cY({className:e,...t}){return o.jsx(iY,{className:q("px-2 py-1.5 font-medium text-muted-foreground text-xs",e),"data-slot":"autocomplete-group-label",...t})}function Ax({className:e,...t}){return o.jsx(rY,{className:q("not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",e),"data-slot":"autocomplete-empty",...t})}function Mx({className:e,...t}){return o.jsx(XM,{scrollbarGutter:!0,scrollFade:!0,children:o.jsx(JM,{className:q("not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3",e),"data-slot":"autocomplete-list",...t})})}function dY({className:e,onClickCapture:t,onPointerDownCapture:n,...s}){return o.jsx(ZM,{className:q("-translate-y-1/2 absolute end-0.5 top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-[color,background-color,box-shadow,opacity] pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",e),"data-slot":"autocomplete-clear",onClickCapture:i=>{t?.(i),i.defaultPrevented||aY(i.currentTarget)},onPointerDownCapture:i=>{n?.(i);const r=i.currentTarget.closest(".t-clear")?.querySelector("input");!i.defaultPrevented&&document.activeElement===r&&i.preventDefault()},...s,children:o.jsx(ln,{})})}function uY({className:e,...t}){return o.jsx(Jq,{className:e,"data-slot":"autocomplete-trigger",...t})}const XT=m.createContext({inputRef:null}),JT=QM,hY=eR;function pY({className:e,...t}){return o.jsx(sR,{className:q("fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",e),"data-slot":"command-dialog-backdrop",...t})}function fY({className:e,...t}){return o.jsx(iR,{className:q("fixed inset-0 z-50 flex flex-col items-center px-4 py-[max(--spacing(4),4vh)] sm:py-[10vh]",e),"data-slot":"command-dialog-viewport",...t})}function ZT({className:e,children:t,...n}){const s=m.useRef(null);return o.jsxs(hY,{children:[o.jsx(tR,{}),o.jsx(pY,{}),o.jsx(fY,{children:o.jsx(nR,{className:q("-translate-y-[calc(1.25rem*var(--nested-dialogs))] relative row-start-2 flex max-h-100 min-h-0 w-full min-w-0 max-w-xl scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border bg-popover bg-clip-padding text-popover-foreground opacity-[calc(1-0.1*var(--nested-dialogs))] shadow-lg transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:bg-muted/50 before:shadow-[0_1px_--theme(--color-black/4%)] data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 **:data-[slot=scroll-area-viewport]:data-has-overflow-y:pe-1 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",e),"data-slot":"command-dialog-popup",initialFocus:s,...n,children:o.jsx(XT.Provider,{value:{inputRef:s},children:t})})})]})}function QT({autoHighlight:e="always",keepHighlight:t=!0,open:n=!0,...s}){return o.jsx(Dx,{autoHighlight:e,keepHighlight:t,open:n,...s})}function eI({className:e,placeholder:t=void 0,endAddon:n,...s}){const{inputRef:i}=m.useContext(XT);return o.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5",children:[o.jsx("div",{className:"min-w-0 flex-1",children:o.jsx(Px,{className:q("border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0",e),placeholder:t,ref:i,size:"lg",startAddon:o.jsx(Js,{}),...s})}),n]})}function tI({className:e,...t}){return o.jsx(Mx,{className:q("not-empty:scroll-py-2 not-empty:p-2",e),"data-slot":"command-list",...t})}function nI({className:e,...t}){return o.jsx(Ax,{className:q("not-empty:py-6",e),"data-slot":"command-empty",...t})}function sI({className:e,...t}){return o.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 Tr({className:e,...t}){return o.jsx(lY,{className:e,"data-slot":"command-group",...t})}function Ir({className:e,...t}){return o.jsx(cY,{className:e,"data-slot":"command-group-label",...t})}function Jo({className:e,...t}){return o.jsx(Ex,{className:q("py-1.5",e),"data-slot":"command-item",...t})}function ky({className:e,...t}){return o.jsx("span",{className:q("ms-auto font-medium text-muted-foreground/72 text-xs tracking-widest",e),"data-slot":"command-shortcut",...t})}function iI({className:e,...t}){return o.jsx("div",{className:q("flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] px-5 py-3 text-muted-foreground text-xs",e),"data-slot":"command-footer",...t})}const _y=e=>e.locator.kind==="timeline"?`${e.chatId}:${e.locator.seq}`:`${e.chatId}:${e.locator.conversationId}:${e.locator.messageIndex}`;function oI({className:e}){const{t}=te(),n=xe(r=>r.keybindings),s=Ii(n)["search-workspace"],i=t("Search messages");return o.jsx("button",{type:"button",className:e,onClick:()=>re.getState().setSearchOpen(!0),title:s?`${i} (${Mi(s)})`:i,children:o.jsx(Js,{className:"h-4 w-4"})})}function mY(){const{t:e,locale:t}=te(),n=re(v=>v.searchOpen),s=re(v=>v.setSearchOpen),i=re(v=>v.bots),r=re(v=>v.chats),[a,l]=m.useState(""),[c,d]=m.useState(),u=a.trim(),h=m.useMemo(()=>new Map(i.map(v=>[v.id,v])),[i]),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 w=window.setTimeout(()=>{window.electronAPI.bots.search({query:u}).then(y=>{v||d(y.ok?{key:u,hits:y.hits,truncated:y.truncated}:{key:u,hits:[],truncated:!1})}).catch(()=>{v||d({key:u,hits:[],truncated:!1})})},150);return()=>{v=!0,window.clearTimeout(w)}},[n,u]);const x=v=>{v.key==="Escape"&&(v.preventDefault(),v.stopPropagation(),s(!1))},g=Date.now();return o.jsx(JT,{open:n,onOpenChange:s,children:o.jsx(ZT,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:x,children:o.jsxs(QT,{children:[o.jsx(eI,{placeholder:e("Search group and direct messages…"),value:a,onChange:v=>l(v.currentTarget.value),onKeyDown:v=>{x(v);const w=f?.hits[0];v.key==="Enter"&&!v.nativeEvent.isComposing&&w&&!document.querySelector('[data-slot="command-dialog-popup"] [data-highlighted]')&&(v.preventDefault(),re.getState().focusHit(w,u))}}),o.jsxs(sI,{children:[u&&f&&f.hits.length===0&&o.jsx(nI,{children:e("No matching messages")}),o.jsxs(tI,{children:[f?.hits.map(v=>{const w=p.get(v.chatId),y=(w?.members??[]).map(j=>h.get(j)).filter(j=>j!==void 0),b=v.speaker.kind==="human"?e("You"):h.get(v.speaker.botId)?.name??e("Deleted member"),_=v.locator.kind==="session"&&!v.locator.current?` · ${e("History")}`:"";return o.jsxs(Jo,{value:_y(v),className:"items-start gap-2.5",onClick:()=>re.getState().focusHit(v,u),children:[o.jsx("span",{className:"mt-0.5 shrink-0",children:v.chatKind==="direct"?o.jsx(Jt,{bot:y[0]}):o.jsx(Za,{bots:y})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-xs",children:[o.jsx("span",{className:"truncate font-medium",children:w?bs(w,i,e):e("Deleted chat")}),o.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[b,_]})]}),o.jsx("p",{className:"line-clamp-2 break-words text-muted-foreground text-xs",children:yq(v.snippet,v.ranges).map((j,N)=>j.match?o.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:j.text},N):o.jsx("span",{children:j.text},N))})]}),o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:v.at?Do(v.at,t,g):""})]},_y(v))}),f?.truncated&&o.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})})]})]}),o.jsxs(iI,{children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsxs(Ck,{children:[o.jsx(ii,{children:"↑"}),o.jsx(ii,{children:"↓"})]}),e("Navigate")]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(ii,{children:"↵"}),e("Open")]})]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(ii,{children:"esc"}),e("Close")]})]})]})})})}function gY({chat:e,onOpenChange:t}){const{t:n}=te(),s=re(f=>f.bots),i=re(f=>f.chats),r=xe(f=>f.projects),[a,l]=m.useState(""),[c,d]=m.useState(!1);if(m.useEffect(()=>{if(!e)return;const f=i.filter(x=>x.kind==="group").map(x=>x.title);l(oR(n("{{title}} copy",{title:bs(e,s,n)}),f)),d(!1)},[e?.id]),!e)return null;const u=f=>s.find(x=>x.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 x=await window.electronAPI.bots.cloneChat({chatId:e.id,title:f});if(!x.ok){We({type:"error",title:Cs(x.error,n)});return}const g=re.getState();g.upsertChat(x.chat),g.setView({kind:"chat",chatId:x.chat.id}),g.loadLatest(x.chat.id),We({type:"success",title:n("Cloned. The chat history is empty.")}),t(!1)}finally{d(!1)}}};return o.jsx(gn,{open:!0,onOpenChange:t,children:o.jsxs(xn,{className:"max-w-md",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:n("Clone group chat")}),o.jsx(Os,{children:n("Copies the setup of “{{title}}”. The original stays as is; replies in progress are not stopped.",{title:bs(e,s,n)})})]}),o.jsxs(Rn,{className:"space-y-4 text-sm",children:[o.jsxs("div",{children:[o.jsx(Bt,{children:n("Group name")}),o.jsx(Wt,{value:a,autoFocus:!0,onChange:f=>l(f.target.value),onKeyDown:f=>f.key==="Enter"&&void p()})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Bt,{children:n("Will copy")}),o.jsxs("p",{children:[o.jsxs("span",{className:"text-muted-foreground",children:[n("Members"),":"]}),e.members.map(u).join("、")]}),o.jsxs("p",{children:[o.jsxs("span",{className:"text-muted-foreground",children:[n("Owner"),":"]}),u(e.bossBotId)]}),o.jsxs("p",{children:[o.jsxs("span",{className:"text-muted-foreground",children:[n("Routing"),":"]}),h]}),o.jsxs("p",{children:[o.jsxs("span",{className:"text-muted-foreground",children:[n("Workspace"),":"]}),e.workspace.kind==="project"?n("Same project: {{name}}",{name:pk(e,r,s,n)}):n("A new empty folder, separate from the original")]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Bt,{children:n("Not copied")}),o.jsx("p",{className:"text-muted-foreground",children:n("Chat history, group notes, routines, task board and group memory")})]})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),o.jsx(le,{size:"sm",disabled:!a.trim()||c,onClick:()=>{p()},children:n("Clone")})]})]})})}const Wo="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function xY({width:e,onCollapse:t,onNewMember:n,onNewGroup:s,onNewTeam:i,onStartFromGoal:r}){const{t:a,locale:l}=te(),c=[{label:a("Start from a goal"),icon:Sa,onClick:r},{label:a("New member"),icon:Ml,onClick:n},{label:a("New group chat"),icon:ta,onClick:s},{label:a("Create team from template"),icon:nf,onClick:i}],d=re(Z=>Z.bots),u=re(Z=>Z.chats),h=re(Z=>Z.queue),p=re(Z=>Z.sessions),f=re(Z=>Z.delegations),x=re(Z=>Z.timelines),g=re(Z=>Z.reads),v=re(Z=>Z.view),w=re(Z=>Z.setView),y=re(Z=>Z.openDirect),b=re(Z=>Z.upsertChat),_=re(Z=>Z.upsertBot),[j,N]=m.useState(!1),[C,k]=m.useState(""),[E,I]=m.useState(null),[T,A]=m.useState(null),D=m.useMemo(()=>new Map(d.map(Z=>[Z.id,Z])),[d]),W=m.useMemo(()=>Object.fromEntries(d.map(Z=>[Z.id,Z.name])),[d]),J=m.useMemo(()=>xk(p,vk(u,f)),[p,u,f]),O=m.useMemo(()=>{const Z=new Set,je=new Set;for(const tt of f)kl(tt.state)&&(tt.chatId&&Z.add(tt.chatId),je.add(tt.targetBotId));return{chatIds:Z,botIds:je}},[f]),B=m.useMemo(()=>rR(u.map(Z=>{const je=Ym(Z,{sessions:p,timeline:x[Z.id],queue:h,names:W});return{chat:Z,summary:{...je,running:je.running||(Z.kind==="group"?O.chatIds.has(Z.id):O.botIds.has(Z.members[0])),pending:J.filter(tt=>tt.chatId===Z.id).length}}}),g),[u,p,x,h,W,J,O,g]),L=B.filter(Z=>!Z.chat.archivedAt),se=aR(L.filter(Z=>Z.chat.kind==="group"&&Z.chat.settledAt===void 0)),Q=new Map(L.filter(Z=>Z.chat.kind==="direct").map(Z=>[Z.chat.members[0],Z])),V=d.filter(Z=>Z.archivedAt===void 0&&Q.get(Z.id)?.chat.settledAt===void 0).map(Z=>({bot:Z,row:Q.get(Z.id)})).sort((Z,je)=>{const tt=Number(je.row?.chat.pinned??!1)-Number(Z.row?.chat.pinned??!1),Et=(Z.row?.chat.pinOrder??Number.POSITIVE_INFINITY)-(je.row?.chat.pinOrder??Number.POSITIVE_INFINITY);return tt||(Z.row?.chat.pinned&&Et?Et:0)||(je.row?.summary.activityAt??je.bot.updatedAt)-(Z.row?.summary.activityAt??Z.bot.updatedAt)}),H=L.filter(Z=>Z.chat.settledAt!==void 0&&(Z.chat.kind==="group"||D.get(Z.chat.members[0])?.archivedAt===void 0)).sort((Z,je)=>(je.chat.settledAt??0)-(Z.chat.settledAt??0)),ne=se.filter(Z=>Z.chat.pinned).map(Z=>Z.chat.id),he=V.flatMap(({row:Z})=>Z?.chat.pinned?[Z.chat.id]:[]),[pe,ke]=m.useState(null),[Me,fe]=m.useState(!0),F=B.filter(Z=>Z.chat.archivedAt!==void 0),U=d.filter(Z=>Z.archivedAt!==void 0),de=F.length+U.length,Y=C.trim().toLowerCase(),X=(...Z)=>!Y||Z.some(je=>je.toLowerCase().includes(Y)),z=F.filter(({chat:Z,summary:je})=>X(bs(Z,d,a),je.preview??"")).sort((Z,je)=>(je.chat.archivedAt??0)-(Z.chat.archivedAt??0)),ue=U.filter(Z=>X(Z.name,Z.title,Z.scope)).sort((Z,je)=>(je.archivedAt??0)-(Z.archivedAt??0)),_e=eg(),Ee=v?.kind==="chat"?v.chatId:null,Be=async(Z,je)=>{const tt=await window.electronAPI.bots.updateChat({chatId:Z.id,...je});tt.ok?b(tt.chat):We({type:"error",title:Cs(tt.error,a)})},De=Z=>Be(Z,Z.pinned?{pinned:!1}:{pinned:!0,pinOrder:Math.max(-1,...u.filter(je=>je.pinned).map(je=>je.pinOrder??0))+1}),Ue=(Z,je,tt)=>{const Et=Object.fromEntries(u.map(zt=>[zt.id,zt.pinOrder]));for(const zt of dR(Z,je,tt,Et)){const we=u.find(ft=>ft.id===zt.chatId);we&&Be(we,{pinOrder:zt.pinOrder})}},St=(Z,je)=>{const tt=je.indexOf(Z.id),Et=B.find(zt=>zt.chat.id===Z.id)?.summary;return{onSettle:()=>{Be(Z,{settled:Z.settledAt===void 0})},onSnooze:zt=>{Be(Z,{snoozedUntil:zt})},onMarkUnread:Et&&Ee!==Z.id&&!Va(Et.marker,g[Et.key])&&lR(Et.marker)!==void 0?()=>re.getState().markUnread(Z.id):void 0,onMoveUp:tt>0?()=>Ue(je,Z.id,tt-1):void 0,onMoveDown:tt>=0&&tt<je.length-1?()=>Ue(je,Z.id,tt+1):void 0}},Ut=(Z,je)=>Z?.pinned?{draggable:!0,onDragStart:tt=>{tt.dataTransfer.effectAllowed="move",ke(Z.id)},onDragEnd:()=>ke(null),onDragOver:tt=>{pe&&pe!==Z.id&&je.includes(pe)&&tt.preventDefault()},onDrop:tt=>{tt.preventDefault(),pe&&je.includes(pe)&&Ue(je,pe,je.indexOf(Z.id)),ke(null)}}:{},tn=async(Z,je)=>{const tt=await window.electronAPI.bots.archive(Z.id,je);tt.ok?_(tt.bot):We({type:"error",title:tt.error})},Ne=Z=>Z?Z.running?a("Working"):Z.queued?a("Queued"):Z.activityAt?Do(Z.activityAt,l):null:null;return o.jsxs("aside",{className:"flex shrink-0 flex-col overflow-hidden border-r bg-background",style:{width:e},children:[o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pt-2 pb-2",children:[o.jsx(Np,{title:a("Group chats"),onAdd:s,addLabel:a("New group chat")}),se.length===0&&o.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No group chats yet")}),se.map(({chat:Z,summary:je})=>o.jsx(Ip,{chat:Z,onPin:()=>{De(Z)},onArchive:()=>{Be(Z,{archived:!0})},onDelete:()=>I(Z),onClone:()=>A(Z),manage:St(Z,ne),children:o.jsx(Tp,{...Ut(Z,ne),active:Ee===Z.id,avatar:o.jsx(Za,{bots:Z.members.map(tt=>D.get(tt)),busy:je.running}),title:bs(Z,d,a),pinned:Z.pinned,meta:Ne(je),preview:je.preview,unread:Va(je.marker,g[je.key]),pending:je.pending,onClick:()=>w({kind:"chat",chatId:Z.id})})},Z.id)),o.jsx(Np,{title:a("Members"),onAdd:n,addLabel:a("New member")}),V.length===0&&o.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No members yet")}),V.map(({bot:Z,row:je})=>o.jsx(Ip,{chat:je?.chat,onPin:je?()=>{De(je.chat)}:void 0,onArchive:je?()=>{Be(je.chat,{archived:!0})}:void 0,onArchiveMember:()=>{tn(Z,!0)},manage:je?St(je.chat,he):void 0,children:o.jsx(Tp,{...Ut(je?.chat,he),active:!!(je&&Ee===je.chat.id),avatar:o.jsx(Jt,{bot:Z,busy:je?.summary.running||O.botIds.has(Z.id)}),title:Z.name,pinned:je?.chat.pinned,meta:O.botIds.has(Z.id)?a("Working"):Ne(je?.summary),preview:je?.summary.preview||Z.title||Z.scope,unread:!!(je&&Va(je.summary.marker,g[je.summary.key])&&Ee!==je.chat.id),pending:je?.summary.pending??0,onClick:()=>{y(Z.id)}})},Z.id)),H.length>0&&o.jsx(Np,{title:`${a("Settled")} · ${H.length}`,onToggle:()=>fe(Z=>!Z)}),Me&&H.map(({chat:Z,summary:je})=>{const tt=Z.kind==="direct"?D.get(Z.members[0]):void 0;return o.jsx(Ip,{chat:Z,onPin:()=>{De(Z)},onArchive:()=>{Be(Z,{archived:!0})},onClone:Z.kind==="group"?()=>A(Z):void 0,manage:St(Z,[]),children:o.jsx(Tp,{className:"opacity-75",active:Ee===Z.id,avatar:tt?o.jsx(Jt,{bot:tt,busy:je.running}):o.jsx(Za,{bots:Z.members.map(Et=>D.get(Et)),busy:je.running}),title:tt?tt.name:bs(Z,d,a),meta:Z.snoozedUntil!==void 0?a("Remind {{time}}",{time:Do(Z.snoozedUntil,l)}):Ne(je),preview:je.preview,unread:Va(je.marker,g[je.key])&&(Z.kind==="group"||Ee!==Z.id),pending:je.pending,onClick:()=>tt?void y(tt.id):w({kind:"chat",chatId:Z.id})})},Z.id)})]}),o.jsxs("div",{className:"@container flex shrink-0 items-center justify-between border-t p-2",children:[t?o.jsx("button",{type:"button",onClick:t,className:Wo,title:a("Collapse sidebar"),children:o.jsx(Xg,{className:"h-4 w-4"})}):o.jsx("span",{}),o.jsxs("div",{className:"flex items-center",children:[o.jsx(oI,{className:Wo}),c.map(({label:Z,icon:je,onClick:tt})=>o.jsx("button",{type:"button",className:q(Wo,"hidden @min-[18.5rem]:flex"),onClick:tt,title:Z,children:o.jsx(je,{className:"h-4 w-4"})},Z)),o.jsxs(zi,{children:[o.jsx(Gi,{className:q(Wo,"@min-[18.5rem]:hidden"),title:a("More actions"),children:o.jsx(sh,{className:"h-4 w-4"})}),o.jsx(Fi,{align:"end",side:"top",children:c.map(({label:Z,icon:je,onClick:tt})=>o.jsxs(dn,{onClick:tt,children:[o.jsx(je,{}),Z]},Z))})]}),(_e>0||v?.kind==="inbox")&&o.jsxs("button",{type:"button",className:q(Wo,v?.kind==="inbox"&&"bg-brand/10 text-foreground hover:bg-brand/10 dark:bg-brand/15 dark:hover:bg-brand/15"),onClick:()=>w({kind:"inbox"}),title:a("Inbox"),children:[o.jsx(qg,{className:"h-4 w-4"}),_e>0&&o.jsx(yh,{count:_e,className:"-top-0.5 -right-1 absolute"})]}),de>0&&o.jsx("button",{type:"button",className:Wo,onClick:()=>{k(""),N(!0)},title:`${a("Archived")} (${de})`,children:o.jsx(ji,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",className:Wo,onClick:()=>{window.electronAPI.window.openSettings()},title:a("Settings"),children:o.jsx(ai,{className:"h-4 w-4"})})]})]}),o.jsx(gn,{open:j,onOpenChange:N,children:o.jsxs(xn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[o.jsxs(vn,{children:[o.jsxs(bn,{className:"flex items-baseline gap-2",children:[a("Archived"),o.jsx("span",{className:"font-sans text-muted-foreground text-sm tabular-nums",children:de})]}),o.jsxs(zu,{"data-size":"sm",className:"mt-1",children:[o.jsx(Gu,{children:o.jsx(Js,{})}),o.jsx(Fu,{value:C,placeholder:a("Search conversations..."),onChange:Z=>k(Z.target.value)})]})]}),o.jsxs(Rn,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[z.length+ue.length===0&&o.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:C.trim()?a("No matching conversations"):a("Nothing archived")}),z.length>0&&o.jsx(jy,{title:a("Chat threads"),count:z.length,children:z.map(({chat:Z,summary:je})=>o.jsx(Ny,{avatar:Z.kind==="group"?o.jsx(Za,{bots:Z.members.map(tt=>D.get(tt))}):o.jsx(Jt,{bot:D.get(Z.members[0])}),title:bs(Z,d,a),preview:je.preview,onOpen:()=>{w({kind:"chat",chatId:Z.id}),N(!1)},onRestore:()=>{Be(Z,{archived:!1})},onDelete:Z.kind==="group"?()=>I(Z):void 0},Z.id))}),ue.length>0&&o.jsx(jy,{title:a("Members"),count:ue.length,children:ue.map(Z=>o.jsx(Ny,{avatar:o.jsx(Jt,{bot:Z}),title:Z.name,preview:Z.title||Z.scope,onRestore:()=>{tn(Z,!1)}},Z.id))})]})]})}),o.jsx(hs,{open:E!==null,onOpenChange:Z=>!Z&&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 Z=E;I(null),Z&&window.electronAPI.bots.deleteChat(Z.id).then(je=>{je.ok?(Ee===Z.id&&w(null),re.getState().refreshChats()):We({type:"error",title:Cs(je.error,a)})})}}),o.jsx(gY,{chat:T,onOpenChange:Z=>!Z&&A(null)})]})}function yh({count:e,className:t}){return o.jsx("span",{className:q("min-w-4 rounded-full bg-destructive px-1 text-center font-medium text-[10px] text-white leading-4",t),children:e>99?"99+":e})}function jy({title:e,count:t,children:n}){return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2 pr-0.5 pl-2",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate py-1 font-medium text-[10px] text-muted-foreground uppercase tracking-wide",children:e}),o.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:t})]}),o.jsx("div",{className:"flex flex-col gap-y-0.5",children:n})]})}function Ny({avatar:e,title:t,preview:n,onOpen:s,onRestore:i,onDelete:r}){const{t:a}=te(),l="shrink-0 rounded p-1 text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground group-hover:opacity-100";return o.jsxs("div",{className:"group flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/60",children:[o.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,o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate text-sm",children:t}),n&&o.jsx("span",{className:"block truncate text-muted-foreground text-xs",children:n})]})]}),o.jsx("button",{type:"button",className:l,onClick:i,title:a("Unarchive"),children:o.jsx(Al,{className:"h-3.5 w-3.5"})}),r&&o.jsx("button",{type:"button",className:q(l,"hover:text-destructive"),onClick:r,title:a("Delete"),children:o.jsx(di,{className:"h-3.5 w-3.5"})})]})}function Np({title:e,onAdd:t,addLabel:n,onToggle:s}){return o.jsxs("div",{className:"flex items-center justify-between px-4 pt-3 pb-1 text-[11px] text-muted-foreground",children:[s?o.jsx("button",{type:"button",onClick:s,className:"hover:text-foreground",children:e}):o.jsx("span",{children:e}),t&&o.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:o.jsx(ps,{className:"h-3.5 w-3.5"})})]})}function Tp({active:e,avatar:t,title:n,pinned:s,meta:i,preview:r,unread:a,pending:l=0,action:c,className:d,...u}){return o.jsxs("div",{role:"button",tabIndex:0,...u,onKeyDown:h=>{h.key==="Enter"&&u.onClick?.(h)},className:q("mx-1.5 flex cursor-default items-center gap-2.5 rounded-lg px-2.5 py-1.5 transition-colors",e?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted",d),children:[t,o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 truncate font-medium text-sm",children:n}),s&&o.jsx(Si,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"flex-1"}),l>0?o.jsx(yh,{count:l}):i&&o.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:i})]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",children:r}),a&&o.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-info"}),c&&o.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 Ip({chat:e,children:t,onPin:n,onArchive:s,onDelete:i,onArchiveMember:r,onClone:a,manage:l}){const{t:c}=te(),d=u=>l?.onSnooze(cR(Date.now())[u]);return o.jsxs(ao,{children:[o.jsx(lo,{render:t}),o.jsxs(co,{className:"min-w-40",children:[n&&o.jsxs(Ht,{onClick:n,children:[e?.pinned?o.jsx(au,{}):o.jsx(Si,{}),e?.pinned?c("Unpin"):c("Pin")]}),l?.onMoveUp&&o.jsxs(Ht,{onClick:l.onMoveUp,children:[o.jsx(nh,{}),c("Move up")]}),l?.onMoveDown&&o.jsxs(Ht,{onClick:l.onMoveDown,children:[o.jsx(th,{}),c("Move down")]}),l&&o.jsxs(Ht,{onClick:l.onSettle,children:[e?.settledAt!==void 0?o.jsx(qm,{}):o.jsx(zm,{}),e?.settledAt!==void 0?c("Back to in progress"):c("Settle")]}),l&&o.jsxs(kk,{children:[o.jsxs(_k,{children:[o.jsx(wH,{}),c("Remind me later")]}),o.jsxs(jk,{className:"min-w-36",children:[o.jsx(Ht,{onClick:()=>d("hour"),children:c("In 1 hour")}),o.jsx(Ht,{onClick:()=>d("later"),children:c("In 3 hours")}),o.jsx(Ht,{onClick:()=>d("tomorrow"),children:c("Tomorrow 9:00")})]})]}),l?.onMarkUnread&&o.jsxs(Ht,{onClick:l.onMarkUnread,children:[o.jsx(HB,{}),c("Mark as unread")]}),a&&o.jsxs(Ht,{onClick:a,children:[o.jsx(Pu,{}),c("Clone group chat")]}),s&&o.jsxs(Ht,{onClick:s,children:[o.jsx(ji,{}),c("Archive chat")]}),r&&o.jsxs(Ht,{onClick:r,children:[o.jsx(Al,{}),c("Archive member")]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(tg,{}),o.jsxs(Ht,{variant:"destructive",onClick:i,children:[o.jsx(di,{}),c("Delete group chat")]})]})]})]})}const vY=30;function Ty({onPick:e}){const{t,locale:n}=te(),s=n==="zh"?"zh":"en",i=Nk(),r=re(_=>_.bots),[a,l]=m.useState(""),[c,d]=m.useState(!1),[u,h]=m.useState(null),[p,f]=m.useState(null),[x,g]=m.useState(""),v=async()=>{if(!(!a.trim()||c)){d(!0),h(null);try{const _=await window.electronAPI.bots.suggestGoal({goal:a.trim(),language:s,...r.length?{members:r.map(({id:j,name:N,title:C,scope:k})=>({id:j,name:N,title:C,scope:k}))}:{},templates:i.slice(0,vY).map(({id:j,data:N})=>({id:j,title:N.title,summary:N.summary}))});if(!_.ok){h(bh(_,t));return}f(_.suggestion),g(_.suggestion.firstMessage)}finally{d(!1)}}},w=async _=>{if(!c){d(!0),h(null);try{await e(_)}catch{h(t("Could not open chat. Try again."))}finally{d(!1)}}};if(!p)return o.jsxs("div",{className:"w-full max-w-lg space-y-2 text-left",children:[o.jsx(Ys,{value:a,autoFocus:!0,rows:3,placeholder:t("e.g. Track competitor news every week and send me a summary"),onChange:_=>l(_.target.value),onKeyDown:_=>{_.key==="Enter"&&(_.metaKey||_.ctrlKey)&&v()}}),u&&o.jsx("p",{className:"text-destructive text-xs",children:u}),o.jsx("div",{className:"flex justify-end",children:o.jsxs(le,{size:"sm",disabled:!a.trim()||c,onClick:()=>{v()},children:[c?o.jsx(Vt,{className:"animate-spin"}):o.jsx(Ls,{}),t("Recommend")]})})]});const y=p.kind==="team"?i.find(_=>_.id===p.templateId)?.data:void 0,b=p.kind==="existing"?r.find(_=>_.id===p.botId):p.kind==="member"?{...p.member,avatar:{color:qo[0]}}:void 0;return o.jsxs("div",{className:"w-full max-w-lg space-y-3 text-left",children:[o.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[o.jsxs("p",{className:"mb-2 flex items-center gap-1.5 text-muted-foreground text-xs",children:[o.jsx(Sa,{className:"h-3.5 w-3.5"}),p.kind==="team"?t("Recommended: a team"):t("Recommended: one member")]}),b?o.jsxs("div",{className:"flex items-start gap-2.5",children:[o.jsx(Jt,{bot:b}),o.jsxs("div",{className:"min-w-0",children:[o.jsxs("p",{className:"font-medium text-sm",children:[b.name,o.jsx("span",{className:"ml-2 font-normal text-muted-foreground text-xs",children:b.title})]}),b.scope&&o.jsx("p",{className:"text-muted-foreground text-xs",children:b.scope})]})]}):y&&o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("div",{className:"-space-x-1.5 flex",children:y.members.map(_=>o.jsx(Jt,{size:"sm",bot:{name:_.name,avatar:{color:_.color}}},_.key))}),o.jsx("p",{className:"font-medium text-sm",children:y.title}),o.jsx("p",{className:"text-muted-foreground text-xs",children:y.summary})]}),p.reason&&o.jsx("p",{className:"mt-2 text-muted-foreground text-xs",children:p.reason})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("p",{className:"text-muted-foreground text-xs",children:t("First message (put into the input box, not sent)")}),o.jsx(Ys,{value:x,rows:3,onChange:_=>g(_.target.value)})]}),u&&o.jsx("p",{className:"text-destructive text-xs",children:u}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs(le,{size:"sm",variant:"ghost",disabled:c,onClick:()=>{f(null),h(null)},children:[o.jsx(Au,{}),t("Back")]}),o.jsxs("div",{className:"flex gap-2",children:[p.kind==="existing"&&o.jsx(le,{size:"sm",variant:"outline",disabled:c,onClick:()=>{w({firstMessage:x})},children:t("Create new instead")}),o.jsx(le,{size:"sm",disabled:c||p.kind==="existing"&&!b,onClick:()=>{w(p.kind==="existing"?{firstMessage:x,botId:p.botId}:p.kind==="member"?{firstMessage:x,member:p.member}:{firstMessage:x,templateId:p.templateId})},children:p.kind==="existing"?t("Use this member"):p.kind==="member"?t("Create this member"):t("Create this team")})]})]})]})}const Hc=e=>({..._T,name:"",title:"",scope:"",persona:"",color:e,engine:null});function bY({open:e,onOpenChange:t,seed:n,onCreated:s}){const{t:i}=te(),r=re(A=>A.bots),a=uR(),l=m.useRef(null),[c,d]=m.useState({kind:"template",id:"pm"}),[u,h]=m.useState(()=>Hc(qo[0])),[p,f]=m.useState(null),[x,g]=m.useState(null),[v,w]=m.useState(!1),[y,b]=m.useState(!1),[_,j]=m.useState(!1),N=()=>{d({kind:"blank"}),h(Hc(qo[r.length%qo.length])),f(null),g(null)},C=A=>{if(!A)return N();const D=hR(A.data);d({kind:"template",id:A.id}),h({..._T,name:D.name??"",title:D.title??"",scope:D.scope??"",persona:D.persona??"",color:D.avatar?.color??qo[0],engine:null,approvalMode:D.approvalMode??"auto-edits",tools:D.tools??"all"}),f(null),g(null)};m.useEffect(()=>{e&&(n?(d({kind:"blank"}),h({...Hc(qo[r.length%qo.length]),...n}),f(null),g(null)):C(a[0]),w(!1),b(!1),j(!1))},[e]);const k=A=>{h(D=>({...D,...A})),g(null)},E=async A=>{const D=new Uint8Array(await A.arrayBuffer()),W=wT(D)==="png",J=W?bK(py(D,"chara")??py(D,"ccv3")??""):new TextDecoder().decode(D),O=J?kK(J):{ok:!1,error:"not-a-card"};if(!O.ok){g(O.error==="invalid-json"&&!W?i("This file is not valid JSON."):i("This file is not a SillyTavern character card."));return}const{color:B,memoryEnabled:L,...se}=O.draft;d({kind:"import"}),h({...Hc(B??u.color),...se,...L!==void 0?{memoryEnabled:L}:{}}),f(W?await lk(A).catch(()=>null):null),w(!0),g(null)},I=Wm(u.name,r,i),T=async()=>{if(w(!0),I)return;const A=CT(u);if(!A.ok){g(i("Budget must be a positive number"));return}const D=Cx(u);if(!D.ok){g(i("Check the per-turn token limit and delegation time limit"));return}b(!0);try{const W=await window.electronAPI.bots.create({name:u.name.trim(),title:u.title.trim(),scope:u.scope.trim(),...D.delegationTimeoutMinutes?{delegationTimeoutMinutes:D.delegationTimeoutMinutes}:{},...D.maxTokensPerTurn?{maxTokensPerTurn:D.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},...A.budget?{budget:A.budget}:{}});if(!W.ok){g(Ja(W.reason,W.error,i));return}re.getState().upsertBot(W.bot),p&&!await ak(W.bot.id,p)&&We({type:"error",title:i("Avatar update failed")}),t(!1);const J=await re.getState().openDirect(W.bot.id);J&&s?.(J)}finally{b(!1)}};return o.jsx(gn,{open:e,onOpenChange:t,children:o.jsxs(xn,{className:"max-h-[85vh] max-w-3xl",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:i("New member")}),o.jsx(Os,{children:i("Members have their own persona, model, tools and memory. Their name is how you @ them in groups.")})]}),o.jsxs(Rn,{className:"space-y-4",children:[o.jsxs("div",{className:"flex gap-2",children:[o.jsx(le,{size:"sm",variant:c.kind==="template"?"default":"outline",disabled:a.length===0,onClick:()=>C(a[0]),children:i("From template")}),o.jsx(le,{size:"sm",variant:c.kind==="blank"?"default":"outline",onClick:N,children:i("Blank")}),o.jsxs(le,{size:"sm",variant:c.kind==="import"?"default":"outline",onClick:()=>l.current?.click(),children:[o.jsx(Bm,{}),i("Import character card")]}),o.jsx("input",{ref:l,type:"file",accept:".json,.png,application/json,image/png",hidden:!0,onChange:A=>{const D=A.target.files?.[0];A.target.value="",D&&E(D)}})]}),c.kind==="template"&&o.jsxs("div",{className:"grid grid-cols-3 gap-2.5",children:[a.map(A=>o.jsxs("button",{type:"button",onClick:()=>C(A),className:q("flex flex-col items-start gap-1 rounded-xl border bg-card p-3 text-left transition-colors hover:bg-muted",c.id===A.id&&"ring-2 ring-info"),children:[o.jsx(Jt,{bot:{name:A.data.title,avatar:{color:A.data.color}}}),o.jsx("span",{className:"font-medium text-sm",children:A.data.title}),o.jsx("span",{className:"text-muted-foreground text-xs",children:A.data.summary})]},A.id)),o.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:[o.jsx(ps,{className:"h-4 w-4"}),i("Blank member")]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Bt,{hint:i("Used for @ in groups; must be unique"),children:i("Name")}),o.jsx(Wt,{value:u.name,onChange:A=>k({name:A.target.value}),onBlur:()=>w(!0)}),v&&I&&o.jsx("p",{className:"mt-1 text-destructive text-xs",children:I})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:i("Title")}),o.jsx(Wt,{value:u.title,onChange:A=>k({title:A.target.value})})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:i("Model")}),o.jsx(rk,{engine:u.engine,onChange:A=>k({engine:A}),zIndex:yn.DROPDOWN_IN_MODAL})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:i("Avatar color")}),o.jsxs("div",{className:"flex items-start gap-2.5",children:[o.jsx(Jt,{bot:{name:u.name||"?",avatar:{color:u.color}},src:p??void 0,size:"md"}),o.jsxs("div",{className:"min-w-0 space-y-1.5",children:[o.jsx(ok,{value:u.color,onChange:A=>k({color:A})}),o.jsx(kT,{nested:!0,hasImage:!!p,onPick:f,onRemove:()=>f(null)})]})]})]}),o.jsxs("div",{className:"col-span-2",children:[o.jsx(Bt,{hint:i("Used for routing and the delegation directory"),children:i("Responsibilities")}),o.jsx(Wt,{value:u.scope,onChange:A=>k({scope:A.target.value})})]}),o.jsxs("div",{className:"col-span-2",children:[o.jsx(Bt,{action:o.jsx(DT,{value:u,onApply:k}),children:i("Persona")}),o.jsx(Ys,{rows:4,value:u.persona,onChange:A=>k({persona:A.target.value})})]}),o.jsxs("div",{className:"col-span-2 rounded-lg border",children:[o.jsxs("button",{type:"button",className:"flex w-full items-center gap-1.5 px-3 py-2 text-left text-sm","aria-expanded":_,onClick:()=>j(A=>!A),children:[o.jsx(kn,{className:q("h-4 w-4 transition-transform",_&&"rotate-90")}),o.jsx("span",{className:"font-medium",children:i("Abilities")}),o.jsx("span",{className:"truncate text-muted-foreground text-xs",children:i("Tools, approval, skills, MCP, delegation and memory")})]}),_&&o.jsx("div",{className:"border-t px-3 py-3",children:o.jsx(jT,{value:u,onChange:k,profile:u,zIndex:yn.DROPDOWN_IN_MODAL})})]})]}),x&&o.jsx("p",{className:"text-destructive text-sm",children:x})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:()=>t(!1),children:i("Cancel")}),o.jsxs(le,{size:"sm",disabled:y||v&&!!I,onClick:()=>{T()},children:[y&&o.jsx(Vt,{className:"animate-spin"}),i("Create and start chatting")]})]})]})})}function rI({projectId:e,onChange:t}){const{t:n}=te(),s=xe(p=>p.projects),i=xe(p=>p.addProject),r=m.useMemo(()=>Ou(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:Tk(f.path),detail:`${f.displayPath} · ${f.sourceName}`}))]},[r,a]),h=async p=>{d(p);const f=r.find(x=>x.path===p);if(f)return t(f.id);try{const x=await i(p);if(!x)throw new Error;t(x.id)}catch(x){We({type:"error",title:n("Failed to add project"),description:x instanceof Error&&x.message||void 0})}};return o.jsxs(Dx,{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 x=f.toLowerCase();return[p.label,p.path,p.detail].some(g=>g.toLowerCase().includes(x))},itemToStringValue:p=>p.path,children:[o.jsxs("div",{className:"mt-2 flex w-full gap-2",children:[o.jsx("div",{className:"min-w-0 flex-1",children:o.jsx(Px,{placeholder:n("Search Code projects or recent folders..."),showClear:!!c,showTrigger:!0})}),o.jsx(le,{type:"button",variant:"outline",onClick:()=>{window.electronAPI.dialog.selectDirectory().then(p=>{p&&h(p)})},children:n("Browse")})]}),o.jsxs(YT,{zIndex:yn.DROPDOWN_IN_MODAL,children:[o.jsx(Ax,{children:n("No matching projects found")}),o.jsx(Mx,{children:p=>o.jsxs(Ex,{value:p,className:"gap-2",children:[o.jsx("span",{className:"shrink-0",children:p.label}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",title:p.path,children:p.detail}),!p.projectId&&o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:n("Add")})]},p.path)})]})]})}function wY({open:e,onOpenChange:t}){const{t:n}=te(),s=re(T=>T.bots),i=m.useMemo(()=>s.filter(T=>T.archivedAt===void 0),[s]),r=Ou(xe(T=>T.projects)),[a,l]=m.useState(""),[c,d]=m.useState([]),[u,h]=m.useState(null),[p,f]=m.useState("project"),[x,g]=m.useState(""),[v,w]=m.useState(String(kr.maxHops)),[y,b]=m.useState(String(kr.maxTurnsPerBot)),[_,j]=m.useState(!1),[N,C]=m.useState(null);m.useEffect(()=>{e&&(l(""),d([]),h(null),f(r.length>0?"project":"chat-home"),g(r[0]?.id??""),w(String(kr.maxHops)),b(String(kr.maxTurnsPerBot)),j(!1),C(null))},[e]);const k=(T,A)=>{const D=A?[...c,T]:c.filter(W=>W!==T);d(D),D.includes(u??"")?!u&&D.length&&h(D[0]):h(D[0]??null)},E=c.length>=2&&u!==null&&(p==="chat-home"||!!x),I=async()=>{if(E){j(!0);try{const T=await window.electronAPI.bots.createChat({kind:"group",title:a.trim(),members:c,bossBotId:u,workspace:p==="project"?{kind:"project",projectId:x}:{kind:"chat-home"},routing:{maxHops:Math.round(Number(v))||kr.maxHops,maxTurnsPerBot:Math.round(Number(y))||kr.maxTurnsPerBot}});if(!T.ok){C(Cs(T.error,n));return}const A=re.getState();A.upsertChat(T.chat),A.setView({kind:"chat",chatId:T.chat.id}),A.loadLatest(T.chat.id),t(!1)}finally{j(!1)}}};return o.jsx(gn,{open:e,onOpenChange:t,children:o.jsxs(xn,{className:"max-h-[85vh] max-w-xl",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:n("New group chat")}),o.jsx(Os,{children:n("One member replies at a time. Without @, the best-fit member is picked to reply.")})]}),o.jsxs(Rn,{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx(Bt,{children:n("Group name")}),o.jsx(Wt,{value:a,onChange:T=>l(T.target.value)})]}),o.jsxs("div",{children:[o.jsx(Bt,{hint:n("Pick at least two, and one owner"),children:n("Members")}),i.length<2&&o.jsx("p",{className:"text-muted-foreground text-xs",children:n("Create at least two members first.")}),o.jsx("div",{className:"space-y-0.5",children:i.map(T=>{const A=c.includes(T.id);return o.jsxs("div",{className:"flex items-center gap-2.5 rounded-md px-1.5 py-1 hover:bg-muted",children:[o.jsx(ec,{checked:A,onCheckedChange:D=>k(T.id,D===!0)}),o.jsx(Jt,{bot:T,size:"sm"}),o.jsxs("span",{className:"min-w-0 flex-1 truncate text-sm",children:[T.name,T.title&&o.jsx("span",{className:"ml-1.5 text-muted-foreground text-xs",children:T.title})]}),A&&o.jsxs("label",{className:"flex shrink-0 items-center gap-1 text-muted-foreground text-xs",children:[o.jsx("input",{type:"radio",name:"group-owner",checked:u===T.id,onChange:()=>h(T.id),className:"accent-primary"}),n("Owner")]})]},T.id)})})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:n("Shared workspace")}),o.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[o.jsxs("button",{type:"button",onClick:()=>f("project"),className:q("rounded-xl border bg-card p-3 text-left disabled:opacity-50",p==="project"&&"ring-2 ring-info"),children:[o.jsx("div",{className:"font-medium text-sm",children:n("Based on a Code project")}),o.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:n("Members read and write directly in the project folder")})]}),o.jsxs("button",{type:"button",onClick:()=>f("chat-home"),className:q("rounded-xl border bg-card p-3 text-left",p==="chat-home"&&"ring-2 ring-info"),children:[o.jsx("div",{className:"font-medium text-sm",children:n("Standalone workspace")}),o.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"&&o.jsx(rI,{projectId:x,onChange:g}),o.jsxs("div",{className:"mt-2 flex gap-2 rounded-lg border border-warning/40 bg-warning/8 px-3 py-2 text-xs",children:[o.jsx(Zm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-warning"}),o.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).")})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Bt,{children:n("@ relay limit (per message of yours)")}),o.jsx(Wt,{type:"number",min:1,max:20,value:v,onChange:T=>w(T.target.value)})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:n("Max replies per member")}),o.jsx(Wt,{type:"number",min:1,max:10,value:y,onChange:T=>b(T.target.value)})]})]}),N&&o.jsx("p",{className:"text-destructive text-sm",children:N})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),o.jsxs(le,{size:"sm",disabled:!E||_,onClick:()=>{I()},children:[_&&o.jsx(Vt,{className:"animate-spin"}),n("Create")]})]})]})})}const Iy={skillIds:[],mcpServerIds:[]};function yY({open:e,onOpenChange:t,seedTemplateId:n,onCreated:s}){const{t:i,locale:r}=te(),a=re(H=>H.bots),l=Nk(),c=Ou(xe(H=>H.projects)),d=m.useRef(null),[u,h]=m.useState(null),[p,f]=m.useState("chat-home"),[x,g]=m.useState(""),[v,w]=m.useState(!1),[y,b]=m.useState(null),[_,j]=m.useState({}),[N,C]=m.useState(null),[k,E]=m.useState(!1);m.useEffect(()=>{if(!e)return;h(null),g(c[0]?.id??""),w(!1),b(null),j({}),C(null);const H=l.find(ne=>ne.id===n);H&&I({team:Nv(H.data)})},[e]);const I=async H=>{w(!0),b(null);try{const ne=await window.electronAPI.bots.previewTeam(H);if(!ne.ok){b(pR(ne.error,i));return}h({team:ne.team,renamed:ne.renamed,picked:ne.team.members.map(he=>he.key)}),j({}),C(null),f(ne.team.workspace==="project"&&c.length>0?"project":"chat-home")}finally{w(!1)}},T=H=>h(ne=>ne&&{...ne,team:H(ne.team)}),A=(H,ne)=>T(he=>({...he,members:he.members.map(pe=>pe.key===H?{...pe,...ne}:pe)})),D=m.useMemo(()=>u?fR(u.team,u.picked):null,[u]),W=m.useMemo(()=>{const H=new Map;if(!D)return H;const ne=[...a,...D.members.map(he=>({id:`team:${he.key}`,name:he.name}))];for(const he of D.members){const pe=Wm(he.name,ne,i,`team:${he.key}`);pe&&H.set(he.key,pe)}return H},[D,a,i]),J=D!==null&&W.size===0&&(p==="chat-home"||!!x)&&!v&&!k,O=H=>_[H]??Iy,B=(H,ne)=>j(he=>({...he,[H]:{...he[H]??Iy,...ne}})),L=async()=>{if(D){E(!0);try{const H=r==="zh"?"zh":"en",ne=await Promise.all(D.members.map(async F=>{try{const U=await window.electronAPI.bots.suggestAbilities({name:F.name,title:F.title,scope:F.scope,persona:F.persona,language:H});return{key:F.key,result:U}}catch{return{key:F.key,result:null}}}));let he=0,pe=0,ke;const Me={..._},fe=new Map;for(const{key:F,result:U}of ne){if(!U?.ok){pe++,U&&!ke&&(ke=bh(U,i));continue}const{suggestion:de}=U,Y={};de.tools&&(Y.tools=de.tools.value),de.approvalMode&&(Y.approvalMode=de.approvalMode.value),Object.keys(Y).length>0&&fe.set(F,Y);const X=de.skillIds?.value??O(F).skillIds,z=de.mcpServerIds?.value??O(F).mcpServerIds;Me[F]={skillIds:[...X],mcpServerIds:[...z]},(X.length+z.length>0||fe.has(F))&&he++}j(Me),fe.size>0&&T(F=>({...F,members:F.members.map(U=>({...U,...fe.get(U.key)}))})),pe>0&&We({type:"error",title:i("Suggestions failed for {{n}} members",{n:pe}),...ke?{description:ke}:{}}),pe<ne.length&&We({type:he>0?"success":"info",title:he>0?i("Configured abilities for {{n}} members",{n:he}):i("Current abilities already match the suggestion.")})}finally{E(!1)}}},se=async()=>{if(!(!D||!J)){w(!0),b(null);try{const H=Object.fromEntries(D.members.map(pe=>[pe.key,O(pe.key)]).filter(([,pe])=>pe.skillIds.length+pe.mcpServerIds.length>0)),ne=await window.electronAPI.bots.createTeam({team:{...D,title:D.title.trim()},workspace:p==="project"?{kind:"project",projectId:x}:{kind:"chat-home"},...Object.keys(H).length>0?{assets:H}:{}});if(!ne.ok){b(Ja(ne.error,Cs(ne.error,i),i));return}const he=re.getState();for(const pe of ne.bots)he.upsertBot(pe);he.upsertChat(ne.chat),he.setView({kind:"chat",chatId:ne.chat.id}),he.loadLatest(ne.chat.id),t(!1),s?.(ne.chat.id)}finally{w(!1)}}},Q=r==="zh"?"zh":"en",V=H=>u?.team.members.find(ne=>ne.key===H)?.name??H;return o.jsx(gn,{open:e,onOpenChange:t,children:o.jsxs(xn,{className:"max-h-[85vh] max-w-2xl",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:i("Create team from template")}),o.jsx(Os,{children:i("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.")})]}),o.jsxs(Rn,{className:"space-y-4",children:[u?o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx(Bt,{children:i("Group name")}),o.jsx(Wt,{value:u.team.title,onChange:H=>{const ne=H.target.value;T(he=>({...he,title:ne}))}})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[o.jsxs("span",{className:"flex items-baseline gap-2",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:i("Members")}),o.jsx("span",{className:"text-[11px] text-muted-foreground/70",children:i("Uncheck members you do not need; the owner stays")})]}),o.jsxs(le,{size:"xs",variant:"outline",disabled:!D||k||v,onClick:()=>{L()},children:[k?o.jsx(Vt,{className:"animate-spin"}):o.jsx(Ls,{}),i("AI auto-configure")]})]}),o.jsx("div",{className:"space-y-1.5",children:u.team.members.map(H=>{const ne=u.picked.includes(H.key),he=H.key===u.team.bossKey,pe=u.renamed.find(de=>de.key===H.key),ke=ne?W.get(H.key):void 0,Me=H.delegation.canDelegateTo,fe=Me==="any"?[]:Me.filter(de=>u.picked.includes(de)),F=O(H.key),U=ne&&N===H.key;return o.jsxs("div",{className:q("flex items-start gap-2.5 rounded-lg border px-2.5 py-2",!ne&&"opacity-60"),children:[o.jsx(ec,{className:"mt-1.5",checked:ne,disabled:he,onCheckedChange:de=>h({...u,picked:de===!0?[...u.picked,H.key]:u.picked.filter(Y=>Y!==H.key)})}),o.jsx(Jt,{bot:H,size:"sm"}),o.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Wt,{className:"h-7 w-36",value:H.name,disabled:!ne,onChange:de=>{const Y=de.target.value;T(X=>({...X,members:X.members.map(z=>z.key===H.key?{...z,name:Y}:z)}))}}),o.jsx("span",{className:"truncate text-muted-foreground text-xs",children:H.title}),he&&o.jsxs("span",{className:"flex shrink-0 items-center gap-0.5 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:[o.jsx(fk,{className:"h-3 w-3"}),i("Owner")]})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:H.scope}),pe&&pe.to===H.name&&o.jsx("p",{className:"text-warning text-xs",children:i('"{{from}}" is taken, renamed to "{{to}}"',pe)}),ke&&o.jsx("p",{className:"text-destructive text-xs",children:ke}),o.jsxs("button",{type:"button",disabled:!ne,onClick:()=>C(U?null:H.key),className:"flex items-start gap-1 text-left text-[11px] text-muted-foreground hover:text-foreground disabled:pointer-events-none",children:[U?o.jsx($n,{className:"mt-px h-3 w-3 shrink-0"}):o.jsx(kn,{className:"mt-px h-3 w-3 shrink-0"}),o.jsxs("span",{children:[H.tools==="readonly"?i("Read-only"):i("All tools")," · ",i(_l[H.approvalMode].labelKey),fe.length>0&&` · ${i("Delegates to {{names}}",{names:fe.map(V).join(Q==="zh"?"、":", ")})}`," · ",F.skillIds.length+F.mcpServerIds.length===0?i("No skills or MCP"):i("{{n}} skills · {{m}} MCP",{n:F.skillIds.length,m:F.mcpServerIds.length})]})]}),U&&o.jsxs("div",{className:"space-y-3 rounded-lg bg-muted/40 p-2.5",children:[o.jsxs("div",{children:[o.jsx(Bt,{children:i("Tools")}),o.jsx(Vm,{value:H.tools,options:[{value:"all",label:i("All tools")},{value:"readonly",label:i("Read-only")}],onChange:de=>A(H.key,{tools:de})})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:i("Approval mode")}),o.jsx(sk,{value:H.approvalMode,onChange:de=>A(H.key,{approvalMode:de}),zIndex:yn.DROPDOWN_IN_MODAL})]}),o.jsx(Tv,{label:i("Can delegate to"),value:H.delegation.canDelegateTo,options:u.picked.filter(de=>de!==H.key),nameOf:V,onChange:de=>A(H.key,{delegation:{...H.delegation,canDelegateTo:de}})}),o.jsx(Tv,{label:i("Accepts delegation from"),value:H.delegation.acceptFrom,options:u.picked.filter(de=>de!==H.key),nameOf:V,onChange:de=>A(H.key,{delegation:{...H.delegation,acceptFrom:de}})}),o.jsx(NT,{value:F,onChange:de=>B(H.key,de)})]})]})]},H.key)})}),!D&&o.jsx("p",{className:"mt-1 text-destructive text-xs",children:i("Keep the owner and at least one other member.")})]}),o.jsxs("div",{children:[o.jsx(Bt,{children:i("Shared workspace")}),o.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[o.jsxs("button",{type:"button",onClick:()=>f("chat-home"),className:q("rounded-xl border bg-card p-3 text-left",p==="chat-home"&&"ring-2 ring-info"),children:[o.jsx("div",{className:"font-medium text-sm",children:i("Standalone workspace")}),o.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:i("A new empty folder for this group, removed with the group")})]}),o.jsxs("button",{type:"button",onClick:()=>f("project"),className:q("rounded-xl border bg-card p-3 text-left disabled:opacity-50",p==="project"&&"ring-2 ring-info"),children:[o.jsx("div",{className:"font-medium text-sm",children:i("Based on a Code project")}),o.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:i("Members read and write directly in the project folder")})]})]}),p==="project"&&o.jsx(rI,{projectId:x,onChange:g}),o.jsxs("div",{className:"mt-2 flex gap-2 rounded-lg border border-info/40 bg-info/8 px-3 py-2 text-xs",children:[o.jsx(Zm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-info"}),o.jsx("span",{children:i(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})})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid grid-cols-3 gap-2.5",children:l.map(({id:H,data:ne})=>o.jsxs("button",{type:"button",disabled:v,onClick:()=>{I({team:Nv(ne)})},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:[o.jsx("div",{className:"-space-x-1.5 flex",children:ne.members.map(he=>o.jsx(Jt,{size:"sm",bot:{name:he.name,avatar:{color:he.color}}},he.key))}),o.jsx("span",{className:"font-medium text-sm",children:ne.title}),o.jsx("span",{className:"text-muted-foreground text-xs",children:ne.summary})]},H))}),o.jsxs(le,{size:"sm",variant:"outline",disabled:v,onClick:()=>d.current?.click(),children:[o.jsx(Bm,{}),i("Import team (JSON)")]}),o.jsx("input",{ref:d,type:"file",accept:".json,application/json",hidden:!0,onChange:H=>{const ne=H.target.files?.[0];H.target.value="",ne&&ne.text().then(he=>I({text:he}))}})]}),y&&o.jsx("p",{className:"text-destructive text-sm",children:y})]}),o.jsxs(ls,{children:[u&&o.jsxs(le,{variant:"ghost",size:"sm",className:"mr-auto",onClick:()=>{h(null),b(null)},children:[o.jsx(Au,{}),i("Back")]}),o.jsx(le,{variant:"outline",size:"sm",onClick:()=>t(!1),children:i("Cancel")}),u&&o.jsxs(le,{size:"sm",disabled:!J,onClick:()=>{se()},children:[v&&o.jsx(Vt,{className:"animate-spin"}),i("Create team")]})]})]})})}const yo="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function SY({sidebarWidth:e,collapsed:t,onToggleCollapse:n,onResize:s}){const i=Hu()==="mobile",{t:r}=te(),a=re(D=>D.view),l=re(D=>D.chats),c=re(D=>D.bots),d=re(D=>D.loaded),u=re(D=>D.setView),[h,p]=m.useState(!1),[f,x]=m.useState(!1),[g,v]=m.useState(!1),[w,y]=m.useState(!1),[b,_]=m.useState(null),j=m.useRef(""),N=eg(),C=a?.kind==="chat"?l.find(D=>D.id===a.chatId):void 0,k=C?.kind==="group"?c$(l,C):void 0;m.useEffect(()=>{d&&a?.kind==="chat"&&!C&&u(null)},[d,a,C,u]);const E=async D=>{if(D.botId){const W=re.getState();if(!W.bots.some(O=>O.id===D.botId))throw new Error("Member not found");const J=await W.openDirect(D.botId);if(!J)throw new Error("Could not open chat");Iv(J,D.firstMessage.trim()),y(!1);return}y(!1),_(D),j.current=D.firstMessage.trim(),D.templateId?v(!0):p(!0)},I=D=>{j.current&&Iv(D,j.current),j.current=""},T=()=>{_(null),j.current="",p(!0)},A=()=>{_(null),j.current="",v(!0)};return o.jsxs(o.Fragment,{children:[t?o.jsxs("aside",{className:"flex w-12 shrink-0 flex-col items-center gap-1 border-r bg-background py-2",children:[o.jsx(oI,{className:yo}),o.jsx("button",{type:"button",className:yo,onClick:()=>y(!0),title:r("Start from a goal"),children:o.jsx(Sa,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",className:yo,onClick:T,title:r("New member"),children:o.jsx(Ml,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",className:yo,onClick:()=>x(!0),title:r("New group chat"),children:o.jsx(ta,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",className:yo,onClick:A,title:r("Create team from template"),children:o.jsx(nf,{className:"h-4 w-4"})}),(N>0||a?.kind==="inbox")&&o.jsxs("button",{type:"button",className:q(yo,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:[o.jsx(qg,{className:"h-4 w-4"}),N>0&&o.jsx(yh,{count:N,className:"-top-0.5 -right-1 absolute"})]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{type:"button",className:yo,onClick:()=>{window.electronAPI.window.openSettings()},title:r("Settings"),children:o.jsx(ai,{className:"h-4 w-4"})}),i&&o.jsx("button",{type:"button",className:yo,onClick:n,title:r("Expand sidebar"),children:o.jsx(p1,{className:"h-4 w-4"})})]}):o.jsxs(o.Fragment,{children:[o.jsx(xY,{width:e,onCollapse:i?n:void 0,onNewMember:T,onNewGroup:()=>x(!0),onNewTeam:A,onStartFromGoal:()=>y(!0)}),o.jsx(cu,{onResize:s})]}),a?.kind==="inbox"?o.jsx($q,{}):C?o.jsx(Oq,{chat:k??C,group:C},k?.id??C.id):o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center justify-center gap-3 bg-background px-6 text-center",children:[o.jsx(Zs,{className:"h-8 w-8 text-muted-foreground"}),o.jsx("p",{className:"font-medium text-lg",children:r("Bot mode")}),o.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&&o.jsx(Ty,{onPick:E}),o.jsxs("div",{className:"flex gap-2",children:[o.jsxs(le,{size:"sm",variant:c.length===0?"outline":"default",onClick:T,children:[o.jsx(Ml,{}),r("New member")]}),c.length>=2&&o.jsxs(le,{size:"sm",variant:"outline",onClick:()=>x(!0),children:[o.jsx(ta,{}),r("New group chat")]}),o.jsxs(le,{size:"sm",variant:"outline",onClick:A,children:[o.jsx(nf,{}),r("Create team from template")]})]})]}),o.jsx(bY,{open:h,onOpenChange:p,seed:b?.member,onCreated:I}),o.jsx(wY,{open:f,onOpenChange:x}),o.jsx(mY,{}),o.jsx(yY,{open:g,onOpenChange:v,seedTemplateId:b?.templateId,onCreated:I}),o.jsx(gn,{open:w,onOpenChange:y,children:o.jsxs(xn,{className:"max-w-xl",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:r("Start from a goal")}),o.jsx(Os,{children:r("Tell us in one sentence what you want done; we will recommend a member or a team and draft your first message.")})]}),o.jsx(Rn,{className:"flex justify-center pb-4",children:w&&o.jsx(Ty,{onPick:E})})]})})]})}const Dy="enso-mode",oo=NC()(e=>({mode:localStorage.getItem(Dy)==="bot"?"bot":"code",setMode:t=>{localStorage.setItem(Dy,t),e({mode:t})}}));function Bc(){return xe.getState().botModeEnabled&&es.getState().activeNodeId==="local"&&oo.getState().mode==="bot"}function CY(){const e=xe(s=>s.botModeEnabled),t=es(s=>s.activeNodeId==="local"),n=oo(s=>s.mode);return e&&t&&n==="bot"}async function kY(e){if(!xe.getState().botModeEnabled)return;const t=typeof e.chatId=="string"?e.chatId:void 0,n=typeof e.conversationId=="string"?e.conversationId:void 0,s=re.getState();t||await s.refreshDelegations(),es.getState().activeNodeId!=="local"&&es.getState().switchNode("local"),oo.getState().setMode("bot");const i=mR({chatId:t,conversationId:n},re.getState().delegations);if(i.kind==="chat"){const r=s.chats.find(a=>a.id===i.chatId);r?.kind==="group"&&s.openThread(r.parentId??r.id,r.id)}s.setView(i)}function _Y(){es.getState().activeNodeId!=="local"&&es.getState().switchNode("local"),oo.getState().setMode("code")}const Ea=[{value:"code",label:"Code",Icon:Eo},{value:"bot",label:"Bot",Icon:gR}],jY={ArrowLeft:-1,ArrowUp:-1,ArrowRight:1,ArrowDown:1},NY={duration:.26,ease:[.22,1,.36,1]},TY={duration:.5,ease:[.34,1.36,.64,1]},IY={duration:.18,ease:[.4,0,.2,1]};function DY({className:e}){const{t}=te(),n=oo(h=>h.mode),s=oo(h=>h.setMode),i=eg(),r=Ii(xe(h=>h.keybindings))["toggle-app-mode"],a=r?`${t("Switch between Code and Bot")} (${Mi(r)})`:void 0,l=vH()??!1,c=m.useId(),d=m.useRef({}),u=h=>{const p=jY[h.key];if(!p)return;h.preventDefault();const f=Ea.findIndex(g=>g.value===n),x=Ea[(f+p+Ea.length)%Ea.length].value;s(x),d.current[x]?.focus()};return o.jsx("div",{role:"radiogroup","aria-label":t("Switch mode"),onKeyDown:u,className:q("flex h-7 shrink-0 rounded-lg bg-muted/60 p-0.5 text-xs",e),children:Ea.map(({value:h,label:p,Icon:f})=>{const x=n===h,g=h==="bot"&&n==="code"&&i>0;return o.jsxs("button",{ref:v=>{d.current[h]=v},type:"button",role:"radio","aria-checked":x,tabIndex:x?0:-1,title:a,onClick:()=>s(h),className:q("relative flex items-center gap-1.5 rounded-md px-2.5 font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",x?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[x&&o.jsx(Es.span,{layoutId:c,"aria-hidden":!0,className:"absolute inset-0 rounded-md bg-background shadow-xs",transition:l?{duration:0}:Yr}),o.jsx(f,{className:"relative h-3.5 w-3.5"}),o.jsx("span",{className:"relative",children:p}),o.jsx(rl,{children:g&&o.jsx(Es.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:NY,children:o.jsx(Es.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:IY},transition:TY,children:o.jsx(yh,{count:i,className:"block"})})})})]},h)})})}const $l="enso:open-chat-find";let dm;function aI(e){dm=e,window.dispatchEvent(new Event($l))}function Py(){const e=dm;return dm=void 0,e}function PY({query:e,onQueryChange:t,current:n,total:s,onPrev:i,onNext:r,onClose:a}){const{t:l}=te(),c=m.useRef(null);return m.useEffect(()=>{const d=()=>{c.current?.focus(),c.current?.select()};return d(),window.addEventListener($l,d),()=>window.removeEventListener($l,d)},[]),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-b px-3 py-1.5",children:[o.jsxs("div",{className:"relative min-w-0 flex-1",children:[o.jsx(Js,{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"}),o.jsx(Wt,{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?i():r())},placeholder:l("Search messages..."),className:"h-8 text-xs [&_input]:pl-8"})]}),o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs tabular-nums",children:s===0?l("No results"):`${n}/${s}`}),o.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:i,"aria-label":l("Previous match"),children:o.jsx(Ik,{className:"h-3.5 w-3.5"})}),o.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:r,"aria-label":l("Next match"),children:o.jsx($n,{className:"h-3.5 w-3.5"})}),o.jsx(le,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a,children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]})}const Ey=e=>Symbol.iterator in e,Ay=e=>"entries"in e,My=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),s=t instanceof Map?t:new Map(t.entries());if(n.size!==s.size)return!1;for(const[i,r]of n)if(!s.has(i)||!Object.is(r,s.get(i)))return!1;return!0},EY=(e,t)=>{const n=e[Symbol.iterator](),s=t[Symbol.iterator]();let i=n.next(),r=s.next();for(;!i.done&&!r.done;){if(!Object.is(i.value,r.value))return!1;i=n.next(),r=s.next()}return!!i.done&&!!r.done};function AY(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Ey(e)&&Ey(t)?Ay(e)&&Ay(t)?My(e,t):EY(e,t):My({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function um(e){const t=Ce.useRef(void 0);return n=>{const s=e(n);return AY(t.current,s)?t.current:t.current=s}}function MY(e,t,n,s){return e.host?.kind==="oauth-login"&&s?.host?.kind==="oauth-login"&&e.child.sessionId===t&&e.child.generation===n&&e.turnId===s.turnId&&e.requestId===s.requestId&&bR(e.child,s.child)}function RY({request:e,conversationId:t}){const{t:n}=te(),s=ie(l=>l.conversations[t]),i=xR({onDone:()=>{wR()}}),r=e.host,a=MY(e,t,s?.generation,s?.activeOauthAsk);return m.useEffect(()=>{if(!(!a||r?.kind!=="oauth-login"))return i.attach(r.providerId,{host:"agent-child-tab",child:e.child,turnId:e.turnId,requestId:e.requestId}),i.reset},[a,i.attach,i.reset,r,e.child,e.requestId,e.turnId]),!a||r?.kind!=="oauth-login"?null:o.jsxs("section",{className:"mb-1 space-y-3 rounded-lg border border-primary/20 bg-primary/5 p-3",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-sm font-medium",children:n("Subscription authorization")}),o.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:r.providerLabel})]}),o.jsx(vR,{flow:i,providerLabel:r.providerLabel})]})}function LY(e){const{t}=te(),n=e?.startsWith("bot:")?e.slice(4):void 0,s=re(a=>n?a.bots.find(l=>l.id===n)?.name:void 0),[i,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=QC(l)?.candidates.find(d=>d.typeKey===e);a&&r(c?.displayName)}).catch(()=>{}),()=>{a=!1}},[e,n,s]),!!n)return s??i??t("Member")}function OY(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 zY(e){const t=e.activeId?e.conversations[e.activeId]:void 0;if(!t)return null;const n=t.activeTabId?e.conversations[t.activeTabId]??t:t;return{id:n.id,parentId:t.id,projectId:n.projectId,parentProjectId:t.projectId,status:n.status,spawning:n.spawning,started:n.started,sessionFile:n.sessionFile,parentStarted:t.started,parentStatus:t.status,parentSessionFile:t.sessionFile,parentWorktreeMissing:t.worktreeMissing,parentWorktreePath:t.worktree?.path,parentWorktreeBranch:t.worktree?.branch,lastProviderId:n.lastProviderId,lastModelId:n.lastModelId,parentLastProviderId:t.lastProviderId,parentLastModelId:t.lastModelId,reasoningEnabled:n.reasoningEnabled,thinkingLevel:n.thinkingLevel,presetId:n.presetId,approvalMode:n.approvalMode,autoRejectApprovals:n.autoRejectApprovals,draftText:n.draftText,draftImages:n.draftImages,draftAppend:n.draftAppend,prefillAgentTypeKey:n.prefillAgentTypeKey,commands:n.commands,compactionError:n.compactionError,agentType:n.agentType,parentHasRunningChild:Pk(t,e.conversations),retry:n.retry,pendingApprovals:n.pendingApprovals,pendingAsks:n.pendingAsks,pendingCapabilityAsks:n.pendingCapabilityAsks,backgroundTasks:n.backgroundTasks,subagents:n.subagents,queuedMessages:n.queuedMessages,goal:n.goal,planState:n.planState,rewinding:n.rewinding,restoringFiles:n.restoringFiles,childLockedProfileId:n.child?.lockedProfileId,activeOauthAsk:n.activeOauthAsk,displayedParentId:n.parentId,busy:Dk(n)}}function GY(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt}function FY(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:GY(e),messages:[],forkedFromConversationId:e.forkedFromConversationId,unread:e.unread,activeRenewedAt:e.activeRenewedAt,pendingAsks:e.pendingAsks,pendingApprovals:e.pendingApprovals,pendingCapabilityAsks:e.pendingCapabilityAsks,coworkerIds:e.coworkerIds,coworkerName:e.coworkerName,child:e.child,subagents:e.subagents,parentId:e.parentId,sessionFile:e.sessionFile,worktree:e.worktree}}function HY(e){return JSON.stringify(e)}let Ki=null;function Rx(e){if(Ki?.source===e)return Ki.value;const t={},n=[];for(const[s,i]of Object.entries(e)){if(!i||i.btwParentId)continue;const r=FY(i,Pk({status:i.status??"idle",spawning:i.spawning,subagents:i.subagents,coworkerIds:i.coworkerIds},e));t[s]=r,n.push(`${s}:${HY(r)}`)}return Ki&&Ki.prints.length===n.length&&Ki.prints.every((s,i)=>s===n[i])?(Ki={source:e,prints:n,value:Ki.value},Ki.value):(Ki={source:e,prints:n,value:t},t)}let Aa=null;function BY(e){if(Aa?.source===e)return Aa.value;const t=[];for(const[i,r]of Object.entries(e))!r||r.parentId||r.btwParentId||!r.sessionFile||t.push({id:r.id??i,title:r.title,projectId:r.projectId,sessionFile:r.sessionFile,createdAt:r.createdAt});const n=JSON.stringify(t),s=Aa?.print===n?Aa.value:t;return Aa={source:e,print:n,value:s},s}const VY=[],Ry=new WeakMap;function $Y(e,t){const n=e[t];if(!n)return VY;const s=Ry.get(n);if(s?.source===e)return s.value;const i=(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,pendingCapabilityAskCount:c.pendingCapabilityAsks?.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(i),a=s?.print===r?s.value:i;return Ry.set(n,{source:e,print:r,value:a}),a}let lI=[],cI=[];const hm=new Set,dI=e=>`/${e.pluginId}:${e.id}`;function WY(e,t){const n=new Set(e.map(s=>s.id));return[...e,...(t??[]).filter(s=>!n.has(s.id))]}function Ly(e){lI=e,cI=e.map(t=>({name:dI(t),description:`${t.title} · ${t.pluginName}`}));for(const t of hm)t()}function Oy(){return cI}function UY(e){return lI.find(t=>dI(t)===e)??null}function KY(e){return hm.add(e),()=>hm.delete(e)}function qY(){return m.useSyncExternalStore(KY,Oy,Oy)}async function YY(e,t){const n=await window.electronAPI.extensionPlugins.call({pluginId:e.pluginId,method:"command.run",payload:{id:e.id},sessionId:t});return n.ok?null:n.error}function XY(e){const t=new Set;for(const n of e)if(n.kind==="tool"){if(n.name==="apply_patch"){n.fileChanges?.length&&t.add(n.key);continue}n.state==="ok"&&(n.output===null&&n.durationMs===null||n.name!=="edit"&&n.name!=="write"||n.name==="edit"&&!(n.edits&&n.edits.length>0)||n.name==="write"&&!n.writeContent||t.add(n.key))}return t}function JY(e,t){const n=xe(r=>r.openChangesOnFileEdit),s=m.useRef(void 0),i=m.useRef(new Set);m.useEffect(()=>{const r=XY(e);if(t!==s.current){s.current=t,i.current=r;return}let a=!1;for(const l of r)i.current.has(l)||(a=!0);i.current=r,a&&n&&UC()},[t,n,e])}function Ma(e,t){const n=e.trim().toLowerCase();return n?t.some(s=>s?.toLowerCase().includes(n)):!0}function ZY(e,t){const n=t.trim().toLowerCase();if(!n)return[];const s=[];for(const i of e){if(i.kind!=="user"&&i.kind!=="text")continue;const r=i.text.toLowerCase();let a=0,l=0;for(;;){const c=r.indexOf(n,a);if(c===-1)break;s.push({key:i.key,nth:l}),l+=1,a=c+n.length}}return s}const QY=[],eX=[],tX=typeof window<"u"&&!!window.electronAPI?.remote;function uI({conversationId:e,cwd:t,emptyTitle:n,onSuggestion:s,timelineRef:i}){const r=ie(H=>H.conversations[e]?.projectId),a=ie(H=>H.conversations[e]?.messages??QY),l=ie(H=>H.conversations[e]?.customEntries??eX),c=ie(H=>H.conversations[e]?.status==="running"),d=ie(H=>H.conversations[e]?.compaction),u=ie(H=>H.conversations[e]?.compactionNoticeAt),h=ie(H=>H.conversations[e]?.historyBaseIndex??0),p=ie(H=>H.conversations[e]?.toolOutputs),f=ie(H=>H.conversations[e]?.toolStartedAt),x=ie(H=>H.conversations[e]?.pendingApprovals),g=ie(H=>H.conversations[e]?.runStartedAt),v=ie(H=>H.conversations[e]?.lastOutputAt),w=ie(H=>H.conversations[e]?.error),y=ie(H=>H.conversations[e]?.started===!0),b=ie(H=>H.conversations[e]?.sessionFile),_=ie(H=>H.conversations[e]?.status),j=ie(H=>H.conversations[e]?.spawning===!0),N=ie(H=>H.conversations[e]?.historyLoadAttempted),C=ie(H=>!!H.conversations[e]?.historyLoading),k=m.useRef({conversationId:"",items:[]}),E=m.useMemo(()=>{k.current.conversationId!==e&&(k.current={conversationId:e,items:[]});const ne=yR(k.current.items,a,c,h)??hr(a,c,l,t,{compaction:d,compactionNoticeAt:u,historyBaseIndex:h,toolOutputs:p,toolStartedAt:f,pendingApprovals:x});return k.current.items=ne,ne},[d,u,e,t,l,h,a,x,c,p,f]);JY(E,e);const I=SR({started:y,sessionFile:b,messages:a,spawning:j,status:_,historyLoadAttempted:N}),[T,A]=m.useState(!1),[D,W]=m.useState(""),[J,O]=m.useState(0),B=m.useMemo(()=>T?ZY(E,D):[],[T,D,E]);m.useEffect(()=>{const H=()=>{const ne=Py();A(!0),ne&&(W(ne),O(0))};return window.addEventListener($l,H),()=>window.removeEventListener($l,H)},[]),m.useEffect(()=>{const H=Py();if(O(0),H){W(H),A(!0);return}e&&(W(""),A(!1))},[e]),m.useEffect(()=>{if(!T||B.length===0)return;const H=Math.min(J,B.length-1);i.current?.scrollToKey(B[H].key)},[T,J,B,i]);const L=m.useCallback(H=>{B.length!==0&&O(ne=>(ne+H+B.length)%B.length)},[B.length]);m.useEffect(()=>{if(!T)return;const H=ne=>{if(ne.key==="Escape"){ne.preventDefault(),A(!1);return}const he=Cl(ne);he==="mod+g"?(ne.preventDefault(),L(1)):he==="mod+shift+g"&&(ne.preventDefault(),L(-1))};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[T,L]);const se=m.useMemo(()=>r?{conversationId:e,projectId:r,...t?{cwd:t}:{}}:null,[e,t,r]),Q=m.useRef(null),V=m.useCallback(()=>{const H=i.current?.getScroller();Q.current=H?{height:H.scrollHeight,top:H.scrollTop}:null,ie.getState().loadOlderHistory(e)},[e,i]);return m.useLayoutEffect(()=>{const H=i.current?.getScroller(),ne=Q.current;!H||!ne||(Q.current=null,H.scrollTop=ne.top+(H.scrollHeight-ne.height))},[h]),o.jsxs(ng.Provider,{value:se,children:[T&&o.jsx(PY,{query:D,onQueryChange:H=>{W(H),O(0)},current:B.length===0?0:Math.min(J,B.length-1)+1,total:B.length,onPrev:()=>L(-1),onNext:()=>L(1),onClose:()=>{A(!1),W("")}}),o.jsx(ph,{virtualize:!tX,ref:i,items:E,busy:I!==null,loading:I==="loading",running:c,runStartedAt:g,lastOutputAt:v,error:CR(a,w),emptyTitle:n,onSuggestion:s,onRetryResume:!y&&b&&_==="failed"?()=>{ie.getState().resumeConversation(e)}:void 0,historyLoading:C,hasOlder:h>0,olderCursor:h,onStartReached:h>0?V:void 0,searchQuery:T?D:"",activeHit:T?B[J]??null:null},e)]})}const nX={sm:"size-2",md:"size-2.5"},sX={sm:"h-3 w-3",md:"h-3.5 w-3.5"};function Sh({tone:e,size:t="sm",title:n,className:s}){const{t:i}=te();if(e==="waiting"){const r=i("Waiting for your answer");return o.jsx("span",{role:"img","aria-label":r,title:r,"data-slot":"conversation-status","data-tone":e,className:q("flex shrink-0 items-center text-amber-500",s),children:o.jsx(FH,{className:q(sX[t],"stroke-[2.5]"),"aria-hidden":!0})})}return o.jsx("span",{"data-slot":"conversation-status","data-tone":e,title:n,className:q("shrink-0 rounded-full",nX[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 iX({parentId:e,coworkerIds:t}){const{t:n,locale:s}=te(),[i,r]=m.useState([]),[a,l]=m.useState(!1),[c,d]=m.useState(null),u=m.useRef(0),h=t.join("\0"),p=m.useCallback(()=>{const g=++u.current;return window.electronAPI.agent.listChildRuns(e).then(v=>{g===u.current&&r(v.ok?v.items:[])})},[e]);m.useEffect(()=>{p()},[p,h]);const f=m.useCallback(g=>{const v=c?.childId;return v?window.electronAPI.agent.readChildRun(e,v,g):Promise.resolve({ok:!1,code:"not-found",error:"No child run."})},[e,c?.childId]),x=g=>{if(g.available){if(l(!1),g.live&&t.includes(g.childId)){ie.getState().selectTab(e,g.childId);return}d(g)}};return o.jsxs(o.Fragment,{children:[i.length>0&&o.jsxs(Pi,{open:a,onOpenChange:g=>{l(g),g&&p()},children:[o.jsxs(Ei,{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:[o.jsx(Lo,{className:"size-3.5"}),o.jsx("span",{className:"text-[11px] tabular-nums leading-none",children:i.length})]}),o.jsx(Ai,{align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",children:o.jsx("ul",{className:"flex flex-col",children:i.map(g=>o.jsx("li",{children:o.jsxs("button",{type:"button",disabled:!g.available,className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",g.available?"hover:bg-muted":"cursor-default text-muted-foreground opacity-40"),onClick:()=>x(g),children:[o.jsx("span",{className:"min-w-0 flex-1 truncate",children:g.name}),g.agentType&&o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Ek(g.agentType,[])}),o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Do(g.startedAt,s)}),g.live&&o.jsx(Sh,{tone:"running",size:"sm",title:n("Running")})]})},g.childId))})})]}),o.jsx(Tx,{conversationId:c?.childId??null,title:c?.name??"",read:f,botSession:!1,onClose:()=>d(null)})]})}const oX=[{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"}],rX={"/goal":oX};function aX(e,t){if(!e)return null;const n=t.trimStart();return n?n.search(/\s/)>=0?null:n:""}function lX(e,t){if(!e)return[];const n=rX[e]??[],s=t.trim().toLowerCase();return s?n.filter(i=>i.name.toLowerCase().startsWith(s)||i.aliases.some(r=>r.toLowerCase().startsWith(s))):n}const hI=50,cX=64,dX=120,uX=32*1024,hX=120,Vc=[];function zy(e){return/(?:^|\s)#([^\s#]*)$/.exec(e)?.[1]??null}function pX(e,t,n){if(!Array.isArray(n))return[];const s=[];for(const i of n){if(s.length>=hI)break;if(typeof i!="object"||i===null)continue;const{id:r,label:a,detail:l}=i;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,cX),...typeof l=="string"&&l?{detail:l.slice(0,dX)}:{}}})}return s}function fX(e){const t=typeof e=="string"?e:typeof e=="object"&&e!==null?e.text:null;return typeof t=="string"&&t.length<=uX?t:null}let pI=[];const pm=new Set;function Gy(e){pI=e;for(const t of pm)t()}function mX(e){return pm.add(e),()=>pm.delete(e)}const Fy=()=>pI;function gX(e,t){const n=m.useSyncExternalStore(mX,Fy,Fy),[s,i]=m.useState(Vc);return m.useEffect(()=>{if(e===null||n.length===0){i(Vc);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?pX(l,c,d.value):Vc})).then(l=>{r||i(l.flat().slice(0,hI))})},hX);return()=>{r=!0,clearTimeout(a)}},[e,n,t]),e===null?Vc:s}async function xX(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?fX(n.value):null}const Ed="composer-drop",fI="pinned-drop",Lx="project-group:__ungrouped__",fm="project:",mm="project-group:",Ad="selector-group:",gm="pinned-chat:",mI=e=>`${fm}${e}`,gI=e=>`${mm}${e}`,Ox=e=>`${Ad}${e}`,vX=e=>`chat:${e}`,xI=e=>`${gm}${e}`,bX=e=>`active-chat:${e}`;function wX(e){return e.split(`
83
- `)[0].trim()||"Untitled chat"}function Hy(e){if(e===Lx||e===`${Ad}__ungrouped__`)return null;if(e.startsWith(mm)){const t=e.slice(mm.length);return t==="__all__"?void 0:t}if(e.startsWith(Ad)){const t=e.slice(Ad.length);return t==="__all__"?void 0:t}}function yX(e,t,n,s){if(!t)return null;if(e.type==="project-group"){const i=Hy(t);return!i||i===e.groupId?null:{kind:"reorder-groups",activeId:e.groupId,overId:i}}if(e.type==="project"){if(t===Ed)return{kind:"insert-file-mention",path:e.path,label:e.name};const i=Hy(t);if(i!==void 0)return(s?.projectGroupId?.(e.projectId)??null)===i?null:{kind:"move-project-to-group",projectId:e.projectId,groupId:i};if(t.startsWith(fm)){const r=t.slice(fm.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===Ed?{kind:"insert-file-mention",path:e.relativePath,label:e.name}:null;if(t===Ed)return!e.sessionFile||e.conversationId===n?null:{kind:"insert-chat-mention",conversationId:e.conversationId,label:wX(e.title),sessionFile:e.sessionFile};if(t===fI)return e.pinned?null:{kind:"pin-conversation",conversationId:e.conversationId};if(t.startsWith(gm)){const i=t.slice(gm.length);return i===e.conversationId?null:e.pinned?{kind:"reorder-pinned",activeId:e.conversationId,overId:i}:{kind:"pin-conversation",conversationId:e.conversationId}}return null}const By=200,SX=Array.from({length:gl},(e,t)=>`bar-${t}`),Vy=mh([],0);function CX({active:e,disabled:t,onChange:n}){const{t:s}=te(),[i,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}om(),r(!0);try{await B9(),n(!0)}catch(h){l(s(oT(h)))}finally{r(!1)}},u=s(e?"Switch to keyboard":"Voice input");return o.jsxs("div",{ref:c,className:"flex shrink-0 items-center",children:[o.jsx("button",{type:"button",disabled:t||i,onClick:()=>e?n(!1):void d(),"aria-label":u,title:u,className:rm,children:i?o.jsx(ar,{className:"h-3.5 w-3.5"}):e?o.jsx(kR,{className:"h-3.5 w-3.5"}):o.jsx(ZC,{className:"h-3.5 w-3.5"})}),a&&c.current?o.jsx(lT,{anchor:c.current,status:!0,children:a}):null]})}let $y;function kX({startSession:e,disabled:t,onText:n}){const{t:s}=te(),{phase:i,elapsed:r,error:a,setError:l,partial:c,correcting:d,start:u,finish:h,cancel:p}=rT({startSession:e,onText:n}),[f,x]=m.useState(Vy),[g,v]=m.useState(!1),[w,y]=m.useState(!1),b=m.useRef(null);m.useEffect(()=>(clearTimeout($y),()=>{$y=setTimeout(oy,0)}),[]),m.useEffect(()=>{const C=window.visualViewport;if(!g||!C)return;const k=()=>{b.current&&(b.current.shifted=!0)};return C.addEventListener("resize",k),C.addEventListener("scroll",k),()=>{C.removeEventListener("resize",k),C.removeEventListener("scroll",k)}},[g]);const _=C=>{t||b.current||i!=="idle"||C.pointerType==="mouse"&&C.button!==0||(C.preventDefault(),document.activeElement?.blur(),C.currentTarget.setPointerCapture(C.pointerId),b.current={id:C.pointerId,y:C.clientY,at:performance.now(),shifted:!1},v(!0),y(!1),x(Vy),u({context:om(),onLevel:k=>x(E=>mh(E,k))}))},j=(C,k)=>{const E=b.current;if(!E||E.id!==C.pointerId)return;b.current=null,v(!1),y(!1);const I=tT({phase:i,heldMs:performance.now()-E.at,cancelZone:k||!E.shifted&&iy(E.y,C.clientY)});I==="finish"?h():I!=="none"&&p(),oy(),om(),I==="too-short"&&l(s("Speech was too short."))},N=g&&(i==="starting"||i==="recording")||i==="transcribing";return o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:t,onPointerDown:_,onPointerMove:C=>{const k=b.current;k?.id===C.pointerId&&(k.shifted&&(k.y=C.clientY,k.shifted=!1),y(iy(k.y,C.clientY)))},onPointerUp:C=>j(C,!1),onPointerCancel:C=>j(C,!0),onContextMenu:C=>C.preventDefault(),className:q("mt-2 flex h-11 w-full touch-none select-none items-center justify-center rounded-xl border bg-background font-medium text-sm shadow-float transition-[opacity,scale,background-color] duration-200 ease-out [-webkit-touch-callout:none] starting:scale-x-25 starting:opacity-0 disabled:opacity-40",g&&"bg-accent",a&&"text-destructive"),children:a??s(g?"Release to finish":"Hold to talk")}),N?o.jsx(_X,{phase:i,cancelling:w,elapsed:r,levels:f,partial:c,correcting:d}):null]})}function _X({phase:e,cancelling:t,elapsed:n,levels:s,partial:i,correcting:r}){const{t:a}=te(),l=e==="transcribing",c=i.length>By?`…${i.slice(-By)}`:i;return Fs.createPortal(o.jsxs("div",{"data-testid":"hold-to-talk",style:{zIndex:yn.TOAST},className:"fixed inset-0 flex touch-none select-none flex-col overflow-hidden bg-black/60 backdrop-blur-[2px]",children:[o.jsx("div",{className:"flex flex-1 items-center justify-center px-6",children:o.jsxs("div",{role:"status","aria-live":"polite",className:q("flex min-w-36 max-w-[85vw] flex-col items-center gap-3 rounded-2xl px-5 py-4 shadow-lg transition-colors duration-150",t?"bg-destructive text-white":"bg-brand text-brand-foreground"),children:[c?o.jsx("p",{"data-testid":"voice-partial",className:"text-[15px] leading-relaxed",children:c}):e==="recording"?o.jsx("p",{className:"text-sm",children:a("Speak now")}):null,l||e==="starting"?o.jsxs("span",{className:"flex items-center gap-1.5 text-xs opacity-85",children:[o.jsx(ar,{"aria-hidden":!0,className:"size-3.5"}),a(e==="starting"?"Getting the microphone ready…":r?"Correcting…":"Transcribing…")]}):o.jsx("span",{"aria-hidden":!0,className:"flex h-8 items-center gap-[3px]",children:SX.map((d,u)=>o.jsx("span",{className:"w-[3px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:4+s[u]*28}},d))})]})}),l?null:o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsx("span",{className:q("mb-3 flex size-14 items-center justify-center rounded-full transition-[scale,background-color,color] duration-150",t?"scale-110 bg-white text-destructive":"bg-white/15 text-white/80"),children:o.jsx(ln,{className:"size-6"})}),o.jsx("p",{className:"mb-5 text-white/80 text-xs",children:a(t?"Release to cancel":"Slide up to cancel")}),o.jsxs("div",{className:q("flex h-[calc(7rem+env(safe-area-inset-bottom))] w-[140%] flex-col items-center rounded-t-[50%] pt-8 transition-colors duration-150",t?"bg-neutral-500 text-white/70":"bg-neutral-100 text-neutral-700"),children:[o.jsx("span",{className:"text-sm",children:a("Release to finish")}),o.jsxs("span",{className:"mt-1 text-xs tabular-nums opacity-60",children:[Math.floor(n/60),":",String(n%60).padStart(2,"0")]})]})]})]}),document.body)}function jX(e,t,n=!1){const s=e.segments.some(r=>r.type!=="text"||r.text.length>0);if(n&&(s||e.slash))return{slash:e.slash,segments:[...e.segments,...t.text?[{type:"text",text:`${s?`
84
-
85
- `:""}${t.text}`}]:[]],images:[...e.images,...t.images??[]]};const i=fu(t.text??"");return{slash:i.slash,segments:i.rest?[{type:"text",text:i.rest}]:[],images:[...n?e.images:[],...t.images??[]]}}const NX={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>'},TX='<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>',IX={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 Dp(e){const t=document.createElement("span");t.contentEditable="false",t.dataset.mentionKind=e.type,e.type==="file"?(t.dataset.path=e.path,e.label&&(t.dataset.label=e.label),t.title=e.path):e.type==="chat"?(t.dataset.label=e.label,t.dataset.sessionFile=e.sessionFile):(t.dataset.id=e.id,t.dataset.label=e.label,t.dataset.path=e.path,t.dataset.text=e.text,t.dataset.imageId=e.imageId,t.title=`${e.path}${e.text?` · ${e.text}`:""}`),t.className=q("mx-0.5 inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium leading-4 select-none",IX[e.type]);const n=document.createElement("span");n.className="shrink-0 inline-flex",n.innerHTML=e.type==="file"&&/[\\/]$/.test(e.path)?TX:NX[e.type],t.appendChild(n);const s=document.createElement("span");return s.className="truncate",s.textContent=e.type==="file"?e.label??ih(e.path):e.label,t.appendChild(s),t}function vI(e){return e.dataset.mentionKind==="file"&&e.dataset.path?{type:"file",path:e.dataset.path,...e.dataset.label?{label:e.dataset.label}:{}}:e.dataset.mentionKind==="chat"&&e.dataset.label&&e.dataset.sessionFile?{type:"chat",label:e.dataset.label,sessionFile:e.dataset.sessionFile}:e.dataset.mentionKind==="ui-element"&&e.dataset.label&&e.dataset.path&&e.dataset.text?{type:"ui-element",id:e.dataset.id??"",label:e.dataset.label,path:e.dataset.path,text:e.dataset.text,imageId:e.dataset.imageId??""}:null}function Pp(e){const t=[],n=i=>{if(!i)return;const r=t.at(-1);r?.type==="text"?r.text+=i:t.push({type:"text",text:i})},s=i=>{if(i.nodeType===Node.TEXT_NODE){n(i.textContent??"");return}if(!(i instanceof HTMLElement))return;if(i.dataset.mentionKind){const a=vI(i);a&&t.push(a);return}if(i.tagName==="BR"){n(`
86
- `);return}(i.tagName==="DIV"||i.tagName==="P")&&t.length>0&&n(`
87
- `);for(const a of i.childNodes)s(a)};for(const i of e.childNodes)s(i);return t}function Ep(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 DX(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 i=n.childNodes,r=i[s],a=s>0?i[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 $c(e){return e instanceof HTMLElement&&!!e.dataset.mentionKind}function Ka(e){return e instanceof Text&&!/[^\s\u00a0]/.test(e.textContent??"")}function PX(e,t){const n=window.getSelection();if(!n||n.rangeCount===0||!n.isCollapsed)return null;const{anchorNode:s,anchorOffset:i}=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,i)))return null;let u=s.previousSibling;for(;Ka(u);)u=u.previousSibling;return $c(u)?u:null}if(/[^\s\u00a0]/.test(c.slice(i)))return null;let d=s.nextSibling;for(;Ka(d);)d=d.nextSibling;return $c(d)?d:null}const r=s.childNodes;if(t==="before"){let c=i-1;for(;c>=0&&Ka(r[c]);)c-=1;const d=c>=0?r[c]:null;return $c(d)?d:null}let a=i;for(;a<r.length&&Ka(r[a]);)a+=1;const l=r[a];return $c(l)?l:null}function EX(e,t){const n=e.nextSibling;Ka(n)&&n.remove();const s=e.previousSibling;if(e.remove(),s){bI(s);return}const i=window.getSelection();if(!i)return;const r=document.createRange();r.setStart(t,0),r.collapse(!0),i.removeAllRanges(),i.addRange(r)}function bI(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.setStartAfter(e),n.collapse(!0),t.removeAllRanges(),t.addRange(n)}const AX=m.forwardRef(function({placeholder:t,disabled:n,className:s,onStateChange:i,onKeyDown:r,onPaste:a,onPasteText:l,onCompositionStart:c,onCompositionEnd:d,onChipActivate:u,ariaProps:h},p){const f=m.useRef(null),x=m.useRef(null);m.useEffect(()=>{const y=()=>{const b=f.current;if(!b||document.activeElement!==b)return;const _=window.getSelection();if(!_||_.rangeCount===0||!_.isCollapsed)return;const j=_.anchorNode;if(j&&(j===b||b.contains(j))){const k=DX(b,_);k?(_.removeAllRanges(),_.addRange(k)):j.nodeType===Node.TEXT_NODE&&(x.current={node:j,offset:_.anchorOffset});return}const N=x.current,C=document.createRange();N?.node.isConnected&&b.contains(N.node)?(C.setStart(N.node,Math.min(N.offset,N.node.length)),C.collapse(!0)):(C.selectNodeContents(b),C.collapse(!0)),_.removeAllRanges(),_.addRange(C)};return document.addEventListener("selectionchange",y),()=>document.removeEventListener("selectionchange",y)},[]);const g=m.useCallback(()=>{const y=f.current;if(!y)return;const b=Pp(y),_=b.map(T=>T.type==="text"?T.text:"").join(""),j=b.some(T=>T.type!=="text");let N=null,C=null,k=null,E=null;const I=Ep(y);if(I){const T=I.node.textContent?.slice(0,I.offset)??"";N=kb(T,T.length),N===null&&(k=im(T,T.length)),N===null&&k===null&&(E=zy(T)),N===null&&I.node===y.firstChild&&/^\/[^\s]*$/.test(T)&&(C=T.slice(1))}i({plainText:_,hasMentions:j,segments:b,mentionQuery:N,slashQuery:C,skillQuery:k,pluginQuery:E})},[i]),v=m.useCallback(y=>{const b=f.current;if(!b)return null;const _=Ep(b);if(!_)return null;const j=_.node.textContent?.slice(0,_.offset)??"";if(y==="#"){const N=zy(j);return N===null?null:{node:_.node,start:j.length-N.length-1,end:_.offset}}if(y==="@"||y==="$"){const N=y==="@"?kb(j,j.length):im(j,j.length);return N===null?null:{node:_.node,start:j.length-N.length-1,end:_.offset}}return _.node!==b.firstChild||!/^\/[^\s]*$/.test(j)?null:{node:_.node,start:0,end:_.offset}},[]),w=m.useCallback((y,b)=>{const _=f.current;if(!_)return;_.focus();const j=document.createRange(),N=b?v("@"):null;if(N)j.setStart(N.node,N.start),j.setEnd(N.node,N.end),j.deleteContents();else{const E=Ep(_);E?(j.setStart(E.node,E.offset),j.collapse(!0)):(j.selectNodeContents(_),j.collapse(!1))}const C=y();j.insertNode(C);const k=document.createTextNode(" ");C.parentNode?.insertBefore(k,C.nextSibling),bI(k),g()},[v,g]);return m.useImperativeHandle(p,()=>({focus:()=>f.current?.focus(),isEmpty:()=>{const y=f.current;return y?!Pp(y).some(_=>_.type!=="text"||_.text.trim().length>0):!0},getSegments:()=>f.current?Pp(f.current):[],setSegments:y=>{const b=f.current;if(b){b.textContent="";for(const _ of y)_.type==="text"?b.appendChild(document.createTextNode(_.text)):b.appendChild(Dp(_));g()}},clear:()=>{const y=f.current;y&&(y.textContent="",g())},insertMention:y=>{const b=y.kind==="file"?{type:"file",path:y.relativePath}:y.kind==="chat"?{type:"chat",label:y.label,sessionFile:y.sessionFile}:{type:"ui-element",id:y.id,label:y.label,path:y.path,text:y.text,imageId:y.imageId};w(()=>Dp(b),y.kind!=="ui-element")},consumeToken:y=>{const b=v(y);if(!b)return;const _=document.createRange();_.setStart(b.node,b.start),_.setEnd(b.node,b.end),_.deleteContents(),g()},insertFileChip:(y,b)=>{w(()=>Dp({type:"file",path:y,...b?{label:b}:{}}),!1)},insertText:y=>{w(()=>document.createTextNode(y),!1)},getMentionAnchorRect:()=>{const y=v("@");if(!y)return null;const b=document.createRange();return b.setStart(y.node,y.start),b.setEnd(y.node,Math.min(y.start+1,y.node.length)),b.getBoundingClientRect()}}),[v,g,w]),o.jsx("div",{ref:f,contentEditable:!n,role:h?.role??"textbox","aria-placeholder":t,"data-placeholder":t,...h,onInput:g,onKeyDown:y=>{if(!y.nativeEvent.isComposing&&(y.key==="Backspace"||y.key==="Delete")){const b=f.current,_=b&&PX(b,y.key==="Backspace"?"before":"after");if(_&&b){y.preventDefault(),EX(_,b),g();return}}r(y)},onClick:y=>{if(!u)return;const b=y.target;if(!(b instanceof Element))return;const _=b.closest("[data-mention-kind]");if(!(_ instanceof HTMLElement)||!f.current?.contains(_))return;const j=vI(_);j&&u(j)},onKeyUp:y=>{y.key!=="Escape"&&g()},onMouseUp:g,onPaste:y=>{if(y.clipboardData.files.length>0){a(y);return}y.preventDefault();const b=y.clipboardData.getData("text/plain");b&&(l?.(b)||document.execCommand("insertText",!1,b))},onCompositionStart:c,onCompositionEnd:()=>{d(),g()},className:q("max-h-40 min-h-10 min-w-0 flex-1 overflow-y-auto pt-0.5 text-sm break-words whitespace-pre-wrap outline-none","empty:before:pointer-events-none empty:before:text-muted-foreground empty:before:content-[attr(data-placeholder)]",n&&"opacity-60",s)})}),MX=/[\\/]/;function RX(e){return e.split(MX).filter(t=>t.length>0)}function LX(e){const t=new Map,n=e.map(RX),s=n.map(i=>i.join("/"));for(let i=0;i<e.length;i++){const r=e[i],a=n[i]??[];let l=Math.max(0,a.length-3);for(;l>0;){const d=a.slice(l).join("/");if(!s.some(h=>h!==s[i]&&(h===d||h.endsWith(`/${d}`))))break;l--}const c=a.slice(l).join("/");t.set(r,l>0?`…/${c}`:c)}return t}function OX({groups:e,query:t,activeIndex:n,onActiveIndexChange:s,openFolderId:i,folderIndex:r,onOpenFolderIdChange:a,onFolderIndexChange:l,onSelect:c,id:d="composer-mention-picker",left:u=0,flyoutSide:h="right"}){const{t:p}=te(),f=m.useMemo(()=>uT(e,t),[e,t]),x=m.useMemo(()=>LX(e.files.map(C=>C.relativePath)),[e.files]),g=m.useRef(new Map),v=m.useRef(new Map),w=f[0]?.type==="folder";if(m.useEffect(()=>{g.current.get(n)?.scrollIntoView({block:"nearest"})},[n]),m.useEffect(()=>{i&&v.current.get(r)?.scrollIntoView({block:"nearest"})},[i,r]),f.length===0)return null;const y={agents:p("Agents"),members:p("Members"),chats:p("Chats")},b={agents:Zs,members:ta,chats:Lo},_=i?e[i]:[];let j=0;const N=(C,k)=>{const E=e[C];if(E.length===0)return null;const I=C==="files"?p("Files"):y[C];return o.jsxs("div",{role:"group","aria-label":I,children:[o.jsx("p",{className:q("px-2 pb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",k?"pt-2":"pt-1.5"),children:I}),E.map(T=>{const A=j++;return o.jsx(Wy,{ref:D=>{D?g.current.set(A,D):g.current.delete(A)},id:`${d}-option-${A}`,candidate:T,active:A===n,pathLabel:T.kind==="file"?x.get(T.relativePath):void 0,onHover:()=>{s(A),w&&a(null)},onSelect:()=>c(T)},`${C}:${T.id}`)})]})};return o.jsxs("div",{"data-slot":"mention-picker",className:"absolute bottom-full z-10 mb-1.5 max-w-full",style:{left:u},children:[o.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:w?o.jsxs(o.Fragment,{children:[f.filter(C=>C.type==="folder").map(C=>{const k=j++,E=b[C.id];return o.jsxs("button",{ref:I=>{I?g.current.set(k,I):g.current.delete(k)},id:`${d}-option-${k}`,type:"button",role:"option","aria-selected":n===k,onClick:()=>{s(k),a(C.id),l(0)},onMouseMove:()=>{s(k),i!==C.id&&(a(C.id),l(0))},className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",n===k&&"bg-foreground/10"),children:[o.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background",children:o.jsx(E,{className:"h-3.5 w-3.5 text-muted-foreground"})}),o.jsx("span",{className:"min-w-0 flex-1 font-medium",children:y[C.id]}),o.jsx(kn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},`folder:${C.id}`)}),N("files",!0)]}):o.jsxs(o.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)]})}),i&&_.length>0&&o.jsx("div",{role:"listbox","aria-label":y[i],"data-slot":"mention-flyout",className:q("absolute top-0 z-20 max-h-72 w-72 overflow-y-auto rounded-lg border bg-popover p-1 shadow-md",h==="right"?"left-full ml-1":"right-full mr-1"),children:_.map((C,k)=>o.jsx(Wy,{ref:E=>{E?v.current.set(k,E):v.current.delete(k)},id:`${d}-sub-${k}`,candidate:C,active:k===r,onHover:()=>l(k),onSelect:()=>c(C)},`sub:${C.id}`))})]})}function Wy({ref:e,id:t,candidate:n,active:s,pathLabel:i,onHover:r,onSelect:a}){const{t:l}=te(),c=zX(n),d=n.kind==="agent-type"?n.source==="bot"?ta:Zs:n.kind==="chat"?Lo:c?uc:go;return o.jsxs("button",{ref:e,id:t,type:"button",role:"option","aria-selected":s,onClick:a,onMouseMove:r,className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",s&&"bg-foreground/10"),children:[o.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background",children:o.jsx(d,{className:"h-3.5 w-3.5 text-muted-foreground"})}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"shrink-0 font-medium",children:n.label}),o.jsx(ea,{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&&o.jsx(ea,{variant:"secondary",className:"px-1 py-0 text-[9px]",children:l("Locked")})]}),o.jsx("span",{className:q("block text-muted-foreground",n.kind==="file"?"whitespace-normal break-all":"truncate"),title:n.kind==="file"?n.relativePath:void 0,children:n.kind==="agent-type"?n.source==="bot"?n.description:l(n.description):n.kind==="chat"?n.sessionFile.split("/").at(-1):n.kind==="file"?i??n.relativePath:n.path})]})]})}function zX(e){return e.kind==="file"&&/[\\/]$/.test(e.relativePath)}const Uy=new Map,GX=()=>!!window.electronAPI?.remote&&window.matchMedia?.("(pointer: coarse)").matches===!0;function zx({cwd:e,commands:t,running:n,busy:s,focusKey:i,pluginPresetId:r=null,autoFocus:a=!window.electronAPI?.remote,enterToSend:l=!GX(),toolbar:c,locked:d=!1,injectedDraft:u,injectedImages:h,injectedDraftAppend:p,onDraftConsumed:f,initialRecipient:x,onInitialRecipientConsumed:g,chatCandidates:v,onActivate:w,onSend:y,onAbort:b,queuedCount:_=0,onSteerQueued:j,isolated:N=!1,placeholder:C,planMode:k=!1,voice:E,requestMicAccess:I,voiceMode:T="click",savePastedText:A}){const{t:D}=te(),W=fa(),[J,O]=m.useState(!1),B=T==="hold"?E:void 0,L=xe(oe=>oe.keybindings),se=xe(oe=>oe.privacyMasking),Q=Ii(L)["send-message"],V=Ii(L)["voice-hold"],H=m.useId(),[ne,he]=m.useState([]),[pe,ke]=m.useState(null),[Me,fe]=m.useState(x),F=m.useRef(i),[U,de]=m.useState(!1),{setNodeRef:Y,isOver:X}=rc({id:N?`isolated-composer:${i??"side"}`:Ed,disabled:N}),[z,ue]=m.useState(null),[_e,Ee]=m.useState(null),Be=m.useRef(new Set);m.useEffect(()=>{if(N)return;const oe=hU(qe=>De.current?.insertMention(qe)),Te=fU(qe=>De.current?.insertText(qe)),Xe=pU(()=>De.current?.focus()),Le=mU((qe,st)=>{st&&he(at=>[...at,{...st,id:qe.imageId}]),De.current?.insertMention(qe),De.current?.focus()}),Ze=xU(qe=>{he(st=>[...st,{data:qe.data,mimeType:qe.mimeType}]),De.current?.focus()});return()=>{oe(),Te(),Xe(),Le(),Ze()}},[N]);const De=m.useRef(null),Ue=m.useRef(null),St=m.useRef(null),Ut=m.useRef(!1),tn=m.useRef(d);tn.current=d,m.useEffect(()=>{if(!(N||!i))return _R({key:i,segments:()=>De.current?.getSegments()??[],insertText:oe=>De.current?.insertText(oe),setText:oe=>De.current?.setSegments(oe?[{type:"text",text:oe}]:[]),busy:()=>Ut.current||tn.current||!De.current})},[N,i]);const[Ne,Z]=m.useState({left:0,flyoutSide:"right"}),[je,tt]=m.useState(""),[Et,zt]=m.useState(!1),[we,ft]=m.useState(null),mt=hT(e,we,v),ze=m.useMemo(()=>uT(mt,we??""),[mt,we]),[Ct,K]=m.useState(null),[be,Re]=m.useState(null),[Ve,Ke]=m.useState(null),nt=gX(Ve,i??null),[ge,$e]=m.useState(0),[it,xt]=m.useState(null),[Mt,Gt]=m.useState(0),sn=m.useRef(null),wn=m.useCallback(oe=>{(oe.plainText.trim()||oe.hasMentions)&&w?.(),tt(oe.plainText),zt(oe.hasMentions);const Te=new Set(oe.segments.filter(Le=>Le.type==="ui-element"&&Le.imageId).map(Le=>Le.type==="ui-element"?Le.imageId:"")),Xe=[...Be.current].filter(Le=>!Te.has(Le));Be.current=Te,Xe.length>0&&(he(Le=>zV(Le,Xe)),ue(Le=>Le&&Xe.includes(Le.imageId)?null:Le)),ft(Le=>(Le!==oe.mentionQuery&&($e(0),xt(null),Gt(0)),oe.mentionQuery)),K(oe.slashQuery),Re(oe.skillQuery),Ke(oe.pluginQuery)},[w]);m.useEffect(()=>{const oe=F.current;if(oe!==i){oe&&Uy.set(oe,{segments:De.current?.getSegments()??[],images:ne,slash:pe,recipient:Me});const Te=i?Uy.get(i):void 0,Xe=i?jR(i):void 0;De.current?.setSegments(Xe?[{type:"text",text:Xe}]:Te?.segments??[]),Be.current=new Set((Te?.segments??[]).filter(Le=>Le.type==="ui-element"&&Le.imageId).map(Le=>Le.type==="ui-element"?Le.imageId:"")),he(Te?.images??[]),ke(Te?.slash??null),fe(Te?.recipient),F.current=i,ft(null),K(null),Re(null),$e(0),xt(null),Gt(0)}a&&De.current?.focus()},[i]),m.useEffect(()=>{x&&(fe(x),g?.())},[x,g]),m.useEffect(()=>{if(!u&&!h?.length)return;const oe=jX({segments:De.current?.getSegments()??[],images:ne,slash:pe},{text:u,images:h},p);ke(oe.slash),he(oe.images),De.current?.setSegments(oe.segments),f?.(),window.setTimeout(()=>De.current?.focus(),0)},[u,h,p]);const On=aX(pe,je.replaceAll("","")),rn=D9(t,Ct,be),cn=Ct===null&&be===null&&On!==null?lX(pe,On):[];m.useEffect(()=>{$e(0)},[Ct,be,On,Ve]),m.useEffect(()=>{sn.current?.children[ge]?.scrollIntoView({block:"nearest"})},[ge]);const Bn=m.useCallback(oe=>{if(oe.kind==="agent-type"){De.current?.consumeToken("@"),fe(oe),ft(null);return}De.current?.insertMention(oe),ft(null)},[]),P=m.useCallback(oe=>{Ke(null),xX(oe,i??null).then(Te=>{const Xe=De.current;Xe&&(Xe.consumeToken("#"),Te&&Xe.insertText(Te))})},[i]),M=we!==null&&ze.length>0?"mention":Ve!==null&&nt.length>0?"plugin":rn.length>0?"slash":cn.length>0?"slash-sub":null;m.useLayoutEffect(()=>{if(M!=="mention")return;const oe=Ue.current;if(!oe)return;const Te=()=>{const Xe=oe.getBoundingClientRect(),Le=oe.querySelector('[data-slot="mention-picker"]'),Ze=Le?.querySelector('[role="listbox"]'),qe=Le?.querySelector('[data-slot="mention-flyout"]'),st=De.current?.getMentionAnchorRect(),at=GV({anchorLeft:st?st.left-Xe.left:0,containerWidth:Xe.width,popupWidth:Ze instanceof HTMLElement?Ze.offsetWidth:280,flyoutWidth:qe instanceof HTMLElement?qe.offsetWidth:252,flyoutGap:4});Z(et=>et.left===at.left&&et.flyoutSide===at.flyoutSide?et:at)};return Te(),window.addEventListener("resize",Te),()=>window.removeEventListener("resize",Te)},[we,je,it,M]);const R=M==="mention"?ze.length:M==="plugin"?nt.length:M==="slash-sub"?cn.length:rn.length,S=m.useCallback((oe,Te)=>{const Xe=[{type:"text",text:oe}];if(De.current?.setSegments(Xe),!Te)return;const Le=Nb({segments:Xe,slash:pe,images:ne,recipient:Me});y(Le)!==!1&&(De.current?.clear(),he([]),ke(null),fe(void 0),ft(null),K(null),Re(null))},[ne,y,Me,pe]),G=m.useCallback(oe=>{De.current?.consumeToken(be!==null?"$":"/"),K(null),Re(null);const Te=UY(oe);if(!Te){ke(oe);return}YY(Te,N?null:i??null).then(Xe=>{Xe&&We({type:"error",title:D("Plugin command failed"),description:Xe})})},[be,N,i,D]),ae=m.useCallback((oe=!1)=>{if(M==="mention"){if(it){const Xe=mt[it][Mt];Xe&&Bn(Xe);return}const Te=ze[ge];Te?.type==="item"&&Bn(Te.candidate)}else if(M==="plugin"){const Te=nt[ge];Te&&P(Te)}else if(M==="slash"){const Te=rn[ge];Te&&G(Te.name)}else if(M==="slash-sub"){const Te=cn[ge];if(!Te)return;S(Te.name,oe)}},[ge,Mt,it,mt,ze,Bn,P,nt,M,rn,G,cn,S]),ce=je.replaceAll("","").trim(),Ie=!!(ce||pe||ne.length>0||Et),He=Me!==void 0,ht=s&&!He,Qe={sessionId:N?null:i??null,draft:je.replaceAll("",""),busy:d,pluginPresetId:r},qt=n&&_>0&&j!==void 0&&l&&!!Q,lt=qt&&!Ie&&!He&&!d,bt=m.useMemo(()=>se.enabled&&ce?Dv(ce,se):null,[ce,se]),kt=()=>{if(!Ie)return;const oe=Nb({segments:De.current?.getSegments()??[],slash:pe,images:ne,recipient:Me}),Te=se.enabled?Dv(oe.text,se).blocked:[];if(Te.length>0){We({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:Te.join(", ")})});return}y(oe)!==!1&&(De.current?.clear(),he([]),ke(null),fe(void 0),ft(null),K(null),Re(null))},_t=m.useCallback(oe=>{for(const Te of oe){if(Te.type.startsWith("image/")){const Ze=new FileReader;Ze.onload=()=>{const qe=Ze.result,st=qe.slice(qe.indexOf(",")+1);he(at=>[...at,{data:st,mimeType:Te.type}])},Ze.readAsDataURL(Te);continue}const Xe=window.electronAPI.files.pathForFile(Te),Le=window.electronAPI.remote;if(!Xe&&Le){Le.upload(Te).then(Ze=>{Ze&&De.current?.insertFileChip(Ze)}).catch(()=>{});continue}Xe&&De.current?.insertFileChip(Xe)}},[]),jt=oe=>{const Te=oe.nativeEvent.isComposing||Ut.current;if(M){const Le=M==="mention"?ze[ge]:void 0,Ze=FV({key:oe.key,shiftKey:oe.shiftKey,isComposing:Te,activeIndex:ge,itemCount:R,folderOpen:M==="mention"&&it!==null,activeIsFolder:M==="mention"&&Le?.type==="folder",folderIndex:Mt,folderItemCount:it?mt[it].length:0});if(Ze.type==="move"){oe.preventDefault(),$e(Ze.index),xt(null);return}if(Ze.type==="move-folder"){oe.preventDefault(),Gt(Ze.index);return}if(Ze.type==="open-folder"){oe.preventDefault(),Le?.type==="folder"&&xt(Le.id),Gt(0);return}if(Ze.type==="close-folder"){oe.preventDefault(),xt(null);return}if(Ze.type==="pick"){oe.preventDefault(),ae(M==="slash-sub"&&oe.key==="Enter");return}if(Ze.type==="close"){oe.preventDefault(),ft(null),K(null),Re(null),Ke(null),xt(null);return}}if(Te)return;const Xe=Cl(oe);if(!N&&Xe&&Xe===Ii(xe.getState().keybindings)["switch-model"]){oe.preventDefault(),NR();return}if(oe.key==="Backspace"&&pe&&ce.length===0&&!Et){oe.preventDefault(),ke(null);return}if(oe.key==="Backspace"&&Me&&De.current?.isEmpty()&&!pe){oe.preventDefault(),fe(void 0);return}l&&!M&&Cl(oe,{allowBare:!0})===Q&&(oe.preventDefault(),lt?j?.():kt())};return o.jsxs("div",{ref:Ue,className:"relative",children:[M==="mention"&&o.jsx(OX,{id:H,groups:mt,query:we??"",activeIndex:ge,onActiveIndexChange:$e,openFolderId:it,folderIndex:Mt,onOpenFolderIdChange:xt,onFolderIndexChange:Gt,onSelect:Bn,left:Ne.left,flyoutSide:Ne.flyoutSide}),M==="plugin"&&o.jsx("div",{ref:sn,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:nt.map((oe,Te)=>o.jsxs("button",{type:"button",role:"option","aria-selected":Te===ge,onMouseDown:Xe=>Xe.preventDefault(),onClick:()=>P(oe),onMouseMove:()=>$e(Te),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Te===ge&&"bg-foreground/10"),children:[o.jsx("span",{className:"shrink-0 font-mono text-muted-foreground",children:"#"}),o.jsx("span",{className:"shrink-0 font-medium",children:oe.item.label}),oe.item.detail&&o.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:oe.item.detail})]},oe.key))}),(M==="slash"||M==="slash-sub")&&o.jsx("div",{ref:sn,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"?rn:cn).map((oe,Te)=>o.jsxs("button",{type:"button",role:"option","aria-selected":Te===ge,onClick:()=>{$e(Te),M==="slash"?G(oe.name):S(oe.name,!1)},onMouseMove:()=>$e(Te),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Te===ge&&"bg-foreground/10"),children:[o.jsx(x1,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"shrink-0 font-mono font-medium",children:be!==null?`$${oe.name.slice(7)}`:oe.name}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:D(oe.description)})]},oe.name))}),o.jsxs("div",{ref:Y,"data-slot":"composer","data-enso":"composer",className:q("rounded-[24px] border bg-card shadow-[0_2px_6px_rgb(0_0_0/0.03),0_12px_32px_rgb(0_0_0/0.07)] transition-[border-color,box-shadow] duration-200 focus-within:border-foreground/20 [.dark_&]:shadow-[0_2px_6px_rgb(0_0_0/0.2),0_12px_32px_rgb(0_0_0/0.3)]",(U||X)&&"border-brand/50 bg-brand/5",(He||k)&&"border-primary/35 shadow-primary/5"),onDragOver:oe=>{oe.dataTransfer.types.includes("Files")&&(oe.preventDefault(),de(!0))},onDragLeave:oe=>{oe.currentTarget.contains(oe.relatedTarget)||de(!1)},onDrop:oe=>{const Te=Array.from(oe.dataTransfer.files);Te.length!==0&&(oe.preventDefault(),de(!1),_t(Te))},children:[ne.filter(oe=>!oe.id).length>0&&o.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:ne.filter(oe=>!oe.id).map((oe,Te)=>o.jsxs("div",{className:"group relative",children:[o.jsx("button",{type:"button",onClick:()=>Ee(oe),className:"block rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none","aria-label":D("Preview"),children:o.jsx("img",{src:`data:${oe.mimeType};base64,${oe.data}`,alt:"",className:"h-16 w-16 rounded-md border object-cover"})}),o.jsx("button",{type:"button",onClick:()=>he(Xe=>Xe.filter((Le,Ze)=>Ze!==Te)),className:"absolute -top-1.5 -right-1.5 rounded-full border bg-background p-0.5 text-muted-foreground shadow-sm transition-opacity hover:text-destructive",children:o.jsx(ln,{className:"h-3 w-3"})})]},Te))}),o.jsxs("div",{className:q("flex items-start gap-1.5 px-4",ne.length>0?"pt-1.5":"pt-3.5"),children:[Me&&o.jsx(A8,{recipient:Me,onRemove:()=>fe(void 0)}),pe&&o.jsx(bx,{name:pe,className:"mt-0.5 shrink-0",trailing:o.jsx("button",{type:"button",onClick:()=>ke(null),className:"rounded-sm opacity-70 hover:opacity-100","aria-label":D("Remove"),children:o.jsx(ln,{className:"h-3 w-3"})})}),o.jsx(AX,{ref:De,placeholder:pe?"":d?D("Resolve the pending approval to continue"):He?D("Message the selected Agent…"):qt?D("Press {{key}} to steer the next queued message into this round…",{key:Mi(Q)}):C||D(n?"Message will queue until this round finishes…":"Type @ to choose a file or Agent"),disabled:d,onStateChange:wn,onChipActivate:oe=>{oe.type==="ui-element"&&ue({kind:"ui-element",id:oe.id,label:oe.label,path:oe.path,text:oe.text,imageId:oe.imageId})},onKeyDown:jt,onPasteText:oe=>!A||!ek(oe)?!1:(A(oe).catch(()=>({ok:!1,error:"unavailable"})).then(Te=>{const Xe=De.current;Te.ok?Xe?.insertFileChip(Te.path,`${mk} · ${D("{{count}} chars",{count:Te.chars.toLocaleString()})}`):Xe?.insertText(oe)}),!0),onPaste:oe=>{const Te=Array.from(oe.clipboardData.files);Te.length!==0&&(oe.preventDefault(),_t(Te))},onCompositionStart:()=>{Ut.current=!0},onCompositionEnd:()=>{Ut.current=!1},ariaProps:{role:"combobox","aria-autocomplete":"list","aria-expanded":M!==null,"aria-controls":M==="mention"?H:void 0,"aria-activedescendant":M==="mention"?it?`${H}-sub-${Mt}`:`${H}-option-${ge}`:void 0}})]}),He&&o.jsx("p",{className:"sr-only",children:D("Send only to the selected Agent")}),o.jsxs("div",{className:"flex items-center justify-between gap-1.5 px-3 pt-0.5 pb-2.5",children:[o.jsxs("div",{className:q("flex min-w-0 flex-1 items-center gap-1",W?"overflow-x-auto [scrollbar-width:none]":"overflow-hidden"),children:[o.jsx("input",{ref:St,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:oe=>{_t(Array.from(oe.target.files??[])),oe.target.value=""}}),o.jsx("button",{type:"button",disabled:d,onClick:()=>St.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:o.jsx(Kg,{className:"h-3.5 w-3.5"})}),o.jsx(Pv,{side:"left",...Qe}),B?o.jsx(CX,{active:J,disabled:d,onChange:oe=>{O(oe),oe?document.activeElement?.blur():De.current?.focus()}}):E?o.jsx(cT,{startSession:E,requestMicAccess:I,disabled:d,holdBinding:V||void 0,holdScope:Ue,onText:oe=>{De.current?.insertText(oe),De.current?.focus()}}):null,c,o.jsx(Pv,{side:"right",...Qe}),bt&&(bt.blocked.length>0||bt.masked>0)&&o.jsxs("span",{className:q("flex shrink-0 items-center gap-1 text-[11px]",bt.blocked.length>0?"text-red-600 dark:text-red-400":"text-sky-600 dark:text-sky-400"),"data-privacy-precheck":!0,children:[bt.blocked.length>0?o.jsx(FC,{className:"size-3.5"}):o.jsx(Du,{className:"size-3.5"}),bt.blocked.length>0?D("Will be blocked: {{kinds}}",{kinds:bt.blocked.join(", ")}):D("{{count}} will be masked",{count:bt.masked})]})]}),ht&&!Ie?o.jsx(le,{variant:"outline",size:"icon",className:"size-8 shrink-0 rounded-full",onClick:b,"aria-label":D("Stop"),children:o.jsx(BH,{className:"h-4 w-4"})}):o.jsx(le,{size:"icon",className:"size-8 shrink-0 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-35",onClick:kt,disabled:!Ie||d,"aria-label":D(He?"Send only to the selected Agent":"Send"),title:He?D("Send only to the selected Agent"):l&&Q?`${D("Send")} ${Mi(Q)}`:D("Send"),children:o.jsx(nh,{className:"h-4 w-4"})})]})]}),B&&J?o.jsx(kX,{startSession:B,disabled:d,onText:oe=>{De.current?.insertText(oe),document.activeElement?.blur()}}):null,o.jsx(gn,{open:z!==null,onOpenChange:oe=>!oe&&ue(null),children:o.jsxs(xn,{className:"max-w-md",children:[o.jsx(vn,{children:o.jsx(bn,{children:z?.label??D("Selected UI element")})}),o.jsx(Rn,{className:"space-y-2 text-xs",children:z&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-muted-foreground break-all",children:z.path}),z.text&&o.jsx("p",{children:z.text}),(()=>{const oe=ne.find(Te=>Te.id===z.imageId);return oe?o.jsx("img",{src:`data:${oe.mimeType};base64,${oe.data}`,alt:"",className:"max-h-72 w-full rounded-md border object-contain"}):null})()]})})]})}),o.jsx(gn,{open:_e!==null,onOpenChange:oe=>!oe&&Ee(null),children:o.jsxs(xn,{className:"max-w-3xl",children:[o.jsx(vn,{children:o.jsx(bn,{children:D("Preview")})}),o.jsx(Rn,{children:_e&&o.jsx("img",{src:`data:${_e.mimeType};base64,${_e.data}`,alt:"",className:"max-h-[80vh] w-full rounded-md object-contain"})})]})})]})}function wI({title:e,className:t,onCommit:n,onCancel:s}){const[i,r]=m.useState(e),a=()=>{const l=i.trim();!l||l===e?s():n(l)};return o.jsx("input",{className:q("min-w-0 flex-1 rounded bg-transparent px-0.5 text-inherit outline-none ring-1 ring-ring",t),value:i,autoFocus:!0,onChange:l=>r(l.target.value),onBlur:a,onClick:l=>l.stopPropagation(),onPointerDown:l=>l.stopPropagation(),onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"?(l.preventDefault(),a()):l.key==="Escape"&&(l.preventDefault(),s())}})}async function yI(e,t){const n=await ie.getState().reloadConversation(e);n&&We({type:"error",title:t("Failed to reload conversation"),description:n})}async function FX(e,t){const n=await ie.getState().restartConversation(e);n&&We({type:"error",title:t("Failed to restart conversation"),description:n})}function HX({parentId:e,displayedId:t,trailing:n}){const{t:s}=te(),i=ie(p=>p.conversations[e]?.title??""),r=ie(p=>p.conversations[e]?.started===!0),a=ie(p=>p.conversations[e]?.reloading===!0),l=ie(p=>!!p.conversations[e]?.spawning),c=ie(p=>$Y(p.conversations,e)),[d,u]=m.useState(!1),h=p=>q("flex min-w-0 shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",p?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50");return o.jsxs(Ak,{"data-enso":"session-tabs",className:"border-b",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none]",children:[o.jsx(Ky,{id:e,label:i||s("New conversation"),className:h(t===e),leading:o.jsx(pr,{className:"h-3 w-3 shrink-0"}),reloadDisabled:a||l,reloading:a,onSelect:()=>ie.getState().selectTab(e,void 0)}),c.map(p=>{const f=TR({status:p.status,spawning:p.spawning,pendingApprovalCount:p.pendingApprovalCount,pendingAskCount:p.pendingAskCount,pendingCapabilityAskCount:p.pendingCapabilityAskCount});return o.jsxs("div",{className:"group/tab relative shrink-0",children:[o.jsx(Ky,{id:p.id,label:p.title||p.child?.agentInstanceName||p.coworkerName||p.id,className:q(h(t===p.id),t!==p.id&&"group-hover/tab:bg-muted/50"),leading:p.mode==="task"?o.jsx(sg,{className:"h-3 w-3 shrink-0"}):o.jsx(Zs,{className:"h-3 w-3 shrink-0"}),trailing:o.jsx("span",{className:"inline-flex h-3 w-3 shrink-0 items-center justify-center group-hover/tab:invisible",children:o.jsx(Sh,{tone:f,size:"sm"})}),reloadDisabled:p.reloading||p.spawning,reloading:p.reloading,onSelect:()=>ie.getState().selectTab(e,p.id)}),o.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."))&&ie.getState().dismissCoworkerFromUI(e,p.id)},children:o.jsx(ln,{className:"h-3 w-3"})})]},p.id)}),o.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:o.jsx(ps,{className:"h-3.5 w-3.5"})})]}),n,d&&o.jsx(BX,{parentId:e,onClose:()=>u(!1)})]})}function Ky({id:e,label:t,className:n,leading:s,trailing:i,reloadDisabled:r,reloading:a,onSelect:l}){const{t:c}=te(),[d,u]=m.useState(!1),h=o.jsxs("button",{type:"button",className:n,onClick:()=>{d||l()},onDoubleClick:p=>{p.preventDefault(),p.stopPropagation(),u(!0)},children:[s,d?o.jsx(wI,{title:t,className:"max-w-48 text-xs",onCommit:p=>{ie.getState().renameConversation(e,p),u(!1)},onCancel:()=>u(!1)}):o.jsx("span",{className:"max-w-48 truncate",children:t}),i]});return o.jsxs(ao,{children:[o.jsx(lo,{render:h}),o.jsxs(co,{className:"min-w-36",children:[o.jsxs(Ht,{onClick:()=>u(!0),children:[o.jsx(Xs,{}),c("Rename")]}),o.jsxs(Ht,{disabled:r,onClick:()=>{yI(e,c)},children:[o.jsx(Mo,{className:a?"animate-spin":void 0}),c("Reload conversation")]})]})]})}function BX({parentId:e,onClose:t}){const{t:n}=te(),s=xe(g=>g.agentTypes),i=xe(g=>g.disabledBuiltinAgentTypes),[r,a]=m.useState(""),[l,c]=m.useState(""),[d,u]=m.useState(null),h=new Set(s.map(g=>g.name.trim().toLowerCase())),p=[...IR.filter(g=>!i.includes(g.name)&&!h.has(g.name)).map(g=>g.name),...s.map(g=>g.name)],f=[{value:"",label:"general"},...p.map(g=>({value:g,label:g}))],x=async()=>{const g=await ie.getState().hireCoworker(e,r.trim(),l||void 0);g?u(g):t()};return o.jsx(gn,{open:!0,onOpenChange:g=>!g&&t(),children:o.jsxs(xn,{className:"max-w-sm",children:[o.jsx(vn,{children:o.jsx(bn,{children:n("Hire coworker")})}),o.jsxs(Rn,{className:"space-y-4",children:[o.jsxs(Hs,{children:[o.jsx(Bs,{children:n("Name (slug)")}),o.jsx(Wt,{value:r,onChange:g=>a(g.target.value),placeholder:"reviewer",autoFocus:!0})]}),o.jsxs(Hs,{children:[o.jsx(Bs,{children:n("Agent type")}),o.jsxs(ms,{items:f,value:l,onValueChange:g=>c(g??""),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:f.map(g=>o.jsx(ts,{value:g.value,children:g.label},g.value||"general"))})]})]}),d&&o.jsx("p",{className:"text-destructive text-xs",children:d}),o.jsx("div",{className:"h-1"})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"ghost",onClick:t,children:n("Cancel")}),o.jsx(le,{onClick:()=>{x()},disabled:!r.trim(),children:n("Hire")})]})]})})}function VX(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 $X={active:"bg-green-500 animate-pulse",paused:"bg-amber-500",waiting:"bg-amber-500",blocked:"bg-destructive",completed:"bg-blue-500"};function WX({conversationId:e,goal:t}){const{t:n}=te(),s={active:n("working"),paused:n("paused"),waiting:n("waiting"),blocked:n("blocked"),completed:n("completed")};return o.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:[o.jsx(Sa,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsxs("span",{className:"min-w-0 flex-1 truncate",title:t.note?`${t.text} — ${t.note}`:t.text,children:[t.text,t.note&&o.jsxs("span",{className:"text-muted-foreground",children:[" — ",t.note]})]}),o.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",$X[t.status])}),o.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"?o.jsx("button",{type:"button",title:n("Pause goal"),onClick:()=>ie.getState().pauseGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:o.jsx(QB,{className:"h-3.5 w-3.5"})}):t.status!=="completed"?o.jsx("button",{type:"button",title:n("Resume goal"),onClick:()=>ie.getState().resumeGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:o.jsx($m,{className:"h-3.5 w-3.5"})}):null,o.jsx("button",{type:"button",title:n("Clear goal"),onClick:()=>ie.getState().clearGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-destructive",children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]})}function UX(e,t){return e.trim().length>0||t>0}function qy(e,t){return e>0?`${e} ${t}`:null}function SI({conversationId:e,queued:t}){const{t:n}=te(),[s,i]=m.useState(null),[r,a]=m.useState("");if(t.length===0)return null;const l=c=>{UX(r,c.images?.length??0)&&ie.getState().updateQueuedMessage(e,c.id,r.trim()),i(null)};return o.jsx("div",{className:"mb-1 flex flex-col gap-0.5",children:t.map(c=>o.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:[o.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground uppercase tracking-wide",children:n("Queued")}),s===c.id?o.jsx("input",{value:r,onChange:d=>a(d.target.value),onKeyDown:d=>{d.nativeEvent.isComposing||(d.key==="Enter"&&l(c),d.key==="Escape"&&i(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"}):o.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.text||"[image]"}),qy(c.images?.length??0,n("attachments"))&&o.jsxs("span",{title:qy(c.images?.length??0,n("attachments"))??void 0,className:"flex shrink-0 items-center gap-0.5 text-muted-foreground",children:[o.jsx(RB,{className:"h-3 w-3"}),c.images?.length]}),s===c.id?o.jsx("button",{type:"button",onClick:()=>l(c),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground",children:o.jsx(Jn,{className:"h-3.5 w-3.5"})}):o.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:[o.jsx("button",{type:"button",title:n("Withdraw message"),"aria-label":n("Withdraw message"),onClick:()=>ie.getState().withdrawMessage(e,{kind:"queue",id:c.id}),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:o.jsx(ra,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",title:n("Edit"),onClick:()=>{i(c.id),a(c.text)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:o.jsx(Xs,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",title:n("Send now"),onClick:()=>ie.getState().sendQueuedNow(e,c.id),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:o.jsx(Jg,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",title:n("Interrupt and send now"),onClick:()=>{ie.getState().interruptAndSendQueued(e,c.id)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:o.jsx(hV,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",title:n("Remove"),onClick:()=>ie.getState().removeQueuedMessage(e,c.id),className:"rounded p-0.5 text-muted-foreground hover:text-destructive",children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]})]},c.id))})}const CI="mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2 text-xs";function kI({doc:e}){return o.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:o.jsx(Ds,{text:e.text})})}function KX({conversationId:e,planState:t,approvalMode:n}){const s=Mk(t);return s==="awaiting_review"&&t?.pending?o.jsx(qX,{conversationId:e,doc:t.pending,approvalMode:n},t.pending.planId):s==="executing"&&t?.executing?o.jsx(YX,{conversationId:e,doc:t.executing},t.executing.planId):null}function qX({conversationId:e,doc:t,approvalMode:n}){const{t:s}=te(),i=DR(),[r,a]=m.useState(!0),[l,c]=m.useState(!1),[d,u]=m.useState(""),[h,p]=m.useState(!1),[f,x]=m.useState(!1),g=async(v,w)=>{x(!0);const y=ie.getState();w&&w!==n&&y.setApprovalMode(e,w);const b=await y.respondPlan(e,t.planId,v,v==="revise"?d.trim():void 0);b&&(x(!1),We({type:"error",title:s("Plan response failed"),description:b}))};return o.jsxs("div",{className:CI,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(da,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),o.jsx("span",{className:"shrink-0 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:s("Plan awaiting approval")}),o.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:[o.jsx("span",{className:"truncate",children:t.title}),o.jsx(kn,{className:q("h-3 w-3 shrink-0 transition-transform",r&&"rotate-90")})]})]}),r&&o.jsx(kI,{doc:t}),l&&o.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(),g("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"}),o.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[o.jsx("button",{type:"button",disabled:f,onClick:()=>{g("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?o.jsx("button",{type:"button",disabled:f||!d.trim(),onClick:()=>{g("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")}):o.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")}),o.jsxs("div",{className:"flex",children:[o.jsx("button",{type:"button",disabled:f,onClick:()=>{g("approve")},title:s(_l[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")}),o.jsxs(Pi,{open:h,onOpenChange:p,children:[o.jsx(Ei,{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:o.jsx($n,{className:"h-3.5 w-3.5"})}),o.jsxs(Ai,{side:"top",align:"end",className:"w-80 [&_[data-slot=popover-viewport]]:p-1",children:[o.jsx("p",{className:"px-2 pt-1 pb-1.5 text-muted-foreground text-xs",children:s("Approve and execute with")}),PR.map(v=>{const w=_l[v],y=w.icon,b=v==="assistant"&&!i;return o.jsxs("button",{type:"button",disabled:b,onClick:()=>{p(!1),g("approve",v)},className:q("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",v===n?"bg-muted":"hover:bg-muted/60",b&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[o.jsx(y,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block",children:s(w.labelKey)}),o.jsx("span",{className:"block text-xs text-muted-foreground",children:s(w.descKey)})]})]},v)})]})]})]})]})]})}function YX({conversationId:e,doc:t}){const{t:n}=te(),[s,i]=m.useState(!1);return o.jsxs("div",{className:q(CI,"py-1.5"),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(c1,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"shrink-0 text-muted-foreground",children:n("Executing plan")}),o.jsxs("button",{type:"button",onClick:()=>i(r=>!r),className:"flex min-w-0 flex-1 items-center gap-1 text-left",title:t.title,children:[o.jsx("span",{className:"truncate",children:t.title}),o.jsx(kn,{className:q("h-3 w-3 shrink-0 transition-transform",s&&"rotate-90")})]}),o.jsx("button",{type:"button",title:n("Finish plan"),onClick:()=>{ie.getState().respondPlan(e,t.planId,"finish")},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]}),s&&o.jsx(kI,{doc:t})]})}function XX({active:e,onToggle:t}){const{t:n}=te();return o.jsxs("button",{type:"button","aria-pressed":e,title:n(e?"Plan mode is on: read-only research, then a plan for your approval":"Plan first: research read-only and submit a plan for approval"),onClick:()=>t(!e),className:q("flex h-7 min-w-0 shrink-0 items-center gap-1 rounded-lg px-2 text-xs transition-colors",e?"bg-primary/10 text-primary hover:bg-primary/15":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[o.jsx(da,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"hidden @min-[28rem]:inline",children:n("Plan")})]})}function JX({presetId:e,onSelect:t,onModel:n,disabled:s}){const{t:i}=te(),r=xe(h=>h.presets),a=ER(),[l,c]=m.useState(!1),d=[{id:AR,name:i("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:MR(e)?i("Plugin preset unavailable"):d[0]?.name??""};return s?o.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:i("Preset is locked after the conversation starts"),children:[o.jsx(Gd,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"truncate",children:u.name})]}):o.jsxs(Pi,{open:l,onOpenChange:c,children:[o.jsxs(Ei,{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:[o.jsx(Gd,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"min-w-0 truncate",children:u.name}),o.jsx($n,{className:"h-3 w-3 shrink-0"})]}),o.jsx(Ai,{side:"top",align:"start",className:"w-52 [&_[data-slot=popover-viewport]]:p-1",children:d.map(h=>{const p=h.id===u.id;return o.jsxs("button",{type:"button",onClick:()=>{t(h.id);const f=r.find(g=>g.id===h.id)?.pluginPresetId,x=RR(f??h.id,a);x&&n?.(x),c(!1)},className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",p?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[o.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.name}),p&&o.jsx(Jn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},h.id)})})]})}const ZX=[];function QX({projectId:e,conversationId:t}){const{t:n}=te(),s=xe(p=>p.projects.find(f=>f.id===e)?.trustedProjectCode??ZX),i=xe(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?o.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:[o.jsx(Jr,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1",children:n("Project extensions trusted. They load in new sessions and after this one restarts.")}),o.jsx("button",{type:"button",onClick:()=>c(!0),title:n("Dismiss"),children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]}):o.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:[o.jsx(Jr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-warning"}),o.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[o.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.")}),o.jsx("p",{className:"truncate font-mono text-muted-foreground",title:h.join(`
88
- `),children:h.join(", ")})]}),o.jsx(le,{size:"xs",variant:"outline",onClick:()=>{i(e,r),u(!0)},children:n("Trust and load")}),o.jsx("button",{type:"button",onClick:()=>c(!0),title:n("Dismiss"),children:o.jsx(ln,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}const Yy={system:"System prompt",instructions:"Enabled instructions",skills:"Enabled skills",tools:"Tool definitions",conversation:"Conversation",compaction:"Compaction summary",reminders:"Reminders"};function eJ({conversationId:e}){const{t}=te(),n=ie(r=>r.conversations[e]?.compaction);if(!ie(r=>r.conversations[e]?.started))return null;const i=t(n==="running"?"Compacting…":n==="queued"?"Compacts after this turn":"Compact context");return o.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:()=>ie.getState().compact(e),children:i})}function tJ({occupancy:e,conversationId:t}){const{t:n}=te();if(!e)return o.jsx("p",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:n("Context occupancy unavailable until the session starts")});const s=e.contextWindow;return o.jsxs("div",{className:"flex flex-col gap-2 px-2 py-1.5",children:[o.jsxs("div",{className:"flex items-baseline justify-between gap-2 text-xs",children:[o.jsxs("span",{className:"tabular-nums",children:[js(e.used),s?` / ${js(s)}`:" · ?",e.percent!==void 0?` · ${e.percent}%`:""]}),o.jsx("span",{className:"text-muted-foreground",children:n("Estimate")})]}),e.compactionModelMismatch&&o.jsx("p",{className:"text-[11px] text-muted-foreground",children:n("Current summary was produced by another model family")}),e.compactedMessageCount>0&&o.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[o.jsx("p",{children:n("{{count}} older messages are folded into the summary",{count:e.compactedMessageCount})}),t&&e.compactionEntryId&&o.jsx("button",{type:"button",className:"shrink-0 text-foreground/80 hover:underline",onClick:()=>{ie.getState().forkFromEntry(t,e.compactionEntryId)},children:n("Conversation branch")})]}),o.jsx("ul",{className:"flex flex-col gap-1",children:Object.keys(Yy).map(i=>{const r=e.buckets[i],a=e.used>0?Math.round(r/e.used*100):0;return o.jsxs("li",{className:"flex items-center gap-2 text-[11px]",children:[o.jsx("span",{className:"w-28 shrink-0 truncate text-muted-foreground",children:n(Yy[i])}),o.jsx("span",{className:"min-w-0 flex-1",children:o.jsx("span",{className:"block h-1 overflow-hidden rounded-full bg-muted",children:o.jsx("span",{className:"block h-full bg-foreground/50",style:{width:`${a}%`}})})}),o.jsx("span",{className:"w-10 shrink-0 text-right tabular-nums",children:js(r)})]},i)})}),t&&o.jsx(eJ,{conversationId:t})]})}const nJ=70;function sJ({percent:e,critical:t}){return o.jsx("span",{"aria-hidden":!0,className:"h-1 w-7 shrink-0 overflow-hidden rounded-full bg-muted-foreground/20",children:o.jsx("span",{className:q("block h-full rounded-full",t?"bg-destructive":e>=nJ?"bg-warning":"bg-muted-foreground/70"),style:{width:`${e}%`}})})}function iJ(e){return e?e.used:null}const Gx=90;function _I(e,t){const n=iJ(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 oJ(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 rJ(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:`${js(a)} · ${l}%`,percent:l,critical:l>=Gx}}else n.context={compact:`${js(r)}·?`,full:`${js(r)} · ?`}}const s=[],i=[];return t.ttftAvgMs!==void 0&&(s.push(rs(t.ttftAvgMs)),i.push(e("First token avg {{duration}}",{duration:rs(t.ttftAvgMs)}))),t.tokensPerSecond!==void 0&&(s.push(`${t.tokensPerSecond} tok/s`),i.push(e("{{speed}} tok/s",{speed:t.tokensPerSecond}))),s.length>0&&(n.speed={compact:s.join(" · "),full:i.join(" · ")}),(t.inputTokens>0||t.outputTokens>0)&&(n.tokens={compact:`↑${js(t.inputTokens)} ↓${js(t.outputTokens)}`,full:e("Input {{input}} tok · Output {{output}} tok",{input:js(t.inputTokens),output:js(t.outputTokens)})}),t.cacheHitPercent!==void 0&&(n.cache={compact:`${t.cacheHitPercent}%`,full:e("Cache hit {{percent}}%",{percent:t.cacheHitPercent})}),n}function aJ(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:Ap(t.bytes),full:`${Ap(t.bytes)} / ${Ap(t.limitBytes)} · ${n}% · ${s}`,critical:t.blocked||n>=Gx}}function Ap(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 lJ({className:e,orientation:t="horizontal",...n}){return o.jsx(LR,{className:q("shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px data-[orientation=vertical]:not-[[class^='h-']]:not-[[class*='_h-']]:self-stretch",e),"data-slot":"separator",orientation:t,...n})}const cJ={minimal:"Minimal",default:"Default",full:"Full"};function dJ({icons:e,values:t}){const{t:n}=te(),s=xe(g=>g.statusLineSegments),i=m.useMemo(()=>jI(s),[s]),r=xe(g=>g.toggleStatusLineSegment),a=xe(g=>g.setStatusLineSegments),[l,c]=m.useState(null),[d,u]=m.useState(null),h=OR(i),p=Rk.filter(g=>!i.includes(g)),f=()=>{c(null),u(null)},x=()=>{if(l!==null&&d!==null){const g=d>l?d-1:d,v=HR(i,l,g);v!==i&&a([...v])}f()};return o.jsxs("div",{className:"flex flex-col",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b p-2",children:[o.jsx("div",{className:"flex gap-1",children:zR.map(g=>o.jsx(le,{variant:h===g?"secondary":"ghost",size:"xs",onClick:()=>a([...GR[g]]),children:n(cJ[g])},g))}),h==="custom"&&o.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:n("Custom")})]}),o.jsxs("div",{className:"max-h-80 overflow-y-auto p-2",onDragOver:g=>{l!==null&&g.preventDefault()},onDrop:g=>{l!==null&&(g.preventDefault(),x())},children:[i.map((g,v)=>{const w=e[g],y=t[g];return o.jsxs("div",{children:[l!==null&&d===v&&o.jsx("div",{className:"mx-2 my-0.5 h-0.5 rounded-full bg-primary"}),o.jsxs("div",{onDragOver:b=>{if(l===null)return;b.preventDefault();const _=b.currentTarget.getBoundingClientRect(),j=b.clientY<_.top+_.height/2;u(j?v:v+1)},onDrop:b=>{b.preventDefault(),x()},className:q("flex items-center justify-between gap-3 rounded-md px-2 py-1.5",l===v&&"opacity-40"),children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("span",{role:"button",tabIndex:0,draggable:!0,onDragStart:b=>{b.dataTransfer.effectAllowed="move",b.dataTransfer.setData("text/plain",g),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:o.jsx(FR,{className:"h-3.5 w-3.5"})}),o.jsx(w,{className:"h-3.5 w-3.5 shrink-0"}),o.jsxs("div",{className:"flex min-w-0 flex-col",children:[o.jsx("span",{className:"text-sm",children:n(bu[g])}),o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:y?.full||n("No data yet")})]})]}),o.jsx(_i,{checked:!0,onCheckedChange:b=>r(g,b)})]})]},g)}),l!==null&&d===i.length&&o.jsx("div",{className:"mx-2 my-0.5 h-0.5 rounded-full bg-primary"}),p.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(lJ,{className:"my-2"}),p.map(g=>{const v=e[g],w=t[g];return o.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md px-2 py-1.5",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:"w-3.5 shrink-0"}),o.jsx(v,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),o.jsxs("div",{className:"flex min-w-0 flex-col",children:[o.jsx("span",{className:"text-sm",children:n(bu[g])}),o.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:w?.full||n("No data yet")})]})]}),o.jsx(_i,{checked:!1,onCheckedChange:y=>r(g,y)})]},g)})]})]})]})}function jI(e){const t=Array.isArray(e)?e:VR,n=new Set(Rk),s=new Set,i=[];for(const r of t)typeof r=="string"&&n.has(r)&&!s.has(r)&&(s.add(r),i.push(r));return i}const bu={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"},uJ={minimal:"Min",low:"Low",medium:"Med",high:"High",xhigh:"Extra",max:"Max"},hJ={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"},pJ={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},fJ={supervised:KR,"auto-edits":Du,full:UR,assistant:Ls},mJ={model:nB,context:YR,requestBody:qR,turns:sV,duration:d1,sessionTime:DB,speed:sg,tokens:XH,cache:iB,cwd:Qs,sessionName:fV,coworkers:ta,usage:jV};function gJ(e,t,n){if(e.status!=="running")return{llm:0,tool:0};for(let s=t.length-1;s>=0;s--){const i=t[s];if(!(i.role!=="assistant"||!i.timing))return i.timing.completedMs===void 0?{llm:Math.max(0,n-i.timing.stepStartMs),tool:0}:{llm:0,tool:Math.max(0,n-i.timing.completedMs)}}return{llm:0,tool:0}}function xJ(e){return e.split(/[\\/]+/).filter(Boolean).at(-1)??e}function Wc(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function Xy(e){if(e<=0)return"0m";const t=Math.round(e/6e4),n=Math.floor(t/1440),s=Math.floor(t%1440/60),i=t%60;return n>0?`${n}d${s}h`:s>0?`${s}h${i}m`:`${i}m`}function Jy(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 vJ(e){return{...mJ,approval:fJ[e.approvalMode??"full"]}}function bJ(e,t){const[n,s]=m.useState(()=>{if(!e)return;const i=Ev.get(e);return i?{key:e,data:i.data}:void 0});return m.useEffect(()=>{if(!e)return;let i=!1;const r=Ev.get(e);if(r&&Date.now()-r.fetchedAt<$R){s({key:e,data:r.data});return}return WR(e).then(a=>{i||s({key:e,data:a})}).catch(()=>{i||s(a=>a?.key===e?void 0:a)}),()=>{i=!0}},[e,t]),e&&n?.key===e?n.data:void 0}function wJ(e,t,n,s,i,r,a){const l=o4(n),c={model:void 0,requestBody:aJ(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,...rJ(e,oJ(r4(l),_I(t.occupancy,t.contextWindow)))};if(t.lastModelId){const y=s.find(_=>_.id===t.lastProviderId)?.models.find(_=>_.id===t.lastModelId)?.label??t.lastModelId,b=t.reasoningEnabled?t.thinkingLevel:void 0;c.model={compact:b?`${y} · ${e(uJ[b])}`:y,full:b?`${y} · ${e(hJ[b])}`:y}}l.steps>0&&(c.turns={compact:`${l.turns}·${l.steps}`,full:e("{{turns}} turns · {{steps}} steps",{turns:l.turns,steps:l.steps})});const d=gJ(t,n,r),u=l.llmMs+d.llm,h=l.toolMs+d.tool,p=[],f=[];u>=1e3&&(p.push(rs(u)),f.push(e("LLM {{duration}}",{duration:rs(u)}))),h>=1e3&&(p.push(rs(h)),f.push(e("Tool calls {{duration}}",{duration:rs(h)}))),p.length>0&&(c.duration={compact:p.join(" · "),full:f.join(" · ")});const x=Math.max(0,r-t.createdAt);c.sessionTime={compact:Jy(x),full:Jy(x)};const g=i.find(w=>w.id===t.projectId);if(g){const w=xJ(g.path);c.cwd={compact:w,full:g.path}}t.title.trim().length>0&&(c.sessionName={compact:Wc(t.title,16),full:Wc(t.title,60)}),c.approval={compact:"",full:e(pJ[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 w=a.windows,y=Math.max(...w.map(C=>C.usedPercent)),b=w[0],_=Wc(b.label,24),j=b.resetsAt!==void 0?Xy(b.resetsAt-r):void 0,N=w.length>1?` +${w.length-1}`:"";c.usage={compact:`${_} ${Math.round(b.usedPercent)}%${j?`·${j}`:""}${N}`,full:w.map(C=>{const k=C.resetsAt!==void 0?` · ${e("resets in {{remaining}}",{remaining:Xy(C.resetsAt-r)})}`:"";return`${Wc(C.label,24)} ${Math.round(C.usedPercent)}%${k}`}).join(" · "),critical:y>=Gx}}return c}function NI({conversationId:e}){const{t}=te(),n=ie(k=>k.conversations[e]),s=n?.messages??[],i=ma(),r=xe(k=>k.virtualModels),a=m.useMemo(()=>r.length===0?i:[...i,{id:Lk,models:r.map(k=>({id:k.id,label:k.name}))}],[i,r]),l=xe(k=>k.projects),c=xe(k=>k.statusLineSegments),d=m.useMemo(()=>jI(c),[c]),[u,h]=m.useState(null),[p,f]=m.useState(!1),x=m.useMemo(()=>{if(d.includes("usage"))return ig(i,n)?.accountKey},[d,i,n]),[g,v]=m.useState(()=>Date.now()),w=n?.status==="running"&&d.includes("duration"),y=d.includes("sessionTime"),b=d.includes("usage")&&x!==void 0;m.useEffect(()=>{if(!w&&!y&&!b)return;const k=setInterval(()=>v(Date.now()),1e3);return()=>clearInterval(k)},[w,y,b]);const _=bJ(x,g),j=m.useMemo(()=>n?vJ(n):null,[n]),N=m.useMemo(()=>n?wJ(t,n,s,a,l,g,_):null,[t,n,s,a,l,g,_]);if(!n||!j||!N)return null;const C=d.filter(k=>N[k]);return o.jsxs("div",{"data-slot":"stats-line","data-enso":"status-line",className:"group relative flex h-7 items-center justify-center px-1",children:[C.length>0&&o.jsx("div",{className:"flex min-w-0 flex-nowrap items-center gap-3 overflow-hidden",children:C.map((k,E)=>{const I=N[k];if(!I)return null;const T=j[k],A=o.jsxs("span",{title:`${t(bu[k])} · ${I.full}`,onMouseEnter:()=>h(k),onMouseLeave:()=>h(D=>D===k?null:D),className:q("relative flex items-center gap-1 text-[11px] tabular-nums",I.critical?"text-destructive":"text-subtle-foreground"),children:[k==="context"&&I.percent!==void 0?o.jsx(sJ,{percent:I.percent,critical:!!I.critical}):o.jsx(T,{className:"h-3 w-3 shrink-0 opacity-75"}),I.compact&&o.jsx("span",{className:"truncate",children:I.compact}),u===k&&k!=="context"&&o.jsxs("div",{style:{zIndex:yn.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:[o.jsx("span",{className:"break-words font-medium",children:t(bu[k])}),o.jsx("span",{className:"ml-1 break-words text-muted-foreground",children:I.full})]})]});return o.jsx("span",{className:q("shrink-0 items-center",p||BR(k,E)?"flex":"hidden group-focus-within:flex group-hover:flex"),children:k==="context"?o.jsxs(Pi,{open:p,onOpenChange:f,children:[o.jsx(Ei,{className:"rounded-sm outline-none",children:A}),o.jsx(Ai,{side:"top",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:o.jsx(tJ,{occupancy:n.occupancy,conversationId:n.id})})]}):A},k)})}),o.jsxs(Pi,{children:[o.jsx(Ei,{"aria-label":t("Status line settings"),className:"-translate-y-1/2 absolute top-1/2 right-1 flex h-5.5 w-5.5 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100",children:o.jsx(Ok,{className:"h-3.5 w-3.5"})}),o.jsx(Ai,{side:"top",align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:o.jsx(dJ,{icons:j,values:N})})]})]})}const yJ=["pattern","query","path","file_path"],SJ=["path","file_path","query","pattern"],CJ=["command","cmd","script"],kJ=["path","file_path","pattern","query","command","url","description","summary"],Zy=120;function Ra(e){const t=e.replace(/\s+/g," ").trim();return t.length>Zy?`${t.slice(0,Zy-1)}…`:t}function _J(e){const t=e.toLowerCase();return t.includes("search")||t.includes("grep")||t==="find"?yJ:t==="read"||t.endsWith("_read")?SJ:t==="bash"||t.includes("shell")||t.includes("terminal")?CJ:kJ}function jJ(e,t){const n=t.trim();if(!n)return"";let s;try{s=JSON.parse(n)}catch{return Ra(n)}if(s===null)return"";if(typeof s!="object"||Array.isArray(s))return Ra(JSON.stringify(s)??String(s));const i=zk(e,s);if(i.summary!==void 0)return Ra(i.summary);if(!i.args||typeof i.args!="object")return"";const r=i.args;for(const l of _J(i.name)){const c=r[l];if(typeof c=="string"&&c.trim())return Ra(c)}const a=JSON.stringify(r);return a==="{}"?"":Ra(a)}function NJ(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}const TI=new Map,TJ=e=>{const t=TI.get(e);return t?new Set(t):new Set},Qy=(e,t)=>(TI.set(e,t),t),xm=new Map,IJ=(e,t)=>{const n=xm.get(e)??new Set;xm.set(e,n);for(const s of t)n.add(s);return n};function Fx({sessionId:e,tasks:t,subagents:n,readOnly:s}){const i=xe(w=>w.virtualModels),{t:r}=te(),[a,l]=m.useState(()=>TJ(e)),[c,d]=m.useState(null),u=IJ(e,[...t.filter(w=>w.status==="running").map(w=>w.taskId),...n.filter(w=>w.status==="running").map(w=>w.id)]),h=(w,y)=>!a.has(w)&&(y==="running"||u.has(w)),p=t.filter(w=>h(w.taskId,w.status)),f=n.filter(w=>h(w.id,w.status));if(m.useEffect(()=>{const w=xm.get(e),y=[...t.filter(_=>_.status!=="running").map(_=>_.taskId),...n.filter(_=>_.status!=="running").map(_=>_.id)].filter(_=>w?.has(_)&&!a.has(_)&&_!==c);if(y.length===0)return;const b=setTimeout(()=>{l(_=>{const j=new Set(_);for(const N of y)j.add(N);return Qy(e,j)})},5e3);return()=>clearTimeout(b)},[e,t,n,a,c]),p.length===0&&f.length===0)return null;const x=w=>{l(y=>Qy(e,new Set(y).add(w))),c===w&&d(null)},g=p.find(w=>w.taskId===c)??null,v=f.find(w=>w.id===c)??null;return o.jsxs("div",{className:"relative mb-1.5",children:[(g||v)&&o.jsxs("div",{className:"absolute bottom-full left-0 right-0 z-30 mb-1.5 rounded-xl border bg-card shadow-float",children:[o.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-1.5 text-xs",children:[o.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:[g?g.command:v?.description,v?.modelId?` · ${sf(i,v.modelId)}`:""]}),o.jsx("button",{type:"button",onClick:()=>d(null),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:o.jsx(ln,{className:"h-3.5 w-3.5"})})]}),g&&o.jsx(OJ,{tail:g.tail}),v&&o.jsx(DJ,{agent:v},v.id)]}),o.jsxs("div",{className:"flex flex-col gap-0.5 rounded-xl border bg-card p-1 shadow-xs",children:[p.map(w=>o.jsx(eS,{icon:Eo,status:w.status,meta:o.jsx(LJ,{task:w}),open:c===w.taskId,onToggle:()=>d(c===w.taskId?null:w.taskId),stopTitle:r("Stop task"),onStop:s?void 0:()=>{window.electronAPI.agent.stopTask(e,w.taskId)},onDismiss:()=>x(w.taskId),children:o.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground",title:w.command,children:w.command})},w.taskId)),f.map(w=>o.jsxs(eS,{icon:Zs,status:w.status,meta:o.jsx(RJ,{agent:w}),open:c===w.id,onToggle:()=>d(c===w.id?null:w.id),stopTitle:r("Stop subagent"),onStop:s?void 0:()=>{window.electronAPI.agent.stopSubagent(e,w.id)},onDismiss:()=>x(w.id),children:[w.agentType&&o.jsx("span",{className:"shrink-0 font-medium",children:w.agentType}),o.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:[w.description,w.modelId&&o.jsxs("span",{className:"text-muted-foreground/60",children:[" ","· ",sf(i,w.modelId)]}),w.status==="running"&&w.currentActivity&&o.jsxs("span",{className:"text-muted-foreground/60",children:[" · ",w.currentActivity]})]})]},w.id))]})]})}function eS({icon:e,status:t,meta:n,open:s,onToggle:i,stopTitle:r,onStop:a,onDismiss:l,children:c}){const{t:d}=te();return o.jsxs("div",{className:"flex min-h-[30px] min-w-0 items-center gap-2 px-1 text-[13px]",children:[o.jsx(NU,{icon:e,state:t==="running"?"running":t==="failed"?"error":"ok"}),c,n,o.jsxs("button",{type:"button",onClick:i,"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"),o.jsx($n,{className:q("h-3 w-3 transition-transform",s&&"rotate-180")})]}),t==="running"?a&&o.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:o.jsx(Mu,{className:"h-3 w-3"})}):o.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:o.jsx(ln,{className:"h-3 w-3"})})]})}function DJ({agent:e}){const{t}=te(),n=e.activities??[],s=m.useRef(null),i=m.useRef(!0);return m.useEffect(()=>{const r=s.current;r&&i.current&&(r.scrollTop=r.scrollHeight)},[n,e.resultText]),o.jsxs("div",{ref:s,className:"max-h-96 space-y-2 overflow-auto px-3 py-2 text-sm",onScroll:r=>{i.current=NJ(r.currentTarget)},children:[n.map(r=>o.jsx(PJ,{activity:r},r.id)),n.length===0&&!e.resultText&&o.jsx("pre",{className:"font-mono text-xs whitespace-pre-wrap text-muted-foreground",children:(e.activityLog??[]).join(`
89
- `)||t("(no output yet)")}),e.detailsPruned&&o.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"&&o.jsxs("section",{className:q("rounded-lg border px-3 py-2",e.status==="failed"?"border-destructive/30 bg-destructive/5":"border-blue-500/30 bg-blue-500/5"),children:[o.jsx("div",{className:"mb-1.5 font-medium text-xs text-foreground",children:t("Final report")}),o.jsx(Ds,{text:e.resultText})]})]})}function PJ({activity:e}){const{t}=te(),[n,s]=m.useState(!1);if(e.type==="assistant")return o.jsxs("section",{className:"rounded-md bg-muted/30 px-2.5 py-2",children:[o.jsx("div",{className:"mb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:t("Assistant")}),o.jsx(MJ,{text:e.text,markdown:!0})]});const i=jJ(e.toolName,e.argumentsText),r=zk(e.toolName,e.argumentsText).name,a=WC(r),l=`subagent-tool-${e.id.replace(/[^A-Za-z0-9_-]/g,"-")}`;return o.jsxs("section",{className:"border-b border-border/40 last:border-b-0",children:[o.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:[o.jsx(EJ,{toolName:r}),o.jsx("span",{className:"shrink-0 font-medium text-foreground/80",children:a?.tool??r}),i&&o.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",title:i,children:i}),!i&&o.jsx("span",{className:"min-w-0 flex-1"}),o.jsx(AJ,{status:e.status,label:t(e.status)}),o.jsx(kn,{"aria-hidden":"true",className:q("h-3 w-3 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")})]}),n&&o.jsxs("div",{id:l,className:"ml-5 border-border/50 border-l pb-2 pl-2.5",children:[a&&o.jsxs("div",{className:"mb-1 truncate font-mono text-[10px] text-muted-foreground/70",children:[a.server,".",a.tool]}),o.jsx("div",{className:"text-[10px] text-muted-foreground/70",children:t("Arguments")}),o.jsx("pre",{className:"max-h-28 overflow-auto font-mono text-[10px] leading-relaxed whitespace-pre-wrap text-muted-foreground/80",children:Oi(e.argumentsText)}),e.outputText&&o.jsxs("div",{className:"mt-1.5 border-border/40 border-t pt-1.5",children:[o.jsx("div",{className:"mb-0.5 text-[10px] text-muted-foreground",children:t("Result")}),o.jsx("pre",{className:"overflow-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-foreground/80",children:Oi(e.outputText)})]})]})]})}function EJ({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"?o.jsx(Js,{"aria-hidden":"true",className:n}):t==="read"||t==="write"||t==="edit"||t==="apply_patch"||t.endsWith("_read")?o.jsx(go,{"aria-hidden":"true",className:n}):t==="bash"||t==="exec"||t==="codemode"||t.includes("shell")||t.includes("terminal")?o.jsx(Jp,{"aria-hidden":"true",className:n}):o.jsx(Km,{"aria-hidden":"true",className:n})}function AJ({status:e,label:t}){const n="h-3.5 w-3.5";return o.jsx("span",{role:"status","aria-label":t,title:t,className:q("shrink-0",e==="failed"?"text-destructive":"text-muted-foreground"),children:e==="running"?o.jsx(Vt,{"aria-hidden":"true",className:q(n,"animate-spin")}):e==="done"?o.jsx(Jn,{"aria-hidden":"true",className:n}):e==="failed"?o.jsx(ur,{"aria-hidden":"true",className:n}):o.jsx(TH,{"aria-hidden":"true",className:n})})}function MJ({text:e,label:t,markdown:n=!1}){const{t:s}=te(),i=e.length>800||e.split(`
90
- `).length>16,r=n?o.jsx(Ds,{text:e}):o.jsx("pre",{className:"overflow-x-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:Oi(e)});return i?o.jsxs("details",{className:"group/details",children:[o.jsxs("summary",{className:"cursor-pointer text-[10px] text-muted-foreground hover:text-foreground",children:[t?`${t} · `:"",s("{{count}} chars",{count:e.length})]}),o.jsx("div",{className:"mt-1.5",children:r})]}):o.jsxs("div",{children:[t&&o.jsx("div",{className:"mb-0.5 text-[10px] text-muted-foreground",children:t}),r]})}function RJ({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]),o.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"?rs(Date.now()-e.startedAt):e.status]})}function LJ({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]),o.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:e.status==="running"?rs(Date.now()-e.startedAt):e.exitCode!==void 0?`exit ${e.exitCode}`:e.status})}function OJ({tail:e}){const{t}=te(),n=m.useRef(null);return m.useEffect(()=>{const s=n.current;s&&(s.scrollTop=s.scrollHeight)},[e]),o.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:Oi(e)||t("(no output yet)")})}function Hx(e){return e==="darwin"?"Open in Finder":e==="win32"?"Open in File Explorer":"Open in File Manager"}async function Bx(e,t){try{const n=await window.electronAPI.projects.reveal(e);n.ok||We({type:"error",title:t("Could not complete the file action."),description:n.error})}catch(n){We({type:"error",title:t("Could not complete the file action."),description:String(n)})}}const zJ="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 GJ({project:e,conversationId:t,path:n,branch:s,openDisabled:i,children:r}){const{t:a}=te(),[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=>{Bx({projectId:e.id,conversationId:t,...v?{appId:v}:{}},a)},x=l.filter(v=>v.kind==="editor"),g=l.filter(v=>v.kind==="terminal");return o.jsxs(zi,{onOpenChange:v=>v&&p(),children:[o.jsxs(Gi,{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:[o.jsx(uc,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:`grid grid-cols-[0fr] opacity-0 transition-[grid-template-columns,opacity] duration-(--duration-fast) ease-(--ease-smooth-out) ${zJ}`,children:o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap pl-1.5",children:[o.jsx("span",{className:"max-w-40 truncate",children:h}),s&&!u&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"opacity-40",children:"/"}),o.jsx(Ni,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"max-w-40 truncate",children:s})]})]})}),o.jsx("span",{className:"ml-1.5 flex shrink-0 items-center",children:r})]}),o.jsxs(Fi,{align:"end",className:"min-w-48",children:[d&&o.jsxs(o.Fragment,{children:[o.jsxs(dn,{disabled:i,onClick:()=>f(),children:[o.jsx(Qs,{}),a(Hx(window.electronAPI.env.platform))]}),o.jsx(tS,{label:a("Editors"),apps:x,fallback:o.jsx(u1,{}),disabled:i,onOpen:f}),o.jsx(tS,{label:a("Terminals"),apps:g,fallback:o.jsx(Eo,{}),disabled:i,onOpen:f}),o.jsx(pa,{})]}),o.jsxs(dn,{onClick:()=>{navigator.clipboard.writeText(n)},children:[o.jsx(Pu,{}),a("Copy Path")]})]})]})}function tS({label:e,apps:t,fallback:n,disabled:s,onOpen:i}){return t.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx(pa,{}),o.jsxs(Xm,{children:[o.jsx(Jm,{children:e}),t.map(r=>o.jsxs(dn,{disabled:s,onClick:()=>i(r.id),children:[r.icon?o.jsx("img",{src:r.icon,alt:"",className:"-mx-0.5 size-4 shrink-0"}):n,r.name]},r.id))]})]})}function FJ({conversationId:e}){const{t}=te(),n=ie(r=>r.conversations[e]),s=ie(r=>r.rebuildWorktree),i=ie(r=>r.fallbackToMainWorkspace);return!n?.worktreeMissing||!n.worktree?null:o.jsx(Gk,{open:!0,children:o.jsxs(Fk,{className:"sm:max-w-md",children:[o.jsxs(Hk,{children:[o.jsx(Bk,{className:"text-base",children:t("Isolated worktree is missing")}),o.jsx(Vk,{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})})]}),o.jsxs($k,{variant:"bare",children:[o.jsx(le,{variant:"outline",size:"sm",onClick:()=>{i(e)},children:t("Fall back to main working tree")}),o.jsx(le,{size:"sm",onClick:()=>{s(e).then(r=>{r&&We({type:"error",title:t("Failed to rebuild worktree"),description:r})})},children:t("Rebuild worktree")})]})]})})}function wu(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 HJ({initialName:e,data:t,busy:n,disabled:s,error:i,returnFocus:r,onSubmit:a,onClose:l}){const{t:c}=te(),[d,u]=m.useState(e),h=m.useRef(null),p=m.useId(),f=t?.branches.some(v=>v.name===d.trim()),x=n||s||!t?.headCommit||!!t.blockedReason||!d.trim()||f,g=f?c("A branch with this name already exists."):t?.blockedReason?wu(t.blockedReason,c):t&&!t.headCommit?c("Create a commit before creating a branch from HEAD."):null;return o.jsx(gn,{open:!0,onOpenChange:v=>{!v&&!n&&l()},children:o.jsxs(xn,{className:"max-w-sm",initialFocus:h,finalFocus:r,showCloseButton:!n,children:[o.jsxs(vn,{children:[o.jsx(bn,{children:c("Create branch")}),o.jsx(Os,{children:c("Creates a branch from the current HEAD and switches every conversation in this workspace to it.")})]}),o.jsxs(Rn,{children:[o.jsx(Wt,{ref:h,"aria-label":c("Branch name"),"aria-invalid":!!g,"aria-describedby":g||i?p:void 0,value:d,disabled:n,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.nativeEvent.isComposing&&(v.preventDefault(),x||a(d.trim()))}}),(g||i)&&o.jsx("p",{id:p,role:"alert",className:"mt-2 break-words text-xs text-destructive",children:g||i})]}),o.jsxs(ls,{children:[o.jsx(le,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:l,children:c("Cancel")}),o.jsxs(le,{type:"button",size:"sm",disabled:!!x,onClick:()=>{x||a(d.trim())},children:[n&&o.jsx(Vt,{className:"h-3.5 w-3.5 animate-spin"}),c("Create and switch")]})]})]})})}function BJ({data:e,loading:t,error:n,disabled:s,query:i,searchRef:r,onQueryChange:a,onSelect:l,onCreate:c,onRetry:d}){const{t:u}=te(),h=s||t||!!n||!e||!!e.blockedReason,p=e?.branches.filter(f=>f.name.toLowerCase().includes(i.trim().toLowerCase()))??[];return o.jsxs("section",{"aria-label":u("Local branches"),className:"pb-1",onKeyDown:f=>{if(f.nativeEvent.isComposing||!["ArrowDown","ArrowUp"].includes(f.key))return;const x=Array.from(f.currentTarget.querySelectorAll("button[data-branch-row]:not(:disabled)"));if(!x.length)return;f.preventDefault();const g=x.indexOf(f.target),v=g<0?f.key==="ArrowDown"?0:x.length-1:(g+(f.key==="ArrowDown"?1:-1)+x.length)%x.length;x[v]?.focus()},children:[o.jsxs("div",{className:"relative m-1",children:[o.jsx(Js,{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"}),o.jsx(Wt,{ref:r,value:i,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"})]}),o.jsx("p",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:u("Switching branches affects all conversations in this workspace.")}),e?.blockedReason&&o.jsx("p",{role:"status",className:"px-2 py-1 text-xs text-warning",children:wu(e.blockedReason,u)}),t?o.jsxs("div",{role:"status",className:"flex items-center gap-2 px-2 py-3 text-xs text-muted-foreground",children:[o.jsx(Vt,{className:"h-3.5 w-3.5 animate-spin"}),u("Loading...")]}):n?o.jsxs("div",{role:"alert",className:"px-2 py-2 text-xs",children:[o.jsx("p",{className:"break-words text-destructive",children:n}),o.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")})]}):o.jsxs("div",{className:"max-h-48 overflow-y-auto",children:[p.map(f=>{const x=f.name===e?.currentBranch,g=f.occupied&&!!f.worktreeConversationId,v=g?u("New conversation in this worktree"):f.occupied?u("Branch is checked out in another worktree."):null;return o.jsxs("button",{type:"button","data-branch-row":"","aria-current":x||void 0,disabled:h||x||f.occupied&&!g,title:v?`${f.name}
91
- ${v}`:f.name,onClick:()=>l(f),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",x&&"bg-primary/10"),children:[g?o.jsx(fr,{className:"h-3.5 w-3.5 shrink-0"}):o.jsx(Ni,{className:"h-3.5 w-3.5 shrink-0"}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate",children:f.name}),v&&o.jsx("span",{className:"block text-xs text-muted-foreground",children:v})]}),x&&o.jsx(Jn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},f.name)}),e&&p.length===0&&o.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.")})]}),o.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:[o.jsx(ps,{className:"h-3.5 w-3.5 shrink-0"}),u("Create branch from HEAD…")]})]})}function Md(e){return e.name?.trim()||e.branch}function VJ(e,t,n){const s=new Set,i=[];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),i.push({conversationId:r,worktree:l}))}return i}function $J(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 vm(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[Md(e),e.branch,e.path,s].join(`
92
- `)}function WJ({worktree:e,status:t}){const{t:n}=te();return o.jsx("span",{"data-slot":"worktree-label",title:vm(e,t,n),className:"flex shrink-0 items-center",children:o.jsx(Ni,{className:q("size-2.75",t?.exists===!1?"text-destructive":t?.dirty?"text-warning":(t?.ahead??0)>0?"text-info":"text-subtle-foreground")})})}function II({entity:e,onClose:t}){const{t:n}=te(),s=ie(d=>d.renameWorktree),[i,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,i.trim());d?We({type:"error",title:n("Failed to rename worktree"),description:d}):t()}catch(d){We({type:"error",title:n("Failed to rename worktree"),description:String(d)})}finally{l(!1)}}};return o.jsx(gn,{open:e!==null,onOpenChange:d=>{!d&&!a&&t()},children:o.jsxs(xn,{className:"max-w-sm",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:n("Rename worktree")}),o.jsx(Os,{children:n("Only the display name changes, for all sessions in this worktree. Leave empty to use the branch name.")})]}),o.jsx(Rn,{children:o.jsx(Wt,{"aria-label":n("Worktree name"),maxLength:80,placeholder:e?.worktree.branch,value:i,disabled:a,autoFocus:!0,onChange:d=>r(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.nativeEvent.isComposing&&(d.preventDefault(),c())}})}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",disabled:a,onClick:t,children:n("Cancel")}),o.jsxs(le,{size:"sm",disabled:a,onClick:()=>{c()},children:[a&&o.jsx(Vt,{className:"h-3.5 w-3.5 animate-spin"}),n("Save")]})]})]})})}function UJ({conversationId:e,onBranchChange:t}){const{t:n}=te(),s=ie(ze=>ze.conversations[e]),i=ie(ze=>ze.moveConversationToWorktree),r=ie(ze=>ze.cleanupWorktree),a=ie(ze=>ze.refreshWorktreeStatuses),l=ie(ze=>ze.conversations),c=ie(ze=>ze.worktreeStatuses),d=ie(ze=>ze.attachConversationToWorktree),u=ie(ze=>ze.newConversation),h=ie(ze=>ze.switchWorkspaceBranch),p=ie(ze=>ze.workspaceRevisionByConversation[e]??0),[f,x]=m.useState(null),g=m.useMemo(()=>VJ(l,s?.projectId??"",c),[l,s?.projectId,c]),[v,w]=m.useState(!1),[y,b]=m.useState(!1),[_,j]=m.useState(!1),[N,C]=m.useState(null),[k,E]=m.useState(!1),I=xe(ze=>s?ze.projects.find(Ct=>Ct.id===s.projectId):void 0),T=!!(s&&!s.parentId&&!s.child&&I?.kind!=="ssh"&&I?.kind!=="scratch"),A=`${e}\0${s?.worktree?.path??I?.path??""}`,D=m.useRef(A);D.current=A;const W=m.useRef(0),J=m.useRef(!1),O=m.useRef(null),B=m.useRef(null),L=m.useRef(null);m.useEffect(()=>{v&&(y?B:L).current?.focus()},[v,y]);const[se,Q]=m.useState(null),V=se?.key===A?se.data:null,H=V?.currentBranch??void 0;m.useEffect(()=>{t?.(H)},[t,H]);const[ne,he]=m.useState(!0),[pe,ke]=m.useState(null),[Me,fe]=m.useState(""),[F,U]=m.useState(null),[de,Y]=m.useState(null),X=F===A;m.useEffect(()=>{w(!1),b(!1),fe(""),U(null),Y(null)},[A]);const z=m.useCallback(async(ze=!1)=>{if(!T)return;const Ct=++W.current;he(!0),ke(null);try{const K=await window.electronAPI.worktree.branches(e);if(Ct!==W.current||D.current!==A)return;if(K.ok)Q({key:A,data:K.value});else{const be=wu(K.code,n);ke(be),ze&&We({type:"error",title:n("Failed to load branches"),description:be})}}catch(K){if(Ct!==W.current||D.current!==A)return;ke(n("Failed to load branches")),ze&&We({type:"error",title:n("Failed to load branches"),description:String(K)})}finally{Ct===W.current&&D.current===A&&he(!1)}},[e,T,n,A]);if(m.useEffect(()=>{z();const ze=()=>{J.current||z()};return window.addEventListener("focus",ze),()=>{W.current+=1,window.removeEventListener("focus",ze)}},[z,p]),!s||s.parentId||s.child||I?.kind==="ssh")return null;const ue=!!s.worktree,_e=_||s.spawning||s.status==="running"||!!(s.workspaceMigrating||s.reloading),Ee=s.worktreeMissing||c[e]?.exists===!1,Be=$J(s),De=V?V.currentBranch:s.worktree?.branch,Ue=De??(V?.headCommit?n("Detached HEAD"):""),St=s.worktree?Md(s.worktree):n("Local"),Ut=Ue&&Ue!==St&&(!V?.defaultBranch||De!==V.defaultBranch)?`${St} · ${Ue}`:St,tn=_e||Ee||ne||!!pe||!V||!!V.blockedReason,Ne=async(ze,Ct=!1,K)=>{if(tn||J.current)return;J.current=!0,W.current+=1,j(!0),Y(null);const be=n(K?"Failed to create conversation":"Failed to switch branch");try{if(K){await u(s.projectId,{worktreeFromConversationId:K})?D.current===A&&w(!1):We({type:"error",title:be});return}const Re=await h(e,ze,Ct);if(D.current!==A)return;if(Re.ok)Q({key:A,data:Re.value}),ke(null),U(null),w(!1);else{const Ve=wu(Re.code,n);Y(Ve),We({type:"error",title:be,description:Re.code==="git-error"?`${Ve}
93
- ${Re.error}`:Ve}),z()}}catch(Re){if(D.current!==A)return;Y(String(Re)),We({type:"error",title:be,description:String(Re)})}finally{J.current=!1,j(!1)}},Z=ze=>{ze.name===V?.currentBranch||ze.occupied&&!ze.worktreeConversationId||Ne(ze.name,!1,ze.occupied?ze.worktreeConversationId:void 0)},je=async ze=>{if(_e)return;j(!0);const Ct=n(ze?"Failed to use worktree":"Failed to create conversation");try{if(ze){const K=await d(e,ze);K&&We({type:"error",title:Ct,description:K})}else await u(s.projectId,{worktreeFromConversationId:e})||We({type:"error",title:Ct})}catch(K){We({type:"error",title:Ct,description:String(K)})}finally{j(!1)}},tt=async()=>{j(!0);try{const ze=await r(e);ze?We({type:"error",title:n("Failed to clean up worktree"),description:ze}):a()}catch(ze){We({type:"error",title:n("Failed to clean up worktree"),description:String(ze)})}finally{j(!1)}},Et=async(ze=!1)=>{j(!0);try{const Ct=await i(e,{allowDirtyMainTree:ze});Ct===Wk?E(!0):Ct?We({type:"error",title:n("Failed to move to worktree"),description:Ct}):a()}catch(Ct){We({type:"error",title:n("Failed to move to worktree"),description:String(Ct)})}finally{j(!1)}},zt=async()=>{j(!0);try{const ze=await window.electronAPI.worktree.status(e);if(ze.ok&&fd(ze.value)){C(ze.value);return}await tt()}catch(ze){We({type:"error",title:n("Failed to clean up worktree"),description:String(ze)})}finally{j(!1)}},we=[{id:"local",selected:!ue,icon:o.jsx(yb,{className:"h-3.5 w-3.5 shrink-0"}),name:n("Local workspace"),hint:n("Work directly in the main working tree"),onSelect:()=>{ue&&zt()}},{id:"worktree",selected:ue,icon:o.jsx(Ni,{className:"h-3.5 w-3.5 shrink-0"}),name:s.worktree?Md(s.worktree):n("New isolated worktree"),hint:ue?s.worktree?.branch:n("Run this session on its own git worktree"),onSelect:()=>{ue||Et()}}],ft=o.jsx(hs,{open:k,onOpenChange:E,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:()=>{E(!1),Et(!0)}}),mt=()=>{const ze=[];return N?.dirty&&ze.push(n("Uncommitted changes")),N&&N.ahead>0&&ze.push(n("{{n}} unmerged commits (branch is kept)",{n:N.ahead})),ze.join("; ")};return o.jsxs(o.Fragment,{children:[o.jsxs(Pi,{open:v,onOpenChange:ze=>{_||(w(ze),ze&&(b(!1),fe(""),z()))},children:[o.jsxs(Ei,{ref:O,disabled:_e,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}
94
- ${vm(s.worktree,c[e],n)}`:Ut,children:[_?o.jsx(Vt,{className:"h-3 w-3 shrink-0 animate-spin"}):ue?o.jsx(Ni,{className:"h-3 w-3 shrink-0"}):o.jsx(yb,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"min-w-0 truncate",children:Ut}),o.jsx($n,{className:"h-3 w-3 shrink-0"})]}),o.jsx(Ai,{side:"top",align:"start",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",initialFocus:L,finalFocus:X||f!==null?!1:O,children:y?o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",onClick:()=>b(!1),"aria-label":n("Back to workspaces"),className:"mb-1 flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground",children:[o.jsx(Au,{className:"h-3.5 w-3.5 shrink-0"}),n("Local branches")]}),o.jsx(BJ,{data:V,loading:ne,error:pe,disabled:_e||Ee,query:Me,searchRef:B,onQueryChange:fe,onSelect:Z,onRetry:()=>{z(!0)},onCreate:()=>{tn||!V?.headCommit||(Y(null),U(A),w(!1))}})]}):o.jsxs(o.Fragment,{children:[we.map(ze=>o.jsxs("button",{ref:ze.id==="local"?L:void 0,type:"button",disabled:_e,onClick:()=>{ze.onSelect(),w(!1)},className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",ze.selected?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[ze.icon,o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate",children:ze.name}),ze.hint&&o.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:ze.hint})]}),ze.selected&&o.jsx(Jn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},ze.id)),Be&&g.length>0&&o.jsxs("div",{className:"mt-1 border-t pt-1",children:[o.jsx("p",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:n("Existing worktrees")}),o.jsx("div",{className:"max-h-56 overflow-y-auto",children:g.map(({conversationId:ze,worktree:Ct})=>o.jsxs("button",{type:"button",disabled:_e,title:vm(Ct,c[ze],n),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",onClick:()=>{w(!1),je(ze)},children:[o.jsx(Ni,{className:"h-3.5 w-3.5 shrink-0"}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsx("span",{className:"block truncate",children:Md(Ct)}),o.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:Ct.path})]})]},Ct.path))})]}),s.worktree&&o.jsxs("div",{className:"mt-1 border-t pt-1",children:[o.jsxs("button",{type:"button",disabled:_e||Ee,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:()=>{w(!1),je()},children:[o.jsx(fr,{className:"h-3.5 w-3.5"}),n("New conversation in this worktree")]}),o.jsxs("button",{type:"button",disabled:_e||Ee,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:()=>{w(!1),s.worktree&&x({conversationId:e,worktree:s.worktree})},children:[o.jsx(Xs,{className:"h-3.5 w-3.5"}),n("Rename worktree")]})]}),o.jsx("div",{className:"mt-1 border-t pt-1",children:o.jsxs("button",{type:"button",disabled:_e,onClick:()=>b(!0),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[o.jsx(Ni,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{className:"flex-1",children:n("Switch branch")}),o.jsx(kn,{className:"h-3.5 w-3.5 shrink-0"})]})})]})})]}),o.jsx(hs,{open:N!==null,onOpenChange:ze=>{ze||C(null)},title:n("Clean up worktree?"),description:n("Pending work: {{warning}}. This session returns to the main working tree. The worktree directory and uncommitted changes are removed only when no other sessions use it. The branch is kept.",{warning:mt()}),confirmLabel:n("Clean up"),onConfirm:()=>{C(null),tt()}}),X&&o.jsx(HJ,{initialName:Me.trim(),data:V,busy:_,disabled:tn,error:de,returnFocus:O,onSubmit:ze=>{Ne(ze,!0)},onClose:()=>U(null)},A),ft,o.jsx(II,{entity:f,onClose:()=>x(null)})]})}function KJ(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 qJ=e=>{dh(e)&&wr()};function YJ(){const{t:e}=te(),t=XR(),n=ma(),s=xe(Ne=>Ne.virtualModels),i=xe(Ne=>Ne.agentTypes),r=xe(Ne=>Ne.defaultModel),a=xe(Ne=>Ne.projects),l=xe(Ne=>Ne.projectGroups),c=xe(Ne=>Ne.voiceInputEnabled),d=xe(Ne=>Ne.voiceModel),u=xe(Ne=>Ne.presets),{status:h}=gk(c),p=c&&h?.state!=="unsupported"&&h?.models.find(Ne=>Ne.id===d)?.state==="ready",f=ie(um(zY)),x=ie(Ne=>Ne.conversations[f?.parentId??""]?.coworkerIds),g=JR(f?.presetId,Ne=>u.find(Z=>Z.id===Ne)).pluginPresetId??null,v=LY(f?.displayedParentId?f.agentType:void 0),w=Ao(Ne=>Ne.snapshot),y=og(),b=ie(Ne=>BY(Ne.conversations)),_=f?.parentId,j=f?.parentProjectId,N=m.useMemo(()=>_!==void 0&&j!==void 0?eK(b,j,_):[],[b,_,j]),C=m.useMemo(()=>a.find(Ne=>Ne.id===f?.projectId),[f?.projectId,a]),k=m.useMemo(()=>a.find(Ne=>Ne.id===f?.parentProjectId),[f?.parentProjectId,a]),E=m.useMemo(()=>Fd(C,l),[C,l]),I=m.useMemo(()=>Fd(k,l),[k,l]),T=m.useMemo(()=>jl({defaultModel:r,...E,lastProviderId:f?.lastProviderId,lastModelId:f?.lastModelId,providers:n,credentials:na(w),virtualModels:s}),[f?.lastModelId,f?.lastProviderId,E,r,w,n,s]),A=m.useMemo(()=>jl({defaultModel:r,...I,lastProviderId:f?.parentLastProviderId,lastModelId:f?.parentLastModelId,providers:n,credentials:na(w),virtualModels:s}),[r,w,f?.parentLastModelId,f?.parentLastProviderId,I,n,s]),D=A.source==="none"?null:{providerId:A.providerId,modelId:A.modelId},W=T.source==="none"?void 0:y.find(Ne=>Ne.id===T.providerId),J=T.source==="none"?"":T.modelId,O=T.source==="none"?"":of(T)?T.providerId:W?.id??"",B=ie(Ne=>of(T)&&f?.id?KJ(Ne.conversations[f.id]?.messages):void 0),L=ie(um(Ne=>ig(n,f?.id?Ne.conversations[f.id]:void 0))),se=T.source!=="none"?null:T.reason==="oauth-credentials-error"?e("Subscription credentials could not be loaded. Choose an API-key model or retry the credential refresh."):T.reason==="oauth-credentials-loading"||T.reason==="oauth-credentials-unloaded"?e("Subscription credentials are loading. Choose an API-key model or wait, then retry."):y.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."),Q=a.find(Ne=>Ne.id===f?.projectId),V=f?.id,[H,ne]=m.useState(),he=m.useCallback(Ne=>ne(V&&Ne?{id:V,branch:Ne}:void 0),[V]),pe=f?.parentWorktreeBranch??(H?.id===f?.parentId?H?.branch:void 0),ke=xe(Ne=>Ne.skills),Me=xe(Ne=>Ne.loadLocalSkills),fe=xe(Ne=>ZR(Ne.disabledBuiltinTools,Ne.projects,f?.projectId,"plan")),[F,U]=m.useState([]),de=Me?Q?.path??"":"",Y=f?.presetId;m.useEffect(()=>{let Ne=!1;return window.electronAPI.assets.listProjectSkills(de,Y).then(Z=>{Ne||U(Z)}).catch(()=>{Ne||U([])}),()=>{Ne=!0}},[de,Y]);const X=f?.commands,z=qY(),ue=m.useMemo(()=>{if(!X)return[];const Ne={name:"/goal",description:e("Set a session goal (/goal <objective> · pause · resume · clear)")},Z={name:"/compact",description:e("Compact the context now (/compact [summary focus])")},je={name:"/plan",description:e("Plan mode: research read-only, then approve a plan (/plan [task] · off)")},tt=ke.filter(zt=>zt.enabled!==!1).map(zt=>({name:`/skill:${zt.name}`,description:zt.description})),Et=F.map(zt=>({name:`/skill:${zt.name}`,description:zt.description}));return eT([Ne,Z,...fe?[je]:[],...tt,...Et,...X,...z])},[e,ke,F,X,z,fe]),_e=m.useRef(null),Ee=!f?.displayedParentId&&["planning","awaiting_review"].includes(Mk(f?.planState)),Be=f?.status==="running",De=f?.busy===!0,Ue=f?.parentWorktreePath??Q?.path,St=m.useMemo(()=>(f?.pendingCapabilityAsks??[]).map(Ne=>({requestId:Ne.requestId,tool:Ne.capabilityId,kind:"mcp",summary:Ne.summary})),[f?.pendingCapabilityAsks]),Ut=m.useCallback(()=>{f&&!f.parentStarted&&f.parentSessionFile&&!f.parentWorktreeMissing&&f.parentStatus!=="failed"&&ie.getState().resumeConversation(f.parentId)},[f]);if(m.useEffect(()=>{const Ne=f?.compactionError;!Ne||!f||(We({type:"error",title:e("Compaction failed"),description:Ne}),ie.getState().clearCompactionError(f.id))},[f,e]),!f)return o.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[t&&o.jsx(Ak,{"data-enso":"title-bar"}),o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-1 text-center",children:[o.jsx("p",{className:"text-lg font-medium",children:"EnsoCode"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("Create or select a project to start a conversation")})]})]});const tn=o.jsx(JJ,{status:f.spawning?"running":f.status,pendingAskCount:(f.pendingAsks??[]).length,hasRunningChild:f.id===f.parentId&&f.parentHasRunningChild});return o.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[o.jsx(FJ,{conversationId:f.parentId}),o.jsx(HX,{parentId:f.parentId,displayedId:f.id,trailing:o.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-1",children:[o.jsx(iX,{parentId:f.parentId,coworkerIds:x??[]}),Q?o.jsx(GJ,{project:Q,conversationId:f.parentId,path:f.parentWorktreePath??Q.path,branch:pe,openDisabled:f.parentWorktreeMissing,children:tn}):o.jsx("div",{className:"flex min-w-0 shrink-0 items-center",children:tn})]})}),o.jsx(uI,{conversationId:f.id,cwd:Ue,emptyTitle:Q?.name??"EnsoCode",onSuggestion:Q?qJ:void 0,timelineRef:_e}),o.jsx("div",{className:"@container pt-1",children:o.jsxs("div",{className:fi,children:[Q&&Q.kind!=="ssh"&&Q.kind!=="scratch"&&!f.displayedParentId&&o.jsx(QX,{projectId:Q.id,conversationId:f.id}),f.retry&&o.jsx(wh,{retry:f.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(f.id)}}),(f.rewinding||f.restoringFiles)&&o.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:[o.jsx(Vt,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}),o.jsx("span",{children:f.restoringFiles&&!f.rewinding?e("Restoring files…"):f.restoringFiles?e("Rewinding conversation and files…"):e("Rewinding…")})]}),o.jsx(ng.Provider,{value:{conversationId:f.id,projectId:f.projectId,...Ue?{cwd:Ue}:{}},children:o.jsx(Fx,{sessionId:f.id,tasks:f.backgroundTasks??[],subagents:f.subagents??[]},f.id)}),o.jsx(Rl,{approvals:St,allowSession:!1,handoff:!1,onRespond:(Ne,Z)=>{Z!=="allow"&&Z!=="deny"||ie.getState().respondCapabilityAsk(f.id,Ne,Z)}},St[0]?.requestId??"no-capability-approval"),o.jsx(Rl,{approvals:f.pendingApprovals??[],allowSession:f.childLockedProfileId===void 0,onRespond:(Ne,Z)=>{window.electronAPI.agent.respondApproval(f.id,Ne,Z)}}),o.jsx(oh,{asks:f.pendingAsks??[],onAnswer:(Ne,Z)=>{window.electronAPI.agent.respondAsk(f.id,Ne,Z)}}),f.activeOauthAsk&&o.jsx(RY,{request:f.activeOauthAsk,conversationId:f.id},f.activeOauthAsk.requestId),!f.displayedParentId&&o.jsx(KX,{conversationId:f.id,planState:f.planState,approvalMode:f.approvalMode??"full"}),o.jsx(SI,{conversationId:f.id,queued:f.queuedMessages??[]}),f.goal&&o.jsx(WX,{conversationId:f.id,goal:f.goal}),o.jsx(LU,{conversationId:f.id},f.id),!f.displayedParentId&&se&&o.jsx("div",{role:"status",className:"rounded-md border border-dashed px-3 py-2 text-muted-foreground text-xs",children:se}),o.jsx(zx,{cwd:Q?.path,chatCandidates:N,commands:ue,running:Be,busy:De,locked:(f.pendingApprovals??[]).length>0||St.length>0||!!(f.rewinding||f.restoringFiles),focusKey:f.id,pluginPresetId:g,planMode:Ee,savePastedText:Q?.kind==="ssh"?void 0:Ne=>window.electronAPI.files.savePastedText({conversationId:f.id,text:Ne}),voice:p?YN:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,placeholder:Ee?e("Describe the task — a plan comes first"):void 0,injectedDraft:f.draftText,injectedImages:f.draftImages,injectedDraftAppend:f.draftAppend,onDraftConsumed:()=>ie.getState().clearDraft(f.id),queuedCount:f.queuedMessages?.length??0,onSteerQueued:()=>ie.getState().steerQueued(f.id),initialRecipient:f.prefillAgentTypeKey===Hd?XJ:void 0,onInitialRecipientConsumed:()=>ie.getState().clearAgentPrefill(f.id),toolbar:o.jsxs(o.Fragment,{children:[!f.displayedParentId&&o.jsxs(o.Fragment,{children:[o.jsx(JX,{presetId:f.presetId??"default",disabled:f.started,onSelect:Ne=>ie.getState().setPreset(f.id,Ne),onModel:Ne=>ie.getState().setModel(f.id,Ne.providerId,Ne.modelId)}),o.jsx(UJ,{conversationId:f.id,onBranchChange:he}),(fe||f.planState?.active)&&o.jsx(XX,{active:f.planState?.active??!1,onToggle:Ne=>ie.getState().setPlanMode(f.id,Ne)}),o.jsx(QR,{mode:f.approvalMode??"full",autoReject:f.autoRejectApprovals===!0,onSelect:Ne=>ie.getState().setApprovalMode(f.id,Ne),onToggleAutoReject:Ne=>ie.getState().setAutoRejectApprovals(f.id,Ne)}),o.jsx(Bu,{listenHotkey:!0,providers:y,virtualModels:s,routedModelLabel:B,activeAccount:L,providerId:O,modelId:J,reasoningEnabled:f.reasoningEnabled??!1,thinkingLevel:f.thinkingLevel??"medium",onSelect:(Ne,Z)=>ie.getState().setModel(f.id,Ne,Z),onReasoningChange:Ne=>ie.getState().setReasoning(f.id,Ne),onThinkingChange:Ne=>ie.getState().setThinking(f.id,Ne)})]}),f.displayedParentId&&o.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[v??(f.agentType?Ek(f.agentType,i):"coworker"),f.lastModelId?` · ${sf(s,f.lastModelId)}`:""]})]}),onActivate:Ut,onSend:Ne=>!Ne.recipient&&!Q||!Ne.recipient&&!f.displayedParentId&&(!O||!J)?!1:(VX(Ne,{dispatchAgent:(Z,je)=>{ie.getState().dispatchAgent(Z,je,D)},sendCoding:(Z,je)=>{Q&&(_e.current?.scrollToBottom(),ie.getState().send(Z,{providerId:O,modelId:J,cwd:Q.path},je))}}),!0),onAbort:()=>{ie.getState().abort()}}),o.jsx(NI,{conversationId:f.id})]})})]})}const XJ={kind:"agent-type",id:Hd,typeKey:Hd,label:"Enso",displayName:"Enso",description:"EnsoCode system agent for product capabilities and team setup",source:"system",locked:!0,canDisable:!1,canEdit:!1};function JJ({status:e,pendingAskCount:t=0,hasRunningChild:n=!1}){const s=Uk({status:e,pendingAskCount:t,hasRunningChild:n});return o.jsx(Sh,{tone:s,title:e})}function DI(e,t,n){const s=e.slice();return s.splice(n<0?s.length+n:n,0,s.splice(t,1)[0]),s}function ZJ(e,t){return e.reduce((n,s,i)=>{const r=t.get(s);return r&&(n[i]=r),n},Array(e.length))}function Uc(e){return e!==null&&e>=0}function QJ(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 eZ(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const Kc={scaleX:1,scaleY:1},tZ=e=>{var t;let{rects:n,activeNodeRect:s,activeIndex:i,overIndex:r,index:a}=e;const l=(t=n[i])!=null?t:s;if(!l)return null;const c=nZ(n,a,i);if(a===i){const d=n[r];return d?{x:i<r?d.left+d.width-(l.left+l.width):d.left-l.left,y:0,...Kc}:null}return a>i&&a<=r?{x:-l.width-c,y:0,...Kc}:a<i&&a>=r?{x:l.width+c,y:0,...Kc}:{x:0,y:0,...Kc}};function nZ(e,t,n){const s=e[t],i=e[t-1],r=e[t+1];return!s||!i&&!r?0:n<t?i?s.left-(i.left+i.width):r.left-(s.left+s.width):r?r.left-(s.left+s.width):s.left-(i.left+i.width)}const PI=e=>{let{rects:t,activeIndex:n,overIndex:s,index:i}=e;const r=DI(t,s,n),a=t[i],l=r[i];return!l||!a?null:{x:l.left-a.left,y:l.top-a.top,scaleX:l.width/a.width,scaleY:l.height/a.height}},qc={scaleX:1,scaleY:1},nS=e=>{var t;let{activeIndex:n,activeNodeRect:s,index:i,rects:r,overIndex:a}=e;const l=(t=r[n])!=null?t:s;if(!l)return null;if(i===n){const d=r[a];return d?{x:0,y:n<a?d.top+d.height-(l.top+l.height):d.top-l.top,...qc}:null}const c=sZ(r,i,n);return i>n&&i<=a?{x:0,y:-l.height-c,...qc}:i<n&&i>=a?{x:0,y:l.height+c,...qc}:{x:0,y:0,...qc}};function sZ(e,t,n){const s=e[t],i=e[t-1],r=e[t+1];return s?n<t?i?s.top-(i.top+i.height):r?r.top-(s.top+s.height):0:r?r.top-(s.top+s.height):i?s.top-(i.top+i.height):0:0}const EI="Sortable",AI=Ce.createContext({activeIndex:-1,containerId:EI,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:PI,disabled:{draggable:!1,droppable:!1}});function bm(e){let{children:t,id:n,items:s,strategy:i=PI,disabled:r=!1}=e;const{active:a,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=oc(),h=sc(EI,n),p=l.rect!==null,f=m.useMemo(()=>s.map(N=>typeof N=="object"&&"id"in N?N.id:N),[s]),x=a!=null,g=a?f.indexOf(a.id):-1,v=d?f.indexOf(d.id):-1,w=m.useRef(f),y=!QJ(f,w.current),b=v!==-1&&g===-1||y,_=eZ(r);ui(()=>{y&&x&&u(f)},[y,f,x,u]),m.useEffect(()=>{w.current=f},[f]);const j=m.useMemo(()=>({activeIndex:g,containerId:h,disabled:_,disableTransforms:b,items:f,overIndex:v,useDragOverlay:p,sortedRects:ZJ(f,c),strategy:i}),[g,h,_.draggable,_.droppable,b,f,v,c,p,i]);return Ce.createElement(AI.Provider,{value:j},t)}const iZ=e=>{let{id:t,items:n,activeIndex:s,overIndex:i}=e;return DI(n,s,i).indexOf(t)},oZ=e=>{let{containerId:t,isSorting:n,wasDragging:s,index:i,items:r,newIndex:a,previousItems:l,previousContainerId:c,transition:d}=e;return!d||!s||l!==r&&i===a?!1:n?!0:a!==i&&t===c},rZ={duration:200,easing:"ease"},MI="transform",aZ=Ri.Transition.toString({property:MI,duration:0,easing:"linear"}),lZ={roleDescription:"sortable"};function cZ(e){let{disabled:t,index:n,node:s,rect:i}=e;const[r,a]=m.useState(null),l=m.useRef(n);return ui(()=>{if(!t&&n!==l.current&&s.current){const c=i.current;if(c){const d=va(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,i]),m.useEffect(()=>{r&&a(null)},[r]),r}function Ch(e){let{animateLayoutChanges:t=oZ,attributes:n,disabled:s,data:i,getNewIndex:r=iZ,id:a,strategy:l,resizeObserverConfig:c,transition:d=rZ}=e;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:x,sortedRects:g,overIndex:v,useDragOverlay:w,strategy:y}=m.useContext(AI),b=dZ(s,f),_=u.indexOf(a),j=m.useMemo(()=>({sortable:{containerId:h,index:_,items:u},...i}),[h,i,_,u]),N=m.useMemo(()=>u.slice(u.indexOf(a)),[u,a]),{rect:C,node:k,isOver:E,setNodeRef:I}=rc({id:a,data:j,disabled:b.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...c}}),{active:T,activatorEvent:A,activeNodeRect:D,attributes:W,setNodeRef:J,listeners:O,isDragging:B,over:L,setActivatorNodeRef:se,transform:Q}=gg({id:a,data:j,attributes:{...lZ,...n},disabled:b.draggable}),V=VL(I,J),H=!!T,ne=H&&!x&&Uc(p)&&Uc(v),he=!w&&B,pe=he&&ne?Q:null,Me=ne?pe??(l??y)({rects:g,activeNodeRect:D,activeIndex:p,overIndex:v,index:_}):null,fe=Uc(p)&&Uc(v)?r({id:a,items:u,activeIndex:p,overIndex:v}):_,F=T?.id,U=m.useRef({activeId:F,items:u,newIndex:fe,containerId:h}),de=u!==U.current.items,Y=t({active:T,containerId:h,isDragging:B,isSorting:H,id:a,index:_,items:u,newIndex:U.current.newIndex,previousItems:U.current.items,previousContainerId:U.current.containerId,transition:d,wasDragging:U.current.activeId!=null}),X=cZ({disabled:!Y,index:_,node:k,rect:C});return m.useEffect(()=>{H&&U.current.newIndex!==fe&&(U.current.newIndex=fe),h!==U.current.containerId&&(U.current.containerId=h),u!==U.current.items&&(U.current.items=u)},[H,fe,h,u]),m.useEffect(()=>{if(F===U.current.activeId)return;if(F!=null&&U.current.activeId==null){U.current.activeId=F;return}const ue=setTimeout(()=>{U.current.activeId=F},50);return()=>clearTimeout(ue)},[F]),{active:T,activeIndex:p,attributes:W,data:j,rect:C,index:_,newIndex:fe,items:u,isOver:E,isSorting:H,isDragging:B,listeners:O,node:k,overIndex:v,over:L,setNodeRef:V,setActivatorNodeRef:se,setDroppableNodeRef:I,setDraggableNodeRef:J,transform:X??Me,transition:z()};function z(){if(X||de&&U.current.newIndex===_)return aZ;if(!(he&&!Uu(A)||!d)&&(H||Y))return Ri.Transition.toString({...d,property:MI})}}function dZ(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}}an.Down,an.Right,an.Up,an.Left;const uZ=e=>e==="/"?null:e.replace(/\/[^/]+$/,"")||"/";function hZ(e,t){const n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}function sS({list:e,create:t,initialPath:n,reloadKey:s=0,onSelect:i,onClose:r}){const{t:a}=te(),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,p]=m.useState(""),[f,x]=m.useState(null),[g,v]=m.useState(""),w=m.useRef(0),y=m.useRef(null),b=m.useRef(e);b.current=e;const _=m.useCallback((I,T=!1)=>{const A=++w.current;u(!0),p(""),b.current(I,T).then(D=>{if(!(A!==w.current||!D)){if("error"in D){p(D.error);return}c(D),y.current=D.path}}).catch(()=>{A===w.current&&p(a("Failed to list remote directory."))}).finally(()=>{A===w.current&&u(!1)})},[a]),j=m.useRef(n);m.useEffect(()=>{_(j.current)},[_]),m.useEffect(()=>{s&&_(y.current??j.current,!0)},[s,_]);const N=l?.path??null,C=l?.dirs??[],k=l?.parent??null,E=()=>{if(!t||!N||f===null||!f.trim())return;const I=++w.current;u(!0),v(""),t(N,f).then(T=>{if(I===w.current){if("error"in T){v(a(T.error));return}x(null),p(""),c(T),y.current=T.path}}).catch(()=>{I===w.current&&v(a("Failed to list remote directory."))}).finally(()=>{I===w.current&&u(!1)})};return o.jsxs("div",{className:"w-full space-y-1.5 rounded-md border bg-muted/30 p-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground text-xs",children:N??"…"}),o.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!k||d,onClick:()=>k&&_(k),children:a("Up")}),t&&o.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!N||d||f!==null,onClick:()=>{x(""),v("")},children:a("New Folder")}),o.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:r,children:a("Close")})]}),f!==null&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(Wt,{autoFocus:!0,size:"sm",className:"min-w-0 flex-1 font-mono text-xs",placeholder:a("Folder name"),value:f,disabled:d,onChange:I=>x(I.target.value),onKeyDown:I=>{I.key==="Enter"?(I.preventDefault(),E()):I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),x(null))}}),o.jsx(le,{type:"button",size:"sm",className:"h-7 px-2 text-xs",disabled:d||!f.trim(),onClick:E,children:a("Create")}),o.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",disabled:d,onClick:()=>x(null),children:a("Cancel")})]}),g&&o.jsx("p",{className:"px-1 text-destructive text-xs",children:g})]}),o.jsxs("div",{className:"relative min-h-16 max-h-56 overflow-y-auto",children:[h?o.jsx("p",{className:"px-1 py-2 text-destructive text-xs",children:h}):C.length===0&&!d?o.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:a("No subdirectories")}):o.jsx("div",{className:d?"pointer-events-none space-y-0.5 opacity-40":"space-y-0.5",children:C.map(I=>o.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&&_(hZ(N,I)),children:[I,"/"]},I))}),d&&o.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60",children:[o.jsx(Vt,{className:"h-4 w-4 animate-spin text-muted-foreground"}),o.jsx("span",{className:"sr-only",children:a("Loading...")})]})]}),o.jsx(le,{type:"button",variant:"outline",size:"sm",className:"h-7 w-full text-xs",disabled:!N||d,onClick:()=>N&&i(N),children:a("Use this directory")})]})}function pZ({open:e,onOpenChange:t,onAdd:n,groups:s=[],defaultGroupId:i}){const{t:r}=te(),a=xe(U=>U.projects),[l,c]=m.useState("local"),[d,u]=m.useState(""),[h,p]=m.useState(""),[f,x]=m.useState(""),[g,v]=m.useState([]),[w,y]=m.useState(i),[b,_]=m.useState(!1),[j,N]=m.useState([]),[C,k]=m.useState(""),[E,I]=m.useState(null),[T,A]=m.useState(null),[D,W]=m.useState(0),[J,O]=m.useState(!1),B=m.useMemo(()=>[{value:"",label:r("Ungrouped")},...s.map(U=>({value:U.id,label:U.name}))],[s,r]);m.useEffect(()=>{e&&(c("local"),u(""),p(""),x(""),y(i),_(!1),k(""),I(null),A(null),W(0),window.electronAPI.sshConnections.list().then(v).catch(()=>v([])),window.electronAPI.projects.getRecent().then(N).catch(()=>N([])))},[e,i]);const L=m.useMemo(()=>new Set(a.map(U=>U.path)),[a]),se=m.useMemo(()=>j.filter(U=>!L.has(U.path)),[j,L]),Q=m.useCallback((U,de)=>{if(!de)return!0;const Y=de.toLowerCase();return U.path.toLowerCase().includes(Y)||U.displayPath.toLowerCase().includes(Y)||U.sourceName.toLowerCase().includes(Y)},[]),V=!!window.electronAPI.remote,H=async()=>{if(V){_(de=>!de);return}const U=await window.electronAPI.dialog.selectDirectory();U&&u(U)},ne=m.useCallback(U=>window.electronAPI.projects.listHostDirs(U).then(de=>de.ok?de:{error:de.error}),[]),he=m.useCallback((U,de)=>window.electronAPI.projects.createHostDir(U,de).then(Y=>Y.ok?Y:{error:Y.error}),[]),pe=m.useCallback(async(U,de)=>{const Y=await window.electronAPI.sshConnections.listDirs(h,U);if(Y.ok)return{path:Y.path,parent:uZ(Y.path),dirs:Y.dirs};const X=Av(Y,g.find(z=>z.id===h));return!X||de?{error:Y.error}:(A("browse"),I(X),null)},[h,g]),ke=l==="local"?d.trim().length>0:h.length>0&&f.trim().startsWith("/"),Me=()=>{const U=g.find(de=>de.id===h);n({path:f.trim(),sshConnectionId:h,sshHost:U?.name,...w?{groupId:w}:{}}),t(!1)},fe=U=>{if(U.preventDefault(),!ke)return;if(l!=="ssh"){n({path:d.trim(),...w?{groupId:w}:{}}),t(!1);return}k("");const de=g.find(Y=>Y.id===h);window.electronAPI.sshConnections.test(h).then(Y=>{if(!Y.ok){const X=Av(Y,de);if(X){A("submit"),I(X);return}k(Y.error);return}Me()})},F=async()=>{if(!E)return;O(!0);const U=await window.electronAPI.sshConnections.trustHost(h);if(O(!1),!U.ok){k(U.error||r("Could not save host key.")),I(null),A(null);return}const de=T;if(I(null),A(null),de==="browse"){W(Y=>Y+1);return}de==="submit"&&Me()};return o.jsxs(gn,{open:e,onOpenChange:t,children:[o.jsx(xn,{className:"max-w-lg",children:o.jsxs("form",{onSubmit:fe,className:"flex flex-col",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:r("Add project")}),o.jsx(Os,{children:r("Add a local directory as the conversation working folder.")})]}),o.jsxs(Rn,{className:"space-y-4",children:[o.jsx(Ru,{value:l,onValueChange:U=>{c(U),_(!1)},children:o.jsxs(Lu,{children:[o.jsx(Ns,{value:"local",children:r("Local directory")}),o.jsx(Ns,{value:"ssh",children:r("Remote (SSH)")})]})}),l==="ssh"?o.jsxs(o.Fragment,{children:[o.jsxs(Hs,{className:"w-full",children:[o.jsx(Bs,{children:r("SSH connection")}),g.length===0?o.jsx("p",{className:"text-sm text-muted-foreground",children:r("Add an SSH connection in Settings first.")}):o.jsxs(ms,{items:[{value:"",label:r("Select an SSH connection")},...g.map(U=>({value:U.id,label:`${U.name} (${U.user?`${U.user}@`:""}${U.host})`}))],value:h,onValueChange:U=>p(U??""),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsxs(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:[o.jsx(ts,{value:"",children:r("Select an SSH connection")}),g.map(U=>o.jsxs(ts,{value:U.id,children:[U.name," (",U.user?`${U.user}@`:"",U.host,")"]},U.id))]})]})]}),o.jsxs(Hs,{className:"w-full",children:[o.jsx(Bs,{children:r("Remote directory")}),o.jsxs("div",{className:"flex w-full gap-2",children:[o.jsx(Wt,{value:f,onChange:U=>x(U.target.value),placeholder:"/home/user/project",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,className:"min-w-0 flex-1"}),o.jsx(le,{type:"button",variant:"outline",disabled:!h,onClick:()=>_(U=>!U),children:r("Browse")})]})]}),b&&h&&o.jsx(sS,{list:pe,initialPath:f.trim().startsWith("/")?f.trim():void 0,reloadKey:D,onSelect:U=>{x(U),_(!1)},onClose:()=>_(!1)},h),o.jsx("p",{className:"text-xs text-muted-foreground",children:r("Tools run on the remote host; chat history stays local.")}),C&&o.jsx("p",{className:"text-destructive text-xs",children:C})]}):o.jsxs(Hs,{className:"w-full",children:[o.jsx(Bs,{children:r("Working directory")}),o.jsxs(Dx,{value:d,onValueChange:U=>u(U??""),items:se,filter:Q,itemToStringValue:U=>U.path,children:[o.jsxs("div",{className:"flex w-full gap-2",children:[o.jsx("div",{className:"min-w-0 flex-1",children:o.jsx(Px,{placeholder:r("Type a path or select from recent projects..."),showClear:!!d,showTrigger:!0})}),o.jsx(le,{type:"button",variant:"outline",onClick:()=>{H()},children:r("Browse")})]}),o.jsxs(YT,{zIndex:yn.DROPDOWN_IN_MODAL,children:[o.jsx(Ax,{children:r("No matching projects found")}),o.jsx(Mx,{children:U=>o.jsxs(Ex,{value:U,className:"gap-2",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate",title:U.path,children:U.displayPath}),o.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:U.sourceName})]},U.path)})]})]}),b&&V&&o.jsx(sS,{list:ne,create:he,initialPath:d.trim()||void 0,onSelect:U=>{u(U),_(!1)},onClose:()=>_(!1)})]}),s.length>0&&o.jsxs(Hs,{children:[o.jsx(Bs,{children:r("Project group")}),o.jsxs(ms,{items:B,value:w??"",onValueChange:U=>y(U||void 0),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:B.map(U=>o.jsx(ts,{value:U.value,children:U.label},U.value||"ungrouped"))})]})]})]}),o.jsxs(ls,{children:[o.jsx(le,{type:"button",variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),o.jsx(le,{type:"submit",size:"sm",disabled:!ke,children:r("Add")})]})]})}),o.jsx(e2,{challenge:E,nested:!0,busy:J,onTrust:()=>{F()},onDismiss:()=>{J||(I(null),A(null))}})]})}function fZ(e,t){return{x:e.left-t,width:Math.max(0,e.width)}}const RI="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",LI="flex size-4.5 shrink-0 items-center justify-center rounded-[5px] text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",mZ=24,La=20;function gZ({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:i,ungroupedCount:r,query:a,onQueryChange:l,searchOpen:c,onSearchOpenChange:d,onSelect:u,onAddGroup:h,onEditGroup:p}){const{t:f}=te(),x=e.slice().sort((L,se)=>L.order-se.order),g=x.length>0,v=c||a.length>0,w=m.useRef(null),y=m.useRef(null),b=m.useRef(null),_=m.useRef(null),j=m.useRef(null),[N,C]=m.useState({left:!1,right:!1,overflow:!1}),{active:k}=oc(),E=x.find(L=>L.id===t),I=t===cs?f("Ungrouped"):E?.name??null,T=I?f("Search in {{group}}...",{group:I}):f("Search conversations..."),A=m.useCallback(()=>{const L=b.current,se=y.current,Q=_.current,V=j.current,H=se?.querySelector("[data-selected]");if(!L||!se||!Q||!V||!H||L.offsetParent===null){V&&(V.style.width="0px");return}const ne=se.getBoundingClientRect(),he=L.getBoundingClientRect(),pe=H.getBoundingClientRect(),ke=fZ(pe,ne.left);Q.style.left=`${ne.left-he.left}px`,Q.style.width=`${ne.width}px`,V.style.transform=`translateX(${ke.x}px)`,V.style.width=`${ke.width}px`},[]),D=m.useCallback(()=>{const L=y.current;A(),!(!L||L.clientWidth===0)&&C(se=>{const Q=se.overflow?mZ:0,V={left:L.scrollLeft>1,right:L.scrollLeft+L.clientWidth<L.scrollWidth-1,overflow:L.scrollWidth>L.clientWidth+Q+1};return se.left===V.left&&se.right===V.right&&se.overflow===V.overflow?se:V})},[A]);m.useLayoutEffect(()=>{const L=y.current;if(!L)return;D();const se=new ResizeObserver(D);return se.observe(L),L.firstElementChild&&se.observe(L.firstElementChild),()=>se.disconnect()},[D]),m.useLayoutEffect(()=>{A()},[A,k,t,v,x.length]),m.useEffect(()=>{const L=y.current;if(!L)return;const se=Q=>{Math.abs(Q.deltaY)<=Math.abs(Q.deltaX)||L.scrollWidth<=L.clientWidth||(L.scrollLeft+=Q.deltaY,Q.preventDefault())};return L.addEventListener("wheel",se,{passive:!1}),()=>L.removeEventListener("wheel",se)},[]);const W=m.useRef(!1);m.useLayoutEffect(()=>{const L=y.current,se=L?.querySelector("[data-selected]");if(!L||!se||L.clientWidth===0)return;const Q=W.current?"smooth":"auto";W.current=!0;const V=se.offsetLeft,H=V+se.offsetWidth;V<L.scrollLeft+La?L.scrollTo({left:V-La,behavior:Q}):H>L.scrollLeft+L.clientWidth-La&&L.scrollTo({left:H-L.clientWidth+La,behavior:Q})},[t,g,c]),m.useEffect(()=>{c&&w.current?.focus()},[c]);const J=()=>{l(""),d(!1)},O=L=>L?`${La}px`:"0px",B=N.left||N.right?`linear-gradient(to right, transparent, #000 ${O(N.left)}, #000 calc(100% - ${O(N.right)}), transparent)`:void 0;return o.jsxs("div",{className:"group/bar shrink-0",children:[o.jsxs("div",{className:"relative z-[1] flex h-[35px] items-end gap-1.5 px-3.5",children:[v&&o.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:[o.jsx(v1,{className:"size-3.5 shrink-0"}),o.jsx("input",{ref:w,value:a,onChange:L=>l(L.target.value),onKeyDown:L=>{L.key==="Escape"&&(L.stopPropagation(),J())},onBlur:()=>{!a&&document.hasFocus()&&d(!1)},placeholder:T,className:"h-full min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground"}),o.jsx("button",{type:"button",onClick:J,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:o.jsx(ln,{className:"size-3"})})]}),o.jsxs("div",{ref:b,className:q("relative flex min-w-0 flex-1 items-center gap-1.5",v&&"hidden"),children:[o.jsx("div",{ref:y,onScroll:D,style:{maskImage:B},className:"min-w-0 overflow-x-auto [scrollbar-width:none]",children:o.jsxs("div",{className:"flex w-max gap-3.5",children:[o.jsx("button",{type:"button","data-selected":t===En||void 0,onClick:()=>u(En),className:yu(t===En,!1),children:o.jsx(Su,{label:f("All"),count:s})}),o.jsx("button",{type:"button","data-selected":t===lr||void 0,onClick:()=>u(lr),className:yu(t===lr,!1),children:o.jsx(Su,{label:f("Recent"),count:i})}),o.jsx(bm,{items:x.map(L=>Ox(L.id)),strategy:tZ,children:x.map(L=>o.jsx(xZ,{group:L,count:n[L.id]??0,selected:t===L.id,onSelect:()=>u(L.id)},L.id))}),g&&o.jsx(vZ,{label:f("Ungrouped"),count:r,selected:t===cs,onSelect:()=>u(cs)})]})}),o.jsx("span",{ref:_,"aria-hidden":!0,className:"pointer-events-none absolute -bottom-px z-10 h-[1.5px] overflow-hidden",children:o.jsx("span",{ref:j,className:"absolute top-0 left-0 h-full rounded-full bg-foreground"})}),o.jsx("button",{type:"button",onClick:h,className:q(LI,"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:o.jsx(ps,{className:"size-3"})}),N.overflow&&o.jsx(bZ,{groups:x,selectedId:t,counts:n,totalCount:s,recentCount:i,ungroupedCount:r,onSelect:u,onAddGroup:h,onEditGroup:p})]})]}),o.jsx("div",{className:"mx-3.5 h-px bg-border"})]})}function yu(e,t){return q("flex shrink-0 items-center whitespace-nowrap pt-1 pb-[7px] text-[0.8929rem] transition-colors",e?"font-medium text-foreground":"text-subtle-foreground hover:text-foreground",t&&"rounded-t-md bg-foreground/[0.075] text-foreground")}function Su({label:e,count:t,emoji:n,color:s}){return o.jsxs(o.Fragment,{children:[n&&o.jsx("span",{className:"mr-1 text-[13px] leading-none",children:n}),s&&o.jsx("span",{className:"mr-1.5 size-1.5 shrink-0 rounded-full",style:{backgroundColor:s},"aria-hidden":!0}),o.jsx("span",{className:"max-w-32 truncate",children:e}),o.jsx("span",{className:"ml-1 font-normal text-[0.75rem] text-subtle-foreground/75 tabular-nums",children:t})]})}const OI=e=>e?.type==="project";function xZ({group:e,count:t,selected:n,onSelect:s}){const{attributes:i,listeners:r,setNodeRef:a,transform:l,transition:c,isDragging:d,isOver:u,active:h}=Ch({id:Ox(e.id),data:{type:"project-group",groupId:e.id}});return o.jsx("button",{ref:a,type:"button","data-selected":n||void 0,onClick:s,style:{transform:l?`translate3d(${Math.round(l.x)}px, 0, 0)`:void 0,transition:c},className:q(yu(n,u&&OI(h?.data.current)),d&&"z-10 cursor-grabbing text-foreground"),...i,...r,children:o.jsx(Su,{label:e.name,count:t,emoji:e.emoji,color:e.color})})}function vZ({label:e,count:t,selected:n,onSelect:s}){const{active:i}=oc(),{setNodeRef:r,isOver:a}=rc({id:Ox(cs),disabled:i?.data.current?.type==="project-group"});return o.jsx("button",{ref:r,type:"button","data-selected":n||void 0,onClick:s,className:yu(n,a&&OI(i?.data.current)),children:o.jsx(Su,{label:e,count:t})})}function bZ({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:i,ungroupedCount:r,onSelect:a,onAddGroup:l,onEditGroup:c}){const{t:d}=te(),[u,h]=m.useState(!1),p=f=>()=>{h(!1),f()};return o.jsxs(Pi,{open:u,onOpenChange:h,children:[o.jsx(Ei,{className:q(LI,"ml-auto data-popup-open:bg-foreground/5 data-popup-open:text-foreground"),title:d("All groups"),"aria-label":d("All groups"),children:o.jsx($n,{className:"size-3"})}),o.jsxs(Ai,{side:"bottom",align:"end",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:[o.jsx(Yc,{label:d("All"),count:s,selected:t===En,onSelect:p(()=>a(En))}),o.jsx(Yc,{label:d("Recent"),count:i,selected:t===lr,onSelect:p(()=>a(lr))}),e.map(f=>o.jsx(Yc,{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&&o.jsx(Yc,{label:d("Ungrouped"),count:r,selected:t===cs,onSelect:p(()=>a(cs))}),o.jsx("div",{className:"my-1 border-t"}),o.jsxs("button",{type:"button",onClick:p(l),className:q(RI,"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[o.jsx(ps,{className:"size-3.5 shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:d("New group")})]})]})]})}function Yc({label:e,count:t,emoji:n,color:s,selected:i,onSelect:r,onEdit:a}){const{t:l}=te();return o.jsxs("div",{className:"group/row relative",children:[o.jsxs("button",{type:"button",onClick:r,className:q(RI,i?"bg-brand/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[o.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center gap-1",children:n?o.jsx("span",{className:"text-[13px] leading-none",children:n}):s?o.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:s},"aria-hidden":!0}):null}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:e}),o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs tabular-nums",children:t}),o.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center",children:i&&o.jsx(Jn,{className:q("size-3.5 text-brand",a&&"group-hover/row:opacity-0")})})]}),a&&o.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:o.jsx(Xs,{className:"size-3.5"})})]})}function zI({value:e,reasoningEnabled:t,thinkingLevel:n,onChange:s,onReasoningChange:i,onThinkingChange:r,description:a,inheritLabel:l}){const{t:c}=te(),d=xe(x=>x.virtualModels),u=og(),h=e?u.find(x=>x.id===e.providerId):void 0,p=h?.models.find(x=>x.id===e?.modelId),f=yk(d,e);return o.jsxs(Hs,{className:"w-full items-stretch",children:[o.jsx(Bs,{children:c("Default model")}),o.jsx(Kk,{children:a}),u.length>0&&o.jsx("div",{className:"w-full min-w-0",children:o.jsx(Bu,{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:t2,zIndex:yn.DROPDOWN_IN_MODAL,onSelect:(x,g)=>s({providerId:x,modelId:g}),onReasoningChange:i,onThinkingChange:r})}),e&&!f&&(!h||!p)&&o.jsx("p",{className:"text-muted-foreground text-xs",children:c("Selected model is unavailable — falls back to the default model.")}),e&&o.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"self-start",onClick:()=>s(null),children:c("Follow default model")})]})}const wZ=["#3b82f6","#22c55e","#eab308","#f97316","#ef4444","#a855f7","#06b6d4","#64748b"];function yZ({open:e,group:t,projects:n,onOpenChange:s,onSave:i,onDelete:r}){const{t:a}=te(),l=xe(A=>A.defaultReasoningEnabled),c=xe(A=>A.defaultThinkingLevel),[d,u]=m.useState(""),[h,p]=m.useState(),[f,x]=m.useState(null),[g,v]=m.useState(!0),[w,y]=m.useState("medium"),[b,_]=m.useState(new Set),[j,N]=m.useState(""),C=t===null,k=C?n??[]:[],E=j.trim().toLowerCase(),I=E?k.filter(A=>A.name.toLowerCase().includes(E)):k;m.useEffect(()=>{if(!e)return;u(t?.name??""),p(t?.color),x(t?.defaultModel??null);const A=Bd({defaultReasoningEnabled:l,defaultThinkingLevel:c});v(t?.defaultReasoningEnabled??A.reasoningEnabled),y(t?.defaultThinkingLevel??A.thinkingLevel),_(new Set),N("")},[e,t,l,c]);const T=A=>{_(D=>{const W=new Set(D);return W.has(A)?W.delete(A):W.add(A),W})};return o.jsx(gn,{open:e,onOpenChange:s,children:o.jsx(xn,{className:"max-w-md",children:o.jsxs("form",{className:"flex flex-col",onSubmit:A=>{A.preventDefault();const D=d.trim();D&&(i({name:D,color:h,defaultModel:f,defaultReasoningEnabled:f?g:null,defaultThinkingLevel:f?w:null,...C&&b.size>0?{projectIds:[...b]}:{}}),s(!1))},children:[o.jsxs(vn,{children:[o.jsx(bn,{children:a(t?"Edit group":"New group")}),o.jsx(Os,{children:a("Groups organize projects in the sidebar.")})]}),o.jsxs(Rn,{className:"space-y-3",children:[o.jsxs(Hs,{children:[o.jsx(Bs,{children:a("Name")}),o.jsx(Wt,{value:d,onChange:A=>u(A.target.value),autoFocus:!0})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.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:o.jsx(ln,{className:"h-3 w-3"})}),wZ.map(A=>o.jsx("button",{type:"button",className:"h-6 w-6 rounded-full border border-border",style:{backgroundColor:A,outline:h===A?"2px solid var(--color-ring)":void 0,outlineOffset:2},onClick:()=>p(h===A?void 0:A),"aria-label":A},A))]}),o.jsx(zI,{value:f,reasoningEnabled:g,thinkingLevel:w,onChange:A=>{if(x(A),A)return;const D=Bd({defaultReasoningEnabled:l,defaultThinkingLevel:c});v(D.reasoningEnabled),y(D.thinkingLevel)},onReasoningChange:v,onThinkingChange:y,description:a("Used for new conversations in this group."),inheritLabel:a("Follows the global default")}),k.length>0&&o.jsxs(Hs,{className:"w-full items-stretch",children:[o.jsx(Bs,{children:a("Move projects into this group")}),o.jsx(Wt,{value:j,onChange:A=>N(A.target.value),placeholder:a("Filter projects...")}),o.jsxs("div",{className:"max-h-48 w-full space-y-0.5 overflow-y-auto rounded-md border p-1.5",children:[I.map(A=>o.jsxs("label",{className:"flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 hover:bg-accent/50",children:[o.jsx(ec,{checked:b.has(A.id),onCheckedChange:()=>T(A.id)}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:A.name})]},A.id)),I.length===0&&o.jsx("p",{className:"px-2 py-3 text-center text-xs text-muted-foreground",children:a("No matching projects found")})]})]})]}),o.jsxs(ls,{className:t?"sm:justify-between":void 0,children:[t&&r?o.jsx(le,{type:"button",variant:"outline",size:"sm",className:"text-destructive",onClick:()=>{r(),s(!1)},children:a("Delete group")}):o.jsx("span",{}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(le,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),children:a("Cancel")}),o.jsx(le,{type:"submit",size:"sm",disabled:!d.trim(),children:a("Save")})]})]})]})})})}function SZ({project:e,onClose:t}){const{t:n}=te(),[s,i]=m.useState(null),[r,a]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1);m.useEffect(()=>{e&&(i(null),a(null),c(null),window.electronAPI.sessionImport.scan(e.path).then(i).catch(()=>i([])))},[e]),m.useEffect(()=>{if(!r){c(null);return}c(null),window.electronAPI.sessionImport.read(r.sourceId,r.path).then(c).catch(()=>c([]))},[r]);const h=async()=>{if(!(!e||!r)){u(!0);try{const p=await window.electronAPI.sessionImport.import(r.sourceId,r.path,e.path);p&&(ie.getState().addImportedConversation(e.id,p),t())}finally{u(!1)}}};return o.jsx(gn,{open:e!==null,onOpenChange:p=>!p&&t(),children:o.jsxs(xn,{className:"max-w-3xl",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:n("Import session")}),o.jsx(Os,{children:n("Pick a conversation from a local AI app under {{name}}.",{name:e?.name??""})})]}),o.jsx(Rn,{children:s===null?o.jsx("div",{className:"flex flex-col items-center gap-3 py-12",children:o.jsx(ar,{className:"size-5"})}):s.length===0?o.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:n("No sessions found for this project")}):o.jsxs("div",{className:"flex h-96 gap-3",children:[o.jsx("div",{className:"flex w-64 shrink-0 flex-col overflow-y-auto rounded-lg border",children:s.map(p=>o.jsxs("div",{children:[o.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=>o.jsxs("button",{type:"button",onClick:()=>a({sourceId:p.sourceId,path:f.path}),className:q("w-full px-2.5 py-1.5 text-left",r?.path===f.path?"bg-muted":"hover:bg-muted/50"),children:[o.jsx("p",{className:"truncate text-xs",children:f.title||n("Untitled")}),o.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[new Date(f.updatedAt).toLocaleString()," ·"," ",n("{{count}} messages",{count:f.messageCount})]})]},f.path))]},p.sourceId))}),o.jsx("div",{className:"min-w-0 flex-1 overflow-y-auto rounded-lg border bg-muted/20 p-3",children:r?l===null?o.jsx("div",{className:"flex justify-center py-12",children:o.jsx(ar,{className:"size-4"})}):o.jsx("div",{className:"flex flex-col gap-2.5",children:l.map((p,f)=>o.jsx("div",{className:q("max-w-[90%] rounded-lg px-2.5 py-1.5 text-xs whitespace-pre-wrap",p.role==="user"?"self-end bg-primary/10":"self-start bg-background border"),children:p.text.length>600?`${p.text.slice(0,600)}…`:p.text},f))}):o.jsx("p",{className:"py-12 text-center text-xs text-muted-foreground",children:n("Select a session to preview")})})]})}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",onClick:t,children:n("Cancel")}),o.jsxs(le,{onClick:()=>{h()},disabled:!r||d,children:[d?o.jsx(ar,{className:"mr-1.5 size-3.5"}):o.jsx(Xl,{className:"mr-1.5 h-3.5 w-3.5"}),n("Import")]})]})]})})}function CZ({open:e,project:t,onOpenChange:n}){const{t:s}=te(),i=xe(V=>V.projectGroups),r=xe(V=>V.defaultReasoningEnabled),a=xe(V=>V.defaultThinkingLevel),l=xe(V=>V.setProjectDefaultModel),c=xe(V=>V.setProjectGroupId),d=xe(V=>V.setProjectAlias),u=xe(V=>V.setProjectDisabledBuiltinTools),h=xe(V=>V.setProjectSubagentAllowedModes),p=xe(V=>V.setProjectTrustedCode),f=xe(V=>V.disabledBuiltinTools),x=xe(V=>V.subagentAllowedModes),[g,v]=m.useState(""),[w,y]=m.useState(null),[b,_]=m.useState(!0),[j,N]=m.useState("medium"),[C,k]=m.useState(""),[E,I]=m.useState(!0),[T,A]=m.useState([]),[D,W]=m.useState(!0),[J,O]=m.useState([]),[B,L]=m.useState(!1);m.useEffect(()=>{if(!e)return;L(!1),y(t?.defaultModel??null),k(t?.groupId??""),v(t?.alias??"");const V=t?.groupId?i.find(pe=>pe.id===t.groupId):void 0,H=Bd({groupReasoningEnabled:V?.defaultReasoningEnabled,groupThinkingLevel:V?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});_(t?.defaultReasoningEnabled??H.reasoningEnabled),N(t?.defaultThinkingLevel??H.thinkingLevel);const ne=t?.disabledBuiltinTools===void 0;I(ne),A(ne?[...f]:[...t?.disabledBuiltinTools??[]]);const he=t?.subagentAllowedModes===void 0;W(he),O(he?[...x]:[...t?.subagentAllowedModes??[]])},[e,t,i,r,a,f,x]);const se=m.useMemo(()=>[{value:"",label:s("Ungrouped")},...i.slice().sort((V,H)=>V.order-H.order).map(V=>({value:V.id,label:V.name}))],[i,s]),Q=t?.kind==="ssh"?`${t.sshConnectionName??t.sshHost}:${t.path}`:t?.path??"";return o.jsx(gn,{open:e,onOpenChange:n,children:o.jsx(xn,{className:"max-w-lg",children:o.jsxs("form",{className:"contents",onSubmit:V=>{V.preventDefault(),t&&(l(t.id,w,w?{reasoningEnabled:b,thinkingLevel:j}:null),c(t.id,C||null),d(t.id,g),u(t.id,E?null:T),h(t.id,D?null:J),B&&p(t.id,null),n(!1))},children:[o.jsxs(vn,{children:[o.jsx(bn,{children:s("Project settings")}),o.jsx(Os,{children:t?jo(t):s("Project")})]}),o.jsxs(Rn,{className:"max-h-[60vh] space-y-4",children:[o.jsxs(Hs,{className:"w-full items-stretch",children:[o.jsx(Bs,{children:s("Alias")}),o.jsx(Wt,{value:g,onChange:V=>v(V.target.value),placeholder:t?jo({...t,alias:void 0}):""}),o.jsx(Kk,{children:s("Shown in the sidebar instead of the folder name. Leave blank to reset.")})]}),o.jsxs(Hs,{className:"w-full items-stretch",children:[o.jsx(Bs,{children:s("Path")}),o.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[o.jsx("p",{className:"min-w-0 flex-1 truncate font-mono text-xs",title:Q,children:Q}),o.jsx(_C,{text:Q,className:"shrink-0"}),t&&t.kind!=="ssh"&&o.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:o.jsx(Qs,{className:"h-3 w-3"})})]})]}),i.length>0&&o.jsxs(Hs,{className:"w-full items-stretch",children:[o.jsx(Bs,{children:s("Project group")}),o.jsxs(ms,{items:se,value:C,onValueChange:V=>k(V??""),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:se.map(V=>o.jsx(ts,{value:V.value,children:V.label},V.value||"ungrouped"))})]})]}),o.jsx(zI,{value:w,reasoningEnabled:b,thinkingLevel:j,onChange:V=>{if(y(V),V)return;const H=C?i.find(he=>he.id===C):void 0,ne=Bd({groupReasoningEnabled:H?.defaultReasoningEnabled,groupThinkingLevel:H?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});_(ne.reasoningEnabled),N(ne.thinkingLevel)},onReasoningChange:_,onThinkingChange:N,description:s("Used for new conversations in this project."),inheritLabel:s("Follows group, then global default")}),o.jsx("p",{className:"text-muted-foreground text-xs",children:s("Session choice overrides the project default.")}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"font-medium text-sm",children:s("Follow global built-in tools")}),o.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.")})]}),o.jsx(_i,{checked:E,onCheckedChange:I})]}),!E&&o.jsx("div",{className:"space-y-2",children:n2.map(V=>o.jsxs("div",{className:"flex items-center gap-3 rounded-md border px-3 py-2.5",children:[o.jsx(Km,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"text-sm font-medium",children:s(V.name)}),o.jsx("p",{className:"text-muted-foreground text-xs",children:s(V.description)})]}),o.jsx(_i,{checked:!T.includes(V.id),onCheckedChange:H=>A(ne=>H?ne.filter(he=>he!==V.id):[...new Set([...ne,V.id])])})]},V.id))}),o.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"font-medium text-sm",children:s("Follow global unified agent modes")}),o.jsx("p",{className:"text-muted-foreground text-xs",children:s("When off, this project uses its own explicit Agent mode permission mask.")})]}),o.jsx(_i,{checked:D,onCheckedChange:V=>{W(V),V||O([...x])}})]}),!D&&o.jsxs("div",{className:"space-y-2 rounded-lg border px-3 py-2.5",children:[[["task","One-shot task agents"],["coworker","Persistent coworkers"]].map(([V,H])=>o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsx("span",{className:"text-sm",children:s(H)}),o.jsx(_i,{checked:J.includes(V),disabled:(E?f:T).includes("subagent"),onCheckedChange:ne=>O(he=>ne?[...new Set([...he,V])]:he.filter(pe=>pe!==V))})]},V)),(E?f:T).includes("subagent")&&o.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?o.jsxs("div",{className:"flex items-start gap-3 rounded-lg border px-3 py-2.5",children:[o.jsx(Jr,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"font-medium text-sm",children:s("Trusted project extensions")}),o.jsx("p",{className:"truncate font-mono text-muted-foreground text-xs",title:t.trustedProjectCode.join(`
95
- `),children:t.trustedProjectCode.join(", ")}),B&&o.jsx("p",{className:"text-muted-foreground text-xs",children:s("No longer loaded after saving, starting with the next session.")})]}),o.jsx(le,{type:"button",size:"xs",variant:"outline",disabled:B,onClick:()=>L(!0),children:s("Revoke trust")})]}):null]}),o.jsxs(ls,{children:[o.jsx(le,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),o.jsx(le,{type:"submit",size:"sm",disabled:!t,children:s("Save")})]})]})})})}const kh=5,GI=15,iS=9;function _h(e,t){return e<=0?0:Math.min(e,kh+Math.max(0,t))}function kZ(e,t){return _h(e,t)>=e?0:Math.min(Math.max(0,e-kh),t+GI)}function _Z(e){return Math.max(0,e-GI)}function jZ(e){const{order:t,conversations:n,pinnedOrderIds:s=[],projectIds:i,archivedProjectIds:r=[],collapsedProjects:a={},revealedExtras:l={},searching:c=!1,matches:d=()=>!0,projectMatches:u=()=>!1,leadingIds:h=[]}=e,p=[],f=new Set,x=v=>{f.has(v)||p.length>=iS||(f.add(v),p.push(v))};for(const v of h)x(v);const g=qk(t,n,s,r);for(const v of c?g.filter(d):g)x(v);for(const v of i){if(p.length>=iS)break;if(c?!1:a[v]===!0)continue;const y=Qa(t,n,v),b=!c||u(v)?y:y.filter(d),_=c?b:b.slice(0,_h(b.length,l[v]??0));for(const j of _)x(j)}return p}function Vx(e,t){const n=new Map(e.map(i=>[i.id,i])),s=[];for(const i of t){const r=n.get(i);r&&(s.push(r),n.delete(i))}for(const i of e)n.has(i.id)&&s.push(i);return s}function Xc(e,t,n,s){const i=Vx(e,t).map(l=>l.id),r=i.indexOf(n),a=i.indexOf(s);return r===-1||a===-1||r===a||(i.splice(r,1),i.splice(a,0,n)),i}function NZ(e,t){const n=new Map(e.map(r=>[r.id,r])),s=[],i=new Set;for(const r of t){const a=n.get(r);a&&(s.push(a),i.add(r))}return{pinned:s,rest:e.filter(r=>!i.has(r.id))}}function TZ(e,t){return e.includes(t)?e.filter(n=>n!==t):[t,...e]}function IZ(e,t,n){const s=n.includes(e),i=n.includes(t);return s&&i?"pinned":!s&&!i?"order":null}const Rd="enso-project-order",wm="enso-pinned-order",qa="enso-archived-projects",oS="enso-pinned-projects",ym=new Set;function rr(e){try{const t=JSON.parse(localStorage.getItem(e)??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Uo(e,t){localStorage.setItem(e,JSON.stringify(t));for(const n of ym)n()}function DZ(e){return ym.add(e),()=>ym.delete(e)}function Mp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function rS(e){return e==="browser"||typeof e=="string"&&e.startsWith("browser:")}function PZ(e){if(typeof e.contentComponent=="string")return e.contentComponent;if(typeof e.component=="string")return e.component}function aS(e){if(!Mp(e)||!Mp(e.panels))return{browsers:0,terminals:0};let t=0,n=0;for(const[s,i]of Object.entries(e.panels)){if(!Mp(i))continue;const r=PZ(i);r==="browser"||rS(i.id)||rS(s)?t+=1:r==="terminal"&&(n+=1)}return{browsers:t,terminals:n}}function EZ({conversationId:e}){const{t}=te(),n=pn(i=>aS(i.layouts[e]).browsers),s=pn(i=>aS(i.layouts[e]).terminals);return n===0&&s===0?null:o.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&&o.jsxs("span",{className:"inline-flex items-center gap-0.5",title:t("{{n}} browsers",{n}),children:[o.jsx(uo,{className:"h-3 w-3","aria-hidden":!0}),n]}),s>0&&o.jsxs("span",{className:"inline-flex items-center gap-0.5",title:t("{{n}} terminals",{n:s}),children:[o.jsx(Eo,{className:"h-3 w-3","aria-hidden":!0}),s]})]})}const AZ=[7,15,30],lS="h-6.5 rounded-lg px-2 text-xs text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",cS="enso-collapsed-scratch",qi="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",Rp="-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 dS({width:e,collapsed:t,onToggleCollapse:n,onOpenSearch:s,onNavigate:i}){const{t:r,locale:a}=te(),l=xe($=>$.projects),d=Hu()==="mobile",u=xe($=>$.scratchSessionsEnabled),h=xe($=>$.projectGroups),p=xe($=>$.createProjectGroup),f=xe($=>$.updateProjectGroup),x=xe($=>$.removeProjectGroup),g=xe($=>$.reorderProjectGroups),v=xe($=>$.setProjectGroupId),w=xe($=>$.keybindings),y=xe($=>$.activeRetentionMinutes),b=Ii(w)["search-workspace"],_=b?Mi(b):"",j=xe($=>$.addProject),N=xe($=>$.removeProject),C=ie($=>Rx($.conversations)),k=ie($=>$.order),E=ie($=>$.activeId),I=ie($=>$.newConversation),T=ie($=>$.selectConversation),A=m.useRef(i);A.current=i;const D=m.useCallback($=>{A.current?.(),T($)},[T]),W=ie($=>$.removeConversation),J=ie($=>$.togglePinConversation),O=ie($=>$.toggleArchiveConversation),B=ie($=>$.moveConversationToWorktree),L=ie($=>$.cleanupWorktree),se=ie($=>$.refreshWorktreeStatuses),Q=ie($=>$.worktreeStatuses),[V,H]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-projects")??"{}")}catch{return{}}}),ne=$=>{H(ve=>{const ct={...ve,[$]:!ve[$]};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(ct)),ct})},[he,pe]=m.useState(()=>{try{return localStorage.getItem(cS)==="1"}catch{return!1}}),ke=$=>{try{localStorage.setItem(cS,$?"1":"0")}catch{}},Me=()=>{pe($=>{const ve=!$;return ke(ve),ve})},fe=()=>{pe($=>$&&(ke(!1),!1))},[F,U]=m.useState(()=>rr(Rd)),de=Vx(l.filter($=>$.kind!=="scratch"),F),Y=l.find($=>$.kind==="scratch"),[X,z]=m.useState(()=>rr(qa)),[ue,_e]=m.useState(()=>rr(oS)),Ee=$=>{_e($),Uo(oS,$)},Be=$=>{if(Ee(TZ(ue,$)),!ue.includes($)&&X.includes($)){const ve=X.filter(ct=>ct!==$);z(ve),Uo(qa,ve)}},De=$=>{const ve=X.includes($)?X.filter(ct=>ct!==$):[...X,$];z(ve),Uo(qa,ve),!X.includes($)&&ue.includes($)&&Ee(ue.filter(ct=>ct!==$))},[Ue,St]=m.useState(()=>{try{return localStorage.getItem("enso-selected-project-group")??En}catch{return En}}),[Ut,tn]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-project-groups")??"{}")}catch{return{}}}),Ne=$=>{St($),localStorage.setItem("enso-selected-project-group",$)},Z=$=>{tn(ve=>{const ct={...ve,[$]:!ve[$]};return localStorage.setItem("enso-collapsed-project-groups",JSON.stringify(ct)),ct})},je=Ue===En||Ue===lr||Ue===cs||h.some($=>$.id===Ue)?Ue:En,tt=je===lr,Et=h.find($=>$.id===je)?.id,zt=Rr(de,h,X,je),we=s2(Rr(de,h,X,En),k,C,Date.now()),{pinned:ft,rest:mt}=tt?{pinned:[],rest:we}:NZ(zt,ue),ze=Yk(mt,h,[]),Ct=[...ft,...mt],K=Ct.map($=>$.id),be=new Set(K),[Re,Ve]=m.useState(()=>rr(wm)),{active:Ke}=oc(),nt=Ke?.data.current;r_({onDragEnd:$=>{const ve=$.active.data.current;if(!ve)return;const ct=$.over?String($.over.id):null,vt=yX(ve,ct,E??void 0,{projectGroupId:Nt=>l.find(ns=>ns.id===Nt)?.groupId});if(vt)switch(vt.kind){case"move-project-to-group":{if(tt&&vt.beforeProjectId)break;if(v(vt.projectId,vt.groupId),vt.beforeProjectId){const Nt=Xc(l,F,vt.projectId,vt.beforeProjectId);U(Nt),Uo(Rd,Nt)}break}case"reorder-groups":g(vt.activeId,vt.overId);break;case"reorder-projects":{if(tt)break;const Nt=IZ(vt.activeId,vt.overId,ue);if(Nt==="pinned"){const Fo=Xc(ue.map(vo=>({id:vo})),ue,vt.activeId,vt.overId);Ee(Fo);break}if(Nt!=="order")break;const ns=Xc(l,F,vt.activeId,vt.overId);U(ns),Uo(Rd,ns);break}case"insert-file-mention":Vl({kind:"file",id:vt.path,label:vt.label,relativePath:vt.path});break;case"insert-chat-mention":Vl({kind:"chat",id:vt.conversationId,label:vt.label,sessionFile:vt.sessionFile});break;case"pin-conversation":J(vt.conversationId);break;case"reorder-pinned":{const Nt=Xc(_t.map(ns=>({id:ns})),Re,vt.activeId,vt.overId);Ve(Nt),Uo(wm,Nt);break}}}});const[ge,$e]=m.useState(null),[it,xt]=m.useState(null),[Mt,Gt]=m.useState(!1),[sn,wn]=m.useState(!1),[On,rn]=m.useState(null),cn=$=>{const ve=new Set(l.map(ct=>ct.id));$.sshConnectionId&&rn({name:Tk($.path),path:$.path,sshHost:$.sshHost}),j($.path,$.sshConnectionId?{sshConnectionId:$.sshConnectionId}:void 0,$.groupId??Et).then(ct=>{if(ct){if(X.includes(ct.id)){const vt=X.filter(Nt=>Nt!==ct.id);z(vt),Uo(qa,vt)}if(ve.has(ct.id)){H(Nt=>{if(Nt[ct.id]!==!0)return Nt;const ns={...Nt,[ct.id]:!1};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(ns)),ns});const vt=Qa(k,C,ct.id)[0];if(vt){D(vt);return}}I(ct.id)}}).catch(ct=>{We({type:"error",title:r("Failed to add project"),description:ct instanceof Error?ct.message:String(ct)})}).finally(()=>rn(null))},[Bn,P]=m.useState(null),[M,R]=m.useState(null),S=async $=>{const ve=C[$];let ct;if(ve?.worktree){const vt=await nn($);fd(vt)&&(ct=Wn(vt))}R({kind:"conversation",id:$,worktreeWarning:ct})},[G,ae]=m.useState({}),[ce,Ie]=m.useState(""),[He,ht]=m.useState(!1),[Qe,qt]=m.useState(()=>Date.now());m.useEffect(()=>{const $=setInterval(()=>qt(Date.now()),i2);return()=>clearInterval($)},[]);const lt={now:Qe,ms:y*6e4},bt=o2(k,C,X,lt),kt=$=>{const ve=fS(l,C[$].projectId),ct=l2($,C,lt);if(ct===void 0)return ve;const vt=r("Stays in Active for about {{count}} more min",{count:Math.ceil(ct/6e4)});return ve?`${ve}
96
- ${vt}`:vt},_t=qk(k,C,Re,X),jt=r2(k,C,de.map($=>$.id),X).filter($=>u||$.projectId!==Y?.id),oe=ce.trim().length>0,Te=$=>Ma(ce,[C[$]?.title||r("New conversation")]),Xe=Y?Qa(k,C,Y.id).filter($=>!oe||Te($)):[],Le=oe?!1:he,Ze=$=>{const ve=C[$]?.projectId;return!ve||be.has(ve)},qe=(oe?bt.filter(Te):bt).filter(Ze),st=jZ({order:k,conversations:C,pinnedOrderIds:Re,projectIds:K,archivedProjectIds:X,collapsedProjects:V,revealedExtras:G,searching:oe,matches:Te,projectMatches:$=>{const ve=de.find(ct=>ct.id===$);return!!(ve&&Ma(ce,[ve.alias??"",ve.name,ve.path]))},leadingIds:qe}),at=m.useRef(st);at.current=st;const et=(oe?_t.filter(Te):_t).filter(Ze),ye=new Set(et),Se=new Set(qe),Oe=($,ve)=>{if(t||!He)return;const ct=st.indexOf($);if(!(ct<0||(Se.has($)?"active":ye.has($)?"pinned":"project")!==ve))return Mi(`mod+${ct+1}`)},[Ae,Pe]=m.useState(!1),[Ge,yt]=m.useState(""),[At,Rt]=m.useState(null),Lt=Ge.trim()?jt.map($=>{const ve=l.find(vt=>vt.id===$.projectId);return $.projectArchived===!0&&!!(ve&&Ma(Ge,[ve.alias??"",ve.name,ve.path]))?$:{...$,ids:$.ids.filter(vt=>Ma(Ge,[C[vt]?.title||r("New conversation")]))}}).filter($=>$.ids.length>0):jt,ee=$=>{if(je===En)return!0;const ve=l.find(ct=>ct.id===$.projectId);return ve?je===cs?!ve.groupId||!h.some(ct=>ct.id===ve.groupId):ve.groupId===je:je===cs},Ft=Lt.filter(ee),Kt=jt.filter(ee).reduce(($,ve)=>$+ve.ids.length,0),Zt=()=>{yt(""),Pe(!0)};m.useEffect(()=>{je!==Ue&&(St(En),localStorage.setItem("enso-selected-project-group",En))},[je,Ue]),m.useEffect(()=>{const $=Nt=>{const Fo=(Lv?Nt.metaKey:Nt.ctrlKey)&&!Nt.shiftKey&&!Nt.altKey;if(ht(Fo),!Fo||Nt.repeat||es.getState().activeNodeId!=="local")return;const vo=Number(Nt.key);if(vo<1||vo>9)return;const Ho=at.current[vo-1];Ho&&(Nt.preventDefault(),D(Ho))},ve=Nt=>{const ns=Lv?Nt.metaKey:Nt.ctrlKey;ht(ns&&!Nt.shiftKey&&!Nt.altKey)},ct=()=>ht(!1),vt=()=>{document.hidden&&ct()};return window.addEventListener("keydown",$),window.addEventListener("keyup",ve),window.addEventListener("blur",ct),document.addEventListener("visibilitychange",vt),()=>{window.removeEventListener("keydown",$),window.removeEventListener("keyup",ve),window.removeEventListener("blur",ct),document.removeEventListener("visibilitychange",vt)}},[D]),m.useEffect(()=>{se();const $=setInterval(()=>{se()},3e4),ve=()=>{se()};return window.addEventListener("focus",ve),()=>{clearInterval($),window.removeEventListener("focus",ve)}},[se]);const[Dt,Yt]=m.useState(null),[Xt,Nn]=m.useState(null),nn=async $=>{const ve=await window.electronAPI.worktree.status($);return ve.ok?ve.value:void 0},_n=async($,ve)=>{const ct=await L($);if(ct){We({type:"error",title:r("Failed to clean up worktree"),description:ct});return}ve&&O($),se()},fn=async $=>{const ve=await nn($);if(fd(ve)){Yt({kind:"cleanup",id:$,status:ve});return}await _n($,!1)},hn=async $=>{const ve=C[$];if(!ve)return;if(ve.archived||!ve.worktree){O($);return}const ct=await nn($);if(fd(ct)){Yt({kind:"archive",id:$,status:ct});return}await _n($,!0)},Fn=async $=>{for(const ve of $)!C[ve]||C[ve].archived||await hn(ve)},Ln=async($,ve=!1)=>{const ct=await B($,{allowDirtyMainTree:ve});if(ct===Wk){Nn($);return}if(ct){We({type:"error",title:r("Failed to move to worktree"),description:ct});return}se()},Wn=$=>{const ve=[];return $?.dirty&&ve.push(r("Uncommitted changes")),$&&$.ahead>0&&ve.push(r("{{n}} unmerged commits (branch is kept)",{n:$.ahead})),ve.join("; ")};return o.jsxs(Es.aside,{initial:!1,animate:{width:t?48:e},transition:Yr,"data-enso":"sidebar",className:"flex shrink-0 flex-col overflow-hidden",children:[t&&o.jsxs("div",{className:"flex w-full flex-1 flex-col items-center gap-1 py-2",children:[o.jsx("button",{type:"button",onClick:()=>Gt(!0),className:qi,title:r("Add project"),children:o.jsx(bb,{className:"h-4 w-4"})}),o.jsx("div",{className:"flex-1"}),Kt>0&&o.jsx("button",{type:"button",onClick:Zt,className:qi,title:`${r("Archived")} (${Kt})`,children:o.jsx(ji,{className:"h-4 w-4"})}),window.electronAPI.remote&&o.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:qi,title:r("Compact view"),children:o.jsx(Mv,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",onClick:()=>window.electronAPI.window.openSettings(),className:qi,title:r("Settings"),children:o.jsx(ai,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:q("flex h-full min-h-0 flex-col",d&&"pt-3",t&&"hidden"),style:{width:e},children:[o.jsx(gZ,{groups:h,selectedId:je,counts:Object.fromEntries(h.map($=>[$.id,Rr(de,h,X,$.id).length])),totalCount:Rr(de,h,X,En).length,recentCount:we.length,ungroupedCount:Rr(de,h,X,cs).length,query:ce,onQueryChange:Ie,searchOpen:sn,onSearchOpenChange:wn,onSelect:Ne,onAddGroup:()=>$e({mode:"create"}),onEditGroup:$=>$e({mode:"edit",id:$})}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pt-0.5 pb-2 pl-1.5 [scrollbar-gutter:stable]",children:[de.length===0&&o.jsx("button",{type:"button",onClick:()=>Gt(!0),className:"mt-2 w-full rounded-lg border border-dashed px-3 py-6 text-center text-sm text-muted-foreground transition-colors hover:border-brand/50 hover:text-foreground",children:r("Add a project to start")}),de.length===0&&u&&Y&&o.jsx("button",{type:"button",onClick:()=>{fe(),I(Y.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&&o.jsxs("div",{"data-slot":"active-section",children:[o.jsx(za,{children:r("Active")}),o.jsx("div",{className:"flex flex-col",children:qe.map($=>o.jsx(hS,{id:$,dragId:bX($),conversation:C[$],children:o.jsx(Oa,{id:$,conversation:C[$],active:E===$,switchHint:Oe($,"active"),locale:a,nowTick:Qe,hoverTitle:kt($),worktreeStatus:C[$].worktree?Q[$]:void 0,isolated:!!C[$].worktree,onSelect:D,onTogglePin:J,onToggleArchive:ve=>{hn(ve)},onCleanupWorktree:ve=>{fn(ve)},onMoveToWorktree:ve=>{Ln(ve)},onRemove:ve=>{S(ve)}})},$))})]}),_t.length===0&&nt?.type==="chat"&&!nt.pinned&&o.jsx(pS,{children:o.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:[o.jsx(Si,{className:"h-3.5 w-3.5"}),r("Drop here to pin")]})}),et.length>0&&o.jsxs(pS,{"data-slot":"pinned-section",children:[o.jsx(za,{children:r("Pinned")}),o.jsx("div",{className:"flex flex-col",children:o.jsx(bm,{items:et.map($=>xI($)),strategy:nS,children:et.map($=>o.jsx(zZ,{id:$,conversation:C[$],children:o.jsx(Oa,{id:$,conversation:C[$],active:E===$,switchHint:Oe($,"pinned"),locale:a,nowTick:Qe,hoverTitle:fS(l,C[$].projectId),worktreeStatus:C[$].worktree?Q[$]:void 0,isolated:!!C[$].worktree,onSelect:D,onTogglePin:J,onToggleArchive:ve=>{hn(ve)},onCleanupWorktree:ve=>{fn(ve)},onMoveToWorktree:ve=>{Ln(ve)},onRemove:ve=>{S(ve)}})},$))})})]}),u&&Y&&o.jsxs("div",{"data-slot":"scratch-section",children:[o.jsxs("div",{className:"group flex items-center gap-1 pt-3.5 pr-1 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground",children:[o.jsxs("button",{type:"button",onClick:Me,"aria-expanded":!Le,className:"flex min-w-0 flex-1 items-center gap-1 text-left transition-colors hover:text-foreground",children:[o.jsx("span",{className:"min-w-0 truncate",children:r("Temporary chats")}),o.jsx(kn,{className:q("size-3 shrink-0 transition-[opacity,transform] duration-150",!Le&&"rotate-90 opacity-0 group-hover:opacity-100")}),o.jsx("span",{className:"ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",children:Xe.length})]}),o.jsx("button",{type:"button",className:Rp,title:r("Start a temporary chat"),"aria-label":r("Start a temporary chat"),onClick:()=>{fe(),I(Y.id)},children:o.jsx(ps,{className:"size-3.25"})})]}),o.jsx(rl,{initial:!1,children:!Le&&o.jsx(Es.div,{initial:"initial",animate:"animate",exit:"exit",variants:gp,className:"overflow-hidden",children:o.jsx("div",{className:"flex flex-col",children:Xe.map($=>o.jsx(Oa,{id:$,conversation:C[$],active:E===$,switchHint:Oe($,"project"),locale:a,nowTick:Qe,onSelect:D,onTogglePin:J,onToggleArchive:ve=>{hn(ve)},onCleanupWorktree:ve=>{fn(ve)},onMoveToWorktree:ve=>{Ln(ve)},onRemove:ve=>{S(ve)}},$))})},"scratch-conversations")})]}),de.length>0&&o.jsx(za,{actions:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>wn(!0),className:q(Rp,(sn||oe)&&"bg-foreground/5 text-foreground opacity-100"),title:r("Search conversations..."),"aria-label":r("Search conversations..."),children:o.jsx(v1,{className:"size-3.25"})}),o.jsx("button",{type:"button",onClick:()=>Gt(!0),className:Rp,title:r("Add project"),"aria-label":r("Add project"),children:o.jsx(ps,{className:"size-3.25"})})]}),children:r("Projects")}),On&&o.jsxs("div",{className:"flex h-8 w-full items-center gap-2 rounded-lg px-2 text-muted-foreground",children:[o.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:o.jsx(Vt,{className:"size-4 animate-spin"})}),o.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium",title:On.path,children:[On.name,On.sshHost&&o.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal",children:On.sshHost})]}),o.jsx("span",{className:"shrink-0 text-xs",children:r("Adding...")})]}),o.jsx(bm,{items:[...je===En?ze.map($=>$.groupId===cs?Lx:gI($.groupId)):[],...K.map($=>mI($))],strategy:nS,children:(()=>{const $=ve=>{const ct=Qa(k,C,ve.id),vt=Ma(ce,[ve.alias??"",ve.name,ve.path]),Nt=!oe||vt?ct:ct.filter(Te);if(oe&&Nt.length===0)return null;const ns=oe?!1:V[ve.id]===!0,Fo=G[ve.id]??0,vo=oe?Nt.length:_h(Nt.length,Fo),Ho=Nt.slice(vo),Sr=ue.includes(ve.id),lv=[{kind:"item",key:"pin",label:r(Sr?"Unpin project":"Pin project"),icon:Sr?o.jsx(au,{}):o.jsx(Si,{}),onSelect:()=>Be(ve.id)},{kind:"item",key:"settings",label:r("Project settings"),icon:o.jsx(ai,{}),onSelect:()=>xt(ve.id)},...ve.kind!=="ssh"?[{kind:"item",key:"reveal",label:r(Hx(window.electronAPI.env.platform)),icon:o.jsx(Qs,{}),onSelect:()=>Bx({projectId:ve.id},r)}]:[],{kind:"item",key:"import",label:r("Import session"),icon:o.jsx(c2,{}),onSelect:()=>P(ve)},{kind:"separator",key:"sep-group"},{kind:"submenu",key:"move-to-group",label:r("Move to group"),icon:o.jsx(Lp,{}),items:[{kind:"item",key:"ungrouped",label:r("Ungrouped"),icon:o.jsx(Lp,{}),onSelect:()=>v(ve.id,null)},...h.map($i=>({kind:"item",key:`group-${$i.id}`,label:$i.name,icon:o.jsx(Lp,{emoji:$i.emoji,color:$i.color}),onSelect:()=>v(ve.id,$i.id)}))]},{kind:"item",key:"new-group",label:r("New group"),icon:o.jsx(bb,{}),onSelect:()=>$e({mode:"create"})},{kind:"separator",key:"sep-danger"},{kind:"item",key:"archive",label:r("Archive project"),icon:o.jsx(ji,{}),onSelect:()=>De(ve.id)},{kind:"item",key:"remove",label:r("Remove project"),icon:o.jsx(di,{}),destructive:!0,onSelect:()=>R({kind:"project",project:ve,conversationIds:ct})}];return o.jsx(OZ,{project:ve,activitySorted:tt,children:$i=>o.jsxs(ao,{children:[o.jsx(lo,{render:o.jsxs("div",{ref:$i.setNodeRef,style:$i.style,children:[o.jsxs("div",{className:"group flex h-8 w-full items-center gap-1 rounded-lg px-2 transition-colors hover:bg-foreground/5",...$i.handleProps,children:[o.jsxs("button",{type:"button",onClick:()=>ne(ve.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",title:ve.path,children:[o.jsx(FI,{folded:ns}),o.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium text-foreground",title:ve.kind==="ssh"?`${ve.sshHost}:${ve.path}`:ve.path,children:[jo(ve),ve.kind==="ssh"&&o.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal text-muted-foreground",children:ve.sshConnectionName??ve.sshHost}),tt&&o.jsx("span",{className:"ml-1.5 font-normal text-[0.7857rem] text-subtle-foreground",children:h.find(Zn=>Zn.id===ve.groupId)?.name??r("Ungrouped")})]})]}),o.jsx("button",{type:"button",onClick:()=>Be(ve.id),className:"hidden shrink-0 rounded-md p-1 text-muted-foreground group-hover:block hover:bg-muted hover:text-foreground",title:r(Sr?"Unpin project":"Pin project"),children:Sr?o.jsx(au,{className:"h-3.5 w-3.5"}):o.jsx(Si,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",onClick:()=>{I(ve.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:o.jsx(fr,{className:"h-3.5 w-3.5"})}),o.jsx(FZ,{actions:lv}),(Sr||ns)&&o.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:[Sr&&o.jsx(Si,{className:"h-3.5 w-3.5"}),ns&&ct.length]})]}),o.jsx(rl,{initial:!1,children:!ns&&o.jsx(Es.div,{initial:"initial",animate:"animate",exit:"exit",variants:gp,className:"overflow-hidden",children:o.jsxs("div",{className:"flex flex-col",children:[Nt.slice(0,vo).map(Zn=>o.jsx(Es.div,{layout:nt?.type==="project"?!1:"position",transition:Yr,children:o.jsx(hS,{id:Zn,conversation:C[Zn],children:o.jsx(Oa,{id:Zn,conversation:C[Zn],active:E===Zn,switchHint:Oe(Zn,"project"),locale:a,nowTick:Qe,worktreeStatus:C[Zn].worktree?Q[Zn]:void 0,isolated:!!C[Zn].worktree,onSelect:D,onTogglePin:J,onToggleArchive:Bo=>{hn(Bo)},onCleanupWorktree:Bo=>{fn(Bo)},onMoveToWorktree:Bo=>{Ln(Bo)},onRemove:Bo=>{S(Bo)}})})},Zn)),!oe&&ct.length>kh&&o.jsxs("div",{className:"flex items-center gap-1 pl-6",children:[Ho.length>0&&o.jsxs(ao,{children:[o.jsx(lo,{render:o.jsx("button",{type:"button",onClick:()=>ae(Zn=>({...Zn,[ve.id]:kZ(Nt.length,Zn[ve.id]??0)})),className:lS,children:r("Show {{n}} more",{n:Ho.length})})}),o.jsx(co,{className:"min-w-36",children:o.jsxs(Ht,{onClick:()=>{Fn(Ho)},children:[o.jsx(ji,{}),r("Archive {{n}} conversations",{n:Ho.length})]})})]}),Fo>0&&o.jsx("button",{type:"button",onClick:()=>ae(Zn=>({...Zn,[ve.id]:_Z(Zn[ve.id]??0)})),className:lS,children:r("Collapse")})]}),Nt.length===0&&o.jsx("p",{className:"py-1.5 pl-8 text-xs text-subtle-foreground",children:r("No conversations yet")})]})})})]})}),o.jsx(co,{className:"min-w-40",children:Cu(lv)})]})},ve.id)};return tt&&!oe&&Ct.length===0?o.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:a2})}):!oe&&de.length>0&&Ct.length===0?o.jsx("p",{className:"px-2 py-1.5 text-xs text-subtle-foreground",children:r("No projects in this group yet")}):je===En&&h.length>0?o.jsxs("div",{children:[ft.length>0&&o.jsxs("div",{children:[o.jsx(za,{children:r("Pinned projects")}),o.jsx("div",{children:ft.map($)})]}),ze.map(ve=>{const ct=oe?!1:Ut[ve.groupId]===!0;return o.jsxs("div",{children:[o.jsx(MZ,{groupId:ve.groupId,name:ve.group?.name??r("Ungrouped"),emoji:ve.group?.emoji,color:ve.group?.color,count:ve.projects.length,folded:ct,sortable:ve.groupId!==cs,onToggle:()=>Z(ve.groupId),onEdit:ve.group?()=>$e({mode:"edit",id:ve.groupId}):void 0}),o.jsx(rl,{initial:!1,children:!ct&&o.jsx(Es.div,{initial:"initial",animate:"animate",exit:"exit",variants:gp,className:"overflow-hidden",children:o.jsx("div",{children:ve.projects.map($)})},`content-${ve.groupId}`)})]},ve.groupId)})]}):ft.length>0&&mt.length>0?o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{children:[o.jsx(za,{children:r("Pinned projects")}),o.jsx("div",{children:ft.map($)})]}),o.jsx("div",{children:mt.map($)})]}):Ct.map($)})()})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[o.jsx(Xk,{}),Kt>0&&o.jsx("button",{type:"button","data-slot":"archived-button",onClick:Zt,className:qi,title:`${r("Archived")} (${Kt})`,children:o.jsx(ji,{className:"h-4 w-4"})}),window.electronAPI.remote&&o.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:qi,title:r("Compact view"),children:o.jsx(Mv,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",onClick:()=>window.electronAPI.window.openSettings(),className:qi,title:r("Settings"),"aria-label":r("Settings"),children:o.jsx(ai,{className:"h-4 w-4"})}),d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:s,className:qi,title:_?`${r("Search anything")} (${_})`:r("Search anything"),children:o.jsx(Js,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",onClick:n,className:qi,title:r("Collapse sidebar"),children:o.jsx(Xg,{className:"h-4 w-4"})})]})]})]}),o.jsx(gn,{open:Ae,onOpenChange:Pe,children:o.jsxs(xn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[o.jsxs(vn,{children:[o.jsxs(bn,{className:"flex items-baseline gap-2",children:[r("Archived"),o.jsx("span",{className:"font-sans text-sm text-muted-foreground tabular-nums",children:Kt})]}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsxs(zu,{"data-size":"sm",children:[o.jsx(Gu,{children:o.jsx(Js,{})}),o.jsx(Fu,{value:Ge,placeholder:r("Search conversations..."),onChange:$=>yt($.target.value)})]}),o.jsx(uS,{open:At==="*",onOpenChange:$=>Rt($?"*":null),idsForDays:$=>Rv(k,C,$,Date.now()),onPick:($,ve)=>R({kind:"archived",days:$,conversationIds:ve}),className:"h-8 w-8 rounded-md opacity-100 hover:bg-muted"})]})]}),o.jsxs(Rn,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[Ft.length===0&&o.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:Ge.trim()?r("No matching conversations"):r("No conversations")}),Ft.map($=>{const ve=l.find(vt=>vt.id===$.projectId),ct=ve?jo(ve):r("Other");return o.jsxs("div",{children:[o.jsxs("div",{className:"group flex items-center gap-2 rounded-md pr-0.5 pl-2",children:[$.projectArchived&&o.jsx(xB,{className:"size-4 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"min-w-0 flex-1 truncate py-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:ct}),o.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:$.ids.length}),$.projectArchived?o.jsx("button",{type:"button",onClick:()=>De($.projectId),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",title:r("Unarchive project"),children:o.jsx(Al,{className:"h-3.5 w-3.5"})}):o.jsx(uS,{open:At===$.projectId,onOpenChange:vt=>Rt(vt?$.projectId:null),idsForDays:vt=>Rv(k,C,vt,Date.now(),$.projectId),onPick:(vt,Nt)=>R({kind:"archived",days:vt,conversationIds:Nt,projectName:ct})})]}),o.jsx("div",{className:"flex flex-col",children:$.ids.map(vt=>o.jsx(Es.div,{layout:"position",transition:Yr,children:o.jsx(Oa,{id:vt,conversation:C[vt],active:E===vt,locale:a,nowTick:Qe,worktreeStatus:C[vt].worktree?Q[vt]:void 0,isolated:!!C[vt].worktree,menuZIndex:yn.DROPDOWN_IN_MODAL,onSelect:Nt=>{D(Nt),Pe(!1)},onTogglePin:J,onToggleArchive:Nt=>{hn(Nt)},onCleanupWorktree:Nt=>{fn(Nt)},onMoveToWorktree:Nt=>{Ln(Nt)},onRemove:Nt=>{S(Nt)}})},vt))})]},$.projectId)})]})]})}),o.jsx(pZ,{open:Mt,onOpenChange:Gt,onAdd:cn,groups:h,defaultGroupId:Et}),o.jsx(yZ,{open:ge!==null,group:ge?.mode==="edit"?h.find($=>$.id===ge.id)??null:null,projects:de.filter($=>!X.includes($.id)),onOpenChange:$=>{$||$e(null)},onSave:$=>{if(ge?.mode==="edit"){f(ge.id,$);return}const ve=p($);for(const ct of $.projectIds??[])v(ct,ve.id)},onDelete:ge?.mode==="edit"?()=>{const $=ge.id;x($),Ue===$&&Ne(En)}:void 0}),o.jsx(CZ,{open:it!==null,project:l.find($=>$.id===it)??null,onOpenChange:$=>{$||xt(null)}}),o.jsx(SZ,{project:Bn,onClose:()=>P(null)}),o.jsx(hs,{open:Dt!==null,onOpenChange:$=>{$||Yt(null)},title:Dt?.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:Wn(Dt?.status)}),confirmLabel:Dt?.kind==="archive"?r("Archive"):r("Clean up"),onConfirm:()=>{Dt&&_n(Dt.id,Dt.kind==="archive")}}),o.jsx(hs,{open:Xt!==null,onOpenChange:$=>{$||Nn(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(!Xt)return;const $=Xt;Nn(null),Ln($,!0)}}),o.jsx(hs,{open:M!==null,onOpenChange:$=>{$||R(null)},title:M?.kind==="project"?r("Remove project?"):M?.kind==="archived"?r("Delete archived conversations?"):r("Delete conversation?"),description:M?.kind==="project"?r('"{{name}}" and its {{count}} conversations will be removed from the list.',{name:M.project.name,count:M.conversationIds.length}):M?.kind==="archived"?M.days===0?M.projectName?r('All {{count}} archived conversations in "{{name}}" will be removed from the list.',{count:M.conversationIds.length,name:M.projectName}):r("All {{count}} archived conversations will be removed from the list.",{count:M.conversationIds.length}):M.projectName?r('{{count}} conversations in "{{name}}" archived more than {{days}} days ago will be removed from the list.',{count:M.conversationIds.length,days:M.days,name:M.projectName}):r("{{count}} conversations archived more than {{days}} days ago will be removed from the list.",{count:M.conversationIds.length,days:M.days}):M?.kind==="conversation"&&M.worktreeWarning?r("Pending work: {{warning}}. This conversation will be removed. Its worktree directory and uncommitted changes are removed only when no other sessions use it. The branch is kept.",{warning:M.worktreeWarning}):r("This conversation will be removed from the list."),confirmLabel:r("Remove"),onConfirm:()=>{if(M)if(M.kind==="project"){for(const $ of M.conversationIds)W($);N(M.project.id)}else if(M.kind==="archived")for(const $ of M.conversationIds)W($);else W(M.id)}}),Fs.createPortal(o.jsx(y5,{dropAnimation:null,children:nt?.type==="project"?o.jsx(LZ,{projectId:nt.projectId,name:RZ(l,nt.projectId,nt.name),folded:V[nt.projectId]===!0,revealedExtra:G[nt.projectId]??0,width:e}):(nt?.type==="chat"||nt?.type==="workspace-file")&&o.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:[nt.type==="workspace-file"?o.jsx(go,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):o.jsx(Si,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:nt.type==="workspace-file"?nt.name:nt.title.split(`
97
- `)[0].trim()||r("New conversation")})]})}),document.body)]})}function MZ({groupId:e,name:t,emoji:n,color:s,count:i,folded:r,sortable:a,onToggle:l,onEdit:c}){const d=e===cs?Lx:gI(e),u=rc({id:d}),h=Ch({id:d,data:{type:"project-group",groupId:e},disabled:!a}),p=f=>{u.setNodeRef(f),h.setNodeRef(f)};return o.jsxs("div",{ref:p,style:{transform:Ri.Transform.toString(h.transform),transition:h.transition,opacity:h.isDragging?.4:void 0},className:q("group relative flex w-full select-none items-center rounded-md pt-3.5 pr-2.5 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground transition-colors hover:text-foreground",u.isOver&&"bg-foreground/5 text-foreground",a&&"cursor-grab"),...a?h.listeners:{},...a?h.attributes:{},children:[o.jsxs("button",{type:"button",onClick:l,onPointerDown:f=>f.stopPropagation(),className:"flex min-w-0 flex-1 items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 truncate text-left",children:t}),n&&o.jsx("span",{className:"shrink-0 text-sm leading-none",children:n}),s&&o.jsx("span",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:s}}),o.jsx(kn,{className:q("size-3 shrink-0 transition-[opacity,transform] duration-150",!r&&"rotate-90 opacity-0 group-hover:opacity-100")}),o.jsx("span",{className:q("ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",c&&"transition-opacity group-hover:opacity-0"),children:i})]}),c&&o.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:o.jsx(Xs,{className:"size-3.25"})})]})}function RZ(e,t,n){const s=e.find(i=>i.id===t);return s?jo(s):n}function LZ({projectId:e,name:t,folded:n,revealedExtra:s,width:i}){const{t:r}=te(),a=ie(h=>Rx(h.conversations)),l=ie(h=>h.order),c=Qa(l,a,e),d=n?[]:c.slice(0,_h(c.length,s)),u=Math.max(0,c.length-d.length);return o.jsxs("div",{className:"pointer-events-none rounded-lg border bg-background/95 py-0.5 shadow-float",style:{width:i??224},children:[o.jsxs("div",{className:"flex h-8 items-center gap-2 px-2 text-[0.9286rem] font-medium",children:[o.jsx(FI,{folded:n}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:t})]}),!n&&o.jsxs("div",{className:"flex flex-col",children:[d.map(h=>{const p=a[h];return p?o.jsxs("div",{className:"flex h-8 items-center gap-2 px-2 text-[0.9286rem] text-foreground/88",children:[o.jsx(HI,{conversation:p}),o.jsx("span",{className:"min-w-0 truncate",children:p.title||r("New conversation")})]},h):null}),c.length>kh&&o.jsxs("div",{className:"flex items-center gap-1",children:[u>0&&o.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&&o.jsx("div",{className:"flex-1 rounded-lg py-1 text-center text-xs text-muted-foreground",children:r("Collapse")})]}),c.length===0&&o.jsx("p",{className:"py-1.5 pl-8 text-xs text-muted-foreground",children:r("No conversations yet")})]})]})}function OZ({project:e,activitySorted:t=!1,children:n}){const{setNodeRef:s,transform:i,transition:r,listeners:a,isDragging:l}=Ch({id:mI(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:Ri.Transform.toString(i),transition:r,opacity:l?.4:void 0},handleProps:a??{}})}function uS({open:e,onOpenChange:t,idsForDays:n,onPick:s,className:i}){const{t:r}=te();return o.jsxs(zi,{open:e,onOpenChange:t,children:[o.jsx(Gi,{className:q("flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive",e&&"opacity-100",i),title:r("Clean up archived"),"aria-label":r("Clean up archived"),children:o.jsx(rg,{className:"h-3.5 w-3.5"})}),o.jsxs(Fi,{align:"end",className:"min-w-40",zIndex:yn.DROPDOWN_IN_MODAL,children:[AZ.map(a=>{const l=n(a);return o.jsx(dn,{variant:"destructive",disabled:l.length===0,onClick:()=>s(a,l),children:r("Older than {{days}} days",{days:a})},a)}),(()=>{const a=n(0);return o.jsx(dn,{variant:"destructive",disabled:a.length===0,onClick:()=>s(0,a),children:r("Delete all archived")})})()]})]})}function zZ({id:e,conversation:t,children:n}){const{setNodeRef:s,transform:i,transition:r,listeners:a,isDragging:l}=Ch({id:xI(e),data:{type:"chat",conversationId:e,title:t.title,sessionFile:t.sessionFile,pinned:t.pinned===!0}});return o.jsx("div",{ref:s,...a,style:{transform:Ri.Transform.toString(i),transition:r,opacity:l?.4:void 0},children:n})}function hS({id:e,conversation:t,children:n,dragId:s}){const{setNodeRef:i,listeners:r,isDragging:a}=gg({id:s??vX(e),data:{type:"chat",conversationId:e,title:t.title,sessionFile:t.sessionFile,pinned:t.pinned===!0}});return o.jsx("div",{ref:i,...r,style:{opacity:a?.4:void 0},children:n})}function pS({children:e,...t}){const{setNodeRef:n,isOver:s,active:i}=rc({id:fI}),r=i?.data.current?.type==="chat";return o.jsx("div",{ref:n,className:q("rounded-lg",s&&r&&"bg-brand/8 ring-1 ring-brand/40"),...t,children:e})}function Oa({id:e,conversation:t,active:n,locale:s,nowTick:i,hoverTitle:r,subtitle:a,isolated:l,worktreeStatus:c,switchHint:d,menuZIndex:u,onSelect:h,onTogglePin:p,onToggleArchive:f,onCleanupWorktree:x,onMoveToWorktree:g,onRemove:v}){const{t:w}=te(),y=xe(V=>V.projects.some(H=>H.id===t.projectId&&H.kind!=="ssh")),b=xe(V=>V.projects.some(H=>H.id===t.projectId&&H.kind==="scratch")),[_,j]=m.useState(!1),N=ie(V=>V.conversations[e]?.worktree),C=ie(V=>!!V.conversations[e]?.workspaceMigrating),k=ie(V=>V.conversations[e]?.worktreeMissing),[E,I]=m.useState(!1),[T,A]=m.useState(null),D=E||C||t.spawning||t.status==="running"||t.reloading===!0,W=async()=>{if(!D){I(!0);try{await ie.getState().newConversation(t.projectId,{worktreeFromConversationId:e})||We({type:"error",title:w("Failed to create conversation")})}catch(V){We({type:"error",title:w("Failed to create conversation"),description:String(V)})}finally{I(!1)}}},J=t.pinned===!0,O=t.archived===!0,B=J?au:Si,L=t.title||w("New conversation"),se=t.forkedFromConversationId?ie.getState().conversations[t.forkedFromConversationId]?.title:void 0,Q=o.jsxs("div",{"data-slot":"conversation-row","data-pinned":J?"true":"false",className:q("group flex h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-[0.9286rem] transition-colors",n?"bg-foreground/[0.075] text-foreground dark:bg-foreground/10":"text-foreground/88 hover:bg-foreground/5 hover:text-foreground"),onClick:()=>{_||h(e)},onDoubleClick:V=>{V.preventDefault(),V.stopPropagation(),j(!0)},onKeyDown:V=>{V.key==="Enter"&&!_&&h(e)},role:"button",tabIndex:0,title:r,children:[o.jsx(HI,{conversation:t}),o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[se&&o.jsx("span",{className:"max-w-1/3 truncate text-[0.7857rem] text-subtle-foreground",children:w("Branched from {{title}}",{title:se})}),_?o.jsx(wI,{title:L,onCommit:V=>{ie.getState().renameConversation(e,V),j(!1)},onCancel:()=>j(!1)}):o.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[L,a&&o.jsx("span",{className:"ml-1.5 text-[0.7857rem] text-subtle-foreground",children:a})]})]}),l&&N&&o.jsx(WJ,{worktree:N,status:c}),o.jsx(EZ,{conversationId:e}),!_&&o.jsx(GZ,{pending:t.titleSummaryPending,error:t.titleSummaryError,onRetry:()=>ie.getState().retryTitleSummary(e)}),!_&&(d?o.jsx("span",{className:"shrink-0 text-[0.7857rem] text-subtle-foreground tabular-nums",children:d}):o.jsxs(o.Fragment,{children:[J&&!O&&o.jsx(Si,{className:"h-3 w-3 shrink-0 text-subtle-foreground group-hover:hidden","aria-hidden":!0}),o.jsx("span",{className:"shrink-0 text-[0.7857rem] text-subtle-foreground tabular-nums group-hover:hidden",children:Do(t.lastActiveAt??t.createdAt,s,i)}),!O&&o.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),p(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:w(J?"Unpin":"Pin"),children:o.jsx(B,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),f(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:w(O?"Unarchive":"Archive"),children:O?o.jsx(Al,{className:"h-3.5 w-3.5"}):o.jsx(ji,{className:"h-3.5 w-3.5"})}),O&&o.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),v(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-destructive",title:w("Delete"),children:o.jsx(di,{className:"h-3.5 w-3.5"})})]}))]})]});return o.jsxs(o.Fragment,{children:[o.jsxs(ao,{children:[o.jsx(lo,{render:Q}),o.jsxs(co,{className:"min-w-36",zIndex:u,children:[o.jsxs(Ht,{onClick:()=>j(!0),children:[o.jsx(Xs,{}),w("Rename")]}),o.jsxs(Ht,{disabled:t.reloading===!0||t.spawning,onClick:()=>{yI(e,w)},children:[o.jsx(Mo,{className:t.reloading?"animate-spin":void 0}),w("Reload conversation")]}),o.jsxs(Ht,{disabled:D,onClick:()=>{FX(e,w)},children:[o.jsx(qm,{}),w("Restart conversation (reload settings)")]}),y&&o.jsxs(Ht,{disabled:C||k||c?.exists===!1,onClick:()=>{Bx({projectId:t.projectId,conversationId:e},w)},children:[o.jsx(Qs,{}),w(Hx(window.electronAPI.env.platform))]}),!O&&o.jsxs(Ht,{onClick:()=>p(e),children:[o.jsx(B,{}),w(J?"Unpin":"Pin")]}),o.jsxs(Ht,{onClick:()=>f(e),children:[O?o.jsx(Al,{}):o.jsx(ji,{}),w(O?"Unarchive":"Archive")]}),N&&o.jsxs(o.Fragment,{children:[o.jsxs(Ht,{disabled:D||k||c?.exists===!1,onClick:()=>{W()},children:[E?o.jsx(Vt,{className:"animate-spin"}):o.jsx(fr,{}),w("New conversation in this worktree")]}),o.jsxs(Ht,{disabled:D||k||c?.exists===!1,onClick:()=>A({conversationId:e,worktree:N}),children:[o.jsx(Xs,{}),w("Rename worktree")]})]}),!O&&(l?x&&o.jsxs(Ht,{disabled:D,onClick:()=>x(e),children:[o.jsx(rg,{}),w("Clean up worktree")]}):g&&y&&!b&&o.jsxs(Ht,{disabled:D,onClick:()=>g(e),children:[o.jsx(CB,{}),w("Move to worktree")]})),o.jsx(tg,{}),o.jsxs(Ht,{variant:"destructive",onClick:()=>v(e),children:[o.jsx(di,{}),w("Delete")]})]})]}),o.jsx(II,{entity:T,onClose:()=>A(null)})]})}function GZ({pending:e,error:t,onRetry:n}){const{t:s}=te();return e?o.jsxs(Qp,{children:[o.jsx(ef,{render:o.jsx("span",{role:"status",className:"shrink-0 text-muted-foreground/60","aria-label":s("Summarizing title")}),children:o.jsx(Vt,{className:"h-3 w-3 animate-spin"})}),o.jsx(tf,{side:"right",children:s("Summarizing title")})]}):t?o.jsxs(Qp,{children:[o.jsx(ef,{render:o.jsx("button",{type:"button","aria-label":s("Title summary failed"),className:"shrink-0 rounded p-0.5 text-destructive hover:text-destructive/80",onClick:i=>{i.stopPropagation(),n()}}),children:o.jsx(ur,{className:"h-3 w-3"})}),o.jsxs(tf,{side:"right",className:"max-w-72",children:[o.jsx("p",{className:"font-medium",children:s("Title summary failed")}),o.jsx("p",{className:"mt-0.5 break-all text-muted-foreground",children:t}),o.jsx("p",{className:"mt-1 text-muted-foreground/70",children:s("Click to retry")})]})]}):null}function fS(e,t){const n=e.find(s=>s.id===t);return n?jo(n):void 0}function Lp({emoji:e,color:t}){return e?o.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-sm leading-none",children:e}):o.jsx(yB,{style:t?{color:t}:void 0})}function Cu(e,t="context"){return e.map(n=>n.kind==="separator"?t==="menu"?o.jsx(pa,{},n.key):o.jsx(tg,{},n.key):n.kind==="submenu"?t==="menu"?o.jsxs(dk,{children:[o.jsxs(uk,{children:[n.icon,n.label]}),o.jsx(hk,{className:"min-w-40",children:Cu(n.items,"menu")})]},n.key):o.jsxs(kk,{children:[o.jsxs(_k,{children:[n.icon,n.label]}),o.jsx(jk,{className:"min-w-40",children:Cu(n.items)})]},n.key):t==="menu"?o.jsxs(dn,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key):o.jsxs(Ht,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key))}function FZ({actions:e}){const{t}=te();return o.jsxs(zi,{children:[o.jsx(Gi,{"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:o.jsx(sh,{className:"h-3.5 w-3.5"})}),o.jsx(Fi,{align:"end",className:"min-w-40",children:Cu(e,"menu")})]})}function za({children:e,actions:t}){return o.jsxs("div",{className:"group flex items-center gap-1 pt-3.5 pr-1 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate",children:e}),t]})}function FI({folded:e}){return o.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-subtle-foreground",children:o.jsx(kn,{className:q("size-3.5 transition-transform duration-150",!e&&"rotate-90")})})}function HI({conversation:e}){const t=(e.pendingApprovals?.length??0)>0||(e.pendingCapabilityAsks?.length??0)>0?"attention":Uk({status:e.status,spawning:e.spawning,unread:e.unread,pendingAskCount:e.pendingAsks?.length??0,hasRunningChild:e.hasRunningChild});return o.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:t!=="idle"&&o.jsx(Sh,{tone:t,size:"sm"})})}function HZ(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 Op={exports:{}};const BZ={},VZ=Object.freeze(Object.defineProperty({__proto__:null,default:BZ},Symbol.toStringTag,{value:"Module"})),$Z=d2(VZ);var mS;function WZ(){return mS||(mS=1,(function(e){(function(t){var n=function(P){var M,R=new Float64Array(16);if(P)for(M=0;M<P.length;M++)R[M]=P[M];return R},s=function(){throw new Error("no PRNG")},i=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 x(P,M,R,S){P[M]=R>>24&255,P[M+1]=R>>16&255,P[M+2]=R>>8&255,P[M+3]=R&255,P[M+4]=S>>24&255,P[M+5]=S>>16&255,P[M+6]=S>>8&255,P[M+7]=S&255}function g(P,M,R,S,G){var ae,ce=0;for(ae=0;ae<G;ae++)ce|=P[M+ae]^R[S+ae];return(1&ce-1>>>8)-1}function v(P,M,R,S){return g(P,M,R,S,16)}function w(P,M,R,S){return g(P,M,R,S,32)}function y(P,M,R,S){for(var G=S[0]&255|(S[1]&255)<<8|(S[2]&255)<<16|(S[3]&255)<<24,ae=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,ce=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,Ie=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,He=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,ht=S[4]&255|(S[5]&255)<<8|(S[6]&255)<<16|(S[7]&255)<<24,Qe=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,qt=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,lt=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,bt=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,kt=S[8]&255|(S[9]&255)<<8|(S[10]&255)<<16|(S[11]&255)<<24,_t=R[16]&255|(R[17]&255)<<8|(R[18]&255)<<16|(R[19]&255)<<24,jt=R[20]&255|(R[21]&255)<<8|(R[22]&255)<<16|(R[23]&255)<<24,oe=R[24]&255|(R[25]&255)<<8|(R[26]&255)<<16|(R[27]&255)<<24,Te=R[28]&255|(R[29]&255)<<8|(R[30]&255)<<16|(R[31]&255)<<24,Xe=S[12]&255|(S[13]&255)<<8|(S[14]&255)<<16|(S[15]&255)<<24,Le=G,Ze=ae,qe=ce,st=Ie,at=He,et=ht,ye=Qe,Se=qt,Oe=lt,Ae=bt,Pe=kt,Ge=_t,yt=jt,At=oe,Rt=Te,Lt=Xe,ee,Ft=0;Ft<20;Ft+=2)ee=Le+yt|0,at^=ee<<7|ee>>>25,ee=at+Le|0,Oe^=ee<<9|ee>>>23,ee=Oe+at|0,yt^=ee<<13|ee>>>19,ee=yt+Oe|0,Le^=ee<<18|ee>>>14,ee=et+Ze|0,Ae^=ee<<7|ee>>>25,ee=Ae+et|0,At^=ee<<9|ee>>>23,ee=At+Ae|0,Ze^=ee<<13|ee>>>19,ee=Ze+At|0,et^=ee<<18|ee>>>14,ee=Pe+ye|0,Rt^=ee<<7|ee>>>25,ee=Rt+Pe|0,qe^=ee<<9|ee>>>23,ee=qe+Rt|0,ye^=ee<<13|ee>>>19,ee=ye+qe|0,Pe^=ee<<18|ee>>>14,ee=Lt+Ge|0,st^=ee<<7|ee>>>25,ee=st+Lt|0,Se^=ee<<9|ee>>>23,ee=Se+st|0,Ge^=ee<<13|ee>>>19,ee=Ge+Se|0,Lt^=ee<<18|ee>>>14,ee=Le+st|0,Ze^=ee<<7|ee>>>25,ee=Ze+Le|0,qe^=ee<<9|ee>>>23,ee=qe+Ze|0,st^=ee<<13|ee>>>19,ee=st+qe|0,Le^=ee<<18|ee>>>14,ee=et+at|0,ye^=ee<<7|ee>>>25,ee=ye+et|0,Se^=ee<<9|ee>>>23,ee=Se+ye|0,at^=ee<<13|ee>>>19,ee=at+Se|0,et^=ee<<18|ee>>>14,ee=Pe+Ae|0,Ge^=ee<<7|ee>>>25,ee=Ge+Pe|0,Oe^=ee<<9|ee>>>23,ee=Oe+Ge|0,Ae^=ee<<13|ee>>>19,ee=Ae+Oe|0,Pe^=ee<<18|ee>>>14,ee=Lt+Rt|0,yt^=ee<<7|ee>>>25,ee=yt+Lt|0,At^=ee<<9|ee>>>23,ee=At+yt|0,Rt^=ee<<13|ee>>>19,ee=Rt+At|0,Lt^=ee<<18|ee>>>14;Le=Le+G|0,Ze=Ze+ae|0,qe=qe+ce|0,st=st+Ie|0,at=at+He|0,et=et+ht|0,ye=ye+Qe|0,Se=Se+qt|0,Oe=Oe+lt|0,Ae=Ae+bt|0,Pe=Pe+kt|0,Ge=Ge+_t|0,yt=yt+jt|0,At=At+oe|0,Rt=Rt+Te|0,Lt=Lt+Xe|0,P[0]=Le>>>0&255,P[1]=Le>>>8&255,P[2]=Le>>>16&255,P[3]=Le>>>24&255,P[4]=Ze>>>0&255,P[5]=Ze>>>8&255,P[6]=Ze>>>16&255,P[7]=Ze>>>24&255,P[8]=qe>>>0&255,P[9]=qe>>>8&255,P[10]=qe>>>16&255,P[11]=qe>>>24&255,P[12]=st>>>0&255,P[13]=st>>>8&255,P[14]=st>>>16&255,P[15]=st>>>24&255,P[16]=at>>>0&255,P[17]=at>>>8&255,P[18]=at>>>16&255,P[19]=at>>>24&255,P[20]=et>>>0&255,P[21]=et>>>8&255,P[22]=et>>>16&255,P[23]=et>>>24&255,P[24]=ye>>>0&255,P[25]=ye>>>8&255,P[26]=ye>>>16&255,P[27]=ye>>>24&255,P[28]=Se>>>0&255,P[29]=Se>>>8&255,P[30]=Se>>>16&255,P[31]=Se>>>24&255,P[32]=Oe>>>0&255,P[33]=Oe>>>8&255,P[34]=Oe>>>16&255,P[35]=Oe>>>24&255,P[36]=Ae>>>0&255,P[37]=Ae>>>8&255,P[38]=Ae>>>16&255,P[39]=Ae>>>24&255,P[40]=Pe>>>0&255,P[41]=Pe>>>8&255,P[42]=Pe>>>16&255,P[43]=Pe>>>24&255,P[44]=Ge>>>0&255,P[45]=Ge>>>8&255,P[46]=Ge>>>16&255,P[47]=Ge>>>24&255,P[48]=yt>>>0&255,P[49]=yt>>>8&255,P[50]=yt>>>16&255,P[51]=yt>>>24&255,P[52]=At>>>0&255,P[53]=At>>>8&255,P[54]=At>>>16&255,P[55]=At>>>24&255,P[56]=Rt>>>0&255,P[57]=Rt>>>8&255,P[58]=Rt>>>16&255,P[59]=Rt>>>24&255,P[60]=Lt>>>0&255,P[61]=Lt>>>8&255,P[62]=Lt>>>16&255,P[63]=Lt>>>24&255}function b(P,M,R,S){for(var G=S[0]&255|(S[1]&255)<<8|(S[2]&255)<<16|(S[3]&255)<<24,ae=R[0]&255|(R[1]&255)<<8|(R[2]&255)<<16|(R[3]&255)<<24,ce=R[4]&255|(R[5]&255)<<8|(R[6]&255)<<16|(R[7]&255)<<24,Ie=R[8]&255|(R[9]&255)<<8|(R[10]&255)<<16|(R[11]&255)<<24,He=R[12]&255|(R[13]&255)<<8|(R[14]&255)<<16|(R[15]&255)<<24,ht=S[4]&255|(S[5]&255)<<8|(S[6]&255)<<16|(S[7]&255)<<24,Qe=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,qt=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,lt=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,bt=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,kt=S[8]&255|(S[9]&255)<<8|(S[10]&255)<<16|(S[11]&255)<<24,_t=R[16]&255|(R[17]&255)<<8|(R[18]&255)<<16|(R[19]&255)<<24,jt=R[20]&255|(R[21]&255)<<8|(R[22]&255)<<16|(R[23]&255)<<24,oe=R[24]&255|(R[25]&255)<<8|(R[26]&255)<<16|(R[27]&255)<<24,Te=R[28]&255|(R[29]&255)<<8|(R[30]&255)<<16|(R[31]&255)<<24,Xe=S[12]&255|(S[13]&255)<<8|(S[14]&255)<<16|(S[15]&255)<<24,Le=G,Ze=ae,qe=ce,st=Ie,at=He,et=ht,ye=Qe,Se=qt,Oe=lt,Ae=bt,Pe=kt,Ge=_t,yt=jt,At=oe,Rt=Te,Lt=Xe,ee,Ft=0;Ft<20;Ft+=2)ee=Le+yt|0,at^=ee<<7|ee>>>25,ee=at+Le|0,Oe^=ee<<9|ee>>>23,ee=Oe+at|0,yt^=ee<<13|ee>>>19,ee=yt+Oe|0,Le^=ee<<18|ee>>>14,ee=et+Ze|0,Ae^=ee<<7|ee>>>25,ee=Ae+et|0,At^=ee<<9|ee>>>23,ee=At+Ae|0,Ze^=ee<<13|ee>>>19,ee=Ze+At|0,et^=ee<<18|ee>>>14,ee=Pe+ye|0,Rt^=ee<<7|ee>>>25,ee=Rt+Pe|0,qe^=ee<<9|ee>>>23,ee=qe+Rt|0,ye^=ee<<13|ee>>>19,ee=ye+qe|0,Pe^=ee<<18|ee>>>14,ee=Lt+Ge|0,st^=ee<<7|ee>>>25,ee=st+Lt|0,Se^=ee<<9|ee>>>23,ee=Se+st|0,Ge^=ee<<13|ee>>>19,ee=Ge+Se|0,Lt^=ee<<18|ee>>>14,ee=Le+st|0,Ze^=ee<<7|ee>>>25,ee=Ze+Le|0,qe^=ee<<9|ee>>>23,ee=qe+Ze|0,st^=ee<<13|ee>>>19,ee=st+qe|0,Le^=ee<<18|ee>>>14,ee=et+at|0,ye^=ee<<7|ee>>>25,ee=ye+et|0,Se^=ee<<9|ee>>>23,ee=Se+ye|0,at^=ee<<13|ee>>>19,ee=at+Se|0,et^=ee<<18|ee>>>14,ee=Pe+Ae|0,Ge^=ee<<7|ee>>>25,ee=Ge+Pe|0,Oe^=ee<<9|ee>>>23,ee=Oe+Ge|0,Ae^=ee<<13|ee>>>19,ee=Ae+Oe|0,Pe^=ee<<18|ee>>>14,ee=Lt+Rt|0,yt^=ee<<7|ee>>>25,ee=yt+Lt|0,At^=ee<<9|ee>>>23,ee=At+yt|0,Rt^=ee<<13|ee>>>19,ee=Rt+At|0,Lt^=ee<<18|ee>>>14;P[0]=Le>>>0&255,P[1]=Le>>>8&255,P[2]=Le>>>16&255,P[3]=Le>>>24&255,P[4]=et>>>0&255,P[5]=et>>>8&255,P[6]=et>>>16&255,P[7]=et>>>24&255,P[8]=Pe>>>0&255,P[9]=Pe>>>8&255,P[10]=Pe>>>16&255,P[11]=Pe>>>24&255,P[12]=Lt>>>0&255,P[13]=Lt>>>8&255,P[14]=Lt>>>16&255,P[15]=Lt>>>24&255,P[16]=ye>>>0&255,P[17]=ye>>>8&255,P[18]=ye>>>16&255,P[19]=ye>>>24&255,P[20]=Se>>>0&255,P[21]=Se>>>8&255,P[22]=Se>>>16&255,P[23]=Se>>>24&255,P[24]=Oe>>>0&255,P[25]=Oe>>>8&255,P[26]=Oe>>>16&255,P[27]=Oe>>>24&255,P[28]=Ae>>>0&255,P[29]=Ae>>>8&255,P[30]=Ae>>>16&255,P[31]=Ae>>>24&255}function _(P,M,R,S){y(P,M,R,S)}function j(P,M,R,S){b(P,M,R,S)}var N=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function C(P,M,R,S,G,ae,ce){var Ie=new Uint8Array(16),He=new Uint8Array(64),ht,Qe;for(Qe=0;Qe<16;Qe++)Ie[Qe]=0;for(Qe=0;Qe<8;Qe++)Ie[Qe]=ae[Qe];for(;G>=64;){for(_(He,Ie,ce,N),Qe=0;Qe<64;Qe++)P[M+Qe]=R[S+Qe]^He[Qe];for(ht=1,Qe=8;Qe<16;Qe++)ht=ht+(Ie[Qe]&255)|0,Ie[Qe]=ht&255,ht>>>=8;G-=64,M+=64,S+=64}if(G>0)for(_(He,Ie,ce,N),Qe=0;Qe<G;Qe++)P[M+Qe]=R[S+Qe]^He[Qe];return 0}function k(P,M,R,S,G){var ae=new Uint8Array(16),ce=new Uint8Array(64),Ie,He;for(He=0;He<16;He++)ae[He]=0;for(He=0;He<8;He++)ae[He]=S[He];for(;R>=64;){for(_(ce,ae,G,N),He=0;He<64;He++)P[M+He]=ce[He];for(Ie=1,He=8;He<16;He++)Ie=Ie+(ae[He]&255)|0,ae[He]=Ie&255,Ie>>>=8;R-=64,M+=64}if(R>0)for(_(ce,ae,G,N),He=0;He<R;He++)P[M+He]=ce[He];return 0}function E(P,M,R,S,G){var ae=new Uint8Array(32);j(ae,S,G,N);for(var ce=new Uint8Array(8),Ie=0;Ie<8;Ie++)ce[Ie]=S[Ie+16];return k(P,M,R,ce,ae)}function I(P,M,R,S,G,ae,ce){var Ie=new Uint8Array(32);j(Ie,ae,ce,N);for(var He=new Uint8Array(8),ht=0;ht<8;ht++)He[ht]=ae[ht+16];return C(P,M,R,S,G,He,Ie)}var T=function(P){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var M,R,S,G,ae,ce,Ie,He;M=P[0]&255|(P[1]&255)<<8,this.r[0]=M&8191,R=P[2]&255|(P[3]&255)<<8,this.r[1]=(M>>>13|R<<3)&8191,S=P[4]&255|(P[5]&255)<<8,this.r[2]=(R>>>10|S<<6)&7939,G=P[6]&255|(P[7]&255)<<8,this.r[3]=(S>>>7|G<<9)&8191,ae=P[8]&255|(P[9]&255)<<8,this.r[4]=(G>>>4|ae<<12)&255,this.r[5]=ae>>>1&8190,ce=P[10]&255|(P[11]&255)<<8,this.r[6]=(ae>>>14|ce<<2)&8191,Ie=P[12]&255|(P[13]&255)<<8,this.r[7]=(ce>>>11|Ie<<5)&8065,He=P[14]&255|(P[15]&255)<<8,this.r[8]=(Ie>>>8|He<<8)&8191,this.r[9]=He>>>5&127,this.pad[0]=P[16]&255|(P[17]&255)<<8,this.pad[1]=P[18]&255|(P[19]&255)<<8,this.pad[2]=P[20]&255|(P[21]&255)<<8,this.pad[3]=P[22]&255|(P[23]&255)<<8,this.pad[4]=P[24]&255|(P[25]&255)<<8,this.pad[5]=P[26]&255|(P[27]&255)<<8,this.pad[6]=P[28]&255|(P[29]&255)<<8,this.pad[7]=P[30]&255|(P[31]&255)<<8};T.prototype.blocks=function(P,M,R){for(var S=this.fin?0:2048,G,ae,ce,Ie,He,ht,Qe,qt,lt,bt,kt,_t,jt,oe,Te,Xe,Le,Ze,qe,st=this.h[0],at=this.h[1],et=this.h[2],ye=this.h[3],Se=this.h[4],Oe=this.h[5],Ae=this.h[6],Pe=this.h[7],Ge=this.h[8],yt=this.h[9],At=this.r[0],Rt=this.r[1],Lt=this.r[2],ee=this.r[3],Ft=this.r[4],Kt=this.r[5],Zt=this.r[6],Dt=this.r[7],Yt=this.r[8],Xt=this.r[9];R>=16;)G=P[M+0]&255|(P[M+1]&255)<<8,st+=G&8191,ae=P[M+2]&255|(P[M+3]&255)<<8,at+=(G>>>13|ae<<3)&8191,ce=P[M+4]&255|(P[M+5]&255)<<8,et+=(ae>>>10|ce<<6)&8191,Ie=P[M+6]&255|(P[M+7]&255)<<8,ye+=(ce>>>7|Ie<<9)&8191,He=P[M+8]&255|(P[M+9]&255)<<8,Se+=(Ie>>>4|He<<12)&8191,Oe+=He>>>1&8191,ht=P[M+10]&255|(P[M+11]&255)<<8,Ae+=(He>>>14|ht<<2)&8191,Qe=P[M+12]&255|(P[M+13]&255)<<8,Pe+=(ht>>>11|Qe<<5)&8191,qt=P[M+14]&255|(P[M+15]&255)<<8,Ge+=(Qe>>>8|qt<<8)&8191,yt+=qt>>>5|S,lt=0,bt=lt,bt+=st*At,bt+=at*(5*Xt),bt+=et*(5*Yt),bt+=ye*(5*Dt),bt+=Se*(5*Zt),lt=bt>>>13,bt&=8191,bt+=Oe*(5*Kt),bt+=Ae*(5*Ft),bt+=Pe*(5*ee),bt+=Ge*(5*Lt),bt+=yt*(5*Rt),lt+=bt>>>13,bt&=8191,kt=lt,kt+=st*Rt,kt+=at*At,kt+=et*(5*Xt),kt+=ye*(5*Yt),kt+=Se*(5*Dt),lt=kt>>>13,kt&=8191,kt+=Oe*(5*Zt),kt+=Ae*(5*Kt),kt+=Pe*(5*Ft),kt+=Ge*(5*ee),kt+=yt*(5*Lt),lt+=kt>>>13,kt&=8191,_t=lt,_t+=st*Lt,_t+=at*Rt,_t+=et*At,_t+=ye*(5*Xt),_t+=Se*(5*Yt),lt=_t>>>13,_t&=8191,_t+=Oe*(5*Dt),_t+=Ae*(5*Zt),_t+=Pe*(5*Kt),_t+=Ge*(5*Ft),_t+=yt*(5*ee),lt+=_t>>>13,_t&=8191,jt=lt,jt+=st*ee,jt+=at*Lt,jt+=et*Rt,jt+=ye*At,jt+=Se*(5*Xt),lt=jt>>>13,jt&=8191,jt+=Oe*(5*Yt),jt+=Ae*(5*Dt),jt+=Pe*(5*Zt),jt+=Ge*(5*Kt),jt+=yt*(5*Ft),lt+=jt>>>13,jt&=8191,oe=lt,oe+=st*Ft,oe+=at*ee,oe+=et*Lt,oe+=ye*Rt,oe+=Se*At,lt=oe>>>13,oe&=8191,oe+=Oe*(5*Xt),oe+=Ae*(5*Yt),oe+=Pe*(5*Dt),oe+=Ge*(5*Zt),oe+=yt*(5*Kt),lt+=oe>>>13,oe&=8191,Te=lt,Te+=st*Kt,Te+=at*Ft,Te+=et*ee,Te+=ye*Lt,Te+=Se*Rt,lt=Te>>>13,Te&=8191,Te+=Oe*At,Te+=Ae*(5*Xt),Te+=Pe*(5*Yt),Te+=Ge*(5*Dt),Te+=yt*(5*Zt),lt+=Te>>>13,Te&=8191,Xe=lt,Xe+=st*Zt,Xe+=at*Kt,Xe+=et*Ft,Xe+=ye*ee,Xe+=Se*Lt,lt=Xe>>>13,Xe&=8191,Xe+=Oe*Rt,Xe+=Ae*At,Xe+=Pe*(5*Xt),Xe+=Ge*(5*Yt),Xe+=yt*(5*Dt),lt+=Xe>>>13,Xe&=8191,Le=lt,Le+=st*Dt,Le+=at*Zt,Le+=et*Kt,Le+=ye*Ft,Le+=Se*ee,lt=Le>>>13,Le&=8191,Le+=Oe*Lt,Le+=Ae*Rt,Le+=Pe*At,Le+=Ge*(5*Xt),Le+=yt*(5*Yt),lt+=Le>>>13,Le&=8191,Ze=lt,Ze+=st*Yt,Ze+=at*Dt,Ze+=et*Zt,Ze+=ye*Kt,Ze+=Se*Ft,lt=Ze>>>13,Ze&=8191,Ze+=Oe*ee,Ze+=Ae*Lt,Ze+=Pe*Rt,Ze+=Ge*At,Ze+=yt*(5*Xt),lt+=Ze>>>13,Ze&=8191,qe=lt,qe+=st*Xt,qe+=at*Yt,qe+=et*Dt,qe+=ye*Zt,qe+=Se*Kt,lt=qe>>>13,qe&=8191,qe+=Oe*Ft,qe+=Ae*ee,qe+=Pe*Lt,qe+=Ge*Rt,qe+=yt*At,lt+=qe>>>13,qe&=8191,lt=(lt<<2)+lt|0,lt=lt+bt|0,bt=lt&8191,lt=lt>>>13,kt+=lt,st=bt,at=kt,et=_t,ye=jt,Se=oe,Oe=Te,Ae=Xe,Pe=Le,Ge=Ze,yt=qe,M+=16,R-=16;this.h[0]=st,this.h[1]=at,this.h[2]=et,this.h[3]=ye,this.h[4]=Se,this.h[5]=Oe,this.h[6]=Ae,this.h[7]=Pe,this.h[8]=Ge,this.h[9]=yt},T.prototype.finish=function(P,M){var R=new Uint16Array(10),S,G,ae,ce;if(this.leftover){for(ce=this.leftover,this.buffer[ce++]=1;ce<16;ce++)this.buffer[ce]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(S=this.h[1]>>>13,this.h[1]&=8191,ce=2;ce<10;ce++)this.h[ce]+=S,S=this.h[ce]>>>13,this.h[ce]&=8191;for(this.h[0]+=S*5,S=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=S,S=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=S,R[0]=this.h[0]+5,S=R[0]>>>13,R[0]&=8191,ce=1;ce<10;ce++)R[ce]=this.h[ce]+S,S=R[ce]>>>13,R[ce]&=8191;for(R[9]-=8192,G=(S^1)-1,ce=0;ce<10;ce++)R[ce]&=G;for(G=~G,ce=0;ce<10;ce++)this.h[ce]=this.h[ce]&G|R[ce];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,ae=this.h[0]+this.pad[0],this.h[0]=ae&65535,ce=1;ce<8;ce++)ae=(this.h[ce]+this.pad[ce]|0)+(ae>>>16)|0,this.h[ce]=ae&65535;P[M+0]=this.h[0]>>>0&255,P[M+1]=this.h[0]>>>8&255,P[M+2]=this.h[1]>>>0&255,P[M+3]=this.h[1]>>>8&255,P[M+4]=this.h[2]>>>0&255,P[M+5]=this.h[2]>>>8&255,P[M+6]=this.h[3]>>>0&255,P[M+7]=this.h[3]>>>8&255,P[M+8]=this.h[4]>>>0&255,P[M+9]=this.h[4]>>>8&255,P[M+10]=this.h[5]>>>0&255,P[M+11]=this.h[5]>>>8&255,P[M+12]=this.h[6]>>>0&255,P[M+13]=this.h[6]>>>8&255,P[M+14]=this.h[7]>>>0&255,P[M+15]=this.h[7]>>>8&255},T.prototype.update=function(P,M,R){var S,G;if(this.leftover){for(G=16-this.leftover,G>R&&(G=R),S=0;S<G;S++)this.buffer[this.leftover+S]=P[M+S];if(R-=G,M+=G,this.leftover+=G,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(R>=16&&(G=R-R%16,this.blocks(P,M,G),M+=G,R-=G),R){for(S=0;S<R;S++)this.buffer[this.leftover+S]=P[M+S];this.leftover+=R}};function A(P,M,R,S,G,ae){var ce=new T(ae);return ce.update(R,S,G),ce.finish(P,M),0}function D(P,M,R,S,G,ae){var ce=new Uint8Array(16);return A(ce,0,R,S,G,ae),v(P,M,ce,0)}function W(P,M,R,S,G){var ae;if(R<32)return-1;for(I(P,0,M,0,R,S,G),A(P,16,P,32,R-32,P),ae=0;ae<16;ae++)P[ae]=0;return 0}function J(P,M,R,S,G){var ae,ce=new Uint8Array(32);if(R<32||(E(ce,0,32,S,G),D(M,16,M,32,R-32,ce)!==0))return-1;for(I(P,0,M,0,R,S,G),ae=0;ae<32;ae++)P[ae]=0;return 0}function O(P,M){var R;for(R=0;R<16;R++)P[R]=M[R]|0}function B(P){var M,R,S=1;for(M=0;M<16;M++)R=P[M]+S+65535,S=Math.floor(R/65536),P[M]=R-S*65536;P[0]+=S-1+37*(S-1)}function L(P,M,R){for(var S,G=~(R-1),ae=0;ae<16;ae++)S=G&(P[ae]^M[ae]),P[ae]^=S,M[ae]^=S}function se(P,M){var R,S,G,ae=n(),ce=n();for(R=0;R<16;R++)ce[R]=M[R];for(B(ce),B(ce),B(ce),S=0;S<2;S++){for(ae[0]=ce[0]-65517,R=1;R<15;R++)ae[R]=ce[R]-65535-(ae[R-1]>>16&1),ae[R-1]&=65535;ae[15]=ce[15]-32767-(ae[14]>>16&1),G=ae[15]>>16&1,ae[14]&=65535,L(ce,ae,1-G)}for(R=0;R<16;R++)P[2*R]=ce[R]&255,P[2*R+1]=ce[R]>>8}function Q(P,M){var R=new Uint8Array(32),S=new Uint8Array(32);return se(R,P),se(S,M),w(R,0,S,0)}function V(P){var M=new Uint8Array(32);return se(M,P),M[0]&1}function H(P,M){var R;for(R=0;R<16;R++)P[R]=M[2*R]+(M[2*R+1]<<8);P[15]&=32767}function ne(P,M,R){for(var S=0;S<16;S++)P[S]=M[S]+R[S]}function he(P,M,R){for(var S=0;S<16;S++)P[S]=M[S]-R[S]}function pe(P,M,R){var S,G,ae=0,ce=0,Ie=0,He=0,ht=0,Qe=0,qt=0,lt=0,bt=0,kt=0,_t=0,jt=0,oe=0,Te=0,Xe=0,Le=0,Ze=0,qe=0,st=0,at=0,et=0,ye=0,Se=0,Oe=0,Ae=0,Pe=0,Ge=0,yt=0,At=0,Rt=0,Lt=0,ee=R[0],Ft=R[1],Kt=R[2],Zt=R[3],Dt=R[4],Yt=R[5],Xt=R[6],Nn=R[7],nn=R[8],_n=R[9],fn=R[10],hn=R[11],Fn=R[12],Ln=R[13],Wn=R[14],$=R[15];S=M[0],ae+=S*ee,ce+=S*Ft,Ie+=S*Kt,He+=S*Zt,ht+=S*Dt,Qe+=S*Yt,qt+=S*Xt,lt+=S*Nn,bt+=S*nn,kt+=S*_n,_t+=S*fn,jt+=S*hn,oe+=S*Fn,Te+=S*Ln,Xe+=S*Wn,Le+=S*$,S=M[1],ce+=S*ee,Ie+=S*Ft,He+=S*Kt,ht+=S*Zt,Qe+=S*Dt,qt+=S*Yt,lt+=S*Xt,bt+=S*Nn,kt+=S*nn,_t+=S*_n,jt+=S*fn,oe+=S*hn,Te+=S*Fn,Xe+=S*Ln,Le+=S*Wn,Ze+=S*$,S=M[2],Ie+=S*ee,He+=S*Ft,ht+=S*Kt,Qe+=S*Zt,qt+=S*Dt,lt+=S*Yt,bt+=S*Xt,kt+=S*Nn,_t+=S*nn,jt+=S*_n,oe+=S*fn,Te+=S*hn,Xe+=S*Fn,Le+=S*Ln,Ze+=S*Wn,qe+=S*$,S=M[3],He+=S*ee,ht+=S*Ft,Qe+=S*Kt,qt+=S*Zt,lt+=S*Dt,bt+=S*Yt,kt+=S*Xt,_t+=S*Nn,jt+=S*nn,oe+=S*_n,Te+=S*fn,Xe+=S*hn,Le+=S*Fn,Ze+=S*Ln,qe+=S*Wn,st+=S*$,S=M[4],ht+=S*ee,Qe+=S*Ft,qt+=S*Kt,lt+=S*Zt,bt+=S*Dt,kt+=S*Yt,_t+=S*Xt,jt+=S*Nn,oe+=S*nn,Te+=S*_n,Xe+=S*fn,Le+=S*hn,Ze+=S*Fn,qe+=S*Ln,st+=S*Wn,at+=S*$,S=M[5],Qe+=S*ee,qt+=S*Ft,lt+=S*Kt,bt+=S*Zt,kt+=S*Dt,_t+=S*Yt,jt+=S*Xt,oe+=S*Nn,Te+=S*nn,Xe+=S*_n,Le+=S*fn,Ze+=S*hn,qe+=S*Fn,st+=S*Ln,at+=S*Wn,et+=S*$,S=M[6],qt+=S*ee,lt+=S*Ft,bt+=S*Kt,kt+=S*Zt,_t+=S*Dt,jt+=S*Yt,oe+=S*Xt,Te+=S*Nn,Xe+=S*nn,Le+=S*_n,Ze+=S*fn,qe+=S*hn,st+=S*Fn,at+=S*Ln,et+=S*Wn,ye+=S*$,S=M[7],lt+=S*ee,bt+=S*Ft,kt+=S*Kt,_t+=S*Zt,jt+=S*Dt,oe+=S*Yt,Te+=S*Xt,Xe+=S*Nn,Le+=S*nn,Ze+=S*_n,qe+=S*fn,st+=S*hn,at+=S*Fn,et+=S*Ln,ye+=S*Wn,Se+=S*$,S=M[8],bt+=S*ee,kt+=S*Ft,_t+=S*Kt,jt+=S*Zt,oe+=S*Dt,Te+=S*Yt,Xe+=S*Xt,Le+=S*Nn,Ze+=S*nn,qe+=S*_n,st+=S*fn,at+=S*hn,et+=S*Fn,ye+=S*Ln,Se+=S*Wn,Oe+=S*$,S=M[9],kt+=S*ee,_t+=S*Ft,jt+=S*Kt,oe+=S*Zt,Te+=S*Dt,Xe+=S*Yt,Le+=S*Xt,Ze+=S*Nn,qe+=S*nn,st+=S*_n,at+=S*fn,et+=S*hn,ye+=S*Fn,Se+=S*Ln,Oe+=S*Wn,Ae+=S*$,S=M[10],_t+=S*ee,jt+=S*Ft,oe+=S*Kt,Te+=S*Zt,Xe+=S*Dt,Le+=S*Yt,Ze+=S*Xt,qe+=S*Nn,st+=S*nn,at+=S*_n,et+=S*fn,ye+=S*hn,Se+=S*Fn,Oe+=S*Ln,Ae+=S*Wn,Pe+=S*$,S=M[11],jt+=S*ee,oe+=S*Ft,Te+=S*Kt,Xe+=S*Zt,Le+=S*Dt,Ze+=S*Yt,qe+=S*Xt,st+=S*Nn,at+=S*nn,et+=S*_n,ye+=S*fn,Se+=S*hn,Oe+=S*Fn,Ae+=S*Ln,Pe+=S*Wn,Ge+=S*$,S=M[12],oe+=S*ee,Te+=S*Ft,Xe+=S*Kt,Le+=S*Zt,Ze+=S*Dt,qe+=S*Yt,st+=S*Xt,at+=S*Nn,et+=S*nn,ye+=S*_n,Se+=S*fn,Oe+=S*hn,Ae+=S*Fn,Pe+=S*Ln,Ge+=S*Wn,yt+=S*$,S=M[13],Te+=S*ee,Xe+=S*Ft,Le+=S*Kt,Ze+=S*Zt,qe+=S*Dt,st+=S*Yt,at+=S*Xt,et+=S*Nn,ye+=S*nn,Se+=S*_n,Oe+=S*fn,Ae+=S*hn,Pe+=S*Fn,Ge+=S*Ln,yt+=S*Wn,At+=S*$,S=M[14],Xe+=S*ee,Le+=S*Ft,Ze+=S*Kt,qe+=S*Zt,st+=S*Dt,at+=S*Yt,et+=S*Xt,ye+=S*Nn,Se+=S*nn,Oe+=S*_n,Ae+=S*fn,Pe+=S*hn,Ge+=S*Fn,yt+=S*Ln,At+=S*Wn,Rt+=S*$,S=M[15],Le+=S*ee,Ze+=S*Ft,qe+=S*Kt,st+=S*Zt,at+=S*Dt,et+=S*Yt,ye+=S*Xt,Se+=S*Nn,Oe+=S*nn,Ae+=S*_n,Pe+=S*fn,Ge+=S*hn,yt+=S*Fn,At+=S*Ln,Rt+=S*Wn,Lt+=S*$,ae+=38*Ze,ce+=38*qe,Ie+=38*st,He+=38*at,ht+=38*et,Qe+=38*ye,qt+=38*Se,lt+=38*Oe,bt+=38*Ae,kt+=38*Pe,_t+=38*Ge,jt+=38*yt,oe+=38*At,Te+=38*Rt,Xe+=38*Lt,G=1,S=ae+G+65535,G=Math.floor(S/65536),ae=S-G*65536,S=ce+G+65535,G=Math.floor(S/65536),ce=S-G*65536,S=Ie+G+65535,G=Math.floor(S/65536),Ie=S-G*65536,S=He+G+65535,G=Math.floor(S/65536),He=S-G*65536,S=ht+G+65535,G=Math.floor(S/65536),ht=S-G*65536,S=Qe+G+65535,G=Math.floor(S/65536),Qe=S-G*65536,S=qt+G+65535,G=Math.floor(S/65536),qt=S-G*65536,S=lt+G+65535,G=Math.floor(S/65536),lt=S-G*65536,S=bt+G+65535,G=Math.floor(S/65536),bt=S-G*65536,S=kt+G+65535,G=Math.floor(S/65536),kt=S-G*65536,S=_t+G+65535,G=Math.floor(S/65536),_t=S-G*65536,S=jt+G+65535,G=Math.floor(S/65536),jt=S-G*65536,S=oe+G+65535,G=Math.floor(S/65536),oe=S-G*65536,S=Te+G+65535,G=Math.floor(S/65536),Te=S-G*65536,S=Xe+G+65535,G=Math.floor(S/65536),Xe=S-G*65536,S=Le+G+65535,G=Math.floor(S/65536),Le=S-G*65536,ae+=G-1+37*(G-1),G=1,S=ae+G+65535,G=Math.floor(S/65536),ae=S-G*65536,S=ce+G+65535,G=Math.floor(S/65536),ce=S-G*65536,S=Ie+G+65535,G=Math.floor(S/65536),Ie=S-G*65536,S=He+G+65535,G=Math.floor(S/65536),He=S-G*65536,S=ht+G+65535,G=Math.floor(S/65536),ht=S-G*65536,S=Qe+G+65535,G=Math.floor(S/65536),Qe=S-G*65536,S=qt+G+65535,G=Math.floor(S/65536),qt=S-G*65536,S=lt+G+65535,G=Math.floor(S/65536),lt=S-G*65536,S=bt+G+65535,G=Math.floor(S/65536),bt=S-G*65536,S=kt+G+65535,G=Math.floor(S/65536),kt=S-G*65536,S=_t+G+65535,G=Math.floor(S/65536),_t=S-G*65536,S=jt+G+65535,G=Math.floor(S/65536),jt=S-G*65536,S=oe+G+65535,G=Math.floor(S/65536),oe=S-G*65536,S=Te+G+65535,G=Math.floor(S/65536),Te=S-G*65536,S=Xe+G+65535,G=Math.floor(S/65536),Xe=S-G*65536,S=Le+G+65535,G=Math.floor(S/65536),Le=S-G*65536,ae+=G-1+37*(G-1),P[0]=ae,P[1]=ce,P[2]=Ie,P[3]=He,P[4]=ht,P[5]=Qe,P[6]=qt,P[7]=lt,P[8]=bt,P[9]=kt,P[10]=_t,P[11]=jt,P[12]=oe,P[13]=Te,P[14]=Xe,P[15]=Le}function ke(P,M){pe(P,M,M)}function Me(P,M){var R=n(),S;for(S=0;S<16;S++)R[S]=M[S];for(S=253;S>=0;S--)ke(R,R),S!==2&&S!==4&&pe(R,R,M);for(S=0;S<16;S++)P[S]=R[S]}function fe(P,M){var R=n(),S;for(S=0;S<16;S++)R[S]=M[S];for(S=250;S>=0;S--)ke(R,R),S!==1&&pe(R,R,M);for(S=0;S<16;S++)P[S]=R[S]}function F(P,M,R){var S=new Uint8Array(32),G=new Float64Array(80),ae,ce,Ie=n(),He=n(),ht=n(),Qe=n(),qt=n(),lt=n();for(ce=0;ce<31;ce++)S[ce]=M[ce];for(S[31]=M[31]&127|64,S[0]&=248,H(G,R),ce=0;ce<16;ce++)He[ce]=G[ce],Qe[ce]=Ie[ce]=ht[ce]=0;for(Ie[0]=Qe[0]=1,ce=254;ce>=0;--ce)ae=S[ce>>>3]>>>(ce&7)&1,L(Ie,He,ae),L(ht,Qe,ae),ne(qt,Ie,ht),he(Ie,Ie,ht),ne(ht,He,Qe),he(He,He,Qe),ke(Qe,qt),ke(lt,Ie),pe(Ie,ht,Ie),pe(ht,He,qt),ne(qt,Ie,ht),he(Ie,Ie,ht),ke(He,Ie),he(ht,Qe,lt),pe(Ie,ht,c),ne(Ie,Ie,Qe),pe(ht,ht,Ie),pe(Ie,Qe,lt),pe(Qe,He,G),ke(He,qt),L(Ie,He,ae),L(ht,Qe,ae);for(ce=0;ce<16;ce++)G[ce+16]=Ie[ce],G[ce+32]=ht[ce],G[ce+48]=He[ce],G[ce+64]=Qe[ce];var bt=G.subarray(32),kt=G.subarray(16);return Me(bt,bt),pe(kt,kt,bt),se(P,kt),0}function U(P,M){return F(P,M,r)}function de(P,M){return s(M,32),U(P,M)}function Y(P,M,R){var S=new Uint8Array(32);return F(S,R,M),j(P,i,S,N)}var X=W,z=J;function ue(P,M,R,S,G,ae){var ce=new Uint8Array(32);return Y(ce,G,ae),X(P,M,R,S,ce)}function _e(P,M,R,S,G,ae){var ce=new Uint8Array(32);return Y(ce,G,ae),z(P,M,R,S,ce)}var Ee=[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 Be(P,M,R,S){for(var G=new Int32Array(16),ae=new Int32Array(16),ce,Ie,He,ht,Qe,qt,lt,bt,kt,_t,jt,oe,Te,Xe,Le,Ze,qe,st,at,et,ye,Se,Oe,Ae,Pe,Ge,yt=P[0],At=P[1],Rt=P[2],Lt=P[3],ee=P[4],Ft=P[5],Kt=P[6],Zt=P[7],Dt=M[0],Yt=M[1],Xt=M[2],Nn=M[3],nn=M[4],_n=M[5],fn=M[6],hn=M[7],Fn=0;S>=128;){for(at=0;at<16;at++)et=8*at+Fn,G[at]=R[et+0]<<24|R[et+1]<<16|R[et+2]<<8|R[et+3],ae[at]=R[et+4]<<24|R[et+5]<<16|R[et+6]<<8|R[et+7];for(at=0;at<80;at++)if(ce=yt,Ie=At,He=Rt,ht=Lt,Qe=ee,qt=Ft,lt=Kt,bt=Zt,kt=Dt,_t=Yt,jt=Xt,oe=Nn,Te=nn,Xe=_n,Le=fn,Ze=hn,ye=Zt,Se=hn,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=(ee>>>14|nn<<18)^(ee>>>18|nn<<14)^(nn>>>9|ee<<23),Se=(nn>>>14|ee<<18)^(nn>>>18|ee<<14)^(ee>>>9|nn<<23),Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,ye=ee&Ft^~ee&Kt,Se=nn&_n^~nn&fn,Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,ye=Ee[at*2],Se=Ee[at*2+1],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,ye=G[at%16],Se=ae[at%16],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,qe=Pe&65535|Ge<<16,st=Oe&65535|Ae<<16,ye=qe,Se=st,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=(yt>>>28|Dt<<4)^(Dt>>>2|yt<<30)^(Dt>>>7|yt<<25),Se=(Dt>>>28|yt<<4)^(yt>>>2|Dt<<30)^(yt>>>7|Dt<<25),Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,ye=yt&At^yt&Rt^At&Rt,Se=Dt&Yt^Dt&Xt^Yt&Xt,Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,bt=Pe&65535|Ge<<16,Ze=Oe&65535|Ae<<16,ye=ht,Se=oe,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=qe,Se=st,Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,ht=Pe&65535|Ge<<16,oe=Oe&65535|Ae<<16,At=ce,Rt=Ie,Lt=He,ee=ht,Ft=Qe,Kt=qt,Zt=lt,yt=bt,Yt=kt,Xt=_t,Nn=jt,nn=oe,_n=Te,fn=Xe,hn=Le,Dt=Ze,at%16===15)for(et=0;et<16;et++)ye=G[et],Se=ae[et],Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=G[(et+9)%16],Se=ae[(et+9)%16],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,qe=G[(et+1)%16],st=ae[(et+1)%16],ye=(qe>>>1|st<<31)^(qe>>>8|st<<24)^qe>>>7,Se=(st>>>1|qe<<31)^(st>>>8|qe<<24)^(st>>>7|qe<<25),Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,qe=G[(et+14)%16],st=ae[(et+14)%16],ye=(qe>>>19|st<<13)^(st>>>29|qe<<3)^qe>>>6,Se=(st>>>19|qe<<13)^(qe>>>29|st<<3)^(st>>>6|qe<<26),Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,G[et]=Pe&65535|Ge<<16,ae[et]=Oe&65535|Ae<<16;ye=yt,Se=Dt,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[0],Se=M[0],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[0]=yt=Pe&65535|Ge<<16,M[0]=Dt=Oe&65535|Ae<<16,ye=At,Se=Yt,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[1],Se=M[1],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[1]=At=Pe&65535|Ge<<16,M[1]=Yt=Oe&65535|Ae<<16,ye=Rt,Se=Xt,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[2],Se=M[2],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[2]=Rt=Pe&65535|Ge<<16,M[2]=Xt=Oe&65535|Ae<<16,ye=Lt,Se=Nn,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[3],Se=M[3],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[3]=Lt=Pe&65535|Ge<<16,M[3]=Nn=Oe&65535|Ae<<16,ye=ee,Se=nn,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[4],Se=M[4],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[4]=ee=Pe&65535|Ge<<16,M[4]=nn=Oe&65535|Ae<<16,ye=Ft,Se=_n,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[5],Se=M[5],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[5]=Ft=Pe&65535|Ge<<16,M[5]=_n=Oe&65535|Ae<<16,ye=Kt,Se=fn,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[6],Se=M[6],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[6]=Kt=Pe&65535|Ge<<16,M[6]=fn=Oe&65535|Ae<<16,ye=Zt,Se=hn,Oe=Se&65535,Ae=Se>>>16,Pe=ye&65535,Ge=ye>>>16,ye=P[7],Se=M[7],Oe+=Se&65535,Ae+=Se>>>16,Pe+=ye&65535,Ge+=ye>>>16,Ae+=Oe>>>16,Pe+=Ae>>>16,Ge+=Pe>>>16,P[7]=Zt=Pe&65535|Ge<<16,M[7]=hn=Oe&65535|Ae<<16,Fn+=128,S-=128}return S}function De(P,M,R){var S=new Int32Array(8),G=new Int32Array(8),ae=new Uint8Array(256),ce,Ie=R;for(S[0]=1779033703,S[1]=3144134277,S[2]=1013904242,S[3]=2773480762,S[4]=1359893119,S[5]=2600822924,S[6]=528734635,S[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,Be(S,G,M,R),R%=128,ce=0;ce<R;ce++)ae[ce]=M[Ie-R+ce];for(ae[R]=128,R=256-128*(R<112?1:0),ae[R-9]=0,x(ae,R-8,Ie/536870912|0,Ie<<3),Be(S,G,ae,R),ce=0;ce<8;ce++)x(P,8*ce,S[ce],G[ce]);return 0}function Ue(P,M){var R=n(),S=n(),G=n(),ae=n(),ce=n(),Ie=n(),He=n(),ht=n(),Qe=n();he(R,P[1],P[0]),he(Qe,M[1],M[0]),pe(R,R,Qe),ne(S,P[0],P[1]),ne(Qe,M[0],M[1]),pe(S,S,Qe),pe(G,P[3],M[3]),pe(G,G,u),pe(ae,P[2],M[2]),ne(ae,ae,ae),he(ce,S,R),he(Ie,ae,G),ne(He,ae,G),ne(ht,S,R),pe(P[0],ce,Ie),pe(P[1],ht,He),pe(P[2],He,Ie),pe(P[3],ce,ht)}function St(P,M,R){var S;for(S=0;S<4;S++)L(P[S],M[S],R)}function Ut(P,M){var R=n(),S=n(),G=n();Me(G,M[2]),pe(R,M[0],G),pe(S,M[1],G),se(P,S),P[31]^=V(R)<<7}function tn(P,M,R){var S,G;for(O(P[0],a),O(P[1],l),O(P[2],l),O(P[3],a),G=255;G>=0;--G)S=R[G/8|0]>>(G&7)&1,St(P,M,S),Ue(M,P),Ue(P,P),St(P,M,S)}function Ne(P,M){var R=[n(),n(),n(),n()];O(R[0],h),O(R[1],p),O(R[2],l),pe(R[3],h,p),tn(P,R,M)}function Z(P,M,R){var S=new Uint8Array(64),G=[n(),n(),n(),n()],ae;for(R||s(M,32),De(S,M,32),S[0]&=248,S[31]&=127,S[31]|=64,Ne(G,S),Ut(P,G),ae=0;ae<32;ae++)M[ae+32]=P[ae];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 tt(P,M){var R,S,G,ae;for(S=63;S>=32;--S){for(R=0,G=S-32,ae=S-12;G<ae;++G)M[G]+=R-16*M[S]*je[G-(S-32)],R=Math.floor((M[G]+128)/256),M[G]-=R*256;M[G]+=R,M[S]=0}for(R=0,G=0;G<32;G++)M[G]+=R-(M[31]>>4)*je[G],R=M[G]>>8,M[G]&=255;for(G=0;G<32;G++)M[G]-=R*je[G];for(S=0;S<32;S++)M[S+1]+=M[S]>>8,P[S]=M[S]&255}function Et(P){var M=new Float64Array(64),R;for(R=0;R<64;R++)M[R]=P[R];for(R=0;R<64;R++)P[R]=0;tt(P,M)}function zt(P,M,R,S){var G=new Uint8Array(64),ae=new Uint8Array(64),ce=new Uint8Array(64),Ie,He,ht=new Float64Array(64),Qe=[n(),n(),n(),n()];De(G,S,32),G[0]&=248,G[31]&=127,G[31]|=64;var qt=R+64;for(Ie=0;Ie<R;Ie++)P[64+Ie]=M[Ie];for(Ie=0;Ie<32;Ie++)P[32+Ie]=G[32+Ie];for(De(ce,P.subarray(32),R+32),Et(ce),Ne(Qe,ce),Ut(P,Qe),Ie=32;Ie<64;Ie++)P[Ie]=S[Ie];for(De(ae,P,R+64),Et(ae),Ie=0;Ie<64;Ie++)ht[Ie]=0;for(Ie=0;Ie<32;Ie++)ht[Ie]=ce[Ie];for(Ie=0;Ie<32;Ie++)for(He=0;He<32;He++)ht[Ie+He]+=ae[Ie]*G[He];return tt(P.subarray(32),ht),qt}function we(P,M){var R=n(),S=n(),G=n(),ae=n(),ce=n(),Ie=n(),He=n();return O(P[2],l),H(P[1],M),ke(G,P[1]),pe(ae,G,d),he(G,G,P[2]),ne(ae,P[2],ae),ke(ce,ae),ke(Ie,ce),pe(He,Ie,ce),pe(R,He,G),pe(R,R,ae),fe(R,R),pe(R,R,G),pe(R,R,ae),pe(R,R,ae),pe(P[0],R,ae),ke(S,P[0]),pe(S,S,ae),Q(S,G)&&pe(P[0],P[0],f),ke(S,P[0]),pe(S,S,ae),Q(S,G)?-1:(V(P[0])===M[31]>>7&&he(P[0],a,P[0]),pe(P[3],P[0],P[1]),0)}function ft(P,M,R,S){var G,ae=new Uint8Array(32),ce=new Uint8Array(64),Ie=[n(),n(),n(),n()],He=[n(),n(),n(),n()];if(R<64||we(He,S))return-1;for(G=0;G<R;G++)P[G]=M[G];for(G=0;G<32;G++)P[G+32]=S[G];if(De(ce,P,R),Et(ce),tn(Ie,He,ce),Ne(He,M.subarray(32)),Ue(Ie,He),Ut(ae,Ie),R-=64,w(M,0,ae,0)){for(G=0;G<R;G++)P[G]=0;return-1}for(G=0;G<R;G++)P[G]=M[G+64];return R}var mt=32,ze=24,Ct=32,K=16,be=32,Re=32,Ve=32,Ke=32,nt=32,ge=ze,$e=Ct,it=K,xt=64,Mt=32,Gt=64,sn=32,wn=64;t.lowlevel={crypto_core_hsalsa20:j,crypto_stream_xor:I,crypto_stream:E,crypto_stream_salsa20_xor:C,crypto_stream_salsa20:k,crypto_onetimeauth:A,crypto_onetimeauth_verify:D,crypto_verify_16:v,crypto_verify_32:w,crypto_secretbox:W,crypto_secretbox_open:J,crypto_scalarmult:F,crypto_scalarmult_base:U,crypto_box_beforenm:Y,crypto_box_afternm:X,crypto_box:ue,crypto_box_open:_e,crypto_box_keypair:de,crypto_hash:De,crypto_sign:zt,crypto_sign_keypair:Z,crypto_sign_open:ft,crypto_secretbox_KEYBYTES:mt,crypto_secretbox_NONCEBYTES:ze,crypto_secretbox_ZEROBYTES:Ct,crypto_secretbox_BOXZEROBYTES:K,crypto_scalarmult_BYTES:be,crypto_scalarmult_SCALARBYTES:Re,crypto_box_PUBLICKEYBYTES:Ve,crypto_box_SECRETKEYBYTES:Ke,crypto_box_BEFORENMBYTES:nt,crypto_box_NONCEBYTES:ge,crypto_box_ZEROBYTES:$e,crypto_box_BOXZEROBYTES:it,crypto_sign_BYTES:xt,crypto_sign_PUBLICKEYBYTES:Mt,crypto_sign_SECRETKEYBYTES:Gt,crypto_sign_SEEDBYTES:sn,crypto_hash_BYTES:wn,gf:n,D:d,L:je,pack25519:se,unpack25519:H,M:pe,A:ne,S:ke,Z:he,pow2523:fe,add:Ue,set25519:O,modL:tt,scalarmult:tn,scalarbase:Ne};function On(P,M){if(P.length!==mt)throw new Error("bad key size");if(M.length!==ze)throw new Error("bad nonce size")}function rn(P,M){if(P.length!==Ve)throw new Error("bad public key size");if(M.length!==Ke)throw new Error("bad secret key size")}function cn(){for(var P=0;P<arguments.length;P++)if(!(arguments[P]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Bn(P){for(var M=0;M<P.length;M++)P[M]=0}t.randomBytes=function(P){var M=new Uint8Array(P);return s(M,P),M},t.secretbox=function(P,M,R){cn(P,M,R),On(R,M);for(var S=new Uint8Array(Ct+P.length),G=new Uint8Array(S.length),ae=0;ae<P.length;ae++)S[ae+Ct]=P[ae];return W(G,S,S.length,M,R),G.subarray(K)},t.secretbox.open=function(P,M,R){cn(P,M,R),On(R,M);for(var S=new Uint8Array(K+P.length),G=new Uint8Array(S.length),ae=0;ae<P.length;ae++)S[ae+K]=P[ae];return S.length<32||J(G,S,S.length,M,R)!==0?null:G.subarray(Ct)},t.secretbox.keyLength=mt,t.secretbox.nonceLength=ze,t.secretbox.overheadLength=K,t.scalarMult=function(P,M){if(cn(P,M),P.length!==Re)throw new Error("bad n size");if(M.length!==be)throw new Error("bad p size");var R=new Uint8Array(be);return F(R,P,M),R},t.scalarMult.base=function(P){if(cn(P),P.length!==Re)throw new Error("bad n size");var M=new Uint8Array(be);return U(M,P),M},t.scalarMult.scalarLength=Re,t.scalarMult.groupElementLength=be,t.box=function(P,M,R,S){var G=t.box.before(R,S);return t.secretbox(P,M,G)},t.box.before=function(P,M){cn(P,M),rn(P,M);var R=new Uint8Array(nt);return Y(R,P,M),R},t.box.after=t.secretbox,t.box.open=function(P,M,R,S){var G=t.box.before(R,S);return t.secretbox.open(P,M,G)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var P=new Uint8Array(Ve),M=new Uint8Array(Ke);return de(P,M),{publicKey:P,secretKey:M}},t.box.keyPair.fromSecretKey=function(P){if(cn(P),P.length!==Ke)throw new Error("bad secret key size");var M=new Uint8Array(Ve);return U(M,P),{publicKey:M,secretKey:new Uint8Array(P)}},t.box.publicKeyLength=Ve,t.box.secretKeyLength=Ke,t.box.sharedKeyLength=nt,t.box.nonceLength=ge,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(P,M){if(cn(P,M),M.length!==Gt)throw new Error("bad secret key size");var R=new Uint8Array(xt+P.length);return zt(R,P,P.length,M),R},t.sign.open=function(P,M){if(cn(P,M),M.length!==Mt)throw new Error("bad public key size");var R=new Uint8Array(P.length),S=ft(R,P,P.length,M);if(S<0)return null;for(var G=new Uint8Array(S),ae=0;ae<G.length;ae++)G[ae]=R[ae];return G},t.sign.detached=function(P,M){for(var R=t.sign(P,M),S=new Uint8Array(xt),G=0;G<S.length;G++)S[G]=R[G];return S},t.sign.detached.verify=function(P,M,R){if(cn(P,M,R),M.length!==xt)throw new Error("bad signature size");if(R.length!==Mt)throw new Error("bad public key size");var S=new Uint8Array(xt+P.length),G=new Uint8Array(xt+P.length),ae;for(ae=0;ae<xt;ae++)S[ae]=M[ae];for(ae=0;ae<P.length;ae++)S[ae+xt]=P[ae];return ft(G,S,S.length,R)>=0},t.sign.keyPair=function(){var P=new Uint8Array(Mt),M=new Uint8Array(Gt);return Z(P,M),{publicKey:P,secretKey:M}},t.sign.keyPair.fromSecretKey=function(P){if(cn(P),P.length!==Gt)throw new Error("bad secret key size");for(var M=new Uint8Array(Mt),R=0;R<M.length;R++)M[R]=P[32+R];return{publicKey:M,secretKey:new Uint8Array(P)}},t.sign.keyPair.fromSeed=function(P){if(cn(P),P.length!==sn)throw new Error("bad seed size");for(var M=new Uint8Array(Mt),R=new Uint8Array(Gt),S=0;S<32;S++)R[S]=P[S];return Z(M,R,!0),{publicKey:M,secretKey:R}},t.sign.publicKeyLength=Mt,t.sign.secretKeyLength=Gt,t.sign.seedLength=sn,t.sign.signatureLength=xt,t.hash=function(P){cn(P);var M=new Uint8Array(wn);return De(M,P,P.length),M},t.hash.hashLength=wn,t.verify=function(P,M){return cn(P,M),P.length===0||M.length===0||P.length!==M.length?!1:g(P,0,M,0,P.length)===0},t.setPRNG=function(P){s=P},(function(){var P=typeof self<"u"?self.crypto||self.msCrypto:null;if(P&&P.getRandomValues){var M=65536;t.setPRNG(function(R,S){var G,ae=new Uint8Array(S);for(G=0;G<S;G+=M)P.getRandomValues(ae.subarray(G,G+Math.min(S-G,M)));for(G=0;G<S;G++)R[G]=ae[G];Bn(ae)})}else typeof HZ<"u"&&(P=$Z,P&&P.randomBytes&&t.setPRNG(function(R,S){var G,ae=P.randomBytes(S);for(G=0;G<S;G++)R[G]=ae[G];Bn(ae)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})(Op)),Op.exports}WZ();new TextEncoder;new TextDecoder;function UZ(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 KZ(e){return e.kind!=="ssh"?void 0:e.sshConnectionName?.trim()||e.sshHost}function BI(e){return e.alias?.trim()||e.name}function gS(e){const t=BI(e),n=KZ(e);return n?`${t} (${n})`:t}const Jc={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},xS={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"};function qZ({open:e,onOpenChange:t,projects:n,providers:s,onCreate:i}){const{t:r}=te(),a=xe(A=>A.approvalReviewer),l=xe(A=>A.lastApprovalMode),c=ma(),d=Ao(A=>A.snapshot),u=m.useMemo(()=>u2(a,c,na(d),l),[a,l,c,d]),[h,p]=m.useState(null),[f,x]=m.useState(null),[g,v]=m.useState(null),[w,y]=m.useState(u),[b,_]=m.useState(!1),[j,N]=m.useState("medium");m.useEffect(()=>{e&&(p(null),x(null),v(null),y(u))},[e,u]);const C=n.find(A=>A.id===h)?.id??n[0]?.id??"",k=s.find(A=>A.id===f)??s[0]??{id:"",models:[]},E=k.models.find(A=>A.id===g)?.id??k.models[0]?.id??"",I=!!(C&&k.id&&E),T=()=>{I&&(xe.getState().setLastApprovalMode(w),i({projectId:C,providerId:k.id,modelId:E,approvalMode:w,...b?{reasoningEnabled:!0,thinkingLevel:j}:{}}),t(!1))};return o.jsx(gn,{open:e,onOpenChange:t,children:o.jsxs(xn,{className:"max-w-md",children:[o.jsxs(vn,{children:[o.jsx(bn,{children:r("New remote conversation")}),o.jsx(Os,{children:r("The conversation runs on the remote computer with its projects, models and keys.")})]}),o.jsxs(Rn,{className:"space-y-4",children:[o.jsx(Ga,{label:r("Project"),children:o.jsxs(ms,{items:n.map(A=>({value:A.id,label:gS(A)})),value:C,onValueChange:A=>p(A),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:n.map(A=>o.jsx(ts,{value:A.id,children:gS(A)},A.id))})]})}),o.jsx(Ga,{label:r("Provider"),children:o.jsxs(ms,{items:s.map(A=>({value:A.id,label:A.name})),value:k.id,onValueChange:A=>{x(A),v(null)},children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:s.map(A=>o.jsx(ts,{value:A.id,children:A.name},A.id))})]})}),o.jsx(Ga,{label:r("Model"),children:o.jsxs(ms,{items:k.models.map(A=>({value:A.id,label:A.label??A.id})),value:E,onValueChange:A=>v(A),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:k.models.map(A=>o.jsx(ts,{value:A.id,children:A.label??A.id},A.id))})]})}),o.jsx(Ga,{label:r("Approval mode"),children:o.jsxs(ms,{items:Object.keys(Jc).map(A=>({value:A,label:r(Jc[A])})),value:w,onValueChange:A=>y(A),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:Object.keys(Jc).map(A=>o.jsx(ts,{value:A,children:r(Jc[A])},A))})]})}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:r("Reasoning")}),o.jsx(_i,{checked:b,onCheckedChange:_})]}),b&&o.jsx(Ga,{label:r("Thinking level"),children:o.jsxs(ms,{items:rf.map(A=>({value:A,label:r(xS[A])})),value:j,onValueChange:A=>N(A),children:[o.jsx(gs,{className:"w-full",children:o.jsx(xs,{})}),o.jsx(vs,{zIndex:yn.DROPDOWN_IN_MODAL,children:rf.map(A=>o.jsx(ts,{value:A,children:r(xS[A])},A))})]})})]}),o.jsxs(ls,{children:[o.jsx(le,{variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),o.jsx(le,{size:"sm",disabled:!I,onClick:T,children:r("Create")})]})]})})}function Ga({label:e,children:t}){return o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("span",{className:"text-muted-foreground text-xs",children:e}),t]})}function YZ(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 XZ(e){return rf.includes(e??"")?e:"medium"}function JZ(e){const{t}=te(),{node:n,sessionId:s,entry:i,view:r,syncing:a}=e,l=m.useRef(null),c=r?.status==="running",d=m.useMemo(()=>r?[...r.messages.entries()].sort((v,w)=>v[0]-w[0]):[],[r]),u=m.useMemo(()=>d.map(([,v])=>v),[d]),h=m.useMemo(()=>hr(u,c,[],i?.cwd,{pendingApprovals:r?.approvals,compaction:r?.compaction,compactionNoticeAt:h2(d.map(([v])=>v),r?.compactionNoticeAt)}),[u,d,c,i?.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(()=>YZ(e.providers),[e.providers]),x=i&&!i.parentId,g=n.hostOnline?a&&s?t("Syncing…"):null:n.connected?t("Remote desktop is offline"):t("Connecting…");return o.jsx(ch.Provider,{value:p,children:o.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[o.jsxs("header",{className:"flex h-9 shrink-0 items-center gap-2 border-b px-3",children:[o.jsx(p2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:n.label}),o.jsx(f2,{node:n}),i&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-muted-foreground/50",children:"/"}),o.jsx("span",{className:"min-w-0 truncate text-sm",children:i.title||t("New conversation")}),i.projectName&&o.jsx("span",{className:"truncate font-mono text-muted-foreground text-xs",children:i.projectName})]}),o.jsx("div",{className:"flex-1"}),g&&o.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground",children:g})]}),e.tabGroup&&o.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 py-1",children:[o.jsx(vS,{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:o.jsx(pr,{className:"h-3 w-3 shrink-0"})}),e.tabGroup.children.map(v=>o.jsx(vS,{active:s===v.id,icon:o.jsx(Zs,{className:"h-3 w-3 shrink-0"}),label:v.title||"coworker",status:v.status,onClick:()=>e.onSelectTab(v.id)},v.id))]}),s===null?o.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-1 px-6 text-center",children:[o.jsx("p",{className:"font-medium text-lg",children:n.label}),o.jsx("p",{className:"text-muted-foreground text-sm",children:n.hostOnline?t("Select a conversation on the left, or create one"):g??""})]}):o.jsx(ph,{ref:l,items:h,busy:c||r===null,loading:!c&&r===null,running:c,error:void 0,emptyTitle:i?.projectName||n.label,historyLoading:e.historyLoading,hasOlder:e.hasOlder,onStartReached:e.hasOlder?e.onLoadOlder:void 0},s),s!==null&&o.jsx("div",{className:"@container pt-1",children:o.jsxs("div",{className:fi,children:[r?.retry&&o.jsx(wh,{retry:r.retry}),o.jsx(Fx,{sessionId:s,tasks:r?.tasks??[],subagents:r?.subagents??[]},s),o.jsx(Rl,{approvals:r?.approvals??[],onRespond:e.onApproval}),o.jsx(oh,{asks:r?.asks??[],onAnswer:e.onAsk}),o.jsx(zx,{commands:[],running:c,busy:c,locked:(r?.approvals??[]).length>0,focusKey:`${n.nodeId}:${s}`,toolbar:x&&i?o.jsx(Bu,{providers:f,providerId:i.providerId??"",modelId:i.modelId??"",reasoningEnabled:i.reasoningEnabled??!1,thinkingLevel:XZ(i.thinkingLevel),onSelect:e.onSetModel,onReasoningChange:e.onSetReasoning,onThinkingChange:e.onSetThinking}):o.jsx("span",{className:"text-[11px] text-muted-foreground",children:i?.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 vS({active:e,icon:t,label:n,status:s,onClick:i}){return o.jsxs("button",{type:"button",onClick:i,className:q("flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",e?"bg-muted text-foreground":"text-muted-foreground hover:bg-muted/50"),children:[t,o.jsx("span",{className:"max-w-32 truncate",children:n}),o.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",s==="running"?"animate-pulse bg-brand":s==="failed"?"bg-destructive":"bg-muted-foreground/30")})]})}function ku(e){return[...e].sort((t,n)=>(n.updatedAt??0)-(t.updatedAt??0))}function VI(e){const t=n=>(n.pendingAskCount??0)>0||(n.pendingApprovalCount??0)>0;return[...e.filter(t),...e.filter(n=>!t(n))]}function ZZ(e,t){const n=ku(e),s=new Map(n.map(r=>[r.id,r])),i=[];for(const r of t){const a=s.get(r);a&&(i.push(a),s.delete(r))}return[...i,...VI([...s.values()])]}function bS(e){return VI([...ku(e.filter(t=>t.pinned)),...ku(e.filter(t=>!t.pinned))])}const wS="flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function QZ({width:e,node:t,catalog:n,pinnedOrder:s,projects:i,groups:r=[],activeId:a,canCreate:l,onSelect:c,onNewConversation:d}){const{t:u,locale:h}=te(),[p,f]=m.useState(En),[x,g]=m.useState(""),[v,w]=m.useState({}),[y,b]=m.useState(!1),[_,j]=m.useState(()=>Date.now());m.useEffect(()=>{const L=setInterval(()=>j(Date.now()),6e4);return()=>clearInterval(L)},[]);const N=p===En||p===cs||r.some(L=>L.id===p)?p:En,C=i.filter(L=>L.archived).map(L=>L.id),k=Rr(i,r,C,N),E=new Set(k.map(L=>L.id)),I=x.trim().toLowerCase(),T=m.useMemo(()=>n.filter(L=>!L.parentId&&(!I||L.title.toLowerCase().includes(I))),[n,I]),A=ZZ(T.filter(L=>L.pinned&&!L.archived&&(!L.projectId||E.has(L.projectId))),s),D=ku(T.filter(L=>L.archived?N===En?!0:!!(L.projectId&&E.has(L.projectId)):!1)),W=T.filter(L=>!L.archived),J=new Set(i.map(L=>L.id)),O=bS(W.filter(L=>!J.has(L.projectId))),B=(L,se)=>o.jsxs("button",{type:"button",onClick:()=>c(L.id),className:q("group flex w-full items-center gap-2 rounded-lg py-1.5 pr-2 pl-4 text-left text-sm transition-colors",a===L.id?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted/60"),children:[o.jsx("span",{className:q("h-2 w-2 shrink-0 rounded-full",L.status==="running"&&"animate-pulse bg-brand",L.status==="failed"&&"bg-destructive",L.status==="idle"&&(L.unread?"bg-emerald-500":"bg-muted-foreground/30"))}),o.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[L.title||u("New conversation"),se&&o.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:se})]}),L.updatedAt!==void 0&&o.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/80 tabular-nums",children:Do(L.updatedAt,h,_)})]},L.id);return o.jsxs("aside",{className:"flex shrink-0 flex-col overflow-hidden border-r bg-background",style:{width:e},children:[o.jsx("div",{className:q("shrink-0 px-2 py-2",r.length===0&&"border-b"),children:o.jsxs("div",{className:"relative",children:[o.jsx(Js,{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"}),o.jsx(Wt,{value:x,onChange:L=>g(L.target.value),placeholder:u("Search conversations..."),className:"h-8 border-transparent bg-muted/60 text-xs shadow-none ring-brand/15 before:hidden has-focus-visible:border-brand/45 [&_input]:pl-8"})]})}),r.length>0&&o.jsx("div",{className:"shrink-0 border-b px-2 pb-2",children:o.jsxs(ms,{items:[{value:En,label:u("All")},...r.slice().sort((L,se)=>L.order-se.order).map(L=>({value:L.id,label:L.name})),{value:cs,label:u("Ungrouped")}],value:N,onValueChange:L=>{L&&f(L)},children:[o.jsx(gs,{className:"w-full",size:"sm",children:o.jsx(xs,{})}),o.jsxs(vs,{children:[o.jsx(ts,{value:En,children:u("All")}),r.slice().sort((L,se)=>L.order-se.order).map(L=>o.jsx(ts,{value:L.id,children:L.name},L.id)),o.jsx(ts,{value:cs,children:u("Ungrouped")})]})]})}),o.jsxs("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto p-2",children:[!t.hostOnline&&n.length===0&&o.jsx("p",{className:"rounded-lg border border-dashed px-3 py-6 text-center text-muted-foreground text-sm",children:t.connected?u("Remote desktop is offline"):u("Connecting…")}),t.hostOnline&&i.length===0&&o.jsx("p",{className:"rounded-lg border border-dashed px-3 py-6 text-center text-muted-foreground text-sm",children:u("The remote desktop has no projects yet")}),A.length>0&&o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-2",children:[o.jsx(Si,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"font-medium text-sm",children:u("Pinned")})]}),o.jsx("div",{className:"flex flex-col gap-y-0.5",children:A.map(L=>B(L,L.projectName))})]}),(N===En&&r.length>0?Yk(i,r,C).flatMap(L=>{const se=v[`g:${L.groupId}`]===!0;return[{kind:"header",section:L,foldedSection:se},...se?[]:L.projects.map(Q=>({kind:"project",project:Q}))]}):k.map(L=>({kind:"project",project:L}))).map(L=>{if(L.kind==="header")return o.jsxs("button",{type:"button",onClick:()=>w(H=>({...H,[`g:${L.section.groupId}`]:!H[`g:${L.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:[o.jsx(kn,{className:q("h-3.5 w-3.5 shrink-0 transition-transform duration-150",!L.foldedSection&&"rotate-90")}),L.section.group?.emoji&&o.jsx("span",{className:"shrink-0 text-sm",children:L.section.group.emoji}),L.section.group?.color&&o.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:L.section.group.color}}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:L.section.group?.name??u("Ungrouped")}),o.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/70",children:L.section.projects.length})]},`hdr-${L.section.groupId}`);const{project:se}=L,Q=bS(W.filter(H=>H.projectId===se.id&&!H.pinned));if(I&&Q.length===0)return null;const V=v[se.id]===!0;return o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>w(H=>({...H,[se.id]:!V})),className:"flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60",children:[V?o.jsx(kn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):o.jsx($n,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:BI(se)}),se.sshHost&&o.jsx("span",{className:"shrink-0 rounded bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"ssh"})]}),!V&&o.jsxs("div",{className:"flex flex-col gap-y-0.5",children:[Q.length===0&&o.jsx("p",{className:"px-4 py-1.5 text-muted-foreground text-xs",children:u("No conversations")}),Q.map(H=>B(H))]})]},se.id)}),O.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"px-2 py-2 font-medium text-sm",children:u("Other")}),o.jsx("div",{className:"flex flex-col gap-y-0.5",children:O.map(L=>B(L))})]}),D.length>0&&o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>b(L=>!L),className:"flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60",children:[o.jsx(ji,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:u("Archived")}),o.jsx("span",{className:"text-[10px] text-muted-foreground",children:D.length})]}),y&&o.jsx("div",{className:"flex flex-col gap-y-0.5",children:D.map(L=>B(L,L.projectName))})]})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[o.jsx(Xk,{}),o.jsx("button",{type:"button",onClick:()=>{window.electronAPI.nodes.openSettings(t.nodeId)},disabled:!t.hostOnline,className:q(wS,!t.hostOnline&&"opacity-40"),title:u("Node settings"),children:o.jsx(ai,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",onClick:d,disabled:!l,className:q(wS,!l&&"opacity-40"),title:u("New remote conversation"),children:o.jsx(g1,{className:"h-4 w-4"})})]})]})}function eQ({nodeId:e,sidebarWidth:t}){const n=es(v=>v.nodes.find(w=>w.nodeId===e)),s=es(v=>v.byNode[e])??tQ,i=es(v=>v.selectSession),r=es(v=>v.send),a=es(v=>v.requestHistory),l=es(v=>v.spawn),[c,d]=m.useState(!1),u=s.activeSessionId,h=m.useMemo(()=>s.catalog.find(v=>v.id===u),[s.catalog,u]),p=m.useMemo(()=>{if(!h)return;const v=h.parentId?s.catalog.find(y=>y.id===h.parentId):h;if(!v)return;const w=s.catalog.filter(y=>y.parentId===v.id);return w.length>0?{parent:v,children:w}:void 0},[s.catalog,h]),f=u?s.sessions[u]??null:null,x=!!(f&&f.messages.size>0&&Math.min(...f.messages.keys())>0);if(!n)return null;const g=v=>r(e,v);return o.jsxs(o.Fragment,{children:[o.jsx(QZ,{width:t,node:n,catalog:s.catalog,pinnedOrder:s.pinnedOrder,projects:s.projects,groups:s.groups,activeId:u,canCreate:n.hostOnline&&s.projects.length>0,onSelect:v=>i(e,v),onNewConversation:()=>d(!0)}),o.jsx(JZ,{node:n,sessionId:u,entry:h,tabGroup:p,view:f,syncing:s.sync.state==="syncing",providers:s.providers,hasOlder:x,historyLoading:!!(u&&s.historyPending.has(u)),onLoadOlder:()=>u&&a(e,u),onSelectTab:v=>i(e,v),onSend:(v,w)=>{u&&g({type:f?.status==="running"?"steer":"prompt",sessionId:u,text:v,...w.length?{images:w}:{}})},onAbort:()=>u&&g({type:"abort",sessionId:u}),onApproval:(v,w)=>u&&g({type:"approval-respond",sessionId:u,requestId:v,decision:w}),onAsk:(v,w)=>u&&g({type:"ask-respond",sessionId:u,requestId:v,answer:w}),onSetModel:(v,w)=>u&&g({type:"set-model",sessionId:u,providerId:v,modelId:w}),onSetReasoning:v=>u&&g({type:"set-reasoning",sessionId:u,enabled:v}),onSetThinking:v=>u&&g({type:"set-thinking",sessionId:u,level:v})}),o.jsx(qZ,{open:c,onOpenChange:d,projects:s.projects,providers:s.providers,onCreate:v=>l(e,v)})]})}const tQ=m2(),zp=["welcome","provider","skill","mcp","instruction","preset","agentType","done"];function nQ(){const{t:e}=te();VC();const t=xe(T=>T.setOnboarded),n=ma(),s=xe(T=>T.virtualModels),i=xe(T=>T.skills),r=xe(T=>T.mcpServers),a=xe(T=>T.instructions),l=xe(T=>T.presets),c=xe(T=>T.defaultModel),d=Ao(T=>T.snapshot),u=jl({defaultModel:c,providers:n,credentials:na(d),virtualModels:s}).source!=="none",[h,p]=m.useState(0),[f,x]=m.useState(null),[g,v]=m.useState(!1),[w,y]=m.useState(!1),[b,_]=m.useState(!1),j=zp[h],N=()=>t(!0),C=()=>{N(),window.electronAPI.window.summonAgent({typeKey:Hd})},k=()=>p(T=>Math.min(zp.length-1,T+1)),E=()=>p(T=>Math.max(0,T-1)),I={provider:{icon:x2,title:e("Model Providers"),desc:e("Add a provider subscription or API Key, or import providers from local AI apps"),count:n.length,onImport:()=>y(!0),importLabel:e("Add model or provider"),secondary:{label:e("Import from local apps"),onClick:()=>v(!0)}},skill:{icon:Ls,title:e("Skills"),desc:e("Import skills from Claude Code, Codex or Cursor"),count:i.length,onImport:()=>x("skill"),importLabel:e("Scan and import")},mcp:{icon:kC,title:e("MCP Servers"),desc:e("Import MCP servers configured in local AI apps"),count:r.length,onImport:()=>x("mcp"),importLabel:e("Scan and import")},instruction:{icon:Gd,title:e("Instruction Files"),desc:e("Import global instruction files configured in local AI tools"),count:a.length,onImport:()=>x("instruction"),importLabel:e("Scan and import")}};return o.jsxs("div",{className:"fixed inset-0 z-[45] flex items-center justify-center bg-black/40 backdrop-blur-sm","data-enso-float":"",children:[o.jsxs("div",{className:"relative flex w-[32rem] max-w-[90vw] flex-col rounded-2xl border bg-popover p-6 shadow-xl",children:[o.jsx("button",{type:"button",onClick:N,className:"absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground","aria-label":e("Close"),children:o.jsx(ln,{className:"h-4 w-4"})}),o.jsx("div",{className:"mb-5 flex items-center gap-1.5",children:zp.map((T,A)=>o.jsx("span",{className:q("h-1 flex-1 rounded-full transition-colors",A<=h?"bg-primary":"bg-muted")},T))}),j==="welcome"&&o.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:o.jsx(g2,{className:"h-6 w-6 text-primary"})}),o.jsx("h2",{className:"text-lg font-semibold",children:e("Welcome to EnsoCode")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("Import your providers and assets from local AI apps to get started. You can skip any step.")})]}),j!=="welcome"&&j!=="done"&&j!=="preset"&&j!=="agentType"&&o.jsx(yS,{...I[j],importedLabel:e("{{count}} imported",{count:I[j].count})}),j==="preset"&&o.jsx(yS,{icon:Gd,title:e("Presets"),desc:e("Bundle skills, MCP servers and an instruction file into a preset (optional)"),count:l.length,onImport:()=>_(!0),importedLabel:e("{{count}} presets",{count:l.length}),importLabel:e("New preset")}),j==="agentType"&&o.jsxs("div",{className:"flex flex-col gap-3 py-2",children:[o.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:o.jsx(Zs,{className:"h-6 w-6 text-muted-foreground"})}),o.jsx("h2",{className:"text-lg font-semibold",children:e("Agent types")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("Give subagents their own model, skills and MCP servers (optional)")})]}),o.jsx("div",{className:"max-h-64 overflow-y-auto pr-1",children:o.jsx(v2,{})})]}),j==="done"&&o.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:o.jsx(Jn,{className:"h-6 w-6 text-primary"})}),o.jsx("h2",{className:"text-lg font-semibold",children:e("All set")}),o.jsx("p",{className:"text-sm text-muted-foreground",children:e("You can always import more from Settings later.")})]}),u&&o.jsxs("div",{className:"mt-4 flex items-center justify-between rounded-lg border border-dashed px-3 py-2",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:e("Need help choosing a setup? Ask Enso.")}),o.jsxs(le,{variant:"ghost",size:"sm",onClick:C,children:[o.jsx(Ls,{className:"h-3.5 w-3.5"}),e("Ask Enso")]})]}),o.jsxs("div",{className:"mt-6 flex items-center justify-between",children:[o.jsx(le,{variant:"ghost",size:"sm",onClick:E,disabled:h===0,children:e("Back")}),o.jsxs("div",{className:"flex items-center gap-2",children:[j!=="done"&&j!=="welcome"&&o.jsx(le,{variant:"ghost",size:"sm",onClick:k,children:e("Skip")}),j==="done"?o.jsx(le,{size:"sm",onClick:N,children:e("Done")}):o.jsx(le,{size:"sm",onClick:k,children:e(j==="welcome"?"Get started":"Next")})]})]})]}),o.jsx(b2,{open:g,onOpenChange:v}),o.jsx(w2,{open:w,onOpenChange:y}),f&&o.jsx(y2,{kind:f,open:!0,onOpenChange:T=>!T&&x(null)}),b&&o.jsx(S2,{preset:null,onClose:()=>_(!1)})]})}function yS({icon:e,title:t,desc:n,count:s,onImport:i,importedLabel:r,importLabel:a,secondary:l}){return o.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[o.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:o.jsx(e,{className:"h-6 w-6 text-muted-foreground"})}),o.jsx("h2",{className:"text-lg font-semibold",children:t}),o.jsx("p",{className:"text-sm text-muted-foreground",children:n}),o.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[o.jsx(le,{variant:"outline",size:"sm",onClick:i,children:a}),l&&o.jsx(le,{variant:"ghost",size:"sm",onClick:l.onClick,children:l.label})]}),s>0&&o.jsx("p",{className:"text-xs text-primary",children:r})]})}const Gp=["project","all","all-including-archived"];function SS(e,t=!1){const n=Gp.length,s=Gp.indexOf(e);return Gp[(s+(t?n-1:1))%n]??"all"}const sQ=50,Fp=160,iQ=["title","project","id","body","tool"],$x=/[\p{Letter}\p{Number}]+/gu,oQ=/[\u3400-\u9fff]/u,rQ=/[^.!?。?!]+[.!?。?!]?/g;function $I(e){return e.toLowerCase().match($x)??[]}function Wx(e){return oQ.test(e)}function WI(e){return $I(e)}function UI(e,t){if(t.length===0)return!1;const n=e.toLowerCase(),s=$I(e);return t.every(i=>Wx(i)?n.includes(i):s.some(r=>r.startsWith(i)))}function KI(e,t){return e.isDraftEmpty?!1:t.scope==="project"?e.projectId===t.currentProjectId&&!e.archived:t.scope==="all"?!e.archived:!0}function aQ(e,t){const n=e.toLowerCase(),s=WI(t);if(s.length===0||n.length!==e.length)return[{text:e,match:!1}];const i=[];for(const l of s){if(Wx(l)){for(let c=n.indexOf(l);c>=0;c=n.indexOf(l,c+1))i.push([c,c+l.length]);continue}for(const c of n.matchAll($x))c.index!==void 0&&c[0].startsWith(l)&&i.push([c.index,c.index+l.length])}if(i.length===0)return[{text:e,match:!1}];i.sort((l,c)=>l[0]-c[0]);const r=[];let a=0;for(const[l,c]of i){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 lQ(e,t){const n=e.toLowerCase();let s=-1;for(const i of t){if(Wx(i)){const r=n.indexOf(i);r>=0&&(s<0||r<s)&&(s=r);continue}for(const r of e.matchAll($x))if(r[0].toLowerCase().startsWith(i)&&r.index!==void 0){(s<0||r.index<s)&&(s=r.index);break}}return s}function cQ(e,t){if(e.length<=Fp)return e;const n=Math.max(0,lQ(e,t)),s=Math.min(n,Math.max(0,e.length-Fp));return e.slice(s,s+Fp)}function dQ(e){return(e.match(rQ)??[]).map(t=>t.trim()).filter(Boolean)}function uQ(e,t){const n=dQ(e);if(n.length<=1)return;const s=n.findIndex(r=>UI(r,t));if(s<0)return;const i=[...[n[s-1],n[s-2]].filter(r=>!!r),...[n[s+1],n[s+2]].filter(r=>!!r)];return i.length>0?i:void 0}function hQ(e,t,n,s){return e.title.trim().toLowerCase()===n.trim().toLowerCase()?0:t==="title"?1:e.projectId===s?2:3}function pQ(e,t,n){const s=n.trim().toLowerCase(),i=e.fields.filter(r=>r.field==="id"?r.text.toLowerCase().startsWith(s):UI(r.text,t));if(i.length!==0)return iQ.map(r=>i.find(a=>a.field===r)).find(r=>!!r)}function qI(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:hQ(e,t.field,n,s),lastActiveAt:e.lastActiveAt}}function YI(e,t=sQ){return e.sort((n,s)=>n.rank-s.rank||s.lastActiveAt-n.lastActiveAt),e.slice(0,t).map(({rank:n,lastActiveAt:s,...i})=>i)}function fQ(e,t,n){const s=WI(t);if(s.length===0)return[];const i=[];for(const r of e){if(!KI(r,n))continue;const a=pQ(r,s,t);if(!a)continue;const l=uQ(a.text,s);i.push(qI(r,{field:a.field,snippet:cQ(a.text,s),nearby:l},t,n.currentProjectId))}return YI(i,n.limit)}function mQ(e,t,n,s,i){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)||!KI(c,i)||a.set(l.conversationId,qI(c,l,s,i.currentProjectId))}return YI([...a.values()],i.limit)}const gQ=120,xQ=8;function XI(e){return!e.started&&!e.sessionFile&&e.messages.length===0}function vl(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt??e.createdAt}function vQ(e,t){return e.filter(n=>n.parentId||XI(n)||n.archived&&t.scope!=="all-including-archived"?!1:t.scope!=="project"||n.projectId===t.currentProjectId).sort((n,s)=>vl(s)-vl(n)).slice(0,t.limit??xQ)}function bQ(e){return e.content.map(t=>t.type==="text"?t.text:"").join(`
98
- `).trim()}function wQ(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,gQ);return`${t.join(" ")} ${n}`.trim()}function yQ(e){const t=[{field:"title",text:e.title},{field:"project",text:e.projectName},{field:"id",text:e.conversationId},{field:"body",text:e.messages.map(bQ).filter(Boolean).join(`
99
- `)}],n=e.messages.map(wQ).filter(s=>!!s);return n.length>0&&t.push({field:"tool",text:n.join(`
100
- `)}),{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 CS=[],SQ={project:"This project",all:"All projects","all-including-archived":"Include archived"},CQ={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 Fa({text:e,query:t}){let n=0;return aQ(e,t).map(s=>{const i=n;return n+=s.text.length,s.match?o.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:s.text},i):o.jsx("span",{children:s.text},i)})}function Dr({icon:e,title:t,badges:n,detail:s,meta:i}){return o.jsxs(o.Fragment,{children:[o.jsx(e,{className:"size-4 shrink-0 text-muted-foreground"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:"truncate",children:t}),n]}),s&&o.jsx("p",{className:"truncate text-muted-foreground text-xs",children:s})]}),i&&o.jsx("span",{className:"max-w-48 shrink-0 truncate text-muted-foreground text-xs",children:i})]})}function kQ(e){try{return new URL(e).host||e}catch{return e}}function _Q({open:e,onOpenChange:t}){const{t:n,locale:s}=te(),[i,r]=m.useState(""),[a,l]=m.useState("all"),[c,d]=m.useState(),[u,h]=m.useState([]),[p,f]=m.useState([]),x=ie(F=>F.conversations),g=ie(F=>F.activeId),v=xe(F=>F.projects),w=xe(F=>F.scratchSessionsEnabled),y=xe(F=>F.keybindings),b=(g?x[g]?.projectId:void 0)??v[0]?.id??"",_=i.trim(),j=`${a}
101
- ${b}
102
- ${_}`,N=c?.key===j?c.hits:CS,C=m.useMemo(()=>{if(!e)return[];const U=(g?x[g]:void 0)?.activeTabId,de=U&&x[U]?U:g;return Object.values(x).map(Y=>{const X=v.find(z=>z.id===Y.projectId);return!w&&X?.kind==="scratch"?null:yQ({conversationId:Y.id,projectId:Y.projectId,projectName:X?.name??Y.projectId,title:Y.title,lastActiveAt:vl(Y),archived:Y.archived,isDraftEmpty:XI(Y),isCurrent:Y.id===de,parentConversationId:Y.parentId,coworkerId:Y.parentId?Y.id:void 0,messages:Y.messages})}).filter(Y=>Y!==null)},[g,x,e,v,w]),k=m.useMemo(()=>_?fQ(C,i,{currentProjectId:b,scope:a}):CS,[b,C,i,a,_]),E=m.useMemo(()=>e?vQ(Object.values(x),{scope:a,currentProjectId:b}):[],[x,b,e,a]),I=C2(p),T=m.useMemo(()=>_?k2(I,i,{translate:F=>n(F)}):[],[i,I,n,_]),A=m.useMemo(()=>i.trim()?_2(u,i):[],[u,i]),D=m.useMemo(()=>j2(u),[u]);m.useEffect(()=>{if(!e)return;const F=U=>{U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),t(!1))};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[t,e]),m.useEffect(()=>{if(!e){r(""),l("all"),d(void 0);return}window.electronAPI.browser.listSearchableTabs().then(F=>h(F.filter(U=>!Jk(U.conversationId)))).catch(()=>{h([])}),window.electronAPI.sshConnections.list().then(F=>{f(F.map(U=>({id:U.id,name:U.name})))}).catch(()=>{f([])})},[e]),m.useEffect(()=>{if(!e||!_||!b)return;let F=!1;const U=window.setTimeout(()=>{window.electronAPI.workspaceSearch.query({query:_,currentProjectId:b,scope:a}).then(de=>{F||d({key:j,hits:de.hits})}).catch(()=>{F||d({key:j,hits:[]})})},80);return()=>{F=!0,window.clearTimeout(U)}},[j,b,e,a,_]);const W=m.useMemo(()=>mQ(C,k,N,i,{currentProjectId:b,scope:a}),[N,b,C,k,i,a]),J=F=>{const U=ie.getState(),de=U.conversations[F.conversationId],Y=F.parentConversationId??de?.parentId;if(Y&&U.conversations[Y]?(U.selectConversation(Y),U.selectTab(Y,F.coworkerId??F.conversationId)):U.selectConversation(F.conversationId),t(!1),F.field==="body"||F.field==="tool"){const X=i.trim().split(/\s+/).find(Boolean);X&&window.setTimeout(()=>aI(X),0)}},O=F=>{const U=ie.getState(),Y=U.conversations[F.conversationId]?.parentId;Y&&U.conversations[Y]?(U.selectConversation(Y),U.selectTab(Y,F.conversationId)):U.selectConversation(F.conversationId),ag({conversationId:F.conversationId,tabId:F.tabId,title:F.title||n("Browser")}),t(!1)},B=F=>{window.electronAPI.window.openSettings({category:F.category,rowId:F.id}),t(!1)},L=_.length>0&&W.length===0&&A.length===0&&T.length===0,se=F=>{F.key==="Escape"&&(F.preventDefault(),F.stopPropagation(),t(!1))},Q=F=>{if(F.key!=="Tab"||F.nativeEvent.isComposing){se(F);return}F.altKey||F.ctrlKey||F.metaKey||(F.preventDefault(),l(U=>SS(U,F.shiftKey)))},V=Ii(y),H=Date.now(),ne=F=>{const U=v.find(de=>de.id===F);return U?jo(U):""},he=(F,U)=>[ne(F),U?Do(U,s,H):""].filter(Boolean).join(" · "),pe=(F,U)=>o.jsxs(o.Fragment,{children:[F&&o.jsx(ea,{size:"sm",className:"bg-brand/10 text-brand",children:n("Current")}),U&&o.jsx(ea,{variant:"outline",size:"sm",children:n("Archived")})]}),ke=F=>{const U=x[F.conversationId],de=F.parentConversationId??U?.parentId;let Y=pr;de&&(Y=U?.child?.mode==="task"?sg:Zs);const X=F.title||U?.child?.agentInstanceName||U?.coworkerName||n("New conversation"),z=de?x[de]?.title||n("New conversation"):void 0,ue=F.field==="body"||F.field==="tool"||F.field==="id"?F.snippet.replace(/\s+/g," ").trim():"";return o.jsx(Dr,{icon:Y,title:o.jsxs(o.Fragment,{children:[z&&o.jsxs("span",{className:"text-muted-foreground",children:[z," › "]}),o.jsx(Fa,{text:X,query:i})]}),badges:pe(F.isCurrent,F.archived),detail:ue&&o.jsx(Fa,{text:ue,query:i}),meta:he(F.projectId,U?vl(U):void 0)})},Me=(F,U)=>o.jsx(Jo,{value:U,className:"gap-2.5",onClick:()=>O(F),children:o.jsx(Dr,{icon:uo,title:o.jsx(Fa,{text:F.title||F.url,query:i}),meta:kQ(F.url)})},U),fe=o.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:F=>{F.preventDefault(),F.stopPropagation(),l(U=>SS(U,F.shiftKey))},children:[n(SQ[a]),o.jsx(ii,{className:"h-4 min-w-4 text-[10px]",children:"⇥"})]});return o.jsx(JT,{open:e,onOpenChange:t,children:o.jsx(ZT,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:se,children:o.jsxs(QT,{children:[o.jsx(eI,{placeholder:n("Search conversations, browser tabs, settings…"),value:i,onChange:F=>r(F.currentTarget.value),onKeyDown:Q,endAddon:fe}),o.jsxs(sI,{children:[L&&o.jsxs(nI,{children:[n("No matching results"),a!=="all-including-archived"&&o.jsxs("span",{className:"mt-2 flex items-center justify-center gap-1.5 text-xs",children:[o.jsx(ii,{children:"⇥"}),n(a==="project"?"Search all projects":"Include archived")]})]}),o.jsxs(tI,{children:[!_&&o.jsxs(o.Fragment,{children:[E.length>0&&o.jsxs(Tr,{children:[o.jsx(Ir,{children:n("Recent")}),E.map(F=>o.jsx(Jo,{value:`recent-${F.id}`,className:"gap-2.5",onClick:()=>J({conversationId:F.id,field:"title",snippet:F.title}),children:o.jsx(Dr,{icon:pr,title:F.title||n("New conversation"),badges:pe(F.id===g,F.archived),meta:he(F.projectId,vl(F))})},F.id))]}),D.length>0&&o.jsxs(Tr,{children:[o.jsx(Ir,{children:n("Browser")}),D.map(F=>Me(F,`recent-browser-${F.tabId}`))]}),o.jsxs(Tr,{children:[o.jsx(Ir,{children:n("Actions")}),o.jsxs(Jo,{value:"new-conversation",className:"gap-2.5",onClick:()=>{b&&ie.getState().newConversation(b),t(!1)},children:[o.jsx(Dr,{icon:ps,title:o.jsxs(o.Fragment,{children:[n("New conversation"),ne(b)&&o.jsxs("span",{className:"text-muted-foreground",children:[" · ",ne(b)]})]})}),o.jsx(ky,{children:Mi(V["new-conversation"])})]}),o.jsxs(Jo,{value:"open-settings",className:"gap-2.5",onClick:()=>{window.electronAPI.window.openSettings(),t(!1)},children:[o.jsx(Dr,{icon:ai,title:n("Open settings")}),o.jsx(ky,{children:Mi(V["open-settings"])})]})]})]}),_.length>0&&W.length>0&&o.jsxs(Tr,{children:[o.jsx(Ir,{children:n("Conversations")}),W.map(F=>o.jsx(Jo,{value:`conv-${F.conversationId}-${F.field}`,className:"gap-2.5",onClick:()=>J(F),children:ke(F)},`${F.conversationId}-${F.field}`))]}),_.length>0&&A.length>0&&o.jsxs(Tr,{children:[o.jsx(Ir,{children:n("Browser")}),A.map(F=>Me(F,`browser-${F.tabId}`))]}),_.length>0&&T.length>0&&o.jsxs(Tr,{children:[o.jsx(Ir,{children:n("Settings")}),T.map(F=>o.jsx(Jo,{value:`settings-${F.id}`,className:"gap-2.5",onClick:()=>B(F),children:o.jsx(Dr,{icon:ai,title:o.jsx(Fa,{text:n(F.title),query:i}),detail:F.description&&o.jsx(Fa,{text:n(F.description),query:i}),meta:n(CQ[F.category]??F.category)})},F.id))]})]})]}),o.jsxs(iI,{children:[o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsxs(Ck,{children:[o.jsx(ii,{children:"↑"}),o.jsx(ii,{children:"↓"})]}),n("Navigate")]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(ii,{children:"↵"}),n("Open")]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(ii,{children:"⇥"}),n("Switch scope")]})]}),o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(ii,{children:"esc"}),n("Close")]})]})]})})})}var JI,ZI=class{constructor(){}},Us=class extends ZI{constructor(e,t,n,s){super(),this.viewId=e,this.groupId=t,this.panelId=n,this.tabGroupId=s}},bl=class extends ZI{constructor(e,t){super(),this.viewId=e,this.paneId=t}},fo=class QI{constructor(){}static getInstance(){return QI.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)}};JI=fo;fo.INSTANCE=new JI;function Mn(){const e=fo.getInstance();if(e.hasData(Us.prototype))return e.getData(Us.prototype)[0]}function Ha(){const e=fo.getInstance();if(e.hasData(bl.prototype))return e.getData(bl.prototype)[0]}let en;(function(e){e.NONE={dispose:()=>{}};function t(n){return{dispose:()=>{n()}}}e.from=t})(en||(en={}));var dt=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())}},Gn=class{constructor(){this._disposable=en.NONE}get value(){return this._disposable===en.NONE?void 0:this._disposable}set value(e){this._disposable&&this._disposable.dispose(),this._disposable=e}dispose(){this._disposable&&(this._disposable.dispose(),this._disposable=en.NONE)}};let qs;(function(e){e.any=(...t)=>n=>{const s=t.map(i=>i(n));return{dispose:()=>{s.forEach(i=>{i.dispose()})}}}})(qs||(qs={}));var Ux=class{constructor(){this._defaultPrevented=!1}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}},eD=class{constructor(){this._isAccepted=!1}get isAccepted(){return this._isAccepted}accept(){this._isAccepted=!0}},jQ=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()}},kS=class tD{static create(){var t;return new tD((t=new Error("listener stacktrace").stack)!==null&&t!==void 0?t:"")}constructor(t){this.value=t}print(){console.warn("dockview: stacktrace",this.value)}},NQ=class{constructor(e,t){this.callback=e,this.stacktrace=t}},me=class vi{static setLeakageMonitorEnabled(t){t!==vi.ENABLE_TRACKING&&vi.MEMORY_LEAK_WATCHER.clear(),vi.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 NQ(t,vi.ENABLE_TRACKING?kS.create():void 0);return this._listeners.push(s),{dispose:()=>{const i=this._listeners.indexOf(s);i>-1&&this._listeners.splice(i,1)}}},vi.ENABLE_TRACKING&&vi.MEMORY_LEAK_WATCHER.add(this._event,kS.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,i=s.length;if(i!==0){if(i===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),en.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&&(vi.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=[]),vi.ENABLE_TRACKING&&this._event&&vi.MEMORY_LEAK_WATCHER.delete(this._event))}};me.ENABLE_TRACKING=!1;me.MEMORY_LEAK_WATCHER=new jQ;function rt(e,t,n,s){return e.addEventListener(t,n,s),{dispose:()=>{e.removeEventListener(t,n,s)}}}var _S=class{constructor(){this._onFired=new me,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()}},TQ=class extends dt{constructor(e){super(),this._onDidChange=new me,this.onDidChange=this._onDidChange.event,this._value=null,this.addDisposables(this._onDidChange,yr(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 yr(e,t){const n=new ResizeObserver(s=>{requestAnimationFrame(()=>{const i=s[0];t(i)})});return n.observe(e),{dispose:()=>{n.unobserve(e),n.disconnect()}}}const mi=(e,...t)=>{for(const n of t)e.classList.contains(n)&&e.classList.remove(n)},gi=(e,...t)=>{for(const n of t)e.classList.contains(n)||e.classList.add(n)},Je=(e,t,n)=>{const s=e.classList.contains(t);n&&!s&&e.classList.add(t),!n&&s&&e.classList.remove(t)};function Sm(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}function nD(e){return new IQ(e)}var IQ=class extends dt{constructor(e){super(),this._onDidFocus=new me,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new me,this.onDidBlur=this._onDidBlur.event,this.addDisposables(this._onDidFocus,this._onDidBlur);let t=Sm(document.activeElement,e),n=!1;const s=()=>{n=!1,t||(t=!0,this._onDidFocus.fire())},i=()=>{t&&(n=!0,globalThis.setTimeout(()=>{n&&(n=!1,t=!1,this._onDidBlur.fire())},0))};this._refreshStateHandler=()=>{Sm(document.activeElement,e)!==t&&(t?i():s())},this.addDisposables(rt(e,"focus",s,!0)),this.addDisposables(rt(e,"blur",i,!0))}refreshState(){this._refreshStateHandler()}};const sD="dv-quasiPreventDefault";function iD(e){e[sD]=!0}function jS(e){return e[sD]}function DQ(e,t,n={}){const s=Array.from(t),{nonce:i}=n,r=typeof i=="function"?i(e):i;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 Cm(e){const{left:t,top:n,width:s,height:i}=e.getBoundingClientRect();return{left:t+window.scrollX,top:n+window.scrollY,width:s,height:i}}function oD(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 PQ(e,t){e.dataset.testid=t}function EQ(e,t){const n=[];function s(i){if(i.nodeType===Node.ELEMENT_NODE){e.includes(i.tagName)&&n.push(i),i.shadowRoot&&s(i.shadowRoot);for(const r of i.children)s(r)}}return s(t instanceof Document?t.documentElement:t),n}function Wl(e=document){const t=EQ(["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 i of t){var s;i.style.pointerEvents=(s=n.get(i))!==null&&s!==void 0?s:"auto"}t.splice(0,t.length)}}}function AQ(e){function t(i){const r=[];for(let a=0;a<i.classList.length;a++)r.push(i.classList.item(a));return r}let n,s=e;for(;s!==null&&(n=t(s).find(i=>i.startsWith("dockview-theme-")),typeof n!="string");)s=s.parentElement;return n}var jh=class{constructor(e){this.element=e,this._classNames=[]}setClassNames(e){for(const t of this._classNames)Je(this.element,t,!1);this._classNames=e.split(" ").filter(t=>t.trim().length>0);for(const t of this._classNames)Je(this.element,t,!0)}};const rD=100;function Hp(e,t){const n=Cm(e),s=Cm(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 MQ(e){const t=new me;let n=e.screenX,s=e.screenY,i,r=0,a=!1;const l=()=>{if(a||e.closed)return;const d=e.screenX,u=e.screenY;(d!==n||u!==s)&&(clearTimeout(i),i=setTimeout(()=>{t.fire()},rD),n=d,s=u),r=requestAnimationFrame(l)};l();const c=t.dispose.bind(t);return t.dispose=()=>{a||(a=!0,cancelAnimationFrame(r),clearTimeout(i)),c()},t}function RQ(e,t){let n;return new dt(rt(e,"resize",()=>{clearTimeout(n),n=setTimeout(()=>{t()},rD)}))}function LQ(e,t,n){var s;const i=(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<i?l=i-d:p>i&&(l=-i-p),u<i?c=i-u:h>i&&(c=-h-i),(l!==0||c!==0)&&(e.style.transform=`translate(${l}px, ${c}px)`)}function OQ(e){let t=e;for(;t&&(t.style.zIndex==="auto"||t.style.zIndex==="");)t=t.parentElement;return t}function io(e){if(e.length===0)throw new Error("Invalid tail call");return[e.slice(0,e.length-1),e[e.length-1]]}function aD(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 Bp(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))}function Zc(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))}function zQ(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(t(s))return n}return-1}function lD(e,t){const n=e.indexOf(t);return n>-1?(e.splice(n,1),!0):!1}const In=(e,t,n)=>t>n?t:Math.min(n,Math.max(e,t)),Kx=()=>{let e=1;return{next:()=>(e++).toString()}},ti=(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 GQ=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=In((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 NS(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 Ss;(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})(Ss||(Ss={}));var xr=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,mi(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,Je(this.element,"dv-splitview-disabled",e)}get margin(){return this._margin}set margin(e){this._margin=e,Je(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 me,this.onDidSashEnd=this._onDidSashEnd.event,this._onDidAddView=new me,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new me,this.onDidRemoveView=this._onDidRemoveView.event,this.resize=(i,r,a=this.viewItems.map(f=>f.size),l,c,d=Number.NEGATIVE_INFINITY,u=Number.POSITIVE_INFINITY,h,p)=>{if(i<0||i>this.viewItems.length)return 0;const f=ti(i,-1),x=ti(i+1,this.viewItems.length);if(c)for(const I of c)Bp(f,I),Bp(x,I);if(l)for(const I of l)Zc(f,I),Zc(x,I);const g=f.reduce((I,T)=>I+this.viewItems[T].minimumSize-a[T],0),v=f.reduce((I,T)=>I+this.viewItems[T].maximumSize-a[T],0),w=x.length===0?Number.POSITIVE_INFINITY:x.reduce((I,T)=>I+a[T]-this.viewItems[T].minimumSize,0),y=x.length===0?Number.NEGATIVE_INFINITY:x.reduce((I,T)=>I+a[T]-this.viewItems[T].maximumSize,0),b=Math.max(g,y),_=Math.min(w,v);let j=!1;if(h){const I=this.viewItems[h.index],T=r>=h.limitDelta;j=T!==I.visible,I.setVisible(T,h.size)}if(!j&&p){const I=this.viewItems[p.index],T=r<p.limitDelta;j=T!==I.visible,I.setVisible(T,p.size)}if(j)return this.resize(i,r,a,l,c,d,u);const N=In(r,b,_);let C=0,k=N;for(const I of f){const T=this.viewItems[I],A=a[I],D=In(A+k,T.minimumSize,T.maximumSize),W=D-A;C+=W,k-=W,T.size=D}let E=C;for(const I of x){const T=this.viewItems[I],A=a[I],D=In(A-E,T.minimumSize,T.maximumSize),W=D-A;E+=W,T.size=D}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((i,r)=>{const a=i.visible===void 0||i.visible?i.size:{type:"invisible",cachedVisibleSize:i.size},l=i.view;this.addView(l,a,r,!0)}),this._contentSize=this.viewItems.reduce((i,r)=>i+r.size,0),this.saveProportions())}style(e){e?.separatorBorder==="transparent"?(mi(this.element,"dv-separator-border"),this.element.style.removeProperty("--dv-separator-border")):(gi(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=ti(this.viewItems.length).filter(a=>a!==e),s=[...n.filter(a=>this.viewItems[a].priority==="low"),e],i=n.filter(a=>this.viewItems[a].priority==="high"),r=this.viewItems[e];t=Math.round(t),t=In(t,r.minimumSize,Math.min(r.maximumSize,this._size)),r.size=t,this.relayout(s,i)}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=In(t,e.minimumSize,e.maximumSize),e.size=t;const s=ti(this.viewItems.length).filter(a=>a!==n),i=[...s.filter(a=>this.viewItems[a].priority==="low"),n],r=s.filter(a=>this.viewItems[a].priority==="high");this.relayout([...i,n],r)}addView(e,t=Ss.Distribute,n=this.viewItems.length,s){const i=document.createElement("div");i.className="dv-view",i.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 GQ(i,e,r,{dispose:()=>{a.dispose(),i.remove()}});if(n===this.viewItems.length?this.viewContainer.appendChild(i):this.viewContainer.insertBefore(i,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 O of this.viewItems)O.enabled=!1;const f=(p=c.ownerDocument)!==null&&p!==void 0?p:document,x=Wl(f),g=this._orientation==="HORIZONTAL"?h.clientX:h.clientY,v=zQ(this.sashes,O=>O.container===c),w=this.viewItems.map(O=>O.size);let y,b;const _=ti(v,-1),j=ti(v+1,this.viewItems.length),N=_.reduce((O,B)=>O+(this.viewItems[B].minimumSize-w[B]),0),C=_.reduce((O,B)=>O+(this.viewItems[B].viewMaximumSize-w[B]),0),k=j.length===0?Number.POSITIVE_INFINITY:j.reduce((O,B)=>O+(w[B]-this.viewItems[B].minimumSize),0),E=j.length===0?Number.NEGATIVE_INFINITY:j.reduce((O,B)=>O+(w[B]-this.viewItems[B].viewMaximumSize),0),I=Math.max(N,E),T=Math.min(k,C),A=this.findFirstSnapIndex(_),D=this.findFirstSnapIndex(j);if(typeof A=="number"){const O=this.viewItems[A],B=Math.floor(O.viewMinimumSize/2);y={index:A,limitDelta:O.visible?I-B:I+B,size:O.size}}if(typeof D=="number"){const O=this.viewItems[D],B=Math.floor(O.viewMinimumSize/2);b={index:D,limitDelta:O.visible?T+B:T-B,size:O.size}}const W=O=>{const B=(this._orientation==="HORIZONTAL"?O.clientX:O.clientY)-g;this.resize(v,B,w,void 0,void 0,I,T,y,b),this.distributeEmptySpace(),this.layoutViews()},J=()=>{for(const O of this.viewItems)O.enabled=!0;x.release(),this.saveProportions(),f.removeEventListener("pointermove",W),f.removeEventListener("pointerup",J),f.removeEventListener("pointercancel",J),f.removeEventListener("contextmenu",J),this._onDidSashEnd.fire(void 0)};f.addEventListener("pointermove",W),f.addEventListener("pointerup",J),f.addEventListener("pointercancel",J),f.addEventListener("contextmenu",J)};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=In(n,a.minimumSize,a.maximumSize);const s=ti(this.viewItems.length),i=s.filter(a=>this.viewItems[a].priority==="low"),r=s.filter(a=>this.viewItems[a].priority==="high");this.relayout(i,r)}removeView(e,t,n=!1){const s=this.viewItems.splice(e,1)[0];if(s.dispose(),this.viewItems.length>=1){const i=Math.max(e-1,0);this.sashes.splice(i,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):Ss.Invisible(n),i=this.removeView(e,void 0,!0);this.addView(i,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 i=0;i<this.viewItems.length;i++){const r=this.viewItems[i],a=this.proportions[i];typeof a=="number"?s+=a:e-=r.size}for(let i=0;i<this.viewItems.length;i++){const r=this.viewItems[i],a=this.proportions[i];typeof a=="number"&&s>0&&(r.size=In(Math.round(a*e/s),r.minimumSize,r.maximumSize))}}else{const s=ti(this.viewItems.length),i=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,i,r)}this.distributeEmptySpace(),this.layoutViews()}relayout(e,t){const n=this.viewItems.reduce((s,i)=>s+i.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=ti(this.viewItems.length-1,-1);let i=!1;for(const r of this.viewItems)if(r.priority==="low"||r.priority==="high"){i=!0;break}if(i){const r=s.filter(l=>this.viewItems[l].priority==="low"),a=s.filter(l=>this.viewItems[l].priority==="high");for(const l of a)Bp(s,l);for(const l of r)Zc(s,l)}typeof e=="number"&&Zc(s,e);for(let r=0;n!==0&&r<s.length;r++){const a=this.viewItems[s[r]],l=In(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 i=0;const r=[],a=4;let l=0;this.viewItems.forEach((c,d)=>{i+=this.viewItems[d].size,r.push(i),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,x=this.sashes[d];this._orientation==="HORIZONTAL"&&NS(x,`${f}px`,"0px"),this._orientation==="VERTICAL"&&NS(x,"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 i=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]&&i[l+1]);if(u&&h){const p=ti(l,-1),f=ti(l+1,this.viewItems.length),x=this.findFirstSnapIndex(p),g=this.findFirstSnapIndex(f),v=typeof x=="number"&&!this.viewItems[x].visible,w=typeof g=="number"&&!this.viewItems[g].visible;v&&i[l]&&(a>0||this.startSnappingEnabled)?this.updateSash(c,1):w&&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){Je(e.container,"dv-disabled",t===2),Je(e.container,"dv-enabled",t===3),Je(e.container,"dv-maximum",t===0),Je(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 km=Object.keys({orientation:void 0,descriptor:void 0,proportionalLayout:void 0,styles:void 0,margin:void 0,disableAutoResizing:void 0,className:void 0});var TS=class extends dt{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 me,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 xr(this.element,{orientation:this._orientation,proportionalLayout:!1,descriptor:t.descriptor}),this.getPanes().forEach(s=>{const i=new dt(s.onDidChangeExpansionState(()=>{this.setupAnimation(),this._onDidChange.fire(void 0)})),r={pane:s,disposable:{dispose:()=>{i.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 i=e.onDidChangeExpansionState(()=>{this.setupAnimation(),this._onDidChange.fire(void 0)}),r={pane:e,disposable:{dispose:()=>{i.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),gi(this.element,"dv-animated"),this.animationTimer=setTimeout(()=>{this.animationTimer=void 0,mi(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()}},is=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 me,this.onDidChange=this._onDidChange.event,this._orthogonalSize=n,this._size=s,this._disposable=this.view.onDidChange(i=>{i?this._onDidChange.fire({size:this.orientation==="VERTICAL"?i.width:i.height,orthogonalSize:this.orientation==="VERTICAL"?i.height:i.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()}},Kn=class _m extends dt{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 i of this.children){var s;const r=(s=i.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 _m&&(n.margin=t)})}constructor(t,n,s,i,r,a,l,c){if(super(),this.orientation=t,this.proportionalLayout=n,this.styles=s,this._childrenDisposable=en.NONE,this.children=[],this._onDidChange=new me,this.onDidChange=this._onDidChange.event,this._onDidVisibilityChange=new me,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._orthogonalSize=r,this._size=i,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 xr(this.element,{orientation:this.orientation,descriptor:d,proportionalLayout:n,styles:s,margin:l})}else this.splitview=new xr(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 i=this.splitview.contentSize===0;(n&&s||!n&&i)&&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,i){if(s<0||s>this.children.length)throw new Error("Invalid index");this.splitview.addView(t,n,s,i),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 dt(qs.any(...this.children.map(t=>t.onDidChange))(t=>{this.invalidateCachedSizes(),this._onDidChange.fire({size:t.orthogonalSize})}),...this.children.map((t,n)=>t instanceof _m?t.onDidVisibilityChange(({visible:s})=>{this.setChildVisible(n,s)}):en.NONE))}dispose(){this._childrenDisposable.dispose(),this.splitview.dispose(),this.children.forEach(t=>t.dispose()),super.dispose()}};function jm(e,t){if(e instanceof is)return e;if(e instanceof Kn)return jm(e.children[t?e.children.length-1:0],t);throw new Error("invalid node")}function cD(e,t,n){if(e instanceof Kn){const s=new Kn(e.orientation,e.proportionalLayout,e.styles,t,n,e.disabled,e.margin);for(let i=e.children.length-1;i>=0;i--){const r=e.children[i];s.addChild(cD(r,r.size,r.orthogonalSize),r.size,0,!0)}return s}else return new is(e.view,e.orientation,n)}function Nm(e,t,n){if(e instanceof Kn){const s=new Kn(Ci(e.orientation),e.proportionalLayout,e.styles,t,n,e.disabled,e.margin);let i=0;for(let r=e.children.length-1;r>=0;r--){const a=e.children[r],l=a instanceof Kn?a.orthogonalSize:a.size;let c=e.size===0?0:Math.round(t*l/e.size);i+=c,r===0&&(c+=t-i),s.addChild(Nm(a,n,c),c,0,!0)}return s}else return new is(e.view,Ci(e.orientation),n)}function FQ(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 jn(e){const t=e.parentElement;if(!t)throw new Error("Invalid grid element");if(/\bdv-grid-view\b/.test(t.className))return[];const n=FQ(t),s=t.parentElement.parentElement.parentElement;return[...jn(s),n]}function zs(e,t,n){if(BQ(e,t)===HQ(n)){const[s,i]=io(t);let r=i;return(n==="right"||n==="bottom")&&(r+=1),[...s,r]}else{const s=n==="right"||n==="bottom"?1:0;return[...t,s]}}function HQ(e){return e==="top"||e==="bottom"?"VERTICAL":"HORIZONTAL"}function BQ(e,t){return t.length%2===0?Ci(e):e}const Ci=e=>e==="HORIZONTAL"?"VERTICAL":"HORIZONTAL";function VQ(e){return!!e.children}const Tm=(e,t)=>{const n=t==="VERTICAL"?e.box.width:e.box.height;if(!VQ(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(i=>Tm(i,Ci(t)));return typeof e.cachedVisibleSize=="number"?{type:"branch",data:s,size:e.cachedVisibleSize,visible:!1}:{type:"branch",data:s,size:n}};var dD=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=Nm(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 Kn&&(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=jn(e.element),[s,i]=this.getNode(n);if(!(i instanceof is)||((t=this._maximizedNode)===null||t===void 0?void 0:t.leaf)===i)return;this.hasMaximizedView()&&this.exitMaximizedView(),Tm(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 is?u!==c&&(l.isChildVisible(d)?l.setChildVisible(d,!1):r.push(u)):a(u,c)}}a(this.root,i),this._maximizedNode={leaf:i,hiddenOnMaximize:r},this._onDidMaximizedNodeChange.fire({view:i.view,isMaximized:!0})}exitMaximizedView(){if(!this._maximizedNode)return;const e=this._maximizedNode.hiddenOnMaximize;function t(s){for(let i=s.children.length-1;i>=0;i--){const r=s.children[i];r instanceof is?e.includes(r)||s.setChildVisible(i,!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=jn(e.element));const n=this._onDidMaximizedNodeChange.pause();try{this.hasMaximizedView()&&this.exitMaximizedView();const s={root:Tm(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 Kn(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 i=e.maximizedNode.location,[r,a]=this.getNode(i);if(!(a instanceof is))return;this.maximizeView(a.view)}}_deserialize(e,t,n,s){this.root=this._deserializeNode(e,t,n,s)}_deserializeNode(e,t,n,s){let i;if(e.type==="branch"){const a=e.data.map(l=>({node:this._deserializeNode(l,Ci(t),n,e.size),visible:l.visible}));i=new Kn(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)}i=new is(a,t,s,e.size)}return i}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 is)return;e.element.remove();const n=e.removeChild(0);e.dispose(),n.dispose(),this._root=cD(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 Kn(Ci(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(Nm(t,t.orthogonalSize,t.size),Ss.Distribute,0)}else this._root.addChild(e,Ss.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 is)return{box:s,view:e.view,cachedVisibleSize:n};const i=[];for(let r=0;r<e.children.length;r++){const a=e.children[r],l=e.getChildCachedVisibleSize(r);i.push(this._getViews(a,Ci(t),l))}return{box:s,children:i,cachedVisibleSize:n}}progmaticSelect(e,t=!1){const[n,s]=this.getNode(e);if(!(s instanceof is))throw new TypeError("invalid location");for(let i=n.length-1;i>-1;i--){const r=n[i],a=e[i]||0;if(t?a-1>-1:a+1<r.children.length)return jm(r.children[t?a-1:a+1],t)}return jm(this.root,t)}constructor(e,t,n,s,i){this.proportionalLayout=e,this.styles=t,this._locked=!1,this._margin=0,this._maximizedNode=void 0,this.disposable=new Gn,this._onDidChange=new me,this.onDidChange=this._onDidChange.event,this._onDidViewVisibilityChange=new me,this.onDidViewVisibilityChange=this._onDidViewVisibilityChange.event,this._onDidMaximizedNodeChange=new me,this.onDidMaximizedNodeChange=this._onDidMaximizedNodeChange.event,this.element=document.createElement("div"),this.element.className="dv-grid-view",this._locked=s??!1,this._margin=i??0,this.root=new Kn(n,e,t,0,0,this.locked,this.margin)}isViewVisible(e){const[t,n]=io(e),[,s]=this.getNode(t);if(!(s instanceof Kn))throw new TypeError("Invalid from location");return s.isChildVisible(n)}setViewVisible(e,t){this.hasMaximizedView()&&this.exitMaximizedView();const[n,s]=io(e),[,i]=this.getNode(n);if(!(i instanceof Kn))throw new TypeError("Invalid from location");this._onDidViewVisibilityChange.fire(),i.setChildVisible(s,t)}moveView(e,t,n){this.hasMaximizedView()&&this.exitMaximizedView();const[,s]=this.getNode(e);if(!(s instanceof Kn))throw new TypeError("Invalid location");s.moveChild(t,n)}addView(e,t,n){this.hasMaximizedView()&&this.exitMaximizedView();const[s,i]=io(n),[r,a]=this.getNode(s);if(a instanceof Kn){const l=new is(e,Ci(a.orientation),a.orthogonalSize);a.addChild(l,t,i)}else{const[l,...c]=[...r].reverse(),[d,...u]=[...s].reverse();let h=0;const p=l.getChildCachedVisibleSize(d);typeof p=="number"&&(h=Ss.Invisible(p)),l.removeChild(d).dispose();const f=new Kn(a.orientation,this.proportionalLayout,this.styles,a.size,a.orthogonalSize,this.locked,this.margin);l.addChild(f,a.size,d);const x=new is(a.view,l.orientation,a.size);f.addChild(x,h,0),typeof t!="number"&&t.type==="split"&&(t={type:"split",index:0});const g=new is(e,l.orientation,a.size);f.addChild(g,t,i)}}remove(e,t){const n=jn(e.element);return this.removeView(n,t)}removeView(e,t){this.hasMaximizedView()&&this.exitMaximizedView();const[n,s]=io(e),[i,r]=this.getNode(n);if(!(r instanceof Kn))throw new TypeError("Invalid location");const a=r.children[s];if(!(a instanceof is))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(i.length===0)return l instanceof is||(r.removeChild(0,t),this.root=l),a.view;const[c,...d]=[...i].reverse(),[u,...h]=[...n].reverse(),p=r.isChildVisible(0);r.removeChild(0,t);const f=c.children.map((x,g)=>c.getChildSize(g));if(c.removeChild(u,t).dispose(),l instanceof Kn){f.splice(u,1,...l.children.map(x=>x.size));for(let x=0;x<l.children.length;x++){const g=l.children[x];c.addChild(g,g.size,u+x)}for(;l.children.length>0;)l.removeChild(0)}else{const x=new is(l.view,Ci(l.orientation),l.size),g=p?l.orthogonalSize:Ss.Invisible(l.orthogonalSize);c.addChild(x,g,u)}l.dispose();for(let x=0;x<f.length;x++)c.resizeChild(x,f[x]);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 Kn))throw new TypeError("Invalid location");const[s,...i]=e;if(s<0||s>=t.children.length)throw new Error("Invalid location");const r=t.children[s];return n.push(t),this.getNode(i,r,n)}};const Im=Object.keys({disableAutoResizing:void 0,proportionalLayout:void 0,orientation:void 0,hideBorders:void 0,className:void 0});var qx=class extends dt{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(yr(this._element,n=>{if(this.isDisposed||this.disableResizing||!this._element.offsetParent||!oD(this._element))return;const s=Math.round(n.contentRect.width),i=Math.round(n.contentRect.height);s===this._lastWidth&&i===this._lastHeight||(this._lastWidth=s,this._lastHeight=i,this.layout(s,i))}))}};const $Q=Kx();function _u(e){switch(e){case"left":return"left";case"right":return"right";case"above":return"top";case"below":return"bottom";default:return"center"}}var uD=class extends qx{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=$Q.next(),this._groups=new Map,this._onDidRemove=new me,this.onDidRemove=this._onDidRemove.event,this._onDidAdd=new me,this.onDidAdd=this._onDidAdd.event,this._onDidMaximizedChange=new me,this.onDidMaximizedChange=this._onDidMaximizedChange.event,this._onDidActiveChange=new me,this.onDidActiveChange=this._onDidActiveChange.event,this._bufferOnDidLayoutChange=new _S,this.onDidLayoutChange=this._bufferOnDidLayoutChange.onEvent,this._onDidViewVisibilityChangeMicroTaskQueue=new _S,this.onDidViewVisibilityChangeMicroTaskQueue=this._onDidViewVisibilityChangeMicroTaskQueue.onEvent,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new jh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this.gridview=new dD(!!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()}),en.from(()=>{this.element.remove()}),this.gridview.onDidChange(()=>{this._bufferOnDidLayoutChange.fire()}),qs.any(this.onDidAdd,this.onDidRemove,this.onDidActiveChange)(()=>{this._bufferOnDidLayoutChange.fire()}),this._onDidMaximizedChange,this._onDidViewVisibilityChangeMicroTaskQueue,this._bufferOnDidLayoutChange)}setVisible(e,t){this.gridview.setViewVisible(jn(e.element),t),this._bufferOnDidLayoutChange.fire()}isVisible(e){return this.gridview.isViewVisible(jn(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 i;this._classNames.setClassNames((i=e.className)!==null&&i!==void 0?i:"")}}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??Ss.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,Ss.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 i=Array.from(this._groups.values());this.doSetGroupActive(i.length>0?i[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=jn(e.group.element),i=(n=this.gridview.next(s))===null||n===void 0?void 0:n.view;this.doSetGroupActive(i)}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=jn(e.group.element),i=(n=this.gridview.previous(s))===null||n===void 0?void 0:n.view;this.doSetGroupActive(i)}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 Ul(e){"@babel/helpers - typeof";return Ul=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},Ul(e)}function WQ(e,t){if(Ul(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(Ul(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function UQ(e){var t=WQ(e,"string");return Ul(t)=="symbol"?t:t+""}function KQ(e,t,n){return(t=UQ(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function IS(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,s)}return n}function pt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?IS(Object(n),!0).forEach(function(s){KQ(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):IS(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function qQ(e,t){return e==="center"?`Tab into ${t}`:`Split ${e} of ${t}`}function YQ(e,t){return e==="center"?`docked into ${t}`:`split ${e} of ${t}`}const ju={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)=>`${qQ(e,t)}. Arrows to change, Enter to confirm, Escape to go back.`,moveCommitted:(e,t,n)=>`${e} ${YQ(n,t)}.`,moveCancelled:()=>"Move cancelled.",moveNotAllowed:()=>"That move is not allowed.",moveFloated:e=>`${e} floated.`};function hD(e){return e?pt(pt({},ju),e):ju}var pD=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()}},Kl=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()}},fD=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()}},Yx=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 hD(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()}},mD=class extends dt{constructor(e,t){super(),this.element=e,this.callbacks=t,this.target=null,this.registerListeners()}onDragEnter(e){this.target=e.target,this.callbacks.onDragEnter(e)}onDragOver(e){e.preventDefault(),this.callbacks.onDragOver&&this.callbacks.onDragOver(e)}onDragLeave(e){this.target===e.target&&(this.target=null,this.callbacks.onDragLeave(e))}onDragEnd(e){this.target=null,this.callbacks.onDragEnd(e)}onDrop(e){this.callbacks.onDrop(e)}registerListeners(){this.addDisposables(rt(this.element,"dragenter",e=>{this.onDragEnter(e)},!0)),this.addDisposables(rt(this.element,"dragover",e=>{this.onDragOver(e)},!0)),this.addDisposables(rt(this.element,"dragleave",e=>{this.onDragLeave(e)})),this.addDisposables(rt(this.element,"dragend",e=>{this.onDragEnd(e)})),this.addDisposables(rt(this.element,"drop",e=>{this.onDrop(e)}))}};const XQ={value:50,type:"percentage"},JQ=100,ZQ=100;function Dm(){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 gD(e,t,n,s){var i,r,a;const l=(i=s?.smallWidthBoundary)!==null&&i!==void 0?i:JQ,c=(r=s?.smallHeightBoundary)!==null&&r!==void 0?r:ZQ,d=t<l,u=n<c,h=e==="left",p=e==="right",f=e==="top",x=e==="bottom",g=!d&&p,v=!d&&h,w=!u&&f,y=!u&&x;let b=1;const _=(a=s?.size)!==null&&a!==void 0?a:XQ;return _.type==="percentage"?b=In(_.value,0,100)/100:((g||v)&&(b=In(0,_.value,t)/t),(w||y)&&(b=In(0,_.value,n)/n)),{isSmallX:d,isSmallY:u,isLeft:h,isRight:p,isTop:f,isBottom:x,rightClass:g,leftClass:v,topClass:w,bottomClass:y,size:b}}function xD(e,t,n,s,i){const r=gD(t,n,s,i),{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);Je(e,"dv-drop-target-small-vertical",r.isSmallY),Je(e,"dv-drop-target-small-horizontal",r.isSmallX),Je(e,"dv-drop-target-selection-line",p),Je(e,"dv-drop-target-left",r.isLeft),Je(e,"dv-drop-target-right",r.isRight),Je(e,"dv-drop-target-top",r.isTop),Je(e,"dv-drop-target-bottom",r.isBottom),Je(e,"dv-drop-target-center",t==="center")}function QQ(e,t){const n=`${Math.round(t.top)}px`,s=`${Math.round(t.left)}px`,i=`${Math.round(t.width)}px`,r=`${Math.round(t.height)}px`;return e.style.top!==n||e.style.left!==s||e.style.width!==i||e.style.height!==r}function eee(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 vD(e){const t=gD(e.quadrant,e.width,e.height,e.overlayModel),{rightClass:n,leftClass:s,topClass:i,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,x={top:p,left:f,width:e.width,height:e.height};return n?(x.left=f+e.width*(1-a),x.width=e.width*a):s?x.width=e.width*a:i?x.height=e.height*a:r&&(x.top=p+e.height*(1-a),x.height=e.height*a),t.isSmallX&&t.isLeft&&(x.width=4),t.isSmallX&&t.isRight&&(x.left=f+e.width-4,x.width=4),t.isSmallY&&t.isTop&&(x.height=4),t.isSmallY&&t.isBottom&&(x.top=p+e.height-4,x.height=4),QQ(u,x)?(eee(u,x),u.className=`dv-drop-target-anchor${e.className?` ${e.className}`:""}`,Je(u,"dv-drop-target-left",t.isLeft),Je(u,"dv-drop-target-right",t.isRight),Je(u,"dv-drop-target-top",t.isTop),Je(u,"dv-drop-target-bottom",t.isBottom),Je(u,"dv-drop-target-anchor-line",t.isSmallX&&(t.isLeft||t.isRight)||t.isSmallY&&(t.isTop||t.isBottom)),Je(u,"dv-drop-target-center",e.quadrant==="center"),c.changed&&(Je(u,"dv-drop-target-anchor-container-changed",!0),setTimeout(()=>{Je(u,"dv-drop-target-anchor-container-changed",!1)},10)),{boundsChanged:!0,targetChanged:c.changed}):{boundsChanged:!1,targetChanged:c.changed}}var bD=class extends Ux{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 DS(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 tee(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 nee={value:20,type:"percentage"};var Nh=class Ya extends dt{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 me,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new me,this.onWillShowOverlay=this._onWillShowOverlay.event,this._disabled=!1,this._acceptedTargetZonesSet=new Set(this.options.acceptedTargetZones),this.dnd=new mD(this.element,{onDragEnter:()=>{var s,i;(s=(i=this.options).getOverrideTarget)===null||s===void 0||(s=s.call(i))===null||s===void 0||s.getElements()},onDragOver:s=>{var i,r,a,l,c,d,u;if(this._disabled){this.clearOwnOverlay();return}Ya.ACTUAL_TARGET=this;const h=(i=(r=this.options).getOverrideTarget)===null||i===void 0?void 0:i.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,x=p.offsetHeight;if(f===0||x===0)return;const g=p.getBoundingClientRect(),v=((d=s.clientX)!==null&&d!==void 0?d:0)-g.left,w=((u=s.clientY)!==null&&u!==void 0?u:0)-g.top,y=this.resolvePosition(v,w,f,x,s);if(this.isAlreadyUsed(s)){this.removeDropTarget();return}if(y===null){this.clearOwnOverlay();return}const b=y.position;if(!this.options.canDisplayOverlay(s,b)){this.clearOwnOverlay();return}const _=new bD({nativeEvent:s,position:b,edge:y.edge,edgeGroup:y.edgeGroup});if(this._onWillShowOverlay.fire(_),_.defaultPrevented){this.clearOwnOverlay();return}if(this.markAsUsed(s),y.edge){this.clearOwnOverlay(),this._state=b,this._edge=!0;return}if(this._edge=!1,!h){if(!this.targetElement){const j=Dm();this.targetElement=j.dropzone,this.overlayElement=j.selection,this._state="center",p.classList.add("dv-drop-target"),p.append(this.targetElement)}}this.toggleClasses(b,f,x),this._state=b},onDragLeave:()=>{var s,i;const r=(s=(i=this.options).getOverrideTarget)===null||s===void 0?void 0:s.call(i);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 i,r;const a=(i=(r=this.options).getOverrideTarget)===null||i===void 0?void 0:i.call(r);a&&Ya.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 i,r;s.preventDefault();const a=this._state,l=this._edge;this.removeDropTarget(),(i=(r=this.options).getOverrideTarget)===null||i===void 0||(i=i.call(r))===null||i===void 0||i.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[Ya.USED_EVENT_ID]=!0}isAlreadyUsed(t){const n=t[Ya.USED_EVENT_ID];return typeof n=="boolean"&&n}toggleClasses(t,n,s){var i,r;const a=(i=(r=this.options).getOverrideTarget)===null||i===void 0?void 0:i.call(r);if(a){var l,c,d;vD({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&&xD(this.overlayElement,t,n,s,this.options.overlayModel)}resolvePosition(t,n,s,i,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:i,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,i);return d?{position:d,edge:!1,edgeGroup:!1}:null}calculateQuadrant(t,n,s,i,r){var a,l;const c=(a=(l=this.options.overlayModel)===null||l===void 0?void 0:l.activationSize)!==null&&a!==void 0?a:nee;return c.type==="percentage"?wD(t,n,s,i,r,c.value):yD(t,n,s,i,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,i,r,a;const l=(n=(s=this.options).getOverrideTarget)===null||n===void 0?void 0:n.call(s),c=(i=(r=(a=this.options).getOverlayOutline)===null||r===void 0?void 0:r.call(a))!==null&&i!==void 0?i:this.element,d=c.offsetWidth,u=c.offsetHeight;if(!l&&!this.targetElement){const h=Dm();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}};Nh.USED_EVENT_ID="__dockview_droptarget_event_is_used__";function wD(e,t,n,s,i,r){const a=100*t/s,l=100*n/i;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 yD(e,t,n,s,i,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>i-r?"bottom":e.has("center")?"center":null}function see(e,t,n){var s,i,r;gi(t,"dv-dragged"),t.style.top="-9999px",((s=n?.ownerDocument)!==null&&s!==void 0?s:document).body.appendChild(t),e.setDragImage(t,(i=n?.x)!==null&&i!==void 0?i:0,(r=n?.y)!==null&&r!==void 0?r:0),setTimeout(()=>{mi(t,"dv-dragged"),t.remove()},0)}var Nu=class Xa extends dt{static getInstance(){var t;return(t=Xa._instance)!==null&&t!==void 0||(Xa._instance=new Xa),Xa._instance}constructor(){super(),this._targets=new Set,this._targetByElement=new Map,this._onDragStart=new me,this.onDragStart=this._onDragStart.event,this._onDragMove=new me,this.onDragMove=this._onDragMove.event,this._onDragEnd=new me,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,i;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=Wl((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=(i=a.ownerDocument)===null||i===void 0?void 0:i.defaultView)!==null&&s!==void 0?s:globalThis.window;this._moveListener=rt(d,"pointermove",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleMove(u)}),this._upListener=rt(d,"pointerup",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleEnd(u,!0)}),this._cancelListener=rt(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,i=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,i){const r={clientX:i.clientX,clientY:i.clientY,pointerEvent:i};s?.(r,!1),this._onDragEnd.fire(r)}}_findTargetUnder(t,n){var s,i;const r=((s=(i=this._active)===null||i===void 0?void 0:i.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 i={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(i),(s=this._onDragMoveCallback)===null||s===void 0||s.call(this,i),this._onDragMove.fire(i)}_handleEnd(t,n){const s={clientX:t.clientX,clientY:t.clientY,pointerEvent:t};if(n&&this._currentTarget)this._currentTarget.handleDrop(s);else{var i;(i=this._currentTarget)===null||i===void 0||i.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,i,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(),(i=this._upListener)===null||i===void 0||i.dispose(),(r=this._cancelListener)===null||r===void 0||r.dispose(),this._moveListener=void 0,this._upListener=void 0,this._cancelListener=void 0}};const iee={value:20,type:"percentage"};var oee=class extends dt{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 me,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new me,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,Nu.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,i,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=(i=(r=this.options).getOverlayOutline)===null||i===void 0?void 0:i.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 x=f.position;if(!this.options.canDisplayOverlay(e.pointerEvent,x)){this._clearOwnOverlay();return}const g=new bD({nativeEvent:e.pointerEvent,position:x,edge:f.edge});if(this._onWillShowOverlay.fire(g),g.defaultPrevented){this._clearOwnOverlay();return}if(f.edge){this._clearOwnOverlay(),this._state=x,this._edge=!0;return}if(this._edge=!1,a){vD({outlineElement:l,targetModel:a,quadrant:x,width:c,height:d,overlayModel:this.options.overlayModel,className:this.options.className}),this._state=x;return}if(!this._targetElement){const v=Dm();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&&xD(this._overlayElement,x,c,d,this.options.overlayModel),this._state=x}_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,i=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:i})}_resolvePosition(e,t,n,s,i){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:i});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 i,r;const a=(i=(r=this.options.overlayModel)===null||r===void 0?void 0:r.activationSize)!==null&&i!==void 0?i:iee;return a.type==="percentage"?wD(this._acceptedTargetZonesSet,e,t,n,s,a.value):yD(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 ree=5,aee=250,lee=8;var cee=class extends dt{constructor(e,t){var n;super(),this.element=e,this.options=t,this._disabled=!1,this._armed=!1,this._startX=0,this._startY=0,this._touchOnly=(n=t.touchOnly)!==null&&n!==void 0?n:!0,this.addDisposables(rt(this.element,"pointerdown",s=>{this._onPointerDown(s)}))}setDisabled(e){this._disabled=e,e&&this._cancelPending()}setTouchOnly(e){this._touchOnly!==e&&(this._touchOnly=e,e&&this._cancelPending())}_shouldHandle(e){var t,n;return!(this._disabled||this._touchOnly&&e.pointerType!=="touch"&&e.pointerType!=="pen"||!((t=(n=this.options).isCancelled)===null||t===void 0)&&t.call(n,e))}_onPointerDown(e){var t,n,s,i,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:aee;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:ree,u=this.options.pressTolerance,h=(s=typeof u=="function"?u():u)!==null&&s!==void 0?s:lee,p=(i=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&i!==void 0?i:globalThis.window;this._pendingMoveListener=rt(p,"pointermove",f=>{if(f.pointerId!==this._pendingPointerId)return;const x=f.clientX-this._startX,g=f.clientY-this._startY,v=Math.hypot(x,g);if(this._armed){v>=d&&this._beginDrag(f);return}v>h&&this._beginDrag(f)}),this._pendingUpListener=rt(p,"pointerup",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()}),this._pendingCancelListener=rt(p,"pointercancel",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()})}cancelPending(){this._cancelPending()}_cancelPending(){var e,t,n;this._pendingPointerId=void 0,this._armTimer!==void 0&&(clearTimeout(this._armTimer),this._armTimer=void 0),this._armed=!1,(e=this._pendingMoveListener)===null||e===void 0||e.dispose(),(t=this._pendingUpListener)===null||t===void 0||t.dispose(),(n=this._pendingCancelListener)===null||n===void 0||n.dispose(),this._pendingMoveListener=void 0,this._pendingUpListener=void 0,this._pendingCancelListener=void 0,this._startEvent=void 0}_beginDrag(e){var t,n,s,i,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=(i=(r=this.options).createGhost)===null||i===void 0?void 0:i.call(r,a);Nu.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()}},dee=class{constructor(e){var t,n,s,i,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)`,((i=(r=e.owner)===null||r===void 0?void 0:r.ownerDocument)!==null&&i!==void 0?i: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())}},uee=class extends dt{constructor(e,t){super(),this.el=e,this.opts=t,this._dataDisposable=new Gn,this._pointerEventsDisposable=new Gn,this._disabled=!!t.disabled,this.addDisposables(this._dataDisposable,this._pointerEventsDisposable,rt(this.el,"dragstart",n=>{var s,i,r,a,l,c,d;if(n.defaultPrevented||this._disabled||!((s=(i=this.opts).isCancelled)===null||s===void 0)&&s.call(i,n)){n.preventDefault();return}const u=Wl((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,x;if(see(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:(x=this.el.ownerDocument)!==null&&x!==void 0?x:void 0}),h.dispose){const g=h.dispose;setTimeout(()=>g(),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)}),rt(this.el,"dragend",n=>{var s,i;this._pointerEventsDisposable.dispose(),setTimeout(()=>this._dataDisposable.dispose(),0),(s=(i=this.opts).onDragEnd)===null||s===void 0||s.call(i,n)}))}setDisabled(e){this._disabled=e}setTouchOnly(e){}cancelPending(){}},hee=class{constructor(){this.kind="html5"}createDropTarget(e,t){return new Nh(e,t)}createDragSource(e,t){return new uee(e,t)}},pee=class{constructor(){this.kind="pointer"}createDropTarget(e,t){return new oee(e,t)}createDragSource(e,t){const n=t.createGhost?i=>{const r=t.createGhost(i);if(!r)return;const a=new dee({element:r.element,initialX:i.clientX,initialY:i.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 cee(e,{getData:t.getData,isCancelled:t.isCancelled,onDragStart:t.onDragStart,onDragEnd:t.onDragEnd?i=>t.onDragEnd(i.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 Po=new hee,mo=new pee,Pm=Object.keys({disableAutoResizing:void 0,disableDnd:void 0,className:void 0});var fee=class extends eD{constructor(e,t,n,s){super(),this.nativeEvent=e,this.position=t,this.getData=n,this.panel=s}},SD=class extends Ux{constructor(){super()}},CD=class extends dt{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 Gn,this._onDidDimensionChange=new me,this.onDidDimensionsChange=this._onDidDimensionChange.event,this._onDidChangeFocus=new me,this.onDidFocusChange=this._onDidChangeFocus.event,this._onWillFocus=new me,this.onWillFocus=this._onWillFocus.event,this._onDidVisibilityChange=new me,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._onWillVisibilityChange=new me,this.onWillVisibilityChange=this._onWillVisibilityChange.event,this._onDidActiveChange=new me,this.onDidActiveChange=this._onDidActiveChange.event,this._onActiveChange=new me,this.onActiveChange=this._onActiveChange.event,this._onDidParametersChange=new me,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)}},kD=class extends CD{constructor(e,t){super(e,t),this._onDidConstraintsChangeInternal=new me,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new me({replay:!0}),this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new me,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)}},mee=class extends kD{set pane(e){this._pane=e}constructor(e,t){super(e,t),this._onDidExpansionChange=new me({replay:!0}),this.onDidExpansionChange=this._onDidExpansionChange.event,this._onMouseEnter=new me({}),this.onMouseEnter=this._onMouseEnter.event,this._onMouseLeave=new me({}),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())}},Xx=class extends dt{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=nD(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 SD;this.api._onWillFocus.fire(e),!e.defaultPrevented&&this._element.focus()}layout(e,t){this._width=e,this._height=t,this.api._onDidDimensionChange.fire({width:e,height:t}),this.part&&this._params&&this.part.update(this._params.params)}init(e){this._params=e,this.part=this.getComponent()}update(e){var t,n;this._params=pt(pt({},this._params),{},{params:pt(pt({},(t=this._params)===null||t===void 0?void 0:t.params),e.params)});for(const s of Object.keys(e.params))e.params[s]===void 0&&delete this._params.params[s];(n=this.part)===null||n===void 0||n.update({params:this._params.params})}toJSON(){var e,t;const n=(e=(t=this._params)===null||t===void 0?void 0:t.params)!==null&&e!==void 0?e:{};return{id:this.id,component:this.component,params:Object.keys(n).length>0?n:void 0}}dispose(){var e;this.api.dispose(),(e=this.part)===null||e===void 0||e.dispose(),super.dispose()}},gee=class extends Xx{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 mee(e.id,e.component)),this._onDidChangeExpansionState=new me({replay:!0}),this.onDidChangeExpansionState=this._onDidChangeExpansionState.event,this._onDidChange=new me,this.onDidChange=this._onDidChange.event,this._orthogonalSize=0,this._size=0,this._isExpanded=!1,this.api.pane=this,this.api.initialize(this),this.headerSize=e.headerSize,this.headerComponent=e.headerComponent,this._minimumBodySize=e.minimumBodySize,this._maximumBodySize=e.maximumBodySize,this._isExpanded=e.isExpanded,this._headerVisible=e.isHeaderVisible,this._onDidChangeExpansionState.fire(this.isExpanded()),this._orientation=e.orientation,this.element.classList.add("dv-pane"),this.addDisposables(this.api.onWillVisibilityChange(t=>{const{isVisible:n}=t,{accessor:s}=this._params;s.setVisible(this,n)}),this.api.onDidSizeChange(t=>{this._onDidChange.fire({size:t.size})}),rt(this.element,"mouseenter",t=>{this.api._onMouseEnter.fire(t)}),rt(this.element,"mouseleave",t=>{this.api._onMouseLeave.fire(t)})),this.addDisposables(this._onDidChangeExpansionState,this.onDidChangeExpansionState(t=>{this.api._onDidExpansionChange.fire({isExpanded:t})}),this.api.onDidFocusChange(t=>{this.header&&(t.isFocused?gi(this.header,"focused"):mi(this.header,"focused"))})),this.renderOnce()}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}isExpanded(){return this._isExpanded}setExpanded(e){var t;this._isExpanded!==e&&(this._isExpanded=e,e?(this.animationTimer&&clearTimeout(this.animationTimer),this.body&&this.element.appendChild(this.body)):(this._expandedSize=this._size,this.animationTimer=setTimeout(()=>{var n;(n=this.body)===null||n===void 0||n.remove()},200)),this._onDidChange.fire(e?{size:(t=this._expandedSize)!==null&&t!==void 0?t:this.width}:{}),this._onDidChangeExpansionState.fire(e))}layout(e,t){this._size=e,this._orthogonalSize=t;const[n,s]=this.orientation==="HORIZONTAL"?[e,t]:[t,e];super.layout(n,s)}init(e){var t,n;super.init(e),typeof e.minimumBodySize=="number"&&(this.minimumBodySize=e.minimumBodySize),typeof e.maximumBodySize=="number"&&(this.maximumBodySize=e.maximumBodySize),this.bodyPart=this.getBodyComponent(),this.headerPart=this.getHeaderComponent(),this.bodyPart.init(pt(pt({},e),{},{api:this.api})),this.headerPart.init(pt(pt({},e),{},{api:this.api})),(t=this.body)===null||t===void 0||t.append(this.bodyPart.element),(n=this.header)===null||n===void 0||n.append(this.headerPart.element),typeof e.isExpanded=="boolean"&&this.setExpanded(e.isExpanded)}toJSON(){const e=this._params;return pt(pt({},super.toJSON()),{},{headerComponent:this.headerComponent,title:e.title})}renderOnce(){this.header=document.createElement("div"),this.header.tabIndex=0,this.header.className="dv-pane-header",this.header.style.height=`${this.headerSize}px`,this.header.style.lineHeight=`${this.headerSize}px`,this.header.style.minHeight=`${this.headerSize}px`,this.header.style.maxHeight=`${this.headerSize}px`,this.element.appendChild(this.header),this.body=document.createElement("div"),this.body.className="dv-pane-body",this.element.appendChild(this.body)}getComponent(){return{update:e=>{var t,n;(t=this.bodyPart)===null||t===void 0||t.update({params:e}),(n=this.headerPart)===null||n===void 0||n.update({params:e})},dispose:()=>{var e,t;(e=this.bodyPart)===null||e===void 0||e.dispose(),(t=this.headerPart)===null||t===void 0||t.dispose()}}}},xee=class extends gee{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 me,this.onDidDrop=this._onDidDrop.event,this._onUnhandledDragOver=new me,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:()=>(fo.getInstance().setData([new bl(t,e)],bl.prototype),{dispose:()=>{fo.getInstance().clearData(bl.prototype)}})};this.html5DragSource=Po.createDragSource(this.header,n),this.pointerDragSource=mo.createDragSource(this.header,n);const i={acceptedTargetZones:["top","bottom"],overlayModel:{activationSize:{type:"percentage",value:50}},canDisplayOverlay:(r,a)=>{const l=Ha();if(l&&l.paneId!==this.id&&l.viewId===this.accessor.id)return!0;const c=new fee(r,a,Ha,this);return this._onUnhandledDragOver.fire(c),c.isAccepted}};this.target=Po.createDropTarget(this.element,i),this.pointerTarget=mo.createDropTarget(this.element,i),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=Ha();if(t?.viewId!==this.accessor.id){this._onDidDrop.fire(pt(pt({},e),{},{panel:this,api:new Kl(this.accessor),getData:Ha}));return}const n=this._params.containerApi,s=t.paneId,i=n.getPanel(s);if(!i){this._onDidDrop.fire(pt(pt({},e),{},{panel:this,getData:Ha,api:new Kl(this.accessor)}));return}const r=n.panels,a=r.indexOf(i);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 vee=0;const bee=()=>`dv-tabpanel-${vee++}`;var wee=class extends dt{get element(){return this._element}constructor(e,t){var n,s,i,r,a,l,c;super(),this.accessor=e,this.group=t,this.disposable=new Gn,this._onDidFocus=new me,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new me,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-content-container",this._element.tabIndex=-1,this._element.id=bee(),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 Nh(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=mo.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:(i=(r=this.accessor).resolveDropOverlayModel)===null||i===void 0?void 0:i.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 x=(h=(p=(f=this.accessor).resolveDropOverlayModel)===null||p===void 0?void 0:p.call(f,"content"))!==null&&h!==void 0?h:{};this.dropTarget.setOverlayModel(x),this.pointerDropTarget.setOverlayModel(x)}))!==null&&a!==void 0?a:en.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 i=((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&&i){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(i){const u=nD(l);this.focusTracker=u;const h=new dt;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 Th=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},yee=()=>Th({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"}),_D=()=>Th({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"}),See=()=>Th({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"}),jD=()=>Th({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"}),Cee=500,kee=8;var Jx=class extends dt{constructor(e,t){super(),this.element=e,this.options=t,this._startX=0,this._startY=0,this.addDisposables(rt(this.element,"pointerdown",n=>{this._onPointerDown(n)}))}_onPointerDown(e){var t,n,s,i,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:Cee,l=(s=this.options.tolerance)!==null&&s!==void 0?s:kee,c=(i=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&i!==void 0?i:globalThis.window;this._timer=setTimeout(()=>{this._timer=void 0,this._cancelPending(),this._installContextMenuGuard(c),this._installClickGuard(c),this.options.onLongPress(e)},a),this._moveListener=rt(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=rt(c,"pointerup",d=>{d.pointerId===this._pointerId&&this._cancelPending()}),this._cancelListener=rt(c,"pointercancel",d=>{d.pointerId===this._pointerId&&this._cancelPending()})}_installContextMenuGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=rt(e,"contextmenu",s=>{s.preventDefault(),clearTimeout(n),t?.dispose()},{capture:!0})}_installClickGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=rt(e,"click",s=>{const i=s.target;i&&this.element.contains(i)&&(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 ri(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 _ee()?{html5:!1,pointer:!0,pointerHandlesMouse:!0}:{html5:!0,pointer:!0,pointerHandlesMouse:!1}}}function _ee(){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 jee=0;const Nee=()=>`dv-tab-${jee++}`;var Tee=class extends dt{get element(){return this._element}constructor(e,t,n){var s,i,r,a,l,c,d,u;super(),this.panel=e,this.accessor=t,this.group=n,this.content=void 0,this.panelTransfer=fo.getInstance(),this._direction="horizontal",this._pinIndicator=void 0,this._onPointDown=new me,this.onPointerDown=this._onPointDown.event,this._onTabClick=new me,this.onTabClick=this._onTabClick.event,this._onDropped=new me,this.onDrop=this._onDropped.event,this._onDragStart=new me,this.onDragStart=this._onDragStart.event,this._onDragEnd=new me,this.onDragEnd=this._onDragEnd.event;const h=ri(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=Nee(),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=(i=this.group)===null||i===void 0||(i=i.model)===null||i===void 0?void 0:i.contentContainerId;p&&this._element.setAttribute("aria-controls",p),Je(this.element,"dv-inactive-tab",!0),this._updatePinnedClasses();const f=(g,v)=>{if(this.group.locked)return!1;const w=Mn();if(this.accessor.id===w?.viewId){var y;return((y=this.accessor.options.theme)===null||y===void 0?void 0:y.tabAnimation)!=="smooth"}return this.group.model.canDisplayOverlay(g,v,"tab")};this.dropTarget=Po.createDropTarget(this._element,{acceptedTargetZones:["left","right"],overlayModel:this._buildOverlayModel(),canDisplayOverlay:f,getOverrideTarget:()=>{var g;return(g=n.model.dropTargetContainer)===null||g===void 0?void 0:g.model}}),this.pointerDropTarget=mo.createDropTarget(this._element,{acceptedTargetZones:["left","right"],overlayModel:this._buildOverlayModel(),canDisplayOverlay:f,getOverrideTarget:()=>{var g;return(g=n.model.dropTargetContainer)===null||g===void 0?void 0:g.model}});const x={getData:()=>(this.panelTransfer.setData([new Us(this.accessor.id,this.group.id,this.panel.id)],Us.prototype),{dispose:()=>{this.panelTransfer.clearData(Us.prototype)}}),createGhost:()=>({element:this._buildGhostElement(),offsetX:30,offsetY:-10}),onDragStart:g=>{var v;this._onDragStart.fire(g),!(g instanceof PointerEvent)&&((v=this.accessor.options.theme)===null||v===void 0?void 0:v.tabAnimation)==="smooth"&&requestAnimationFrame(()=>{Je(this.element,"dv-tab--dragging",!0)})},onDragEnd:g=>{this._onDragEnd.fire(g)}};this.html5DragSource=Po.createDragSource(this._element,pt(pt({},x),{},{disabled:!h.html5})),this.pointerDragSource=mo.createDragSource(this._element,pt(pt({},x),{},{disabled:!h.pointer,touchOnly:!h.pointerHandlesMouse,isCancelled:()=>!ri(this.accessor.options).pointer})),this.onWillShowOverlay=qs.any(this.dropTarget.onWillShowOverlay,this.pointerDropTarget.onWillShowOverlay),this.addDisposables(this._onPointDown,this._onTabClick,this._onDropped,this._onDragStart,this._onDragEnd,this.accessor.onDidOptionsChange(()=>{const g=this._buildOverlayModel();this.dropTarget.setOverlayModel(g),this.pointerDropTarget.setOverlayModel(g),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,g=>{var v;this._element.setAttribute("aria-label",(v=g.title)!==null&&v!==void 0?v:this.panel.id)}))!==null&&c!==void 0?c:{dispose:()=>{}},rt(this._element,"dragend",()=>{Je(this.element,"dv-tab--dragging",!1)}),this.html5DragSource,rt(this._element,"pointerdown",g=>{this._onPointDown.fire(g)}),rt(this._element,"click",g=>{this._onTabClick.fire(g)}),rt(this._element,"contextmenu",g=>{var v;(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,g)}),new Jx(this._element,{onLongPress:g=>{var v;this.pointerDragSource.cancelPending(),(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,g)}}),this.dropTarget.onDrop(g=>{this._onDropped.fire(g)}),this.pointerDropTarget.onDrop(g=>{this._onDropped.fire(g)}),this.dropTarget,this.pointerDropTarget,this.pointerDragSource)}_updatePinnedClasses(){var e,t,n,s;const i=(e=(t=this.panel.api)===null||t===void 0?void 0:t.isPinned)!==null&&e!==void 0?e:!1,r=i&&((n=this.accessor.options.pinnedTabs)===null||n===void 0?void 0:n.compact)===!0;Je(this.element,"dv-tab--pinned",i),Je(this.element,"dv-tab--pinned-compact",r);const a=i&&!(!((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(_D()),this._element.insertBefore(l,this._element.firstChild),this._pinIndicator=l}else!a&&this._pinIndicator&&(this._pinIndicator.remove(),this._pinIndicator=void 0)}setActive(e){Je(this.element,"dv-active-tab",e),Je(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 i=((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:i,smallHeightBoundary:i}}setDirection(e){this._direction=e;const t=e==="vertical"?["top","bottom"]:["left","right"];this.dropTarget.setTargetZones(t),this.pointerDropTarget.setTargetZones(t)}updateDragAndDropState(){const e=ri(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(i=>{n&&s.has(i)||t.style.setProperty(i,e.getPropertyValue(i),e.getPropertyPriority(i))}),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}},ql=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}},ND=class extends dt{get group(){return this.groupAccessor()}constructor(e){var t,n;super(),this.panelTransfer=fo.getInstance(),this._onDragStart=new me,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 i=ri(this.accessor.options);this._element.draggable=i.html5,Je(this._element,"dv-draggable",i.html5||i.pointer),this.addDisposables(this._onDragStart);const r=()=>{const p=document.createElement("div"),f=globalThis.getComputedStyle(this._element),x=f.getPropertyValue("--dv-activegroup-visiblepanel-tab-background-color"),g=f.getPropertyValue("--dv-activegroup-visiblepanel-tab-color");return p.style.backgroundColor=x,p.style.color=g,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 Us(this.accessor.id,this.group.id,null)],Us.prototype),{dispose:()=>{this.panelTransfer.clearData(Us.prototype)}}),createGhost:()=>{var p,f;const x=(p=(f=this.accessor).buildGroupDragGhost)===null||p===void 0?void 0:p.call(f,this.group);return x||{element:r(),offsetX:30,offsetY:-10}},onDragStart:p=>{this._onDragStart.fire(p)}};this.html5DragSource=Po.createDragSource(this._element,pt(pt({},l),{},{disabled:!i.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=mo.createDragSource(this._element,pt(pt({},l),{},{disabled:!i.pointer,touchOnly:!i.pointerHandlesMouse,touchInitiationDelay:()=>c()?500:250,pressTolerance:()=>c()?1/0:8,isCancelled:()=>!ri(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 Gn,u=()=>{const p=this.getFloatingOverlay();d.value=p?p.onDidStartMoving(()=>{this.pointerDragSource.cancelPending()}):en.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=ri(this.accessor.options);this._element.draggable=e.html5,Je(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}},Iee=class extends dt{get element(){return this._element}constructor(e,t){var n,s,i,r,a,l,c;super(),this.accessor=e,this.group=t,this._onDrop=new me,this.onDrop=this._onDrop.event,this._onDragStart=new me,this.onDragStart=this._onDragStart.event,this._element=document.createElement("div"),this._element.className="dv-void-container",this.addDisposables(this._onDrop,this._onDragStart,rt(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this.group)}),rt(this._element,"pointerdown",u=>{u.shiftKey&&iD(u)},!0)),this.dragSource=new ND({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=Mn();return this.accessor.id===p?.viewId?!0:t.model.canDisplayOverlay(u,h,"header_space")};this.dropTarget=Po.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=mo.createDropTarget(this._element,{acceptedTargetZones:["center"],canDisplayOverlay:d,getOverrideTarget:()=>{var u;return(u=t.model.dropTargetContainer)===null||u===void 0?void 0:u.model},overlayModel:(i=(r=this.accessor).resolveDropOverlayModel)===null||i===void 0?void 0:i.call(r,"header_space",this.group)}),this.onWillShowOverlay=qs.any(this.dropTarget.onWillShowOverlay,this.pointerDropTarget.onWillShowOverlay),this.addDisposables(this.dragSource,this.dragSource.onDragStart(u=>{this._onDragStart.fire(u)}),this.dropTarget.onDrop(u=>{this._onDrop.fire(u)}),this.pointerDropTarget.onDrop(u=>{this._onDrop.fire(u)}),this.dropTarget,this.pointerDropTarget,(a=(l=(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:en.NONE)}updateDragAndDropState(){this.dragSource.updateDragAndDropState()}},TD=class ID extends dt{get element(){return this._element}get orientation(){return this._orientation}set orientation(t){this._orientation!==t&&(this._scrollOffset=0,this._orientation=t,mi(this._scrollbar,"dv-scrollbar-vertical","dv-scrollbar-horizontal"),t==="vertical"?gi(this._scrollbar,"dv-scrollbar-vertical"):gi(this._scrollbar,"dv-scrollbar-horizontal"))}constructor(t){super(),this.scrollableElement=t,this._scrollOffset=0,this._orientation="horizontal",this._element=document.createElement("div"),this._element.className="dv-scrollable",this._scrollbar=document.createElement("div"),this._scrollbar.className="dv-scrollbar dv-scrollbar-horizontal",this.element.appendChild(t),this.element.appendChild(this._scrollbar),this.addDisposables(rt(this.element,"wheel",n=>{this._scrollOffset+=n.deltaY*ID.MouseWheelSpeed,this.scheduleStyleUpdate()}),rt(this._scrollbar,"pointerdown",n=>{var s;n.preventDefault();const i=(s=this._scrollbar.ownerDocument)!==null&&s!==void 0?s:document;Je(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=()=>{Je(this.element,"dv-scrollable-scrolling",!1),i.removeEventListener("pointermove",l),i.removeEventListener("pointerup",c),i.removeEventListener("pointercancel",c)};i.addEventListener("pointermove",l),i.addEventListener("pointerup",c),i.addEventListener("pointercancel",c)}),rt(this.element,"scroll",()=>{this.scheduleStyleUpdate()}),rt(this.scrollableElement,"scroll",()=>{this._scrollOffset=this._orientation==="horizontal"?this.scrollableElement.scrollLeft:this.scrollableElement.scrollTop,this.scheduleStyleUpdate()}),yr(this.element,()=>{Je(this.element,"dv-scrollable-resizing",!0),this._animationTimer&&clearTimeout(this._animationTimer),this._animationTimer=setTimeout(()=>{clearTimeout(this._animationTimer),Je(this.element,"dv-scrollable-resizing",!1)},500),this.scheduleStyleUpdate()}),en.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=In(this._scrollOffset,0,n-t),this._orientation==="horizontal"?this.scrollableElement.scrollLeft=this._scrollOffset:this.scrollableElement.scrollTop=this._scrollOffset;const i=this._scrollOffset/(n-t);this._orientation==="horizontal"?(this._scrollbar.style.left=`${(t-s)*i}px`,this._scrollbar.style.top=""):(this._scrollbar.style.top=`${(t-s)*i}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}};TD.MouseWheelSpeed=1;const DD="dv-tabs-container--wrap";function Dee(e,t){return typeof e=="boolean"?e:!!e?.[t]}function Em(e){return typeof e=="boolean"?e:e?Object.values(e).some(Boolean):!1}var PD=class extends eD{constructor(e,t,n,s,i){super(),this.nativeEvent=e,this.target=t,this.position=n,this.getData=s,this.group=i}};const Am=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 Pee(e){return!!e.referencePanel}function Eee(e){return!!e.referenceGroup}function Aee(e){return!!e.referencePanel}function Mee(e){return!!e.referenceGroup}const Zx=[{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 ED=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 Vp;function AD(){var e;return(e=Vp)!==null&&e!==void 0||(Vp=new ED(Zx,!0)),Vp}function Qx(e,t,n){const s=(n??AD()).resolveValue(t);s===void 0?e.style.removeProperty("--dv-tab-group-color"):e.style.setProperty("--dv-tab-group-color",s)}function ev(e,t){return(t??AD()).resolveValue(e)}var PS=class extends dt{get element(){return this._element}constructor(e){super(),this._palette=e,this._onClick=new me,this.onClick=this._onClick.event,this._onContextMenu=new me,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 Jx(this._element,{onLongPress:t=>{this._onContextMenu.fire(t)}}),rt(this._element,"click",t=>{this._onClick.fire(t)}),rt(this._element,"contextmenu",t=>{this._onContextMenu.fire(t)}))}init(e){this._tabGroup=e.tabGroup,this.updateColor(e.tabGroup.color),this.updateLabel(e.tabGroup.label),this.updateCollapsed(e.tabGroup.collapsed),this.addDisposables(e.tabGroup.onDidChange(()=>{this._tabGroup&&(this.updateColor(this._tabGroup.color),this.updateLabel(this._tabGroup.label))}),e.tabGroup.onDidCollapseChange(t=>{this.updateCollapsed(t)}),this._onClick.event(()=>{var t;(t=this._tabGroup)===null||t===void 0||t.toggle()}))}update(e){this._tabGroup=e.tabGroup,this.updateColor(e.tabGroup.color),this.updateLabel(e.tabGroup.label),this.updateCollapsed(e.tabGroup.collapsed)}updateColor(e){var t;Qx(this._element,e,this._palette),Je(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,Je(this._label,"dv-tab-group-chip-label--empty",!e)}updateCollapsed(e){Je(this._element,"dv-tab-group-chip--collapsed",e)}};const Ree="dv-tab-group-chip-continuation",ES=8;var MD=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=Ree,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(DD);s||this._clearContinuationMarkers();const i=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 w=u.getBoundingClientRect(),y=getComputedStyle(u),b=n?Number.parseFloat(y.marginTop)||0:Number.parseFloat(y.marginLeft)||0;h=n?w.top-e.top-b:w.left-e.left-b}else{const w=d[0],y=a.get(w);if(y){const b=y.value.element.getBoundingClientRect();h=n?b.top-e.top:b.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 x=f.value.element.getBoundingClientRect();let g=n?x.bottom-e.top:x.right-e.left,v=g-h;if((l.collapsed||l.panelIds.some(w=>{const y=a.get(w);return y?.value.element.classList.contains("dv-tab--group-expanding")}))&&u){const w=u.getBoundingClientRect(),y=n?w.top+w.height/2-e.top:w.left+w.width/2-e.left;let b=0,_=0;for(const N of l.panelIds){const C=a.get(N);if(!C)continue;const k=C.value.element;n?(b+=k.getBoundingClientRect().height,_+=k.scrollHeight):(b+=k.getBoundingClientRect().width,_+=k.scrollWidth)}const j=_>0?Math.min(1,b/_):0;h=y+(h-y)*j,g=y+(g-y)*j,v=Math.max(0,g-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,i,r,e,n)}}_positionWrappedUnderline(e,t,n,s,i){const a=ev(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,i);if(l.length===0){e.style.display="none",this._clearContinuationMarkers(t.id);return}this._positionContinuationMarkers(t.id,l,c,a,i);const d=Math.min(...l.map(b=>b.left)),u=Math.max(...l.map(b=>b.right)),h=Math.min(...l.map(b=>b.top)),p=Math.max(...l.map(b=>b.bottom)),f=i?Math.max(0,u-d):n.width,x=i?n.height:Math.max(0,p-h);e.style.left=i?`${d}px`:"0px",e.style.top=i?"0px":`${h}px`,e.style.bottom="auto",e.style.width=`${f}px`,e.style.height=`${x}px`,e.style.backgroundColor="";const{svg:g,path:v}=this.ensureSvgPath(e);g.setAttribute("width",String(f)),g.setAttribute("height",String(x)),v.setAttribute("stroke",a),v.setAttribute("stroke-width",String(2));const w=this._ctx.getHeaderPosition(),y=i?w==="right":w==="bottom";v.setAttribute("d",this._wrappedPathData(l,i,y,d,h,2))}_computeWrappedRuns(e,t,n,s){const i=[];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,x=s?p:u;let g=i.find(v=>Math.abs((s?v.left:v.top)-x)<=2);g?(g.top=Math.min(g.top,u),g.bottom=Math.max(g.bottom,h),g.left=Math.min(g.left,p),g.right=Math.max(g.right,f)):(g={top:u,bottom:h,left:p,right:f},i.push(g)),(a=r)!==null&&a!==void 0||(r=g)}return{runs:i,firstRun:r}}_wrappedPathData(e,t,n,s,i,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-i+r/2:l.bottom-i-r/2;a+=`M ${l.left},${c} L ${l.right},${c} `}return a.trim()}_positionContinuationMarkers(e,t,n,s,i){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,i){const u=(l.left+l.right)/2;d.style.left=`${u-ES/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-ES/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}}},Lee=class extends MD{_applyStraightLine(e,t,n,s,i,r,a){const l=a?i:s,c=a?s:i;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,i,r,a,l){const d=i,u=s,h=ev(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:x}=this.ensureSvgPath(e);x.setAttribute("stroke",h),x.setAttribute("stroke-width",String(2));const g=2,v=this._ctx.getHeaderPosition(),w=!l&&v==="bottom",y=l&&v==="right";let b,_;if(l?(b=y?d-g:g,_=y?g:d-g):(b=w?g:d-g,_=w?d-g:g),!p){this._applyStraightLine(f,x,e,u,d,b,l);return}const j=p.value.element.getBoundingClientRect();let N,C;if(l?(N=Math.max(0,j.top-a.top-n),C=Math.min(u,j.bottom-a.top-n)):(N=Math.max(0,j.left-a.left-n),C=Math.min(u,j.right-a.left-n)),C<=N){this._applyStraightLine(f,x,e,u,d,b,l);return}const k=6,E=_>b?1:-1;if(l){const I=d,T=u;f.setAttribute("width",String(I)),f.setAttribute("height",String(T)),e.style.width=`${I}px`,e.style.height=`${T}px`;const A=[`M ${b},0`,`L ${b},${N-k}`,`Q ${b},${N} ${b+E*k},${N}`,`L ${_-E*k},${N}`,`Q ${_},${N} ${_},${N+k}`,`L ${_},${C-k}`,`Q ${_},${C} ${_-E*k},${C}`,`L ${b+E*k},${C}`,`Q ${b},${C} ${b},${C+k}`,`L ${b},${T}`].join(" ");x.setAttribute("d",A)}else{const I=u,T=d;f.setAttribute("width",String(I)),f.setAttribute("height",String(T)),e.style.width=`${I}px`,e.style.height=`${T}px`;const A=[`M 0,${b}`,`L ${N-k},${b}`,`Q ${N},${b} ${N},${b+E*k}`,`L ${N},${_-E*k}`,`Q ${N},${_} ${N+k},${_}`,`L ${C-k},${_}`,`Q ${C},${_} ${C},${_-E*k}`,`L ${C},${b+E*k}`,`Q ${C},${b} ${C+k},${b}`,`L ${I},${b}`].join(" ");x.setAttribute("d",A)}}},Oee=class extends MD{applyShape(e,t,n,s,i,r,a,l){const d=ev(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 zee=new Map;var Gee=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:zee}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,i]of this._chipRenderers)if(!t.has(s)){var n;i.chip.element.remove(),i.chip.dispose(),(n=i.dragSourcesDisposable)===null||n===void 0||n.dispose(),i.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",i=this._ctx.tabsList.cloneNode(!0);s?(i.classList.remove("dv-tabs-container-vertical","dv-vertical"),i.classList.add("dv-horizontal"),i.style.writingMode="horizontal-tb",i.style.height=`${this._ctx.tabsList.offsetWidth}px`):i.style.height=`${this._ctx.tabsList.offsetHeight}px`,i.style.width="auto",i.style.overflow="visible",i.style.pointerEvents="none";const r=Array.from(i.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(i),this._ctx.accessor.element.appendChild(l);const d=i.querySelector(".dv-tab-group-chip"),u=n.getBoundingClientRect(),h=e.clientX-u.left,p=e.clientY-u.top;if(d){const f=d.getBoundingClientRect(),x=l.getBoundingClientRect(),g=f.left-x.left+h,v=f.top-x.top+p;e.dataTransfer.setDragImage(l,g,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=ri(this._ctx.accessor.options);for(const i of this._chipRenderers.values()){var t,n,s;i.chip.element.draggable=e.html5,(t=i.html5DragSource)===null||t===void 0||t.setDisabled(!e.html5),(n=i.pointerDragSource)===null||n===void 0||n.setDisabled(!e.pointer),(s=i.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"?Oee:Lee;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 i;return(i=this._ctx.group.activePanel)===null||i===void 0?void 0:i.id},getTabMap:()=>this._ctx.getTabMap(),getChipElement:i=>{var r;return(r=this._chipRenderers.get(i))===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=ri(this._ctx.accessor.options);e.element.draggable=n.html5;const s=fo.getInstance(),i=()=>(s.setData([new Us(this._ctx.accessor.id,this._ctx.group.id,null,t.id)],Us.prototype),{dispose:()=>{s.clearData(Us.prototype)}}),r=Po.createDragSource(e.element,{getData:i,disabled:!n.html5,isCancelled:()=>!ri(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(Us.prototype)};e.element.addEventListener("dragend",a,{once:!0});const l=mo.createDragSource(e.element,{getData:i,disabled:!n.pointer,touchOnly:!n.pointerHandlesMouse,isCancelled:()=>!ri(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 PS(this._ctx.accessor.tabGroupColorPalette);s.init({tabGroup:e,api:this._ctx.accessor.api});const i=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 PS?r.push(s.onContextMenu(a)):r.push(new Jx(s.element,{onLongPress:a}),rt(s.element,"contextmenu",a));const l=this._ctx.getDirection()==="vertical",c=new Nh(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=Mn();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 dt(...r);this._chipRenderers.set(e.id,{chip:s,html5DragSource:i.html5DragSource,pointerDragSource:i.pointerDragSource,dragSourcesDisposable:i.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 i=s[0],r=this._ctx.getTabMap().get(i);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 i=new Map;for(const l of e)for(const c of l.panelIds)i.set(c,l);for(const l of t){const c=l.value,d=c.panel.id,u=i.get(d),h=!!u;if(Je(c.element,"dv-tab--grouped",h),u){const p=u.panelIds,f=p[0]===d,x=p[p.length-1]===d;Je(c.element,"dv-tab--group-first",f),Je(c.element,"dv-tab--group-last",x),Qx(c.element,u.color,this._ctx.accessor.tabGroupColorPalette);const g=c.element.classList.contains("dv-tab--group-collapsed");if(!u.collapsed&&g){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(w),this._pendingTransitionCleanups.delete(d)},w=setTimeout(v,300);this._pendingTransitionCleanups.set(d,v),c.element.addEventListener("transitionend",v)}}else Je(c.element,"dv-tab--group-first",!1),Je(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())}},Fee=class extends dt{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(DD)}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,i=n-(s!==-1&&s<n?1:0);this._animState=null,this.clearWrapDropIndicator(),this.uncollapseSourceTab(t.sourceTabId),i!==s&&this.host.fireDrop({event:e,index:i,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=Mn();e?.tabGroupId&&e.groupId!==this.group.id&&this._animState.sourceTabGroupId!==e.tabGroupId&&(this._animState=null)}_initAnimStateForExternalDrag(){var e;const t=Mn();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),i=s?.model.getTabGroups().find(a=>a.id===e.tabGroupId),r=t*((n=i?.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:i?new Set(i.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,i=this._buildFirstPanelToGroupMap();let r=this._computeDragOverInsertionIndex(s,i),a=null;if(r!==null&&this._tabGroupManager.chipRenderers.size>0){const l=this._resolveInsertionAgainstTabGroups(s,r,i);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,i=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 g=(l=n.chipPositions.get(p))!==null&&l!==void 0?l:0;if(r+g>i){var c;(c=a)!==null&&c!==void 0||(a=u);break}r+=g}const f=n.tabPositions.get(h.panel.id),x=f?f.width:h.element.getBoundingClientRect().width;if(r+x/2<=i)r+=x,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 i=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;i+=(r=n.chipPositions.get(c))!==null&&r!==void 0?r:0}const d=n.tabPositions.get(l.panel.id);i+=d?d.width:l.element.getBoundingClientRect().width}return i}_resolveInsertionAgainstTabGroups(e,t,n){const s=!!this._animState.sourceTabGroupId,i=this._accumulatedWidthUpTo(t,n);for(const r of this.group.model.getTabGroups()){const a=this._evaluateTabGroupForInsertion(r,e,t,i,s);if(a)return a}return{insertionIndex:t,targetTabGroupId:null}}_evaluateTabGroupForInsertion(e,t,n,s,i){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:i?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 i=this._tabs.findIndex(a=>a.value.panel.id===s[0]),r=this._tabs.findIndex(a=>a.value.panel.id===s[s.length-1]);return i===-1||r===-1?null:{firstIdx:i,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,i,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,i)?t>=(e.collapsed?l.containerLeft+s+c/2:l.containerLeft+s+c)?{insertionIndex:i,targetTabGroupId:e.id}:{insertionIndex:n,targetTabGroupId:null}:null;const d=l.containerLeft+s+c;return n===i?{insertionIndex:n,targetTabGroupId:t>=d?e.id:null}:{insertionIndex:n,targetTabGroupId:e.id}}_onlySourceBetween(e,t){const n=this._animState;for(let i=e;i<t;i++){var s;const r=this._tabs[i].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",i=this._wrappedDragEntries();if(i.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(i,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,x)=>d(f.rect)-d(x.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,i=[];for(let r=0;r<this._tabs.length;r++){const a=this._tabs[r].value;a.panel.id!==n&&(s?.has(a.panel.id)||i.push({index:r,rect:a.element.getBoundingClientRect()}))}return i}_bucketWrappedLines(e,t,n){const s=[];for(const i of e){const r=t(i.rect),a=s.find(l=>Math.abs(l.start-r)<=2);a?(a.items.push(i),a.end=Math.max(a.end,n(i.rect))):s.push({start:r,end:n(i.rect),items:[i]})}return s.sort((i,r)=>i.start-r.start),s}_nearestWrappedLine(e,t){const n=s=>t<s.start?s.start-t:t-s.end;return e.reduce((s,i)=>n(i)<n(s)?i: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 i=this._tabs[e].value.element;if(this._tabs[e].value.panel.id===s)return;i.classList.add("dv-tab--reorder-before"),this._wrapIndicatorEl=i}else{const i=this._tabs[n-1].value.element;i.classList.add("dv-tab--reorder-after"),this._wrapIndicatorEl=i}}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",Je(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(),i=this._computeChipToShift(n);this._applyGapMargins(n,s,i,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 i=this._tabs.findIndex(r=>r.value.panel.id===s[0]);if((!n.targetTabGroupId||n.targetTabGroupId===e.id&&e.collapsed)&&!(i<t)){if(this._onlySourceBetween(t,i)){const r=this._tabGroupManager.chipRenderers.get(e.id);if(r)return r.chip.element}return null}}_applyGapMargins(e,t,n,s){const i=this._animState,r=i.sourceGroupPanelIds;let a=!1;for(const[l,c]of this._tabGroupManager.chipRenderers)l!==i.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!==i.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,Je(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"),Je(e,n,!1);else{e.style.marginLeft="0px",Je(e,n,!0);const i=()=>{e.style.removeProperty("margin-left"),Je(e,n,!1),e.removeEventListener("transitionend",i),clearTimeout(r),this._pendingMarginCleanups.delete(e)},r=setTimeout(i,300);this._pendingMarginCleanups.set(e,i),e.addEventListener("transitionend",i)}}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"),Je(e.value.element,"dv-tab--shifting",!1);for(const[,e]of this._tabGroupManager.chipRenderers)e.chip.element.style.removeProperty("margin-left"),Je(e.chip.element,"dv-tab-group-chip--shifting",!1);this._tabGroupManager.positionUnderlines()}commitGroupMove(e,t){const n=Mn();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 i;this.resetTabTransforms(),this.accessor.moveGroupOrPanel({from:{groupId:n.groupId,tabGroupId:(i=n.tabGroupId)!==null&&i!==void 0?i: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 i=!1;for(let r=0;r<this._tabs.length;r++)this._applyFlipTransform(this._tabs[r],r,t,n,e,s)&&(i=!0);i&&this._scheduleFlipReset()}_applyFlipTransform(e,t,n,s,i,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)`,Je(e.value.element,"dv-tab--shifting",!0),!0}if(r!==void 0&&(t<r.from||t>r.to))return!1;const c=i.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)`,Je(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 i of this._tabs)Je(i.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)})}},Hee=class extends dt{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 i=n.value.element;i.classList.add("dv-tab--pinned-sticky"),i.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 TQ(this._tabsList);this._observerDisposable.value=new dt(t,t.onDidChange(n=>{const s=n.hasScrollX||n.hasScrollY;this.toggleDropdown({reset:!s}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}),rt(this._tabsList,"scroll",()=>{this.toggleDropdown({reset:!1}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}))}else this._observerDisposable.value=en.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 dt(rt(e,"dragover",n=>{this._animState&&n.preventDefault()}),rt(e,"drop",n=>{var s;!((s=this._animState)===null||s===void 0)&&s.sourceTabGroupId&&this._animState.currentInsertionIndex!==null&&(n.preventDefault(),n.stopPropagation(),this.handleVoidDrop())})))}handleVoidDrop(){var e,t;if(!(!((e=this._animState)===null||e===void 0)&&e.sourceTabGroupId))return!1;const n=this._animState.sourceTabGroupId,s=(t=this._animState.currentInsertionIndex)!==null&&t!==void 0?t:this._tabs.length;return this._animState=null,this._commitGroupMove(n,s),!0}get panels(){return this._tabs.map(e=>e.value.panel.id)}get size(){return this._tabs.length}get tabs(){return this._tabs.map(e=>e.value)}get direction(){return this._direction}set direction(e){if(this._direction!==e){this._direction=e,this._tabsList.setAttribute("aria-orientation",e==="vertical"?"vertical":"horizontal"),this._scrollbar&&(this._scrollbar.orientation=e),mi(this._tabsList,"dv-horizontal","dv-vertical"),e==="vertical"?gi(this._tabsList,"dv-tabs-container-vertical","dv-vertical"):(mi(this._tabsList,"dv-tabs-container-vertical"),gi(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 Gn,this._pointerActivation=new Gn,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 me,this.onTabDragStart=this._onTabDragStart.event,this._onDrop=new me,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new me,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onOverflowTabsChange=new me,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 TD(this._tabsList),this._scrollbar.orientation=this.direction,this._element=this._scrollbar.element,this.addDisposables(this._scrollbar)),this._tabGroupManager=new Gee({group:this.group,accessor:this.accessor,tabsList:this._tabsList,getTabs:()=>this._tabs,getTabMap:()=>this._tabMap,getDirection:()=>this._direction},{onChipContextMenu:(s,i)=>{var r;(r=this.accessor.contextMenuService)===null||r===void 0||r.showForChip(s,this.group,i)},onChipDragStart:(s,i,r)=>{this._handleChipDragStart(s,i,r)},onChipDragEnd:()=>{this._reorder.resetDragAnimation()},onChipDrop:(s,i)=>{this._handleChipDrop(s,i)}}),this._reorder=new Fee(this),this.addDisposables(this._onOverflowTabsChange,this._observerDisposable,this._pointerActivation,this._onWillShowOverlay,this._onDrop,this._onTabDragStart,this._reorder,Nu.getInstance().onDragEnd(s=>{this._reorder.handlePointerDragEnd(s)}),Nu.getInstance().onDragMove(s=>{this._reorder.handlePointerDragMove(s.clientX,s.clientY)}),rt(this.element,"pointerdown",s=>{s.defaultPrevented||s.button===0&&this.accessor.doSetGroupActive(this.group)}),rt(this._tabsList,"wheel",s=>{const i=this._direction==="vertical",r=i?s.deltaY||s.deltaX:s.deltaX||s.deltaY;if(r===0)return;const a=i?this._tabsList.scrollHeight-this._tabsList.clientHeight:this._tabsList.scrollWidth-this._tabsList.clientWidth;if(a<=0)return;const l=i?this._tabsList.scrollTop:this._tabsList.scrollLeft;r<0&&l<=0||r>0&&l>=a||(s.preventDefault(),s.stopPropagation(),i?this._tabsList.scrollTop=l+r:this._tabsList.scrollLeft=l+r)},{passive:!1}),rt(this._tabsList,"keydown",s=>{this._onKeyDown(s)}),rt(this._tabsList,"dragover",s=>{this._reorder.processDragOver(s.clientX,s.clientY)&&s.preventDefault()},!0),rt(this._tabsList,"dragleave",s=>{this._reorder.processDragLeave(s.relatedTarget)},!0),rt(this._tabsList,"dragend",()=>{this._reorder.resetDragAnimation()}),rt(this._tabsList,"drop",s=>{var i,r,a;if(((i=this._animState)===null||i===void 0?void 0:i.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),en.from(()=>{var s;(s=this._voidContainerListeners)===null||s===void 0||s.dispose(),this._reorder.resetDragAnimation(),this._tabGroupManager.disposeAll();for(const{value:i,disposable:r}of this._tabs)r.dispose(),i.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",i=n?"ArrowUp":"ArrowLeft",r=this._tabs.length-1;switch(e.key){case s:e.preventDefault(),this._focusTab(Math.min(t+1,r));break;case i: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,i,r;const a=(t=this._tabs[e])===null||t===void 0?void 0:t.value;if(!a)return;const l=(n=(s=(i=this._tabs[e+1])===null||i===void 0?void 0:i.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,i=t?e.offsetHeight:e.offsetWidth,r=t?n.scrollTop:n.scrollLeft,a=t?n.clientHeight:n.clientWidth;(s<r||s+i>r+a)&&(t?n.scrollTop=s:n.scrollLeft=s)}_activateOnPointerDown(e){if(!ri(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 Tee(e,this.accessor,this.group);n.setContent(e.view.tab),this._direction!=="horizontal"&&n.setDirection(this._direction);const s={value:n,disposable:new dt(n.onDragStart(i=>{var r;if(this._onTabDragStart.fire({nativeEvent:i,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",Je(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(i=>{i.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(i=>{if(i.defaultPrevented)return;const r=!this.accessor.options.disableFloatingGroups,a=this.group.api.location.type==="floating"&&this.size===1;if(r&&!a&&i.shiftKey){i.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}i.button===0&&this.group.api.location.type!=="edge"&&this.group.activePanel!==e&&this._activateOnPointerDown(e)}),n.onDrop(i=>{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=i.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:i.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=i.position===h?a+1:a,f=Mn(),x=f?this._tabs.findIndex(w=>w.value.panel.id===f.panelId):-1,g=p-(x!==-1&&x<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:i.nativeEvent,index:g,targetTabGroupId:v})}}),n.onWillShowOverlay(i=>{this._onWillShowOverlay.fire(new ql(i,{kind:"tab",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:Mn}))}))};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:i,disposable:r}=s;r.dispose(),i.dispose(),i.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&&!Hp(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&&!Hp(a.value.element,this._tabsList)).map(a=>a.value.panel.id),i=new Set(n),r=[];for(const a of this.group.model.getTabGroups()){const l=this._tabGroupManager.chipRenderers.get(a.id),c=l&&!Hp(l.chip.element,this._tabsList),d=a.panelIds.length>0&&a.panelIds.every(u=>i.has(u));if((c||d)&&(r.push(a.id),a.collapsed))for(const u of a.panelIds)i.has(u)||(i.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 i=e.panelIds[0],r=i?this._tabs.findIndex(d=>d.value.panel.id===i):-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",Je(f.value.element,"dv-tab--dragging",!0));const h=this._tabGroupManager.chipRenderers.get(e.id);h&&(h.chip.element.style.transition="none",Je(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 i=Mn(),r=i?.groupId===this.group.id&&i?.panelId?this._tabs.findIndex(l=>l.value.panel.id===i.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 Bee(){const e=document.createElement("div");e.className="dv-tabs-overflow-dropdown-default";const t=document.createElement("span");t.textContent="";const n=jD();return e.appendChild(n),e.appendChild(t),{element:e,update:s=>{t.textContent=`${s.tabs}`}}}var Vee=class extends dt{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"?(gi(this._element,"dv-groupview-header-vertical"),gi(this.rightActionsContainer,"dv-right-actions-container-vertical"),this.tabs.direction=e):(mi(this._element,"dv-groupview-header-vertical"),mi(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 Gn,this._onDrop=new me,this.onDrop=this._onDrop.event,this._onGroupDragStart=new me,this.onGroupDragStart=this._onGroupDragStart.event,this._onWillShowOverlay=new me,this.onWillShowOverlay=this._onWillShowOverlay.event,this._element=document.createElement("div"),this._element.className="dv-tabs-and-actions-container",Je(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 Hee(t,e,{showTabsOverflowControl:!e.options.disableTabsOverflowList}),this.voidContainer=new Iee(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 ql(n,{kind:"header_space",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:Mn}))}),rt(this.leftActionsContainer,"dragleave",n=>{const s=n.relatedTarget;!this.leftActionsContainer.contains(s)&&!this._element.contains(s)&&this.tabs.clearExternalAnimState()}),rt(this.voidContainer.element,"dragleave",n=>{const s=n.relatedTarget;this.voidContainer.element.contains(s)||(this._element.contains(s)?this.tabs.setExternalInsertionIndex(null):this.tabs.clearExternalAnimState())}),rt(this.voidContainer.element,"pointerdown",n=>{if(!n.defaultPrevented&&!this.accessor.options.disableFloatingGroups&&n.shiftKey&&this.group.api.location.type!=="floating"&&this.group.api.location.type!=="edge"){n.preventDefault();const{top:s,left:i}=this.element.getBoundingClientRect(),{top:r,left:a}=this.accessor.element.getBoundingClientRect();this.accessor.addFloatingGroup(this.group,{x:i-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)),Je(this._element,"dv-tabs-and-actions-container--pinned-row",!!e))}setDropIndexResolver(e){this._dropIndexResolver=e}resolveDropIndex(e,t){return this._dropIndexResolver(e,t)}updateClassnames(){Je(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 i=this._overflowTabs.length+this._overflowPinnedTabs.length;if(i>0&&this.dropdownPart){this.dropdownPart.update({tabs:i});return}if(i===0){this._dropdownDisposable.dispose();return}const r=document.createElement("div");r.className="dv-tabs-overflow-dropdown-root";const a=Bee();a.update({tabs:i}),this.dropdownPart=a,r.appendChild(a.element),this.rightActionsContainer.prepend(r),this._dropdownDisposable.value=new dt(en.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}),rt(r,"pointerdown",l=>{l.preventDefault()},{capture:!0}),rt(r,"click",l=>{const c=OQ(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(),i=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)i.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",Qx(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(x=>x.id===p);this.accessor.withOrigin("user",()=>f?.api.setActive())}}),d};return{overflowGroupIdForPanel:c=>{var d;return(d=i.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=_D();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(g=>g.id===c);if(!d)return;const u=this.tabs.tabs.find(g=>g.panel.id===c),h=i.get(c),p=d.view.createTabRenderer("headerOverflow").element,f=document.createElement("div");Je(f,"dv-tab",!0),Je(f,"dv-active-tab",d.api.isActive),Je(f,"dv-inactive-tab",!d.api.isActive),h&&Je(f,"dv-tab--grouped",!0);const x=()=>{h?.collapsed&&h.expand(),u?.element.scrollIntoView({block:"nearest",inline:"nearest"}),this.accessor.withOrigin("user",()=>d.api.setActive())};return f.addEventListener("click",g=>{a().close(),!g.defaultPrevented&&x()}),f.appendChild(p),{element:f,panel:d,activate:()=>{a().close(),x()}}},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(i=>e.buildRow(i)).filter(i=>i!=null);if(n.length>0){t.appendChild(e.buildPinnedHeader());for(const i of n)t.appendChild(i.element)}const s=new Set;for(const i of this.tabs.tabs.filter(r=>this._overflowTabs.includes(r.panel.id))){const r=e.overflowGroupIdForPanel(i.panel.id);if(r&&!s.has(r)){s.add(r);const l=e.buildGroupHeader(r);l&&t.appendChild(l)}const a=e.buildRow(i.panel.id);a&&t.appendChild(a.element)}return t}updateDragAndDropState(){this.tabs.updateDragAndDropState(),this.voidContainer.updateDragAndDropState()}updateTabGroups(){this.tabs.updateTabGroups()}refreshTabGroupAccent(){this.tabs.refreshTabGroupAccent()}},$ee=class extends dt{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 me,this.onDidChange=this._onDidChange.event,this._onDidPanelChange=new me,this.onDidPanelChange=this._onDidPanelChange.event,this._onDidCollapseChange=new me,this.onDidCollapseChange=this._onDidCollapseChange.event,this._onDidDestroy=new me,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()}},tv=class extends Ux{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()}},RD=class extends tv{get kind(){return this._kind}constructor(e){super(e),this._kind=e.kind}},Wee=class extends dt{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,Je(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?Sm(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(),mi(this.container,"dv-groupview-header-top","dv-groupview-header-bottom","dv-groupview-header-left","dv-groupview-header-right"),gi(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 i;(i=this.groupPanel)===null||i===void 0||i.api._onDidHeaderDirectionChange.fire({direction:n,position:e})}}get location(){return this._location}set location(e){this._location=e,Je(this.container,"dv-groupview-floating",!1),Je(this.container,"dv-groupview-popout",!1),Je(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"]),Je(this.container,"dv-groupview-floating",!0);break;case"popout":t(["top","bottom","left","right","center"]),Je(this.container,"dv-groupview-popout",!0);break;case"edge":t(["center"]),Je(this.container,"dv-groupview-edge",!0);break}this.groupPanel.api._onDidLocationChange.fire({location:this.location})}constructor(e,t,n,s,i){var r,a;super(),this.container=e,this.accessor=t,this.id=n,this.options=s,this.groupPanel=i,this._isGroupActive=!1,this._locked=!1,this._location={type:"grid"},this.mostRecentlyUsed=[],this._overwriteRenderContainer=null,this._overwriteDropTargetContainer=null,this._onDidChange=new me,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 me,this.onMove=this._onMove.event,this._onDidDrop=new me,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new me,this.onWillDrop=this._onWillDrop.event,this._onWillShowOverlay=new me,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onTabDragStart=new me,this.onTabDragStart=this._onTabDragStart.event,this._onGroupDragStart=new me,this.onGroupDragStart=this._onGroupDragStart.event,this._onDidAddPanel=new me,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPanelTitleChange=new me,this.onDidPanelTitleChange=this._onDidPanelTitleChange.event,this._onDidPanelParametersChange=new me,this.onDidPanelParametersChange=this._onDidPanelParametersChange.event,this._onDidRemovePanel=new me,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidActivePanelChange=new me,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onUnhandledDragOver=new me,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._tabGroups=[],this._tabGroupMap=new Map,this._panelToTabGroup=new Map,this._tabGroupIdCounter=0,this._pendingTabGroupUpdate=!1,this._onDidCreateTabGroup=new me,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new me,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new me,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new me,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new me,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new me,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,Je(this.container,"dv-groupview",!0),this.container.setAttribute("role","region"),this._api=new Yx(this.accessor),this.tabsContainer=new Vee(this.accessor,this.groupPanel),this.contentContainer=new wee(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(yr(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=Mn(),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 x=this._panels.findIndex(g=>g.id===u);if(x!==-1){f=0;for(const g of p.panelIds)this._panels.findIndex(v=>v.id===g)<x&&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 ql(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:Mn}))}),this.contentContainer.pointerDropTarget.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(new ql(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:Mn}))}),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 $ee(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 dt(s.onDidChange(()=>{this._onDidTabGroupChange.fire({tabGroup:s})}),s.onDidCollapseChange(i=>{i?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 i=this.getTabGroupForPanel(t);i?.id!==e&&this._bracketTabGroupMutation(()=>{i&&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),i=this._tabGroupMap.get(t);i&&(s&&(s.removePanel(e),this._panelToTabGroup.delete(e),this._onDidRemovePanelFromTabGroup.fire({tabGroup:s,panelId:e}),s.isEmpty&&s.dispose()),i.addPanel(e,n),this._panelToTabGroup.set(e,i),this._enforceContiguity(i,e),this._onDidAddPanelToTabGroup.fire({tabGroup:i,panelId:e}))}moveTabGroup(e,t){const n=this._tabGroupMap.get(e);if(!n||n.panelIds.length===0)return;const s=new Set(n.panelIds),i=n.panelIds.map(c=>this._panels.find(d=>d.id===c)).filter(c=>c!==void 0);if(i.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 i){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,...i);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),i=this._computeGlobalIndex(e,s),r=this._panels.indexOf(n);if(r===i)return;this._panels.splice(r,1);const a=i>r?i-1:i;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(i=>i.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 i=this._panels.find(r=>r.id===n[s]);if(i){const r=this._panels.indexOf(i);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],i=this._findTabGroupForPanel(s.id);if(!i?.collapsed){this.doSetActivePanel(s),this.updateContainer();return}}for(let n=t-1;n>=0;n--){const s=this._panels[n],i=this._findTabGroupForPanel(s.id);if(!i?.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 i of t.panelIds)this._panels.some(r=>r.id===i)&&(n.addPanel(i),this._panelToTabGroup.set(i,s),this._enforceContiguity(s,i));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 i=e.panel?this.panels.indexOf(e.panel):-1;let r;if(i<this.panels.length-1)r=i+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 i=this.panels.indexOf(e.panel);let r;if(i>0)r=i-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(i=>i.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,Je(this.container,"dv-active-group",e),Je(this.container,"dv-inactive-group",!e),this.tabsContainer.setActive(this.isActive),!this._activePanel&&this.panels.length>0){const n=this._panels.find(s=>{const i=this._findTabGroupForPanel(s.id);return!i?.collapsed});n&&this.doSetActivePanel(n)}this.updateContainer()}}layout(e,t){var n;this._width=e,this._height=t;const{width:s,height:i}=this.contentDimensions();this.contentContainer.layout(s,i),!((n=this._activePanel)===null||n===void 0)&&n.layout&&this._activePanel.layout(s,i)}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 dt(e.api.onDidTitleChange(i=>this._onDidPanelTitleChange.fire(i)),e.api.onDidParametersChange(i=>this._onDidPanelParametersChange.fire(i)))),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:i,height:r}=this.contentDimensions();e.layout(i,r),this.updateMru(e),this.contentContainer.refreshFocusState(),this._onDidActivePanelChange.fire({panel:e,origin:(t=(n=(s=this.accessor).currentOrigin)===null||n===void 0?void 0:n.call(s))!==null&&t!==void 0?t:"user"})}this.updateAccessibleLabel()}}updateAccessibleLabel(){var e;const t=(e=this._activePanel)===null||e===void 0?void 0:e.title;t?this.container.setAttribute("aria-label",t):this.container.removeAttribute("aria-label")}updateMru(e){this.mostRecentlyUsed.includes(e)&&this.mostRecentlyUsed.splice(this.mostRecentlyUsed.indexOf(e),1),this.mostRecentlyUsed=[e,...this.mostRecentlyUsed]}updateContainer(){this.panels.forEach(s=>s.runEvents());const e=this.isEmpty||!this._activePanel;if(e&&!this.watermark){const s=this.accessor.createWatermarkComponent();s.init({containerApi:this._api,group:this.groupPanel}),this.watermark=s,rt(this.watermark.element,"pointerdown",()=>{this.isActive||this.accessor.doSetGroupActive(this.groupPanel)}),this.contentContainer.element.appendChild(this.watermark.element)}if(!e&&this.watermark){var t,n;this.watermark.element.remove(),(t=(n=this.watermark).dispose)===null||t===void 0||t.call(n),this.watermark=void 0}}canDisplayOverlay(e,t,n){const s=new PD(e,n,t,Mn,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=Mn();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,i){if(this.locked==="no-drop-target")return;if(e==="content"&&i){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 RD({nativeEvent:t,position:n,panel:a,getData:()=>Mn(),kind:r(),group:this.groupPanel,api:this._api});if(this._onWillDrop.fire(l),l.defaultPrevented)return;const c=Mn();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 tv({nativeEvent:t,position:n,panel:a,getData:()=>Mn(),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()}},nv=class extends CD{constructor(e,t,n){super(e,t),this._onDidConstraintsChangeInternal=new me,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new me,this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new me,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)}},LD=class extends Xx{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 nv(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 me,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(i=>{const{isVisible:r}=i,{accessor:a}=this._params;a.setVisible(this,r)}),this.api.onActiveChange(()=>{const{accessor:i}=this._params;i.doSetGroupActive(this)}),this.api.onDidConstraintsChangeInternal(i=>{(typeof i.minimumWidth=="number"||typeof i.minimumWidth=="function")&&(this._minimumWidth=i.minimumWidth),(typeof i.minimumHeight=="number"||typeof i.minimumHeight=="function")&&(this._minimumHeight=i.minimumHeight),(typeof i.maximumWidth=="number"||typeof i.maximumWidth=="function")&&(this._maximumWidth=i.maximumWidth),(typeof i.maximumHeight=="number"||typeof i.maximumHeight=="function")&&(this._maximumHeight=i.maximumHeight),this._onDidChange.fire(void 0)}),this.api.onDidSizeChange(i=>{this._onDidChange.fire({height:i.height,width:i.width})}),this._onDidChange)}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}init(e){e.maximumHeight&&(this._maximumHeight=e.maximumHeight),e.minimumHeight&&(this._minimumHeight=e.minimumHeight),e.maximumWidth&&(this._maximumWidth=e.maximumWidth),e.minimumWidth&&(this._minimumWidth=e.minimumWidth),this._priority=e.priority,this._snap=!!e.snap,super.init(e),typeof e.isVisible=="boolean"&&this.setVisible(e.isVisible)}updateConstraints(){this.api._onDidConstraintsChange.fire({minimumWidth:this._evaluatedMinimumWidth,maximumWidth:this._evaluatedMaximumWidth,minimumHeight:this._evaluatedMinimumHeight,maximumHeight:this._evaluatedMaximumHeight})}toJSON(){const e=super.toJSON(),t=s=>s===Number.MAX_SAFE_INTEGER?void 0:s,n=s=>s<=0?void 0:s;return pt(pt({},e),{},{minimumHeight:n(this.minimumHeight),maximumHeight:t(this.maximumHeight),minimumWidth:n(this.minimumWidth),maximumWidth:t(this.maximumWidth),snap:this.snap,priority:this.priority})}};const Yi="dockview: DockviewGroupPanelApiImpl not initialized";var Uee=class extends nv{get location(){if(!this._group)throw new Error(Yi);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(Yi);return this._group.locked}set locked(e){if(!this._group)throw new Error(Yi);this._group.locked=e}constructor(e,t){super(e,"__dockviewgroup__"),this.accessor=t,this._onDidLocationChange=new me,this.onDidLocationChange=this._onDidLocationChange.event,this._onDidActivePanelChange=new me,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidCollapsedChange=new me,this.onDidCollapsedChange=this._onDidCollapsedChange.event,this._onDidPeekChange=new me,this.onDidPeekChange=this._onDidPeekChange.event,this._onDidHeaderDirectionChange=new me,this.onDidHeaderDirectionChange=this._onDidHeaderDirectionChange.event,this.addDisposables(this._onDidLocationChange,this._onDidActivePanelChange,this._onDidCollapsedChange,this._onDidPeekChange,this._onDidHeaderDirectionChange,this._onDidVisibilityChange.event(n=>{n.isVisible&&this._pendingSize&&(super.setSize(this._pendingSize),this._pendingSize=void 0)}))}setSize(e){this._pendingSize=pt({},e),super.setSize(e)}close(){if(this._group)return this.accessor.removeGroup(this._group)}getWindow(){return this.location.type==="popout"?this.location.getWindow():globalThis.window}setHeaderPosition(e){if(!this._group)throw new Error(Yi);this._group.model.headerPosition=e}getHeaderPosition(){if(!this._group)throw new Error(Yi);return this._group.model.headerPosition}moveTo(e){if(!this._group)throw new Error(Yi);this.accessor.withOrigin("api",()=>{var t,n,s,i;const r=(t=e.group)!==null&&t!==void 0?t:this.accessor.addGroup({direction:tee((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&&(i=e.position)!==null&&i!==void 0?i:"center",index:e.index},skipSetActive:e.skipSetActive})})}maximize(){if(!this._group)throw new Error(Yi);this.location.type==="grid"&&this.accessor.maximizeGroup(this._group)}isMaximized(){if(!this._group)throw new Error(Yi);return this.accessor.isMaximizedGroup(this._group)}exitMaximized(){if(!this._group)throw new Error(Yi);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 Kee=100,qee=100;var Qc=class extends LD{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,i,r,a,l,c;super(t,"groupview_default",{minimumHeight:(s=(i=n.constraints)===null||i===void 0?void 0:i.minimumHeight)!==null&&s!==void 0?s:qee,minimumWidth:(r=(a=n.constraints)===null||a===void 0?void 0:a.minimumWidth)!==null&&r!==void 0?r:Kee,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 Uee(t,e)),this._explicitConstraints={},this.api.initialize(this),this._model=new Wee(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 Yee={name:"dark",className:"dockview-theme-dark",colorScheme:"dark"},Xee={name:"light",className:"dockview-theme-light",colorScheme:"light"},Jee={className:"dockview-theme-abyss",tabGroupIndicator:"none"};var Zee=class extends nv{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,i){super(e.id,s),this.panel=e,this.accessor=n,this._onDidTitleChange=new me,this.onDidTitleChange=this._onDidTitleChange.event,this._onDidChangePinned=new me,this.onDidChangePinned=this._onDidChangePinned.event,this._onDidActiveGroupChange=new me,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._onDidGroupChange=new me,this.onDidGroupChange=this._onDidGroupChange.event,this._onDidRendererChange=new me,this.onDidRendererChange=this._onDidRendererChange.event,this._onDidLocationChange=new me,this.onDidLocationChange=this._onDidLocationChange.event,this.groupEventsDisposable=new Gn,this._tabComponent=i,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 dt(this.group.api.onDidVisibilityChange(s=>{const i=!s.isVisible&&this.isVisible,r=s.isVisible&&!this.isVisible,a=this.group.model.isPanelActive(this.panel);(i||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}))}))}},Or=class extends dt{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,i,r,a,l){super(),this.id=e,this.accessor=s,this.containerApi=i,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 Zee(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(pt(pt({},e),{},{api:this.api,containerApi:this.containerApi})),this.setTitle(e.title)}focus(){const e=new SD;this.api._onWillFocus.fire(e),!e.defaultPrevented&&(this.api.isActive||this.api.setActive())}toJSON(){return{id:this.id,contentComponent:this.view.contentComponent,tabComponent:this.view.tabComponent,params:Object.keys(this._params||{}).length>0?this._params:void 0,title:this.title,renderer:this._renderer,minimumHeight:this._minimumHeight,maximumHeight:this._maximumHeight,minimumWidth:this._minimumWidth,maximumWidth:this._maximumWidth,pinned:this._pinned?!0:void 0}}setTitle(e){e!==this.title&&(this._title=e,this.view.setTitle(e),this.api._onDidTitleChange.fire({title:e}))}setPinned(e){this._pinned!==e&&(this._pinned=e,this.api._onDidChangePinned.fire({isPinned:e}))}setRenderer(e){e!==this.renderer&&(this._renderer=e,this.api._onDidRendererChange.fire({renderer:e}))}update(e){this._params=pt(pt({},this._params),e.params);for(const t of Object.keys(e.params))e.params[t]===void 0&&delete this._params[t];this.view.update({params:this._params})}updateFromStateModel(e){var t,n,s,i,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(((i=e.pinned)!==null&&i!==void 0?i:!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()}},AS=class extends dt{get element(){return this._element}constructor(){super(),this._messages=ju,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=yee();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:ju,this.addDisposables(e.api.onDidTitleChange(n=>{this._title=n.title,this.render()}),rt(this.action,"pointerdown",n=>{n.preventDefault()}),rt(this.action,"click",n=>{n.defaultPrevented||(n.preventDefault(),e.api.close())})),this.render()}render(){if(this._content.textContent!==this._title){var e;this._content.textContent=(e=this._title)!==null&&e!==void 0?e:""}this.action.setAttribute("aria-label",this._title?this._messages.closeTab(this._title):this._messages.closeTabPlain())}},OD=class{get content(){return this._content}get tab(){return this._tab}constructor(e,t,n,s){this.accessor=e,this.id=t,this.contentComponent=n,this.tabComponent=s,this._content=this.createContentComponent(this.id,n),this._tab=this.createTabComponent(this.id,s)}createTabRenderer(e){const t=this.createTabComponent(this.id,this.tabComponent);if(this._params&&t.init(pt(pt({},this._params),{},{tabLocation:e})),this._updateEvent){var n;(n=t.update)===null||n===void 0||n.call(t,this._updateEvent)}return t}init(e){this._params=e,this.content.init(e),this.tab.init(pt(pt({},e),{},{tabLocation:"header"}))}setTitle(e){this._params&&(this._params.title=e)}layout(e,t){var n,s;(n=(s=this.content).layout)===null||n===void 0||n.call(s,e,t)}update(e){var t,n,s,i;this._updateEvent=e,(t=(n=this.content).update)===null||t===void 0||t.call(n,e),(s=(i=this.tab).update)===null||s===void 0||s.call(i,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 AS}console.warn(`dockview: tabComponent '${t}' was not found. falling back to the default tab.`)}return new AS}},Qee=class{constructor(e){this.accessor=e}fromJSON(e,t){var n,s,i;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 OD(this.accessor,r,d,u),p=new Or(r,d,u,this.accessor,new Yx(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&&(!((i=this.accessor.options.pinnedTabs)===null||i===void 0)&&i.enabled)&&p.setPinned(!0),p}},ete=class extends dt{get element(){return this._element}constructor(){super(),this._element=document.createElement("div"),this._element.className="dv-watermark"}init(t){}},tte=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 ed=new tte;var sv=class Zo extends dt{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 me,this.onDidChange=this._onDidChange.event,this._onDidChangeEnd=new me,this.onDidChangeEnd=this._onDidChangeEnd.event,this._onDidStartMoving=new me,this.onDidStartMoving=this._onDidStartMoving.event,this._dragMove=new Gn,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&&(Je(this._element,"dv-resize-container-with-titlebar",!0),this._element.appendChild(this.options.header)),this._element.appendChild(this.options.content),this.options.container.appendChild(this._element),this.setBounds(pt(pt(pt(pt({height:this.options.height,width:this.options.width},"top"in this.options&&{top:this.options.top}),"bottom"in this.options&&{bottom:this.options.bottom}),"left"in this.options&&{left:this.options.left}),"right"in this.options&&{right:this.options.right})),ed.push(this._element)}setVisible(t){t!==this.isVisible&&(this._isVisible=t,Je(this.element,"dv-hidden",!this.isVisible))}bringToFront(){ed.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(),i=Math.max(0,this.getMinimumWidth(s.width)),r=Math.max(0,this.getMinimumHeight(s.height));if(this.verticalAlignment==="top"){const a=In(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=In(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=In(s.left-n.left,-i,Math.max(0,n.width-s.width+i));this._element.style.left=`${a}px`,this._element.style.right="auto"}if(this.horiziontalAlignment==="right"){const a=In(n.right-s.right,-i,Math.max(0,n.width-s.width+i));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,Je(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=en.NONE)}setupDrag(t,n){const s=(i,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=Wl();if(i&&typeof r=="number"&&typeof i.setPointerCapture=="function")try{i.setPointerCapture(r)}catch{}const f=()=>{Je(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=en.NONE,this._onDidChangeEnd.fire()};this._dragMove.value=new dt({dispose:()=>{if(p.release(),i&&typeof r=="number"&&typeof i.releasePointerCapture=="function")try{i.releasePointerCapture(r)}catch{}}},rt(globalThis.window,"pointermove",x=>{var g;if(this._dragCancelled)return;const v=this.options.container.getBoundingClientRect(),w=x.clientX-v.left,y=x.clientY-v.top;Je(this._element,"dv-resize-container-dragging",!0);const b=this._element.getBoundingClientRect();(g=d)!==null&&g!==void 0||(d={x:x.clientX-b.left,y:x.clientY-b.top});const _=Math.max(0,this.getMinimumWidth(b.width)),j=Math.max(0,this.getMinimumHeight(b.height));let N=y-d.y,C=w-d.x;if(this.options.transformDragPosition){const J=this.options.transformDragPosition({proposed:{top:N,left:C,width:b.width,height:b.height},container:{width:v.width,height:v.height},others:h,modifiers:{altKey:x.altKey,ctrlKey:x.ctrlKey,metaKey:x.metaKey,shiftKey:x.shiftKey}});J&&(N=J.top,C=J.left)}const k=Math.max(0,v.height-b.height+j),E=Math.max(0,v.width-b.width+_),I=In(N,-j,k),T=In(v.height-b.height-N,-j,k),A=In(C,-_,E),D=In(v.width-b.width-C,-_,E),W={};I<=T?W.top=I:W.bottom=T,A<=D?W.left=A:W.right=D,this.setBounds(W),u||(u=!0,this._onDidStartMoving.fire())}),rt(globalThis.window,"pointerup",f),rt(globalThis.window,"pointercancel",f))};this.addDisposables(rt(t,"pointerdown",i=>{if(i.defaultPrevented){i.preventDefault();return}jS(i)||s(t,i.pointerId)}),rt(this.options.content,"pointerdown",i=>{i.defaultPrevented||jS(i)||i.shiftKey&&s(this.options.content,i.pointerId)}),rt(this.options.content,"pointerdown",()=>{ed.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 Gn;this.addDisposables(s,rt(n,"pointerdown",i=>{i.preventDefault();let r=null;const a=Wl(),l=i.pointerId;if(typeof n.setPointerCapture=="function")try{n.setPointerCapture(l)}catch{}const c=()=>{s.dispose(),this._onDidChangeEnd.fire()};s.value=new dt(rt(globalThis.window,"pointermove",d=>{var u;const h=this.options.container.getBoundingClientRect(),p=this._element.getBoundingClientRect(),f=d.clientY-h.top,x=d.clientX-h.left;(u=r)!==null&&u!==void 0||(r={originalY:f,originalHeight:p.height,originalX:x,originalWidth:p.width});let g,v,w,y,b,_;const j=()=>{const I=r.originalY+r.originalHeight>h.height?Math.max(0,h.height-Zo.MINIMUM_HEIGHT):Math.max(0,r.originalY+r.originalHeight-Zo.MINIMUM_HEIGHT);g=In(f,0,I),w=r.originalY+r.originalHeight-g,v=h.height-g-w},N=()=>{g=r.originalY-r.originalHeight;const I=g<0&&typeof this.options.minimumInViewportHeight=="number"?-g+this.options.minimumInViewportHeight:Zo.MINIMUM_HEIGHT,T=h.height-Math.max(0,g);w=In(f-g,I,T),v=h.height-g-w},C=()=>{const I=r.originalX+r.originalWidth>h.width?Math.max(0,h.width-Zo.MINIMUM_WIDTH):Math.max(0,r.originalX+r.originalWidth-Zo.MINIMUM_WIDTH);y=In(x,0,I),_=r.originalX+r.originalWidth-y,b=h.width-y-_},k=()=>{y=r.originalX-r.originalWidth;const I=y<0&&typeof this.options.minimumInViewportWidth=="number"?-y+this.options.minimumInViewportWidth:Zo.MINIMUM_WIDTH,T=h.width-Math.max(0,y);_=In(x-y,I,T),b=h.width-y-_};switch(t){case"top":j();break;case"bottom":N();break;case"left":C();break;case"right":k();break;case"topleft":j(),C();break;case"topright":j(),k();break;case"bottomleft":N(),C();break;case"bottomright":N(),k();break}const E={};g<=v?E.top=g:E.bottom=v,y<=b?E.left=y:E.right=b,E.height=w,E.width=_,this.setBounds(E)}),{dispose:()=>{if(a.release(),typeof n.releasePointerCapture=="function")try{n.releasePointerCapture(l)}catch{}}},rt(globalThis.window,"pointerup",c),rt(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(){ed.destroy(this._element),this._element.remove(),super.dispose()}};sv.MINIMUM_HEIGHT=20;sv.MINIMUM_WIDTH=20;var nte=class extends dt{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 me,this.onDragStart=this._onDragStart.event,this._group=t,this._element=document.createElement("div"),this._element.className="dv-floating-titlebar",this.addDisposables(this._onDragStart,rt(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this._group)}),rt(this._element,"pointerdown",n=>{n.shiftKey&&iD(n)},!0)),this.dragSource=new ND({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 xo(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 ste=new Set(["AdvancedOverflow","AutoEdgeGroup","AutoHideEdgeGroup","ContextMenu","DndCompass","KeyboardDocking","KeyboardNavigation","LayoutHistory","License","MultiRowTabs","PinnedTabs","SmartGuides"]),MS=new Set;function zD(e,t){const n=t===void 0?[]:[].concat(t),s=n.map(a=>`\`${a}\``).join(", "),i=n.length>1?"require":"requires",r=n.length?`${s} ${i} the "${e}" module`:`The "${e}" module is required`;return ste.has(e)?`dockview: ${r}, which ships in dockview-enterprise.
103
-
104
- npm install dockview-enterprise
105
- import 'dockview-enterprise'; // self-registers every enterprise module
106
- `:`dockview: ${r}, but it is not registered.`}function GD(e,t){const n=`${e}|${(t===void 0?[]:[].concat(t)).join("|")}`;MS.has(n)||(MS.add(n),console.error(zD(e,t)))}function Ps(e,t,n){if(e!==void 0)return e;GD(t,n)}var ite=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 ote=[];function rte(){return[...ote]}const ate=[{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=>Em(e.autoHideEdgeGroups)},{optionKey:"dockToEdgeGroups",reason:"dockToEdgeGroups",moduleName:"AutoEdgeGroup",when:e=>Em(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 lte(e,t){const n=new Map;for(const s of ate){if(!s.when(e)||t(s.moduleName))continue;const i=n.get(s.moduleName);i?i.push(s.reason):n.set(s.moduleName,[s.reason])}for(const[s,i]of n)GD(s,i)}const So={left:100,top:100,width:300,height:300};var cte=class extends dt{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)}},dte=class{get floatingGroups(){return this._floatingGroups}constructor(e){this._floatingGroups=[],this._host=e}add(e,t,n){const s=new cte(e,t,n),i=new dt(e.api.onDidActiveChange(a=>{a.isActive&&t.bringToFront()}),(()=>{let a=-1,l=-1;return yr(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:()=>{i.dispose(),lD(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 ute=xo({name:"FloatingGroup",serviceKey:"floatingGroupService",create:e=>new dte(e)});var hte=class{constructor(e){this._entries=[],this._restorationCleanups=new Set,this._restorationPromise=Promise.resolve(),this._onDidRemove=new me,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){lD(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 i=(s=e.window)===null||s===void 0?void 0:s.ResizeObserver;if(!i)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 i(()=>{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 i=()=>{this._restorationCleanups.delete(i),clearTimeout(r),n?.(),s()},r=setTimeout(()=>{if(this._restorationCleanups.delete(i),this._host.isDisposed){s();return}t(),s()},e);this._restorationCleanups.add(i)})}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,i={gridReferenceGroup:e.referenceGroup,position:e.window.dimensions(),url:s};return n.type==="branch"&&n.data.length===1&&n.data[0].type==="leaf"?pt(pt({},i),{},{data:n.data[0].data}):pt(pt({},i),{},{grid:t})})}disposeAll(){for(const e of[...this._entries])e.disposable.dispose()}dispose(){this.cancelPendingRestorations(),this.disposeAll(),this._onDidRemove.dispose()}};const pte=xo({name:"PopoutWindow",serviceKey:"popoutWindowService",create:e=>new hte(e)});var fte=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",PQ(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 mte=xo({name:"Watermark",serviceKey:"watermarkService",create:e=>new fte(e),init:(e,t)=>(t.update(),new dt(qs.any(e.onDidAdd,e.onDidRemove)(()=>{t.update()}),e.onDidViewVisibilityChangeMicroTaskQueue(()=>{t.update()})))});var gte=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 xte=xo({name:"EdgeGroup",serviceKey:"edgeGroupService",create:()=>new gte}),vte={activationSize:{type:"pixels",value:10},size:{type:"pixels",value:20}},bte={activationSize:{type:"pixels",value:32},size:{type:"pixels",value:20}};function RS(e,t){return typeof e.dndEdges=="object"&&e.dndEdges!==null?e.dndEdges:t&&Em(e.dockToEdgeGroups)?bte:vte}var wte=class{constructor(e){this._host=e;const t=(s,i)=>{const r=Mn();return r?r.viewId!==e.id?!1:i==="center"?e.isGridEmpty():!0:i==="center"&&!e.isGridEmpty()?!1:e.dispatchUnhandledDragOver(s,i)},n=RS(e.options,!1);this._html5Target=Po.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=mo.createDropTarget(e.element,{className:"dv-drop-target-edge",canDisplayOverlay:t,acceptedTargetZones:["top","bottom","left","right","center"],overlayModel:n,getOverrideTarget:()=>e.rootDropTargetOverrideTarget(),getPositionResolver:()=>e.options.dropPositionResolver}),this.onWillShowOverlay=qs.any(this._html5Target.onWillShowOverlay,this._pointerTarget.onWillShowOverlay),this.onDrop=qs.any(this._html5Target.onDrop,this._pointerTarget.onDrop),this.setOptions(e.options)}setOptions(e){if("dndEdges"in e){const t=typeof e.dndEdges=="boolean"&&e.dndEdges===!1;this._html5Target.disabled=t,this._pointerTarget.disabled=t}if("dndEdges"in e||"dockToEdgeGroups"in e){const t=RS({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 yte=xo({name:"RootDropTarget",serviceKey:"rootDropTargetService",create:e=>new wte(e),init:(e,t)=>(t.setOptions(e.options),en.NONE)}),Ste={left:"createLeftHeaderActionComponent",right:"createRightHeaderActionComponent",prefix:"createPrefixHeaderActionComponent"};var Cte=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 Gn,right:new Gn,prefix:new Gn},this._perGroup.set(e,t)),t}_refreshSlot(e,t,n){const s=this._host.options[Ste[e]];if(s){const i=s(t);n.value=i,i.init({containerApi:this._host.api,api:t.api,group:t}),t.model.attachHeaderAction(e,i.element)}else n.dispose(),t.model.attachHeaderAction(e,void 0)}};const kte=xo({name:"HeaderActions",serviceKey:"headerActionsService",create:e=>new Cte(e),init:(e,t)=>new dt(e.onDidRemoveGroup(n=>{t.disposeGroup(n)}))}),LS=e=>e==="load"||e==="clear";function td(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 _te=class extends dt{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:td(n,"polite"),assertive:td(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(i=>this._announce(i,"open")),e.onDidRemovePanel(i=>this._announce(i,"close")),e.onWillMutateLayout(i=>{LS(i.kind)&&this._suppressDepth++}),e.onDidMutateLayout(i=>{LS(i.kind)&&(this._suppressDepth=Math.max(0,this._suppressDepth-1))}),e.onDidMaximizedGroupChange(i=>{const r=i.group.activePanel;r&&this._announce(r,i.isMaximized?"maximize":"restore")}),e.onDidAddGroup(i=>this._trackLocation(i)),e.onDidRemoveGroup(i=>{var r;(r=this._locationSubs.get(i.id))===null||r===void 0||r.dispose(),this._locationSubs.delete(i.id)}),{dispose:()=>{this._locationSubs.forEach(i=>i.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 i=s.document,r=(n=i.body)!==null&&n!==void 0?n:i.documentElement,a={polite:td(i,"polite"),assertive:td(i,"assertive")};r.appendChild(a.polite),r.appendChild(a.assertive),this._regions.set(s,a)}for(const[s,i]of this._regions)t.has(s)||(i.polite.remove(),i.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 i=s.location.type;if(i===t)return;t=i;const r=e.activePanel;if(!r)return;let a;switch(i){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(),i=t==="assertive"?s.assertive:s.polite;i.textContent="",i.textContent=e}_announce(e,t){var n,s;const i=(n=(s=this._host.options).getAnnouncement)===null||n===void 0?void 0:n.call(s,{kind:t,panel:e});i===null||i===""||this.announce(i??this._defaultMessage(e,t))}_defaultMessage(e,t){var n;const s=hD(this._host.options.messages),i=(n=e.title)!==null&&n!==void 0?n:e.id;switch(t){case"open":return s.panelOpened(i);case"close":return s.panelClosed(i);case"maximize":return s.groupMaximized(i);case"restore":return s.groupRestored(i);case"float":return s.groupFloated(i);case"dock":return s.groupDocked(i);case"popout":return s.groupPoppedOut(i)}}};const jte=xo({name:"LiveRegion",serviceKey:"liveRegionService",create:e=>new _te(e)}),Nte=30,Tte=-10;var Ite=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:Nte,offsetY:Tte,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),en.from(()=>n.clearOverlay())}dispose(){}};const Dte=xo({name:"AdvancedDnD",serviceKey:"advancedDnDService",create:e=>new Ite(e)});var Pte=class{constructor(e){this._host=e}attachToGroup(e){return new dt(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 Ete=xo({name:"TabGroupChips",serviceKey:"tabGroupChipsService",create:e=>new Pte(e),init:(e,t)=>{const n=new Map;return new dt(e.onDidAddGroup(s=>{n.set(s,t.attachToGroup(s))}),e.onDidRemoveGroup(s=>{var i;(i=n.get(s))===null||i===void 0||i.dispose(),n.delete(s)}),{dispose:()=>{for(const s of n.values())s.dispose();n.clear()}})}}),Ate=[ute,pte,mte,xte,yte,kte,jte,Dte,Ete];var Mte=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=Cm(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 OS=-1;function Rte(){const e=document.createElement("div");return e.tabIndex=-1,e}var zS=class extends dt{constructor(e,t){super(),this.element=e,this.accessor=t,this.map={},this._disposed=!1,this._generation=0,this.positionCache=new Mte,this.addDisposables(en.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 i=this.map[e];i&&(i.forceVisible=t,i.clip=n,this.positionCache.invalidate(),(s=i.resize)===null||s===void 0||s.call(i))}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=Rte();p.className="dv-render-overlay",p.style.visibility="hidden",this.map[t.api.id]={panel:t,disposable:en.NONE,destroy:en.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 i=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!==i||f.pendingUpdate!==void 0)return;f.pendingUpdate=OS;const x=requestAnimationFrame(()=>{var g;const v=this.map[p];if(v&&(v.pendingUpdate=void 0),this.isDisposed||v?.generation!==i)return;const w=(g=v.forceVisible)!==null&&g!==void 0?g:!1,y=v.clip,b=this.positionCache.getPosition(n.element),_=this.positionCache.getPosition(this.element),j=b.left-_.left,N=b.top-_.top,C=b.width,k=b.height;if(v.retainPreviousGeometry&&(C===0||k===0)){!t.api.isVisible&&!w&&(r.style.visibility="hidden",r.style.pointerEvents="none");return}if(v.retainPreviousGeometry=!1,v.positioned=!0,r.style.left=`${j}px`,r.style.top=`${N}px`,r.style.width=`${C}px`,r.style.height=`${k}px`,t.api.isVisible||w?(r.style.visibility="",r.style.pointerEvents=""):(r.style.visibility="hidden",r.style.pointerEvents="none"),w?r.style.zIndex="1000":t.api.location.type!=="floating"&&(r.style.zIndex=""),y){var E,I;const T=this.element.ownerDocument.defaultView,A=(E=T?.scrollX)!==null&&E!==void 0?E:0,D=(I=T?.scrollY)!==null&&I!==void 0?I:0,W=y.top+D,J=y.left+A,O=Math.max(0,W-b.top),B=Math.max(0,J-b.left),L=Math.max(0,b.left+C-(y.right+A)),se=Math.max(0,b.top+k-(y.bottom+D));r.style.clipPath=`inset(${O}px ${L}px ${se}px ${B}px)`}else r.style.clipPath="";Je(r,"dv-render-overlay-float",t.group.api.location.type==="floating")});f.pendingUpdate===OS&&(f.pendingUpdate=x)},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 Gn,u=()=>{t.api.location.type==="floating"?queueMicrotask(()=>{const p=this.accessor.getFloatingWindowForGroup(t.api.group);if(!p)return;const f=p.overlay.element,x=()=>{const v=Number(f.getAttribute("aria-level"));r.style.zIndex=`calc(var(--dv-overlay-z-index, 999) + ${v*2+1})`},g=new MutationObserver(()=>{x()});d.value=en.from(()=>g.disconnect()),g.observe(f,{attributeFilter:["aria-level"],attributes:!0}),x()}):r.style.zIndex=""},h=new dt(d,new mD(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=en.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 GS(e,t,n,s,i,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,i)}function FD(e){return function(){var t=this,n=arguments;return new Promise(function(s,i){var r=e.apply(t,n);function a(c){GS(r,s,i,a,l,"next",c)}function l(c){GS(r,s,i,a,l,"throw",c)}a(void 0)})}}function Lte(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 Ote=class extends dt{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 me,this.onWillClose=this._onWillClose.event,this._onDidClose=new me,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 FD(function*(){var t,n;if(e._window)throw new Error("instance of popout window is already open");const s=`${e.options.url}`;Lte(s);const i=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,i);if(!r)return null;const a=new dt;e._window={value:r,disposable:a},a.addDisposables(en.from(()=>{r.close()}),rt(globalThis.window,"beforeunload",()=>{e.close()}));const l=e.createPopoutWindowContainer();return e.className&&l.classList.add(e.className),(t=(n=e.options).onDidOpen)===null||t===void 0||t.call(n,{id:e.target,window:r}),new Promise((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),DQ(u,globalThis.document.styleSheets,{nonce:e.options.nonce}),rt(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}},zte=class extends dt{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 Gte(e){if(!e.matchMedia)return!1;const t=e.matchMedia("(pointer: coarse)").matches,n=e.matchMedia("(pointer: fine)").matches;return t&&!n}function Fte(e){var t,n,s,i,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=(i=e.keys)!==null&&i!==void 0?i:[],p=(r=e.outsidePointerDown)!==null&&r!==void 0?r:!0,f=(a=e.pointerDownGraceMs)!==null&&a!==void 0?a:0,x=(l=e.now)!==null&&l!==void 0?l:Date.now,g=x(),v=new dt,w=y=>{var b,_;if(e.isInside)return e.isInside(y);const j=y.target;return j instanceof Node?((b=(_=e.elements)===null||_===void 0?void 0:_.call(e))!==null&&b!==void 0?b:[]).some(N=>N.contains(j)):!1};if((u||h.length>0)&&v.addDisposables(rt(c,"keydown",y=>{(u&&y.key==="Escape"||h.includes(y.key))&&e.onDismiss()},d)),(p||e.onInsidePointerDown)&&v.addDisposables(rt(c,"pointerdown",y=>{if(w(y)){var b;(b=e.onInsidePointerDown)===null||b===void 0||b.call(e,y);return}!p||x()-g<f||e.onDismiss()},d)),e.resize&&v.addDisposables(rt(c,"resize",()=>{Gte(c)||e.onDismiss()})),e.focusOut){const y=_=>{var j,N;return e.isFocusInside?e.isFocusInside(_):((j=(N=e.elements)===null||N===void 0?void 0:N.call(e))!==null&&j!==void 0?j:[]).some(C=>C.contains(_))},b=_=>{const j=_.target;j instanceof Element&&!y(j)&&e.onDismiss()};c.addEventListener("focusin",b,d),v.addDisposables({dispose:()=>c.removeEventListener("focusin",b,d)})}return v}var FS=class extends dt{constructor(e,t=globalThis.window){super(),this._active=null,this._activeDisposable=new Gn,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(en.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 i=this._element.getBoundingClientRect(),r=i.left,a=i.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=Fte({window:this._window,onDismiss:()=>this.close(),elements:()=>this._active?[this._active]:[],keys:["Enter"],pointerDownGraceMs:l,resize:!0}),this._window.requestAnimationFrame(()=>{LQ(s,this._root)})}close(){this._active&&(this._active.remove(),this._activeDisposable.dispose(),this._active=null)}},$p=class extends dt{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(),i=this.createAnchor();if(this._model={root:s,overlay:i,changed:n},s.appendChild(i),this.element.appendChild(s),e?.target instanceof HTMLElement){const r=e.target.getBoundingClientRect(),a=this.element.getBoundingClientRect();i.style.left=`${r.left-a.left}px`,i.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(en.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}},Hte=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 i,r,a;this._onDidChange=new me,this.onDidChange=this._onDidChange.event,this.snap=!1,this.priority="low",this._isCollapsed=!1,this._tabSizeDisposables=new dt,this._group=t,this._orientation=n,t.element.classList.add("dv-edge-group"),t.element.dataset.testid=`dv-edge-group-${e.id}`,this._baseCollapsedSize=(i=e.collapsedSize)!==null&&i!==void 0?i: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(yr(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()}},Bte=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 me,this.onDidChange=this._onDidChange.event}layout(e,t){this._layoutDockview(t,e)}setVisible(e){}dispose(){this._onDidChange.dispose()}},Vte=class{get element(){return this._element}constructor(e,t=0){this._onDidChange=new me,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 xr(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()}},$te=class{constructor(e,t,n,s=0,i=35){this._disposables=new dt,this._viewConfigs=new Map,this._currentWidth=0,this._currentHeight=0,this._gap=s,this._defaultCollapsedSize=i,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 Bte(t,n);this._middleColumn=new Vte(r,s),this._outerSplitview=new xr(this._shellElement,{orientation:"HORIZONTAL",proportionalLayout:!1,margin:s}),this._middleIndex=0,this._outerSplitview.addView(this._middleColumn,{type:"distribute"},0),this._disposables.addDisposables(yr(this._shellElement,a=>{if(!this._shellElement.offsetParent||!oD(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),i=1+(this._viewConfigs.has("top")?1:0)+(this._viewConfigs.has("bottom")?1:0),r=s>1?this._gap*(s-1)/s:0,a=i>1?this._gap*(i-1)/i:0,l=e==="left"||e==="right",c=l?r:a,d=l?"horizontal":"vertical",u=new Hte(pt({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,i,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=(g,v,w)=>{var y;const b=(y=v.collapsedSize)!==null&&y!==void 0?y:t;g.updateSizing(b,v.minimumSize,w)},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 x=this._viewConfigs.get("right");this._rightView&&x&&u(this._rightView,x,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),!((i=this._topView)===null||i===void 0)&&i.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,i,r,a)=>s.isCollapsed?s.lastExpandedSize:i?r:a??s.lastExpandedSize;if(this._leftView&&this._leftIndex!==void 0){const s=this._outerSplitview.isViewVisible(this._leftIndex);e.left=pt({size:n(this._leftView,s,this._outerSplitview.getViewSize(this._leftIndex),this._outerSplitview.getViewCachedVisibleSize(this._leftIndex)),visible:s,collapsed:this._leftView.isCollapsed||void 0},t(this._leftView))}if(this._rightView&&this._rightIndex!==void 0){const s=this._outerSplitview.isViewVisible(this._rightIndex);e.right=pt({size:n(this._rightView,s,this._outerSplitview.getViewSize(this._rightIndex),this._outerSplitview.getViewCachedVisibleSize(this._rightIndex)),visible:s,collapsed:this._rightView.isCollapsed||void 0},t(this._rightView))}if(this._topView){const s=this._middleColumn.isViewVisible("top");e.top=pt({size:n(this._topView,s,this._middleColumn.getViewSize("top"),this._middleColumn.getViewCachedVisibleSize("top")),visible:s,collapsed:this._topView.isCollapsed||void 0},t(this._topView))}if(this._bottomView){const s=this._middleColumn.isViewVisible("bottom");e.bottom=pt({size:n(this._bottomView,s,this._middleColumn.getViewSize("bottom"),this._middleColumn.getViewCachedVisibleSize("bottom")),visible:s,collapsed:this._bottomView.isCollapsed||void 0},t(this._bottomView))}return e}fromJSON(e){if(e.left&&this._leftIndex!==void 0){var t,n,s,i,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&&(i=(r=this._leftView)===null||r===void 0?void 0:r.collapsedSize)!==null&&i!==void 0?i: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,x,g;(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&&(x=(g=this._topView)===null||g===void 0?void 0:g.collapsedSize)!==null&&x!==void 0?x:e.top.size),e.top.visible||this._middleColumn.setViewVisible("top",!1)}if(e.bottom){var v,w,y,b,_;(v=this._bottomView)===null||v===void 0||v.restoreExpandedSize(e.bottom.size),(w=this._bottomView)===null||w===void 0||w.setCollapsed((y=e.bottom.collapsed)!==null&&y!==void 0?y:!1),this._middleColumn.resizeView("bottom",e.bottom.collapsed&&(b=(_=this._bottomView)===null||_===void 0?void 0:_.collapsedSize)!==null&&b!==void 0?b:e.bottom.size),e.bottom.visible||this._middleColumn.setViewVisible("bottom",!1)}}dispose(){this._disposables.dispose(),this._shellElement.remove()}};function Wte(e){var t;return new ED((t=e.tabGroupColors)!==null&&t!==void 0?t:Zx,e.tabGroupAccent!=="off")}function nd(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 Mm=()=>({dispose:()=>{}}),Ute=Mm;var Kte=class extends uD{fireDidCreateTabGroup(e){this._onDidCreateTabGroup.fire(e)}fireDidDestroyTabGroup(e){this._onDidDestroyTabGroup.fire(e)}fireDidAddPanelToTabGroup(e){this._onDidAddPanelToTabGroup.fire(e)}fireDidRemovePanelFromTabGroup(e){this._onDidRemovePanelFromTabGroup.fire(e)}fireDidTabGroupChange(e){this._onDidTabGroupChange.fire(e)}fireDidTabGroupCollapsedChange(e){this._onDidTabGroupCollapsedChange.fire(e)}get orientation(){return this.gridview.orientation}get totalPanels(){return this.panels.length}get panels(){return this.groups.flatMap(e=>e.panels)}get options(){return this._options}get tabGroupColorPalette(){return this._tabGroupColorPalette}get activePanel(){const e=this.activeGroup;if(e)return e.activePanel}get renderer(){var e;return(e=this.options.defaultRenderer)!==null&&e!==void 0?e:"onlyWhenVisible"}get defaultHeaderPosition(){var e;return(e=this.options.defaultHeaderPosition)!==null&&e!==void 0?e:"top"}get api(){return this._api}get floatingGroups(){var e,t;return(e=(t=this._moduleRegistry)===null||t===void 0||(t=t.services.floatingGroupService)===null||t===void 0?void 0:t.floatingGroups)!==null&&e!==void 0?e:[]}getFloatingWindowForGroup(e){var t;return(t=this._floatingGroupService)===null||t===void 0?void 0:t.findByGroup(e)}_gatherFloatingGroupBoxes(e){return this.getFloatingGroupSnapshots(e).map(t=>t.box)}getFloatingContainer(){var e;return(e=this._floatingOverlayHost)!==null&&e!==void 0?e:this.gridview.element}getFloatingGroupSnapshots(e){const t=this.getFloatingContainer().getBoundingClientRect();return this.floatingGroups.filter(n=>n.group!==e).map(n=>{const s=n.overlay.element.getBoundingClientRect();return{group:n.group,box:{left:s.left-t.left,top:s.top-t.top,width:s.width,height:s.height}}})}mergeFloatInto(e,t,n){e===t||!this.getPanel(t.id)||this.moveGroupOrPanel({from:{groupId:e.id},to:{group:t,position:n}})}getGridSplitterRects(){const e=this.getFloatingContainer().getBoundingClientRect(),t=[];return this.gridview.element.querySelectorAll(".dv-sash").forEach(n=>{const s=n.getBoundingClientRect();t.push({left:s.left-e.left,top:s.top-e.top,width:s.width,height:s.height})}),t}get _smartGuidesService(){return this._moduleRegistry.services.smartGuidesService}get smartGuidesEnabled(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.enabled)!==null&&e!==void 0?e:!1}setSmartGuidesEnabled(e){var t;(t=Ps(this._smartGuidesService,"SmartGuides","api.setSmartGuidesEnabled"))===null||t===void 0||t.setEnabled(e)}updateSmartGuidesOptions(e){var t;(t=Ps(this._smartGuidesService,"SmartGuides","api.updateSmartGuidesOptions"))===null||t===void 0||t.updateOptions(e)}get onDidSnapFloat(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.onDidSnapFloat)!==null&&e!==void 0?e:Mm}get onDidSnapTogether(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.onDidSnapTogether)!==null&&e!==void 0?e:Mm}_buildFloatingDragTransform(e,t){const n=this.options.transformFloatingGroupDrag,s=!t;if(!(!n&&!(s&&this._smartGuidesService)))return i=>{var r,a;const l=n?.({group:e,proposed:i.proposed,container:i.container,others:i.others,modifiers:i.modifiers}),c=l?pt(pt({},i.proposed),l):i.proposed,d=s?(r=this._smartGuidesService)===null||r===void 0?void 0:r.transformFloatingGroupDrag({group:e,proposed:c,container:i.container,others:i.others,modifiers:i.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 i;return(i=n.resolveEdge(s))!==null&&i!==void 0?i:t.resolve(s)}}:t??n?.resolver}dockToLayoutEdge(e,t){const n=new RD({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:Mn,kind:"edge"});if(this._onWillDrop.fire(n),n.defaultPrevented)return;const s=Mn();if(s){var i;this.moveGroupOrPanel({from:{groupId:s.groupId,panelId:(i=s.panelId)!==null&&i!==void 0?i:void 0},to:{group:this.orthogonalize(t),position:"center"}})}else this._onDidDrop.fire(new tv({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:Mn}))}get headerActionsService(){return this._moduleRegistry.services.headerActionsService}get _layoutHistoryService(){return this._moduleRegistry.services.layoutHistoryService}undo(){var e;(e=Ps(this._layoutHistoryService,"LayoutHistory","api.undo"))===null||e===void 0||e.undo()}redo(){var e;(e=Ps(this._layoutHistoryService,"LayoutHistory","api.redo"))===null||e===void 0||e.redo()}get canUndo(){var e,t;return(e=(t=this._layoutHistoryService)===null||t===void 0?void 0:t.canUndo)!==null&&e!==void 0?e:!1}get canRedo(){var e,t;return(e=(t=this._layoutHistoryService)===null||t===void 0?void 0:t.canRedo)!==null&&e!==void 0?e:!1}clearHistory(){var e;(e=this._layoutHistoryService)===null||e===void 0||e.clear()}get onDidChangeHistory(){var e,t;return(e=(t=this._layoutHistoryService)===null||t===void 0?void 0:t.onDidChangeHistory)!==null&&e!==void 0?e:Ute}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 PD(e,"edge",t,Mn);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=jn(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,i=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-i;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:en.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,i,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=Kx(),this._deserializer=new Qee(this),this._moduleRegistry=new ite,this._onWillDragPanel=new me,this.onWillDragPanel=this._onWillDragPanel.event,this._onWillDragGroup=new me,this.onWillDragGroup=this._onWillDragGroup.event,this._onDidDrop=new me,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new me,this.onWillDrop=this._onWillDrop.event,this._mutationDepth=0,this._pendingLocationChanges=new Map,this._origin="user",this._originDepth=0,this._onWillMutateLayout=new me,this.onWillMutateLayout=this._onWillMutateLayout.event,this._onDidMutateLayout=new me,this.onDidMutateLayout=this._onDidMutateLayout.event,this._onWillShowOverlay=new me,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onUnhandledDragOver=new me,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._onDidRemovePanel=new me,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidAddPanel=new me,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPopoutGroupSizeChange=new me,this.onDidPopoutGroupSizeChange=this._onDidPopoutGroupSizeChange.event,this._onDidPopoutGroupPositionChange=new me,this.onDidPopoutGroupPositionChange=this._onDidPopoutGroupPositionChange.event,this._onDidAddPopoutGroup=new me,this.onDidAddPopoutGroup=this._onDidAddPopoutGroup.event,this._onDidRemovePopoutGroup=new me,this.onDidRemovePopoutGroup=this._onDidRemovePopoutGroup.event,this._onDidChangePopouts=new me,this.onDidChangePopouts=this._onDidChangePopouts.event,this._onDidOpenPopoutWindowFail=new me,this.onDidOpenPopoutWindowFail=this._onDidOpenPopoutWindowFail.event,this._onDidStartFloatingGroupDrag=new me,this.onDidStartFloatingGroupDrag=this._onDidStartFloatingGroupDrag.event,this._onDidEndFloatingGroupDrag=new me,this.onDidEndFloatingGroupDrag=this._onDidEndFloatingGroupDrag.event,this._onDidLayoutFromJSON=new me,this.onDidLayoutFromJSON=this._onDidLayoutFromJSON.event,this._onDidActivePanelChange=new me({replay:!0}),this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidPanelPinnedChange=new me,this.onDidPanelPinnedChange=this._onDidPanelPinnedChange.event,this._onDidMovePanel=new me,this.onDidMovePanel=this._onDidMovePanel.event,this._onDidCreateTabGroup=new me,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new me,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new me,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new me,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new me,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new me,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,this._onDidMaximizedGroupChange=new me,this.onDidMaximizedGroupChange=this._onDidMaximizedGroupChange.event,this._inShellLayout=!1,this._onDidRemoveGroup=new me,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidEdgeGroupAutoHideChange=new me,this.onDidEdgeGroupAutoHideChange=this._onDidEdgeGroupAutoHideChange.event,this._onDidAddGroup=new me,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidOptionsChange=new me,this.onDidOptionsChange=this._onDidOptionsChange.event,this._onDidActiveGroupChange=new me,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._peekingGroups=new Set,this._moving=!1,this._options=t,this._tabGroupColorPalette=Wte(t);const l=t.modules,c=l??[...Ate,...rte()];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 FS(this.element),this._api=new Yx(this),this.disableResizing=!0,this.element.remove(),this._shellManager=new $te(e,this.element,(h,p)=>this._layoutFromShell(h,p),(i=(r=t.theme)===null||r===void 0?void 0:r.gap)!==null&&i!==void 0?i:0,(a=t.theme)===null||a===void 0?void 0:a.edgeGroupCollapsedSize),this.popupService.updateRoot(this._shellManager.element),this._shellThemeClassnames=new jh(this._shellManager.element),this.rootDropTargetContainer=new $p(this._shellManager.element,{disabled:!0}),this.floatingDropTargetContainer=new $p(this._shellManager.element,{disabled:!1}),this.overlayRenderContainer=new zS(this._shellManager.element,this),this._floatingOverlayHost=document.createElement("div"),this._floatingOverlayHost.className="dv-floating-overlay-host",this._shellManager.element.appendChild(this._floatingOverlayHost),Je(this.gridview.element,"dv-dockview",!0),Je(this.element,"dv-debug",!!t.debug),this.updateTheme(),t.debug&&this.addDisposables(new zte(this)),this.addDisposables(en.from(()=>this._pendingLocationChanges.clear()),this.rootDropTargetContainer,this.floatingDropTargetContainer,rt(this._shellManager.element,"dragend",()=>{var h,p;(h=this.rootDropTargetContainer.model)===null||h===void 0||h.clear(),(p=this.floatingDropTargetContainer.model)===null||p===void 0||p.clear()},!0),this.overlayRenderContainer,this._onWillDragPanel,this._onWillDragGroup,this._onWillShowOverlay,this._onDidActivePanelChange,this._onDidPanelPinnedChange,this._onDidAddPanel,this._onDidRemovePanel,this._onDidLayoutFromJSON,this._onDidDrop,this._onWillDrop,this._onWillMutateLayout,this._onDidMutateLayout,this._onDidMovePanel,this._onDidMovePanel.event(()=>{this.debouncedUpdateAllPositions()}),this._onDidAddGroup,this._onDidRemoveGroup,this._onDidEdgeGroupAutoHideChange,this._onDidActiveGroupChange,this._onUnhandledDragOver,this._onDidMaximizedGroupChange,this._onDidPopoutGroupSizeChange,this._onDidPopoutGroupPositionChange,this._onDidAddPopoutGroup,this._onDidRemovePopoutGroup,this._onDidChangePopouts,this._onDidAddPopoutGroup.event(()=>this._onDidChangePopouts.fire()),this._onDidRemovePopoutGroup.event(()=>this._onDidChangePopouts.fire()),this._onDidOpenPopoutWindowFail,this._onDidStartFloatingGroupDrag,this._onDidEndFloatingGroupDrag,this._onDidCreateTabGroup,this._onDidDestroyTabGroup,this._onDidAddPanelToTabGroup,this._onDidRemovePanelFromTabGroup,this._onDidTabGroupChange,this._onDidTabGroupCollapsedChange,qs.any(this.onDidPopoutGroupSizeChange,this.onDidPopoutGroupPositionChange,this.onDidCreateTabGroup,this.onDidDestroyTabGroup,this.onDidAddPanelToTabGroup,this.onDidRemovePanelFromTabGroup,this.onDidTabGroupChange,this.onDidTabGroupCollapsedChange)(()=>{this.fireLayoutChange()}),this._onDidOptionsChange,this.onDidAdd(h=>{this._moving||this._onDidAddGroup.fire(h)}),this.onDidRemove(h=>{this._moving||this._onDidRemoveGroup.fire(h)}),this.onDidActiveChange(h=>{this._moving||this._onDidActiveGroupChange.fire(h)}),this.onDidMaximizedChange(h=>{this._onDidMaximizedGroupChange.fire({group:h.panel,isMaximized:h.isMaximized})}),qs.any(this.onDidAddPanel,this.onDidRemovePanel,this.onDidAddGroup,this.onDidRemove,this.onDidRemoveGroup,this.onDidMovePanel,this.onDidActivePanelChange)(()=>{this._bufferOnDidLayoutChange.fire()}),en.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 ql(h,{kind:"edge",panel:void 0,api:this._api,group:void 0,getData:Mn}))}),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,i,r,a;const l=Ps(this._popoutWindowService,"PopoutWindow","api.addPopoutGroup");if(!l||e instanceof Qc&&e.model.location.type==="edge")return Promise.resolve(!1);if(e instanceof Or&&e.group.size===1)return this.addPopoutGroup(e.group,t);const c=AQ(this.gridview.element),d=this.element;function u(){var v,w;if(t?.position)return t.position;const y=(e instanceof Qc?e.element:(v=(w=e.group)===null||w===void 0?void 0:w.element)!==null&&v!==void 0?v:d).getBoundingClientRect();return{left:window.screenX+y.left,top:window.screenY+y.top,width:y.width,height:y.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=(i=t?.popoutUrl)!==null&&i!==void 0?i:(r=this.options)===null||r===void 0?void 0:r.popoutUrl,x=new Ote(`${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}),g=new dt(x,x.onDidClose(()=>{g.dispose()}));return x.open().then(v=>{var w,y;if(x.isDisposed)return!1;const b=(w=t?.referenceGroup)!==null&&w!==void 0?w:e instanceof Or?e.group:e,_=e.api.location.type,j=b.element.parentElement!==null;let N;if(t?.overridePopoutGridview){var C;N=(C=t.overridePopoutGroup)!==null&&C!==void 0?C:b}else j?t?.overridePopoutGroup?N=t.overridePopoutGroup:(N=this.createGroup({id:p}),v&&this._onDidAddGroup.fire(N)):N=b;if(v===null)return this.handleBlockedPopout({group:N,referenceGroup:b,options:t,popoutWindowDisposable:g}),!1;const k=document.createElement("div");k.className="dv-overlay-render-container";const E=new zS(k,this);N.model.renderContainer=E;const I=(y=t?.overridePopoutGridview)!==null&&y!==void 0?y:this.createNestedGridview();t?.overridePopoutGridview||I.addView(N,Ss.Distribute,[0]),I.element.style.width="100%",I.element.style.height="100%",I.layout(x.window.innerWidth,x.window.innerHeight);let T=!1;const A=()=>{T||(T=!0,I.dispose())};let D,W=[];if(!t?.overridePopoutGroup&&!t?.overridePopoutGridview&&j)if(e instanceof Or){const ke=e.group;this.movingLock(()=>{const Me=b.model.removePanel(e);N.model.openPanel(Me)}),W=[{panel:e,from:ke}]}else switch(this.movingLock(()=>nd({from:b,to:N})),W=N.panels.map(ke=>({panel:ke,from:b})),_){case"grid":b.api.setVisible(!1);break;case"floating":case"popout":var J;D=(J=this.floatingGroups.find(ke=>ke.group.api.id===e.api.id))===null||J===void 0?void 0:J.overlay.toJSON(),this.removeGroup(b);break}v.classList.add("dv-dockview"),v.style.overflow="hidden",v.appendChild(k),v.appendChild(I.element);const O=document.createElement("div"),B=new $p(O,{disabled:this.rootDropTargetContainer.disabled});v.appendChild(O),N.model.dropTargetContainer=B;const L=new FS(v,x.window);if(g.addDisposables(L),N.model.location={type:"popout",getWindow:()=>x.window,popoutUrl:f},t?.overridePopoutGridview){const ke=this.groups.filter(Me=>I.element.contains(Me.element));for(const Me of ke)Me.model.renderContainer=E,Me.model.dropTargetContainer=B,Me.model.location={type:"popout",getWindow:()=>x.window,popoutUrl:f}}j&&e.api.location.type==="grid"&&e.api.setVisible(!1),this.doSetGroupAndPanelActive(N);const se=l.observeGridviewSize(x,I,E);se&&g.addDisposables(se);const Q=new Gn;g.addDisposables(Q);const V=ke=>{Q.value=new dt(ke.api.onDidActiveChange(Me=>{if(Me.isActive){var fe;(fe=x.window)===null||fe===void 0||fe.focus()}}),ke.api.onWillFocus(()=>{var Me;(Me=x.window)===null||Me===void 0||Me.focus()}))};V(N);const H={},ne=j&&b&&this.getPanel(b.id),he={window:x,popoutGroup:N,gridview:I,overlayRenderContainer:E,dropTargetContainer:B,getWindow:()=>x.window,popoutUrl:f,referenceGroup:ne?b.id:void 0,popupService:L,setAnchorGroup:ke=>{he.popoutGroup=ke,V(ke)},disposable:{dispose:()=>(g.dispose(),H.returnedGroup)}},pe=MQ(x.window);g.addDisposables(pe,RQ(x.window,()=>{this._onDidPopoutGroupSizeChange.fire({width:x.window.innerWidth,height:x.window.innerHeight,group:he.popoutGroup})}),pe.event(()=>{this._onDidPopoutGroupPositionChange.fire({screenX:x.window.screenX,screenY:x.window.screenY,group:he.popoutGroup})}),rt(x.window,"resize",()=>{I.layout(x.window.innerWidth,x.window.innerHeight)}),E,en.from(()=>this.disposePopoutWindow({group:N,referenceGroup:b,popoutGridview:I,isGroupAddedToDom:j,floatingBox:D,disposePopoutGridview:A,closeResult:H}))),l.add(he),this._onDidAddPopoutGroup.fire({id:he.popoutGroup.id,group:he.popoutGroup,window:he.getWindow()});for(const{panel:ke,from:Me}of W)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:i}=e;if(console.error("dockview: failed to create popout. perhaps you need to allow pop-ups for this website"),i.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(()=>nd({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:i,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(x=>x.gridview===i)),u=this.groups.filter(x=>i.element.contains(x.element)),h=u.includes(n),p=h&&u.length===1,f=[];if(d){for(const x of u)if(x!==n){this.movingLock(()=>{this.doRemoveGroup(x,{skipDispose:!0,skipActive:!0,skipPopoutReturn:!0}),this.redockGroupToMainGrid(x)});for(const g of x.panels)f.push({panel:g,from:x})}}if(h&&r&&this.getPanel(s.id)){const x=[...n.panels];this.movingLock(()=>nd({from:n,to:s}));for(const g of x)f.push({panel:g,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 x of n.panels)f.push({panel:x,from:n})}this.doSetGroupAndPanelActive(n)}l();for(const{panel:x,from:g}of f)this.fireDidMovePanel(x,g)}addFloatingGroup(e,t){this.mutation("float",()=>this._doAddFloatingGroup(e,t))}_doAddFloatingGroup(e,t){if(!Ps(this._floatingGroupService,"FloatingGroup","api.addFloatingGroup")||e instanceof Qc&&e.model.location.type==="edge")return;let n,s=[];if(e instanceof Or){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 i;n=e;const c=(i=this._popoutWindowService)===null||i===void 0?void 0:i.findReferenceGroupId(n),d=c?this.getPanel(c):void 0;typeof t?.skipRemoveGroup=="boolean"&&t.skipRemoveGroup||(d?(this.movingLock(()=>nd({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=So.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=So.top,typeof t.width=="number"?c.width=Math.max(t.width,0):c.width=So.width,typeof t.height=="number"?c.height=Math.max(t.height,0):c.height=So.height,c}return{left:typeof t?.x=="number"?Math.max(t.x,0):So.left,top:typeof t?.y=="number"?Math.max(t.y,0):So.top,width:typeof t?.width=="number"?Math.max(t.width,0):So.width,height:typeof t?.height=="number"?Math.max(t.height,0):So.height}}const a=r(),l=this.createNestedGridview();l.addView(n,Ss.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 dD(!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,i){var r,a,l,c,d,u,h,p,f;const x=Ps(this._floatingGroupService,"FloatingGroup","api.addFloatingGroup");if(!x)return;const g=((r=(a=i?.dragHandle)!==null&&a!==void 0?a:this.options.floatingGroupDragHandle)!==null&&r!==void 0?r:"titlebar")==="titlebar"?new nte(this,t):void 0,v=new sv(pt(pt({container:(l=this._floatingOverlayHost)!==null&&l!==void 0?l:this.gridview.element,content:e.element,header:g?.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=i?.disableSmartGuides)!==null&&p!==void 0?p:!1),getSiblingBoxes:()=>this._gatherFloatingGroupBoxes(t)})),w=(f=g?.element)!==null&&f!==void 0?f:t.element.querySelector(".dv-void-container");if(!w)throw new Error("dockview: failed to find drag handle");v.setupDrag(w,{inDragMode:typeof i?.inDragMode=="boolean"?i.inDragMode:!1});const y=x.add(t,v,e);y.addDisposables(v.onDidStartMoving(()=>this._onDidStartFloatingGroupDrag.fire(t)),v.onDidChangeEnd(()=>this._onDidEndFloatingGroupDrag.fire(t))),g&&(y.setTitleBar(g),y.addDisposables(g,en.from(()=>y.setTitleBar(void 0)),g.onDragStart(b=>{this._onWillDragGroup.fire({nativeEvent:b,group:y.group})})));for(const b of n)b.model.location={type:"floating"};i?.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,i=this.options.dndStrategy;this._options=pt(pt({},this.options),e);const r=this.options.disableDnd,a=this.options.dndStrategy;if((s!==r||i!==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:Zx),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){lte(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(zD("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 i=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,i),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 i;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:(i=t.panelId)!==null&&i!==void 0?i:void 0},to:{group:r,position:"center"}})})}getEdgeGroup(e){var t;return(t=this._edgeGroupService)===null||t===void 0||(t=t.get(e))===null||t===void 0?void 0:t.api}getEdgeGroupPanel(e){var t;return(t=this._edgeGroupService)===null||t===void 0?void 0:t.get(e)}pinEdgeGroup(e){var t;(t=Ps(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.pinEdgeGroup"))===null||t===void 0||t.pin(e)}autoHideEdgeGroup(e){var t;(t=Ps(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.autoHideEdgeGroup"))===null||t===void 0||t.autoHide(e)}peekEdgeGroup(e,t){var n;(n=Ps(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.peekEdgeGroup"))===null||n===void 0||n.peek(e,t)}get overlayRoot(){return this.rootElement}getDropZoneRect(){return this.element.getBoundingClientRect()}getEdgeGroupExpandedSize(e){var t,n;return(t=(n=this._shellManager)===null||n===void 0?void 0:n.getEdgeGroupExpandedSize(e))!==null&&t!==void 0?t:0}repositionPanelOverlay(e,t,n){this.overlayRenderContainer.repositionPanelOverlay(e.api.id,t,n)}setEdgeGroupVisible(e,t){this._shellManager.setEdgeGroupVisible(e,t)}isEdgeGroupVisible(e){return this._shellManager.isEdgeGroupVisible(e)}removeEdgeGroup(e){const t=Ps(this._edgeGroupService,"EdgeGroup","api.removeEdgeGroup");if(!t)return;const n=t.get(e);if(!n)throw new Error(`dockview: no edge group exists at position '${e}'`);this.mutation("remove",()=>{for(const s of[...n.panels])this.removePanel(s,{removeEmptyGroup:!1,skipDispose:!1});this._shellManager.removeEdgeView(e),t.remove(e),n.dispose(),this._groups.delete(n.id),this._onDidRemoveGroup.fire(n)})}setEdgeGroupCollapsed(e,t){var n;const s=(n=this._edgeGroupService)===null||n===void 0?void 0:n.findPositionOf(e);s&&this._shellManager.isEdgeGroupCollapsed(s)!==t&&(this._shellManager.setEdgeGroupCollapsed(s,t),e.api._onDidCollapsedChange.fire({isCollapsed:t}))}isEdgeGroupCollapsed(e){var t;const n=(t=this._edgeGroupService)===null||t===void 0?void 0:t.findPositionOf(e);return n?this._shellManager.isEdgeGroupCollapsed(n):!1}isEdgeGroupPeeking(e){return this._peekingGroups.has(e)}setEdgeGroupPeeking(e,t){this._peekingGroups.has(e)!==t&&(t?this._peekingGroups.add(e):this._peekingGroups.delete(e),e.api._onDidPeekChange.fire({isPeeking:t}))}isEdgeGroupAutoHide(e){var t,n;const s=(t=this._edgeGroupService)===null||t===void 0?void 0:t.isAutoHide(e);if(s!==void 0)return s;const i=(n=this._edgeGroupService)===null||n===void 0?void 0:n.findPositionOf(e);return i===void 0?!1:Dee(this.options.autoHideEdgeGroups,i)}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=jn(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=jn(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,i;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:(i=this.activeGroup)===null||i===void 0?void 0:i.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 i=t[n];if(!i)continue;if(this._edgeGroupService.isAutoReveal(s)&&s.model.isEmpty){delete t[n];continue}i.group=s.toJSON(),this._edgeGroupService.isAutoReveal(s)&&(i.autoReveal=!0);const r=this._edgeGroupService.isAutoHide(s);r!==void 0&&(i.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 i=new Map,r=new Map,a=[],l=[],c=()=>{for(const b of l)try{b.dispose()}catch(_){console.error("dockview: failed to dispose a temporary group created for reuseExistingPanels",_)}l.length=0};if(t?.reuseExistingPanels){const b=Object.keys(e.panels);let _;const j=()=>{const N=this.createGroup(),C=this._groups.get(N.api.id);return this._groups.delete(N.api.id),l.push(en.from(()=>{this.movingLock(()=>{for(const k of N.panels.slice())N.model.removePanel(k)}),C?.disposable.dispose(),N.dispose()})),N};try{for(const N of this.panels)if(b.includes(N.api.id)){i.set(N.api.id,N);let C;if(N.api.renderer==="always"&&N.api.isVisible)C=j();else{var d;(d=_)!==null&&d!==void 0||(_=j()),C=_}r.set(N.api.id,C),a.push({panel:N,temporaryGroup:C})}this.movingLock(()=>{a.forEach(({panel:N,temporaryGroup:C})=>{this.moveGroupOrPanel({from:{groupId:N.api.group.api.id,panelId:N.api.id},to:{group:C,position:"center"},keepEmptyGroups:!0})})}),this.clear()}catch(N){throw c(),N}}else this.clear();const{grid:u,panels:h,activeGroup:p}=e;try{var f,x,g,v,w;const b=this.width,_=this.height,j=C=>{const{id:k,locked:E,hideHeader:I,headerPosition:T,views:A,activeView:D}=C;if(typeof k!="string")throw new TypeError("dockview: group id must be of type string");const W=this.createGroup({id:k,locked:!!E,hideHeader:!!I,headerPosition:T});this._onDidAddGroup.fire(W);const J=[],O=A.filter(B=>h[B]);for(const B of O){const L=i.get(B),se=r.get(B);if(se&&L)this.movingLock(()=>{se.model.removePanel(L)}),J.push(L),L.updateFromStateModel(h[B]);else{const Q=this._deserializer.fromJSON(h[B],W);J.push(Q)}}for(const B of J){const L=typeof D=="string"&&D===B.id;i.has(B.api.id)?this.movingLock(()=>{W.model.openPanel(B,{skipSetActive:!L,skipSetGroupActive:!0})}):W.model.openPanel(B,{skipSetActive:!L,skipSetGroupActive:!0})}return C.tabGroups&&C.tabGroups.length>0&&W.model.restoreTabGroups(C.tabGroups),!W.activePanel&&W.panels.length>0&&W.model.openPanel(W.panels[W.panels.length-1],{skipSetGroupActive:!0}),W};this.gridview.deserialize(u,{fromJSON:C=>j(C.data)}),this._layoutFromShell(b,_),e.edgeGroups&&this.deserializeEdgeGroups(e.edgeGroups,h,i,r),this.deserializeFloatingWindows((f=e.floatingGroups)!==null&&f!==void 0?f:[],j);const N=this.deserializePopoutWindows((x=e.popoutGroups)!==null&&x!==void 0?x:[],j);if((g=this._popoutWindowService)===null||g===void 0||g.finishRestoration(N),(v=this._floatingGroupService)===null||v===void 0||v.constrainBounds(),typeof p=="string"){const C=this.getPanel(p);C&&this.doSetGroupAndPanelActive(C)}(w=this._watermarkService)===null||w===void 0||w.update()}catch(b){var y;console.error("dockview: failed to deserialize layout. Reverting changes",b);for(const _ of this.groups)for(const j of _.panels)this.removePanel(j,{removeEmptyGroup:!1,skipDispose:!1});for(const _ of this.groups)_.dispose(),this._groups.delete(_.id),this._onDidRemoveGroup.fire(_);throw(y=this._floatingGroupService)===null||y===void 0||y.disposeAll(),this.clear(),b}finally{c()}this.debouncedUpdateAllPositions(),this._onDidLayoutFromJSON.fire()}deserializeNestedGridview(e,t){const n=this.createNestedGridview(e.orientation),s=[];return n.deserialize(e,{fromJSON:i=>{const r=t(i.data);return s.push(r),r}}),{gridview:n,members:s}}deserializeEdgeGroups(e,t,n,s){const i=Ps(this._edgeGroupService,"EdgeGroup","fromJSON edge restoration");if(i){for(const a of["top","bottom","left","right"]){const l=e[a];if(l&&!i.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 i.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 x=n.get(f),g=s.get(f);if(g&&x)this.movingLock(()=>{g.model.removePanel(x)}),p.push(x),x.updateFromStateModel(t[f]);else{const v=this._deserializer.fromJSON(t[f],l);p.push(v)}}for(const f of p){const x=h===f.id;n.has(f.api.id)?this.movingLock(()=>{l.model.openPanel(f,{skipSetActive:!x,skipSetGroupActive:!0})}):l.model.openPanel(f,{skipSetActive:!x,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:i,position:r}=n;if(i){const{gridview:a,members:l}=this.deserializeNestedGridview(i,t);if(l.length===0)continue;this.mountFloatingWindow(a,l[0],l,r,{inDragMode:!1})}else if(s){const a=t(s);this.addFloatingGroup(a,{position:r,width:r.width,height:r.height,skipRemoveGroup:!0,inDragMode:!1})}}}deserializePopoutWindows(e,t){const n=e.length>0?Ps(this._popoutWindowService,"PopoutWindow","fromJSON popout restoration"):this._popoutWindowService;return n?e.flatMap((s,i)=>{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(i*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 x of[...f.panels])this.removePanel(x,{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 i=[...s.panels];for(const r of i)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 i=u=>!!e.inactive&&u.model.size>0;if(e.position)if(Pee(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(Eee(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(DS(e.position.direction)),h=this.createPanel(e,u);return u.model.openPanel(h,{skipSetActive:i(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=_u(((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,pt(pt({},p),{},{inDragMode:!1,skipRemoveGroup:!0,skipActiveGroup:!0})),c=this.createPanel(e,h),h.model.openPanel(c,{skipSetActive:i(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:i(t),skipSetGroupActive:e.inactive,index:s}),t.api.setSize({width:n?.width,height:n?.height}),e.inactive||this.doSetGroupAndPanelActive(t);else{const h=jn(t.element),p=zs(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:i(f),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(f)}}else if(e.floating){const u=this.createGroup();this._onDidAddGroup.fire(u);const h=typeof e.floating=="object"&&e.floating!==null?e.floating:{};this.addFloatingGroup(u,pt(pt({},h),{},{inDragMode:!1,skipRemoveGroup:!0,skipActiveGroup:!0})),c=this.createPanel(e,u),u.model.openPanel(c,{skipSetActive:i(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:i(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 ete}addGroup(e){return this.mutation("add",()=>this._doAddGroup(e))}_doAddGroup(e){if(e){let i;if(Aee(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(i=this.findGroup(u),!i)throw new Error(`dockview: reference group for reference panel ${h} does not exist`)}else if(Mee(e)){var n;if(i=typeof e.referenceGroup=="string"?(n=this._groups.get(e.referenceGroup))===null||n===void 0?void 0:n.value:e.referenceGroup,!i){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(DS(e.direction),e);return e.skipSetActive||this.doSetGroupAndPanelActive(u),u}const r=_u(e.direction||"within"),a=jn(i.element),l=zs(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 i=this.createGroup(e);return this.doAddGroup(i),this.doSetGroupAndPanelActive(i),i}}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 i=(n=this._popoutWindowService)===null||n===void 0?void 0:n.findByGroup(e);if(i){const r=this.nestedWindowMembers(e);return r.length<=1?!1:(i.gridview.remove(e),i.popoutGroup===e&&i.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 i;this.removePanel(u,{removeEmptyGroup:!1,skipDispose:(i=t?.skipDispose)!==null&&i!==void 0?i:!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 FD(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,i=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(i===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(i,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!d)throw new Error(`dockview: No panel with id ${i}`);!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=jn(n.element),h=zs(d.orientation,u,r);if(l.size<2){const[p,f]=io(h);if(l.api.location.type==="grid"&&d===this.gridview){const[w,y]=io(jn(l.element));if(aD(w,p)){this.gridview.moveView(w,y,f),this.fireDidMovePanel(this.getGroupPanel(i),l);return}}if(l.api.location.type==="popout"&&this.nestedWindowMembers(l).length<=1){var c;const w=(c=this._popoutWindowService)===null||c===void 0?void 0:c.findByGroup(l);if(!w)return;const y=this.movingLock(()=>w.popoutGroup.model.removePanel(w.popoutGroup.panels[0],{skipSetActive:!0,skipSetActiveGroup:!0}));this.doRemoveGroup(l,{skipActive:!0});const b=zs(d.orientation,jn(n.element),r),_=this.createGroupAtLocation(b,void 0,void 0,d);this.movingLock(()=>_.model.openPanel(y,{skipSetActive:!0})),this.doSetGroupAndPanelActive(_),this.fireDidMovePanel(this.getGroupPanel(i),l);return}if(l.api.location.type==="edge"){const w=this.movingLock(()=>l.model.removePanel(i,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!w)throw new Error(`dockview: No panel with id ${i}`);const y=this.createGroupAtLocation(h,void 0,void 0,d);this.movingLock(()=>y.model.openPanel(w,{skipSetGroupActive:!0})),this.doSetGroupAndPanelActive(y),this.fireDidMovePanel(w,l);return}const x=this.movingLock(()=>this.doRemoveGroup(l,{skipActive:!0,skipDispose:!0})),g=jn(n.element),v=zs(d.orientation,g,r);this.movingLock(()=>this.doAddGroup(x,v,void 0,d)),this.setGroupLocationForRoot(x,d),this.doSetGroupAndPanelActive(x),this.fireDidMovePanel(this.getGroupPanel(i),l)}else{const p=this.movingLock(()=>l.model.removePanel(i,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!p)throw new Error(`dockview: No panel with id ${i}`);const f=zs(d.orientation,u,r),x=this.createGroupAtLocation(f,void 0,void 0,d);this.movingLock(()=>x.model.openPanel(p,{skipSetGroupActive:!0})),this.doSetGroupAndPanelActive(x),this.fireDidMovePanel(p,l)}}}moveTabGroupToGroup(e){const{sourceGroup:t,tabGroupId:n,destinationGroup:s,destinationTarget:i,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=i&&i!=="center"?jn(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 x=v=>{this.movingLock(()=>{for(const y of f)v.model.openPanel(y,{index:r,skipSetActive:!0,skipSetGroupActive:!0})});const w=v.model.createTabGroup({label:l,color:c,collapsed:d,componentParams:u});for(const y of f)v.model.addPanelToTabGroup(w.id,y.id);e.skipSetActive||this.doSetGroupAndPanelActive(v);for(const y of f)this.fireDidMovePanel(y,t)};let g;if(!i||i==="center"||!p)g=s;else{const v=zs(this.gridview.orientation,p,i);g=this.createGroupAtLocation(v)}!e.keepEmptyGroups&&t.model.size===0&&t!==g&&this.doRemoveGroup(t,{skipActive:!0}),x(g)}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,i=e.to.position;let r=n,a;if(i==="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 x=s.model.createTabGroup({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams});for(const g of f.panelIds)s.model.addPanelToTabGroup(x.id,g)}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 x=r.model.createTabGroup({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams});for(const g of f.panelIds)r.model.addPanelToTabGroup(x.id,g)}}else switch(n.api.location.type){case"grid":this.gridview.removeView(jn(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=jn(s.element),p=zs(u.orientation,h,i);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 Qc(this,n,e);if(s.init({params:{},accessor:this}),!this._groups.has(s.id)){const i=new dt(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)}),qs.any(s.model.onDidPanelTitleChange,s.model.onDidPanelParametersChange)(()=>{this._bufferOnDidLayoutChange.fire()}));this._groups.set(s.id,{value:s,disposable:i})}return s.initialize(),s}createPanel(e,t){var n,s,i;const r=e.component,a=(n=e.tabComponent)!==null&&n!==void 0?n:this.options.defaultTabComponent,l=new OD(this,e.id,r,a),c=new Or(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:(i=e?.params)!==null&&i!==void 0?i:{}}),c}createGroupAtLocation(e,t,n,s=this.gridview){const i=this.createGroup(n);return this.doAddGroup(i,e,t,s),this.setGroupLocationForRoot(i,s),i}setGroupLocationForRoot(e,t){var n;const s=(n=this._popoutWindowService)===null||n===void 0?void 0:n.entries.find(i=>i.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 i=(n=this._popoutWindowService)===null||n===void 0?void 0:n.findByGroup(e);return i?i.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:Ci(t)}updateTheme(){var e,t,n,s,i,r,a,l;const c=(e=this._options.theme)!==null&&e!==void 0?e:Jee;(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=(i=this._popoutWindowService)===null||i===void 0?void 0:i.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";Je(this.element,"dv-tab-group-indicator-none",p),this._shellManager&&Je(this._shellManager.element,"dv-tab-group-indicator-none",p);for(const f of this.groups)f.model.updateTabGroups()}},qte=class extends uD{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 me,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidRemoveGroup=new me,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidAddGroup=new me,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidActiveGroupChange=new me,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._options=t,this.addDisposables(this._onDidAddGroup,this._onDidRemoveGroup,this._onDidActiveGroupChange,this.onDidAdd(s=>{this._onDidAddGroup.fire(s)}),this.onDidRemove(s=>{this._onDidRemoveGroup.fire(s)}),this.onDidActiveChange(s=>{this._onDidActiveGroupChange.fire(s)}))}updateOptions(e){super.updateOptions(e);const t=typeof e.orientation=="string"&&this.gridview.orientation!==e.orientation;this._options=pt(pt({},this.options),e),t&&(this.gridview.orientation=e.orientation),this.layout(this.gridview.width,this.gridview.height,!0)}removePanel(e){this.removeGroup(e)}toJSON(){var e;return{grid:this.gridview.serialize(),activePanel:(e=this.activeGroup)===null||e===void 0?void 0:e.id}}setVisible(e,t){this.gridview.setViewVisible(jn(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=[],i=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(i,r,!0),s.forEach(a=>a()),typeof n=="string"){const a=this.getPanel(n);a&&this.doSetGroupActive(a)}}catch(s){for(const i of this.groups)i.dispose(),this._groups.delete(i.id),this._onDidRemoveGroup.fire(i);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 i=_u(t.direction);if(i==="center")throw new Error(`${i} not supported as an option`);const r=jn(s.element),a=zs(this.gridview.orientation,r,i),l=this.gridview.remove(e);this.doAddGroup(l,a,t.size)}addPanel(e){var t,n,s;let i=(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=_u(e.position.direction);if(c==="center")throw new Error(`${c} not supported as an option`);{const d=jn(l.element);i=zs(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,i,e.size),this.registerPanel(a),this.doSetGroupActive(a),a}registerPanel(e){const t=new dt(e.api.onDidFocusChange(n=>{n.isFocused&&this._groups.forEach(s=>{const i=s.value;i.setActive(i===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 i=jn(e.element),[r,a]=io(zs(this.gridview.orientation,i,n)),[l,c]=io(jn(s.element));if(aD(l,r)){this.gridview.moveView(l,c,a);return}const d=this.doRemoveGroup(s,{skipActive:!0,skipDispose:!0}),u=jn(e.element),h=zs(this.gridview.orientation,u,n);this.doAddGroup(d,h)}removeGroup(e){super.removeGroup(e)}dispose(){super.dispose(),this._onDidLayoutfromJSON.dispose()}},Yte=class extends qx{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 dt(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 Gn,this._panels=new Map,this._onDidLayoutfromJSON=new me,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidAddView=new me,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new me,this.onDidRemoveView=this._onDidRemoveView.event,this._onDidLayoutChange=new me,this.onDidLayoutChange=this._onDidLayoutChange.event,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new jh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.splitview=new xr(this.element,t),this.addDisposables(this._onDidAddView,this._onDidLayoutfromJSON,this._onDidRemoveView,this._onDidLayoutChange)}updateOptions(e){if("className"in e){var t;this._classNames.setClassNames((t=e.className)!==null&&t!==void 0?t:"")}if("disableResizing"in e){var n;this.disableResizing=(n=e.disableAutoResizing)!==null&&n!==void 0?n:!1}typeof e.orientation=="string"&&(this.splitview.orientation=e.orientation),this._options=pt(pt({},this.options),e),this.splitview.layout(this.splitview.size,this.splitview.orthogonalSize)}focus(){var e;(e=this._activePanel)===null||e===void 0||e.focus()}movePanel(e,t){this.splitview.moveView(e,t)}setVisible(e,t){const n=this.panels.indexOf(e);this.splitview.setViewVisible(n,t)}setActive(e,t){this._activePanel=e,this.panels.filter(n=>n!==e).forEach(n=>{n.api._onDidActiveChange.fire({isActive:!1}),t||n.focus()}),e.api._onDidActiveChange.fire({isActive:!0}),t||e.focus()}removePanel(e,t){const n=this._panels.get(e.id);if(!n)throw new Error(`unknown splitview panel ${e.id}`);n.dispose(),this._panels.delete(e.id);const s=this.panels.indexOf(e);this.splitview.removeView(s,t).dispose();const i=this.panels;i.length>0&&this.setActive(i[i.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:Ss.Distribute,i=typeof e.index=="number"?e.index:void 0;return this.splitview.addView(n,s,i),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:i}=e,r=[],a=this.width,l=this.height;if(this.splitview=new xr(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 i=="string"){const c=this.getPanel(i);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,Ss.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()}},HS=class extends dt{get element(){return this._element}constructor(){super(),this._expandedIcon=See(),this._collapsedIcon=jD(),this.disposable=new Gn,this.apiRef={api:null},this._element=document.createElement("div"),this.element.className="dv-default-header",this._content=document.createElement("span"),this._expander=document.createElement("div"),this._expander.className="dv-pane-header-icon",this.element.appendChild(this._expander),this.element.appendChild(this._content),this.addDisposables(rt(this._element,"click",()=>{var e;(e=this.apiRef.api)===null||e===void 0||e.setExpanded(!this.apiRef.api.isExpanded)}))}init(e){this.apiRef.api=e.api,this._content.textContent=e.title,this.updateIcon(),this.disposable.value=e.api.onDidExpansionChange(()=>{this.updateIcon()})}updateIcon(){var e;const t=!!(!((e=this.apiRef.api)===null||e===void 0)&&e.isExpanded);Je(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 Xte=Kx(),BS=22,VS=0,$S=Number.MAX_SAFE_INTEGER;var WS=class extends xee{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}},Jte=class extends qx{get id(){return this._id}get panels(){return this.paneview.getPanes()}set paneview(e){this._paneview=e,this._disposable.value=new dt(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=Xte.next(),this._disposable=new Gn,this._viewDisposables=new Map,this._onDidLayoutfromJSON=new me,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidLayoutChange=new me,this.onDidLayoutChange=this._onDidLayoutChange.event,this._onDidDrop=new me,this.onDidDrop=this._onDidDrop.event,this._onDidAddView=new me,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new me,this.onDidRemoveView=this._onDidRemoveView.event,this._onUnhandledDragOver=new me,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 jh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.paneview=new TS(this.element,{orientation:"VERTICAL"}),this.addDisposables(this._disposable)}setVisible(e,t){const n=this.panels.indexOf(e);this.paneview.setViewVisible(n,t)}focus(){}updateOptions(e){if("className"in e){var t;this._classNames.setClassNames((t=e.className)!==null&&t!==void 0?t:"")}if("disableAutoResizing"in e){var n;this.disableResizing=(n=e.disableAutoResizing)!==null&&n!==void 0?n:!1}this._options=pt(pt({},this.options),e)}addPanel(e){var t,n,s;const i=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 HS);const a=new WS({id:e.id,component:e.component,headerComponent:e.headerComponent,header:r,body:i,orientation:"VERTICAL",isExpanded:!!e.isExpanded,disableDnd:!!this.options.disableDnd,accessor:this,headerSize:(n=e.headerSize)!==null&&n!==void 0?n:BS,minimumBodySize:VS,maximumBodySize:$S});this.doAddPanel(a);const l=typeof e.size=="number"?e.size:Ss.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 Kl(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 i=this.paneview.getViewCachedVisibleSize(s),r=typeof i=="number";return pt({size:r?i: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=[],i=this.width,r=this.height;this.paneview=new TS(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 HS);const x=new WS({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:BS,minimumBodySize:(d=a.minimumSize)!==null&&d!==void 0?d:VS,maximumBodySize:(u=a.maximumSize)!==null&&u!==void 0?u:$S});return this.doAddPanel(x),s.push(()=>{var g;x.init({params:(g=h.params)!==null&&g!==void 0?g:{},minimumBodySize:a.minimumSize,maximumBodySize:a.maximumSize,title:h.title,isExpanded:!!a.expanded,containerApi:new Kl(this),accessor:this}),x.orientation=this.paneview.orientation}),setTimeout(()=>{this._onDidAddView.fire(x)},0),{size:a.size,view:x,visible:a.visible}})}}),this.layout(i,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 dt(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()}},Zte=class extends Xx{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 kD(e,t)),this._evaluatedMinimumSize=0,this._evaluatedMaximumSize=Number.POSITIVE_INFINITY,this._minimumSize=0,this._maximumSize=Number.POSITIVE_INFINITY,this._snap=!1,this._onDidChange=new me,this.onDidChange=this._onDidChange.event,this.api.initialize(this),this.addDisposables(this._onDidChange,this.api.onWillVisibilityChange(n=>{const{isVisible:s}=n,{accessor:i}=this._params;i.setVisible(this,s)}),this.api.onActiveChange(()=>{const{accessor:n}=this._params;n.setActive(this)}),this.api.onDidConstraintsChangeInternal(n=>{(typeof n.minimumSize=="number"||typeof n.minimumSize=="function")&&(this._minimumSize=n.minimumSize),(typeof n.maximumSize=="number"||typeof n.maximumSize=="function")&&(this._maximumSize=n.maximumSize),this.updateConstraints()}),this.api.onDidSizeChange(n=>{this._onDidChange.fire({size:n.size})}))}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}layout(e,t){const[n,s]=this.orientation==="HORIZONTAL"?[e,t]:[t,e];super.layout(n,s)}init(e){super.init(e),this._priority=e.priority,e.minimumSize&&(this._minimumSize=e.minimumSize),e.maximumSize&&(this._maximumSize=e.maximumSize),e.snap&&(this._snap=e.snap)}toJSON(){const e=n=>n===Number.MAX_SAFE_INTEGER||n===Number.POSITIVE_INFINITY?void 0:n,t=n=>n<=0?void 0:n;return pt(pt({},super.toJSON()),{},{minimumSize:t(this.minimumSize),maximumSize:e(this.maximumSize)})}updateConstraints(){this.api._onDidConstraintsChange.fire({maximumSize:this._evaluatedMaximumSize,minimumSize:this._evaluatedMinimumSize})}};function Qte(e,t){return new Kte(e,t).api}function ene(e,t){return new pD(new Yte(e,t))}function tne(e,t){return new fD(new qte(e,t))}function nne(e,t){return new Kl(new Jte(e,t))}function Yl(e){"@babel/helpers - typeof";return Yl=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},Yl(e)}function sne(e,t){if(Yl(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(Yl(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ine(e){var t=sne(e,"string");return Yl(t)=="symbol"?t:t+""}function one(e,t,n){return(t=ine(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function US(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,s)}return n}function Ts(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?US(Object(n),!0).forEach(function(s){one(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):US(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}const HD=(e,t)=>{const[,n]=Ce.useState(0),s=Ce.useRef(e.componentProps);return Ce.useImperativeHandle(t,()=>({update:i=>{s.current=Ts(Ts({},s.current),i),n(r=>r+1)}}),[]),Ce.createElement(e.component,s.current)};HD.displayName="DockviewReactJsBridge";const rne=(()=>{let e=1;return{next:()=>`dockview_react_portal_key_${(e++).toString()}`}})(),ane=Ce.createContext({});var Vi=class{constructor(e,t,n,s,i){this.parent=e,this.portalStore=t,this.component=n,this.parameters=s,this.context=i,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=Ts(Ts({},this._initialProps),e)}createPortal(){if(this.disposed)throw new Error("invalid operation: resource is already disposed");if(!lne(this.component))throw new Error("Dockview: Only React.memo(...), React.ForwardRef(...) and functional components are accepted as components");const e=Ce.createElement(Ce.forwardRef(HD),{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?Ce.createElement(ane.Provider,{value:this.context},e):e,n=jC.createPortal(t,this.parent,rne.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 Ih=()=>{const[e,t]=Ce.useState([]);return Ce.useDebugValue(`Portal count: ${e.length}`),[e,Ce.useCallback(n=>{t(i=>[...i,n]);let s=!1;return en.from(()=>{if(s)throw new Error("invalid operation: resource already disposed");s=!0,t(i=>i.filter(r=>r!==n))})},[])]};function lne(e){return typeof e=="function"||!!e?.$$typeof}var KS=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._onDidFocus=new me,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new me,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 Vi(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()}},qS=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 Vi(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()}},YS=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 Vi(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()}},cne=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 Gn,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 dt(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 Vi(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}})}},dne=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 Vi(this._element,this.reactPortalStore,this.component,e)}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}},XS=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 Vi(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()}},JS=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 Vi(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 Pr(e,t){return e?n=>new cne(e,t,n):void 0}const sd="props.defaultTabComponent";function une(e){return Am.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const BD=Ce.forwardRef((e,t)=>{const n=Ce.useRef(null),s=Ce.useRef(void 0),[i,r]=Ih();Ce.useImperativeHandle(t,()=>n.current,[]);const a=Ce.useRef({});return Ce.useEffect(()=>{const l={};Am.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},Am.map(l=>e[l])),Ce.useEffect(()=>{if(!n.current)return;const l=Ts({},e.tabComponents);e.defaultTabComponent&&(l[sd]=e.defaultTabComponent);const c={createLeftHeaderActionComponent:Pr(e.leftHeaderActionsComponent,{addPortal:r}),createRightHeaderActionComponent:Pr(e.rightHeaderActionsComponent,{addPortal:r}),createPrefixHeaderActionComponent:Pr(e.prefixHeaderActionsComponent,{addPortal:r}),createComponent:f=>new KS(f.id,e.components[f.name],{addPortal:r}),createTabComponent(f){return new qS(f.id,l[f.name],{addPortal:r})},createWatermarkComponent:e.watermarkComponent?()=>new YS("watermark",e.watermarkComponent,{addPortal:r}):void 0,defaultTabComponent:e.defaultTabComponent?sd:void 0,createContextMenuItemComponent:f=>{if(f.component)return new dne(f.id,f.component,{addPortal:r})}},d=une(e);if(e.tabGroupChipComponent){const f=e.tabGroupChipComponent;d.createTabGroupChipComponent=()=>new XS(f,{addPortal:r})}if(e.groupDragGhostComponent){const f=e.groupDragGhostComponent;d.createGroupDragGhostComponent=()=>new JS(f,{addPortal:r})}const u=Qte(n.current,Ts(Ts({},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()}},[]),Ce.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onDidDrop(c=>{e.onDidDrop&&e.onDidDrop(c)});return()=>{l.dispose()}},[e.onDidDrop]),Ce.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onWillDrop(c=>{e.onWillDrop&&e.onWillDrop(c)});return()=>{l.dispose()}},[e.onWillDrop]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createTabGroupChipComponent:e.tabGroupChipComponent?()=>new XS(e.tabGroupChipComponent,{addPortal:r}):void 0})},[e.tabGroupChipComponent]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createGroupDragGhostComponent:e.groupDragGhostComponent?()=>new JS(e.groupDragGhostComponent,{addPortal:r}):void 0})},[e.groupDragGhostComponent]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new KS(l.id,e.components[l.name],{addPortal:r})})},[e.components]),Ce.useEffect(()=>{if(!s.current)return;const l=Ts({},e.tabComponents);e.defaultTabComponent&&(l[sd]=e.defaultTabComponent),s.current.updateOptions({defaultTabComponent:e.defaultTabComponent?sd:void 0,createTabComponent(c){return new qS(c.id,l[c.name],{addPortal:r})}})},[e.tabComponents,e.defaultTabComponent]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createWatermarkComponent:e.watermarkComponent?()=>new YS("watermark",e.watermarkComponent,{addPortal:r}):void 0})},[e.watermarkComponent]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createRightHeaderActionComponent:Pr(e.rightHeaderActionsComponent,{addPortal:r})})},[e.rightHeaderActionsComponent]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createLeftHeaderActionComponent:Pr(e.leftHeaderActionsComponent,{addPortal:r})})},[e.leftHeaderActionsComponent]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createPrefixHeaderActionComponent:Pr(e.prefixHeaderActionsComponent,{addPortal:r})})},[e.prefixHeaderActionsComponent]),Ce.createElement("div",{style:{height:"100%",width:"100%"},ref:n},i)});BD.displayName="DockviewComponent";var ZS=class extends Zte{constructor(e,t,n,s){super(e,t),this.reactComponent=n,this.reactPortalStore=s}getComponent(){var e,t;return new Vi(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 pD(this._params.accessor)})}};function hne(e){return km.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const pne=Ce.forwardRef((e,t)=>{const n=Ce.useRef(null),s=Ce.useRef(void 0),[i,r]=Ih();Ce.useImperativeHandle(t,()=>n.current,[]);const a=Ce.useRef({});return Ce.useEffect(()=>{const l={};km.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},km.map(l=>e[l])),Ce.useEffect(()=>{if(!n.current)return()=>{};const l=ene(n.current,Ts(Ts({},hne(e)),{createComponent:u=>new ZS(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()}},[]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new ZS(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ce.createElement("div",{style:{height:"100%",width:"100%"},ref:n},i)});pne.displayName="SplitviewComponent";var QS=class extends LD{constructor(e,t,n,s){super(e,t),this.reactComponent=n,this.reactPortalStore=s}getComponent(){var e,t;return new Vi(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 fD(this._params.accessor)})}};function fne(e){return Im.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const mne=Ce.forwardRef((e,t)=>{const n=Ce.useRef(null),s=Ce.useRef(void 0),[i,r]=Ih();Ce.useImperativeHandle(t,()=>n.current,[]);const a=Ce.useRef({});return Ce.useEffect(()=>{const l={};Im.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},Im.map(l=>e[l])),Ce.useEffect(()=>{if(!n.current)return()=>{};const l=tne(n.current,Ts(Ts({},fne(e)),{createComponent:u=>new QS(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()}},[]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new QS(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ce.createElement("div",{style:{height:"100%",width:"100%"},ref:n},i)});mne.displayName="GridviewComponent";var id=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 Vi(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 gne(e){return Pm.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const xne=Ce.forwardRef((e,t)=>{const n=Ce.useRef(null),s=Ce.useRef(void 0),[i,r]=Ih();Ce.useImperativeHandle(t,()=>n.current,[]);const a=Ce.useRef({});return Ce.useEffect(()=>{const l={};Pm.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},Pm.map(l=>e[l])),Ce.useEffect(()=>{var l;if(!n.current)return()=>{};const c=(l=e.headerComponents)!==null&&l!==void 0?l:{},d=nne(n.current,Ts(Ts({},gne(e)),{createComponent:p=>new id(p.id,e.components[p.name],{addPortal:r}),createHeaderComponent:p=>new id(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()}},[]),Ce.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new id(l.id,e.components[l.name],{addPortal:r})})},[e.components]),Ce.useEffect(()=>{var l;if(!s.current)return;const c=(l=e.headerComponents)!==null&&l!==void 0?l:{};s.current.updateOptions({createHeaderComponent:d=>new id(d.id,c[d.name],{addPortal:r})})},[e.headerComponents]),Ce.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onDidDrop(c=>{e.onDidDrop&&e.onDidDrop(c)});return()=>{l.dispose()}},[e.onDidDrop]),Ce.createElement("div",{style:{height:"100%",width:"100%"},ref:n},i)});xne.displayName="PaneviewComponent";function Xr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function vne(e,t,n){if(!Xr(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 VD(e,t){if(Xr(e)){if(e.type==="leaf"){const n=Xr(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 i=typeof n?.activeView=="string"&&t.has(n.activeView)?n.activeView:s[0];return{type:"leaf",data:{...n,views:s,activeView:i},size:e.size}}if(e.type==="branch"){const n=Array.isArray(e.data)?e.data.flatMap(s=>{const i=VD(s,t);return i?[i]:[]}):[];return n.length===0?void 0:{type:"branch",data:n,size:e.size}}}}function bne(e,t){if(!Xr(e)||!Xr(e.panels))return;const n={};for(const[a,l]of Object.entries(e.panels))vne(a,l,t)&&(n[a]=l);const s=new Set(Object.keys(n));if(s.size===0)return;const i=Xr(e.grid)?e.grid:void 0,r=i?VD(i.root,s):void 0;if(r)return{...e,panels:n,grid:{...i,root:r}}}function eC(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 wne(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=eC(e)&&e!=="."?e:e.split("/").pop()??"",i=s.lastIndexOf("/"),r=i===-1?"":s.slice(0,i),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||!eC(c)?null:c}function tC(e,t){const n=new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>]+))`,"i").exec(e);return n?n[1]??n[2]??n[3]??"":null}function yne(e,t,n){return e.replace(new RegExp(`\\b${t}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>]+)`,"i"),`${t}="${n}"`)}function Sne(e){return e?.trim().toLowerCase().split(/\s+/).includes("stylesheet")??!1}function Cne(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}catch{return null}}function kne(e,t){const n=[],s=(i,r,a,l)=>{const c=r[1]??"";if(!l(c))return;const d=tC(c,a);if(d===null)return;const u=wne(t,d);u&&n.push({start:r.index,end:r.index+r[0].length,kind:i,rel:u,attrs:c,full:r[0]})};for(const i of e.matchAll(/<script\b([^>]*)>[\s\S]*?<\/script>/gi))s("script",i,"src",()=>!0);for(const i of e.matchAll(/<link\b([^>]*?)\/?>/gi))s("style",i,"href",r=>Sne(tC(r,"rel")));for(const i of e.matchAll(/<img\b([^>]*?)\/?>/gi))s("img",i,"src",()=>!0);return n.sort((i,r)=>i.start-r.start),n}async function _ne(e,t,n){const s=kne(e,t),i=new Map;await Promise.all([...new Set(s.map(l=>l.rel))].map(async l=>{i.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=i.get(l.rel);if(!c){a+=l.full;continue}if(l.kind==="img"){const u=c.mime||"application/octet-stream";a+=`<img${yne(l.attrs,"src",`data:${u};base64,${c.base64}`)}>`;continue}const d=Cne(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 jne="plugin-view.html";function nC(){return document.documentElement.classList.contains("dark")?"dark":"light"}function Nne({pluginId:e,viewId:t,sessionId:n}){const{t:s}=te(),i=Zk().find(u=>u.pluginId===e&&u.id===t),r=m.useRef(null),[a,l]=m.useState(null),c=i?.entry,d=m.useRef(n);return d.current=n,m.useEffect(()=>{const u=r.current;if(!u||!c)return;l(null);let h=!1,p=null;const f=()=>{try{p?.port1.postMessage(N2(nC()))}catch{}},x=new MutationObserver(f);x.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const g=D2(async(w,y)=>{const b=await window.electronAPI.extensionPlugins.call({pluginId:e,method:"renderer.call",payload:{method:w,args:y},sessionId:d.current});if(!b.ok)throw new Error(b.error);return b.value}),v=async w=>{if(w.source!==u.contentWindow||w.data?.type!=="enso-view-ready")return;p?.port1.close();const y=new MessageChannel;p=y,y.port1.onmessage=N=>{const C=T2(N.data);if(C){window.electronAPI.extensionPlugins.viewStateSet(e,C);return}g(N.data).then(k=>{k&&!h&&p===y&&y.port1.postMessage(k)})};const[b,_]=await Promise.all([window.electronAPI.extensionPlugins.asset(e,c),window.electronAPI.extensionPlugins.viewStateGet(e)]);if(h||p!==y)return;if(!b.ok){l(b.error);return}const j=await _ne(I2(b.base64),c,async N=>{const C=await window.electronAPI.extensionPlugins.asset(e,N);return C.ok?{mime:C.mime,base64:C.base64}:null});h||p!==y||u.contentWindow?.postMessage({type:"enso-view-init",html:j,theme:nC(),storage:_.ok?_.state:{}},"*",[y.port2])};return window.addEventListener("message",v),u.src=new URL(jne,document.baseURI).href,()=>{h=!0,x.disconnect(),window.removeEventListener("message",v),p?.port1.close(),u.removeAttribute("src")}},[e,c]),i?o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a&&o.jsx("div",{className:"shrink-0 px-3 py-2 text-xs text-destructive",children:a}),o.jsx("iframe",{ref:r,title:i.title,className:"min-h-0 w-full flex-1 border-0 bg-background"})]}):o.jsx("div",{className:"flex h-full items-center justify-center p-6 text-sm text-muted-foreground",children:s("Plugin is not enabled")})}function Tne({conversationId:e,panelApi:t}){const{t:n}=te(),s=t.id.startsWith("btw:")?t.id.slice(4):t.id,i=ma(),r=xe(O=>O.virtualModels),a=xe(O=>O.defaultModel),l=xe(O=>O.projects),c=xe(O=>O.projectGroups),d=Ao(O=>O.snapshot),u=og(),[h,p]=m.useState("contextual"),[f,x]=m.useState(!1),[g]=m.useState(()=>q6(ie.getState().conversations[e]?.messages??[])),v=ie(um(O=>O.conversations[s]??null)),w=v?.title,y=v?.projectId,b=m.useMemo(()=>l.find(O=>O.id===y),[y,l]),_=m.useMemo(()=>Fd(b,c),[b,c]),j=m.useMemo(()=>jl({defaultModel:a,..._,lastProviderId:v?.lastProviderId,lastModelId:v?.lastModelId,providers:i,credentials:na(d),virtualModels:r}),[r,v?.lastModelId,v?.lastProviderId,_,a,d,i]),N=j.source==="none"?void 0:u.find(O=>O.id===j.providerId),C=j.source==="none"?"":j.modelId,k=j.source==="none"?"":of(j)?j.providerId:N?.id??"",E=m.useMemo(()=>Y6(v?.messages??[]),[v?.messages]),I=m.useRef(null),T=v?.status==="running",A=f||(v?Dk({started:v.started,sessionFile:v.sessionFile,messages:v.messages,spawning:v.spawning,status:v.status,historyLoadAttempted:v.historyLoadAttempted}):!0),D=m.useMemo(()=>{const O={name:"/compact",description:n("Compact the context now (/compact [summary focus])")},B=new Set([O.name]);return[O,...(v?.commands??[]).filter(L=>!B.has(L.name))]},[v?.commands,n]);m.useEffect(()=>{const O=ie.getState().conversations[e],B=xe.getState();ie.getState().ensureBtwConversation({id:s,projectId:O?.projectId??"",btwParentId:e,rolePrompt:Zb("contextual",g),lastProviderId:O?.lastProviderId??B.defaultModel?.providerId,lastModelId:O?.lastModelId??B.defaultModel?.modelId,reasoningEnabled:O?.reasoningEnabled??B.defaultReasoningEnabled,thinkingLevel:O?.thinkingLevel??B.defaultThinkingLevel,approvalMode:O?.approvalMode??"full",presetId:O?.presetId})},[e,s,g]),m.useEffect(()=>{w&&t.setTitle(w)},[t,w]);const W=O=>{O===h||f||(x(!0),(async()=>(ie.getState().abort(s),await ie.getState().resetBtwSession(s,Zb(O,g)),p(O),t.setTitle(n("Btw")),x(!1)))())},J=()=>{const O=J6(E);if(O){if(!dh(O)){We({type:"warning",title:n("No Composer for this selection")});return}wr()}};return o.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[o.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[o.jsx(sC,{label:n("Contextual"),active:h==="contextual",onClick:()=>W("contextual")}),o.jsx(sC,{label:n("Tangent"),active:h==="tangent",onClick:()=>W("tangent")}),o.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:!E,onClick:J,children:n("Insert into chat")})]}),v?o.jsx(uI,{conversationId:s,cwd:b?.path,emptyTitle:n("Btw"),timelineRef:I}):o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-2 text-center text-muted-foreground",children:[o.jsx(pr,{className:"h-5 w-5"}),o.jsx("p",{className:"text-xs",children:n("Ask a side question without sending it to the main agent.")})]}),o.jsx("div",{className:"@container pt-1",children:o.jsxs("div",{className:fi,children:[v?.retry?o.jsx(wh,{retry:v.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(s)}}):null,o.jsx(ng.Provider,{value:y?{conversationId:s,projectId:y,...b?.path?{cwd:b.path}:{}}:null,children:o.jsx(Fx,{sessionId:s,tasks:v?.backgroundTasks??[],subagents:v?.subagents??[]},s)}),o.jsx(Rl,{approvals:v?.pendingApprovals??[],allowSession:!0,onRespond:(O,B)=>{window.electronAPI.agent.respondApproval(s,O,B)}}),o.jsx(oh,{asks:v?.pendingAsks??[],onAnswer:(O,B)=>{window.electronAPI.agent.respondAsk(s,O,B)}}),o.jsx(SI,{conversationId:s,queued:v?.queuedMessages??[]}),o.jsx(zx,{isolated:!0,cwd:b?.path,commands:D,running:T,busy:A,locked:(v?.pendingApprovals??[]).length>0,focusKey:s,injectedDraft:v?.draftText,injectedImages:v?.draftImages,injectedDraftAppend:v?.draftAppend,onDraftConsumed:()=>ie.getState().clearDraft(s),queuedCount:v?.queuedMessages?.length??0,onSteerQueued:()=>ie.getState().steerQueued(s),autoFocus:!1,placeholder:n("Ask aside…"),toolbar:o.jsx(Bu,{providers:u,activeAccount:ig(i,v??void 0),virtualModels:r,providerId:k,modelId:C,reasoningEnabled:v?.reasoningEnabled??!1,thinkingLevel:v?.thinkingLevel??"medium",onSelect:(O,B)=>ie.getState().setModel(s,O,B),onReasoningChange:O=>ie.getState().setReasoning(s,O),onThinkingChange:O=>ie.getState().setThinking(s,O),side:"top"}),onSend:O=>!k||!C||!b?!1:(I.current?.scrollToBottom(),ie.getState().send(O.text,{providerId:k,modelId:C,cwd:b.path},O.images,s),!0),onAbort:()=>{ie.getState().abort(s)}}),o.jsx(NI,{conversationId:s})]})})]})}function sC({label:e,active:t,onClick:n}){return o.jsx("button",{type:"button",className:q("rounded-md px-2 py-1 text-xs transition-colors",t?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:n,children:e})}function $D(e,t,n,s={}){const i=new Set,r=e.map(a=>{const l=`diff:${a.path}`;i.add(l);const c=t.has(l),d=n.get(l),u=s.ignoreLineEndings?a.oldText.replace(/\r\n/g,`
107
- `):a.oldText,h=s.ignoreLineEndings?a.newText.replace(/\r\n/g,`
108
- `):a.newText,p=!d||d.oldText!==u||d.newText!==h,f=p||!d?po({name:a.path,contents:u},{name:a.path,contents:h}):d.fileDiff;(p||!d)&&(f.cacheKey=ux(a.path,u,h));const x=d?p||d.collapsed!==c?d.version+1:d.version:0;return n.set(l,{oldText:u,newText:h,collapsed:c,version:x,fileDiff:f}),{id:l,type:"diff",fileDiff:f,version:x,collapsed:c}});for(const a of n.keys())i.has(a)||n.delete(a);return r}const Ine={theme:ha,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0},Dne={height:"100%",overflow:"auto"},Pne=new Set;function WD({result:e,loading:t}){const{t:n}=te(),s=Jl(Ine),[i,r]=m.useState(!1),[a,l]=m.useState(!1),c=m.useRef(new Map);m.useEffect(()=>{let h=!0;return Qr().then(()=>{h&&r(!0)},()=>{h&&l(!0)}),()=>{h=!1}},[]);const d=m.useMemo(()=>$D(e?.ok?[e]:[],Pne,c.current,{ignoreLineEndings:!0}),[e]),u=t?n("Loading..."):a?n("Could not load the diff viewer."):e?e.ok?i?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 o.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:u?o.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}):o.jsx(_N,{className:"min-h-0 w-full flex-1",items:d,style:Dne,options:s})})}function UD({tree:e,onToggle:t}){const{t:n}=te(),s=n(e?"List view":"Tree view");return o.jsx(le,{variant:"ghost",size:"icon-xs",title:s,"aria-label":s,onClick:t,children:e?o.jsx(Yg,{className:"size-3.5"}):o.jsx(zB,{className:"size-3.5"})})}function KD({files:e,tree:t,children:n}){const s=m.useId(),[i,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=>o.jsxs(o.Fragment,{children:[[...c.directories.values()].sort((d,u)=>d.name.localeCompare(u.name)).map(d=>{const u=!i.has(d.path),h=`${s}-${encodeURIComponent(d.path)}`;return o.jsxs("div",{children:[o.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:[o.jsx($n,{"aria-hidden":"true",className:q("size-3 shrink-0 text-muted-foreground",!u&&"-rotate-90")}),u?o.jsx(Qs,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}):o.jsx(uc,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"truncate",children:d.name})]}),u&&o.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=>o.jsx(m.Fragment,{children:n(d)},`file:${d.path}`))]});return t?l(a):e.map(c=>o.jsx(m.Fragment,{children:n(c)},c.path))}const Ene={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 qD({file:e,selected:t,onSelect:n,actions:s,showDirectory:i=!0}){const{t:r}=te(),a=e.path.lastIndexOf("/"),l=e.path.slice(a+1),c=e.path.slice(0,Math.max(0,a)),d=Ene[e.status];return o.jsxs("div",{className:q("group flex min-w-0 items-center rounded-md pr-1 hover:bg-muted/50",t&&"bg-brand/10 dark:bg-brand/15"),children:[o.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:[o.jsx(go,{"aria-hidden":"true",className:q("size-3.5 shrink-0",d.color)}),o.jsx("span",{className:q("truncate",!i&&"flex-1"),children:l}),i&&o.jsx("span",{className:"min-w-0 flex-1 truncate text-[11px] text-muted-foreground",children:c}),o.jsxs("span",{className:q("shrink-0 font-mono text-[11px]",d.color),title:r(e.status),children:[o.jsx("span",{"aria-hidden":"true",children:d.label}),o.jsx("span",{className:"sr-only",children:r(e.status)})]})]}),s&&o.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 YD({title:e,hasSelection:t,navigation:n,actions:s,children:i}){const{t:r}=te(),a=m.useId(),[l,c]=m.useState(!0),d=!t||l;return o.jsx("div",{className:"@container/git flex min-h-0 min-w-0 flex-1 flex-col",children:o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex-row",children:[o.jsxs("div",{className:q("flex min-h-0 min-w-0 flex-col overflow-hidden border-b @min-[720px]/git:h-full @min-[720px]/git:max-h-none @min-[720px]/git:flex-none @min-[720px]/git:border-r @min-[720px]/git:border-b-0",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:[o.jsxs("div",{className:"flex shrink-0 items-center",children:[o.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:[o.jsx($n,{className:q("size-3.5 shrink-0",!d&&"-rotate-90")}),o.jsx("span",{className:q("truncate",!d&&"@min-[720px]/git:hidden"),children:e})]}),d&&s&&o.jsx("div",{className:"mr-1 flex shrink-0 items-center",children:s})]}),o.jsx("div",{id:a,className:q("flex min-h-0 flex-1 flex-col overflow-hidden",!d&&"hidden"),children:n})]}),o.jsx("div",{className:q("min-h-0 min-w-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex",t?"flex":"hidden"),children:i})]})})}function Ane({request:e,head:t,tree:n,onToggleTree:s}){const{t:i}=te(),r=m.useId(),[a,l]=m.useState([]),[c,d]=m.useState(0),[u,h]=m.useState(0),[p,f]=m.useState(!1),[x,g]=m.useState(!0),[v,w]=m.useState(null),[y,b]=m.useState(null),[_,j]=m.useState([]),[N,C]=m.useState(!1),[k,E]=m.useState(null),[I,T]=m.useState(null),[A,D]=m.useState(null),[W,J]=m.useState(!1);return m.useEffect(()=>{let O=!0;return g(!0),w(null),window.electronAPI.git.history({...e,head:t??void 0,skip:c,limit:20}).then(B=>{O&&(B.ok?(l(L=>c===0?B.commits:[...L,...B.commits]),f(B.hasMore)):w(B.error))}).catch(()=>{O&&w("Could not load Git history.")}).finally(()=>{O&&g(!1)}),()=>{O=!1}},[e,t,c,u]),m.useEffect(()=>{if(!y)return;let O=!0;return C(!0),E(null),window.electronAPI.git.commitFiles({...e,hash:y.hash}).then(B=>{O&&(B.ok?j(B.files):E(B.error))}).catch(()=>{O&&E("Could not load the changed files.")}).finally(()=>{O&&C(!1)}),()=>{O=!1}},[e,y]),m.useEffect(()=>{if(!I||!y)return;let O=!0;return J(!0),window.electronAPI.git.commitDiff({...e,hash:y.hash,path:I}).then(B=>{O&&D(B)}).catch(()=>{O&&D({ok:!1,error:"Could not load the diff."})}).finally(()=>{O&&J(!1)}),()=>{O=!1}},[e,y,I]),o.jsxs(YD,{title:i("History"),hasSelection:I!==null,actions:o.jsx(UD,{tree:n,onToggle:s}),navigation:o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-1 pb-1",children:[a.map(O=>{const B=y?.hash===O.hash;return o.jsxs("div",{children:[o.jsxs("button",{type:"button","aria-expanded":B,"aria-controls":B?`${r}-${O.hash}`:void 0,className:q("flex w-full min-w-0 items-start gap-1.5 rounded-md px-2 py-1.5 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",B&&"bg-brand/10 dark:bg-brand/15"),title:`${O.subject}
109
- ${O.hash}
110
- ${O.author} · ${O.date}`,onClick:()=>{b(B?null:O),j([]),C(!B),E(null),T(null),D(null),J(!1)},children:[o.jsx($n,{"aria-hidden":"true",className:q("mt-0.5 size-3.5 shrink-0 text-muted-foreground",!B&&"-rotate-90")}),o.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o.jsx("span",{className:"truncate text-xs",children:O.subject}),o.jsxs("span",{className:"flex min-w-0 gap-2 text-[11px] text-muted-foreground",children:[o.jsx("span",{className:"shrink-0 font-mono",children:O.hash.slice(0,7)}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:O.author}),o.jsx("time",{className:"shrink-0",dateTime:O.date,children:new Date(O.date).toLocaleDateString()})]})]})]}),B&&o.jsx("div",{id:`${r}-${O.hash}`,className:"my-1 ml-3 border-l pl-1",children:N?o.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:i("Loading...")}):k?o.jsx("p",{role:"alert",className:"px-2 py-3 text-xs text-destructive",children:i(k)}):_.length===0?o.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:i("No file changes in this commit.")}):o.jsx(KD,{files:_,tree:n,children:L=>o.jsx(qD,{file:L,showDirectory:!n,selected:I===L.path,onSelect:()=>{I!==L.path&&(T(L.path),D(null),J(!0))}})},O.hash)})]},O.hash)}),x&&o.jsx("div",{className:"flex justify-center p-3",children:o.jsx(Vt,{className:"size-4 animate-spin","aria-label":i("Loading...")})}),v&&o.jsx("p",{role:"alert",className:"px-2 py-3 text-xs text-destructive",children:i(v)}),!x&&!v&&a.length===0&&o.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-5 text-center text-xs text-muted-foreground",children:i("No commits yet.")}),p&&!x&&!v&&o.jsx(le,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>d(a.length),children:i("Load more commits")}),v&&o.jsx(le,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>h(O=>O+1),children:i("Retry")})]}),children:[y&&I&&o.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:`${y.subject} · ${I}`,children:[y.hash.slice(0,7)," · ",I]}),o.jsx(WD,{result:A,loading:W})]})}function Mne({conversationId:e,projectId:t,disabled:n,unavailable:s,editWriteKey:i}){const{t:r}=te(),a=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),[l,c]=m.useState(null),[d,u]=m.useState(!0),[h,p]=m.useState(null),[f,x]=m.useState(null),[g,v]=m.useState(null),[w,y]=m.useState("changes"),[b,_]=m.useState(!0),[j,N]=m.useState(""),[C,k]=m.useState(""),E=m.useRef(null),[I,T]=m.useState(null),[A,D]=m.useState(null),[W,J]=m.useState(null),[O,B]=m.useState(!1),[L,se]=m.useState(0),Q=m.useRef(!1),V=m.useRef(!1),H=m.useRef(0),ne=m.useRef(0),he=m.useCallback(async(z=!1)=>{if(n||s||V.current||ne.current!==0&&!z)return;const ue=++H.current;ne.current=ue,z&&u(!0);try{const _e=await window.electronAPI.git.status(a);if(!Q.current||ue!==H.current)return;_e.ok?(c(_e),p(null)):(c(null),p(_e.error))}catch{Q.current&&ue===H.current&&(c(null),p("Could not read Git status."))}finally{ne.current===ue&&(ne.current=0),Q.current&&ue===H.current&&u(!1)}},[n,s,a]);m.useEffect(()=>{Q.current=!0;const z=()=>{he()},ue=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&he()},5e3);return window.addEventListener("focus",z),()=>{Q.current=!1,H.current+=1,window.clearInterval(ue),window.removeEventListener("focus",z)}},[he]),m.useEffect(()=>{he(!0)},[he,i]),m.useEffect(()=>{if(!I||!l)return;(I.staged?l.staged:l.unstaged).some(ue=>ue.path===I.path)||(T(null),J(null),B(!1))},[I,l]),m.useEffect(()=>{if(!I||n||s||g!==null||w!=="changes")return;let z=!0,ue=!1;const _e=async()=>{if(!ue){ue=!0;try{const De=await window.electronAPI.git.fileDiff({...a,...I});z&&J(De)}catch{z&&J({ok:!1,error:"Could not load the diff."})}finally{ue=!1,z&&B(!1)}}};_e();const Ee=()=>{_e()},Be=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&_e()},5e3);return window.addEventListener("focus",Ee),()=>{z=!1,window.clearInterval(Be),window.removeEventListener("focus",Ee)}},[a,I,L,n,s,w,g]);const pe=async(z,ue,_e)=>{if(!(V.current||n||s||d||!l)){V.current=!0,H.current+=1,v(z),x(null);try{const Ee=await ue();if(!Q.current)return;Ee.ok?_e?.():x(Ee.error)}catch{Q.current&&x("Could not complete the Git operation.")}finally{V.current=!1,Q.current&&(v(null),se(Ee=>Ee+1),he(!0),ie.getState().refreshWorktreeStatuses().catch(()=>{}))}}},ke=n||s||d||g!==null||!l,Me=!ke&&!!j.trim()&&!!l?.staged.length,fe=(z,ue)=>{I?.path===z.path&&I.staged===ue||(J(null),B(!0),T({path:z.path,staged:ue}))},F=[{id:"staged",staged:!0,title:r("Staged changes"),files:l?.staged??[]},{id:"unstaged",staged:!1,title:r("Unstaged changes"),files:l?.unstaged.filter(z=>z.status!=="untracked")??[]},{id:"untracked",staged:!1,title:r("Untracked changes"),files:l?.unstaged.filter(z=>z.status==="untracked")??[]}],U=C.trim().toLowerCase(),de=F.map(z=>({...z,files:z.files.filter(ue=>ue.path.toLowerCase().includes(U))})),Y=de.reduce((z,ue)=>z+ue.files.length,0),X=()=>{Me&&pe("Commit",()=>window.electronAPI.git.commit({...a,message:j}),()=>N(""))};return o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[o.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[l&&!n&&!s&&!h&&o.jsxs("div",{className:"flex shrink-0 items-center gap-1",role:"tablist","aria-label":r("Git views"),children:[o.jsxs(le,{role:"tab","aria-selected":w==="changes",variant:w==="changes"?"secondary":"ghost",size:"xs",onClick:()=>y("changes"),children:[o.jsx(aB,{className:"size-3.5"}),r("Changes")]}),o.jsxs(le,{role:"tab","aria-selected":w==="history",variant:w==="history"?"secondary":"ghost",size:"xs",onClick:()=>y("history"),children:[o.jsx(Lo,{className:"size-3.5"}),r("History")]})]}),o.jsx(Ni,{className:"size-3.5 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"min-w-0 flex-1 truncate text-xs",title:l?.branch??void 0,children:l?.branch??r(l?"Detached HEAD":"Git")}),l?.upstream&&o.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",title:l.upstream,children:["↓",l.behind," ↑",l.ahead]}),l&&!l.upstream&&o.jsx("span",{className:"max-w-20 truncate text-[11px] text-muted-foreground",title:r("No upstream branch configured."),children:r("No upstream")}),o.jsx(Ko,{title:r("Fetch"),disabled:ke,onClick:()=>{pe("Fetch",()=>window.electronAPI.git.fetch(a))},children:o.jsx(Xl,{className:"size-3.5"})}),o.jsx(Ko,{title:r("Pull"),disabled:ke||!l?.upstream,onClick:()=>{pe("Pull",()=>window.electronAPI.git.pull(a))},children:o.jsx(th,{className:"size-3.5"})}),o.jsx(Ko,{title:r("Push"),disabled:ke||!l?.upstream,onClick:()=>{pe("Push",()=>window.electronAPI.git.push(a))},children:o.jsx(nh,{className:"size-3.5"})}),o.jsx(Ko,{title:r("Refresh"),disabled:n||s||g!==null||d,onClick:()=>{se(z=>z+1),he(!0)},children:o.jsx(Mo,{className:q("size-3.5",d&&!s&&!n&&"animate-spin")})})]}),g&&o.jsxs("p",{role:"status",className:"flex shrink-0 items-center gap-2 px-3 py-1 text-xs text-muted-foreground",children:[o.jsx(Vt,{className:"size-3 animate-spin"}),r(g),"…"]}),f&&o.jsx("p",{role:"alert",className:"max-h-24 shrink-0 overflow-auto whitespace-pre-wrap break-words border-b px-3 py-2 text-xs text-destructive",children:r(f)}),s||n||h||!l?o.jsx("div",{role:"status",className:"m-3 flex min-h-0 flex-1 items-center justify-center rounded-md border border-dashed p-4 text-center text-xs text-muted-foreground",children:r(s?"Git diff is not available for this workspace.":n?"Workspace is changing. Please wait.":h??"Loading...")}):o.jsx(o.Fragment,{children:w==="history"?o.jsx(Ane,{request:a,head:l.head,tree:b,onToggleTree:()=>_(z=>!z)},`${l.head}:${L}`):o.jsxs(YD,{title:r("Changed files"),hasSelection:I!==null,actions:o.jsx(UD,{tree:b,onToggle:()=>_(z=>!z)}),navigation:o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"shrink-0 px-2 pb-1.5",children:o.jsxs(zu,{className:"text-xs",children:[o.jsx(Fu,{ref:E,size:"sm",type:"search",value:C,onChange:z=>k(z.target.value),placeholder:r("Filter changed files…"),"aria-label":r("Filter changed files…")}),C.length>0&&o.jsx(Gu,{align:"inline-end",children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-xs",title:r("Clear"),"aria-label":r("Clear"),onClick:()=>{k(""),E.current?.focus()},children:o.jsx(ln,{className:"size-3.5"})})})]})}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-1 pb-1",children:[de.map(z=>z.files.length===0?null:o.jsxs("section",{className:"mb-2 last:mb-0",children:[o.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 text-[11px] font-medium text-muted-foreground",children:[o.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[z.title," ",o.jsx("span",{className:"ml-1 font-normal",children:z.files.length})]}),o.jsx(Ko,{title:r(z.staged?"Unstage all":"Stage all"),disabled:ke,onClick:()=>{pe(z.staged?"Unstage":"Stage",()=>window.electronAPI.git[z.staged?"unstage":"stage"]({...a,paths:z.files.map(ue=>ue.path)}))},children:z.staged?o.jsx(Ov,{className:"size-3.5"}):o.jsx(ps,{className:"size-3.5"})})]}),o.jsx(KD,{files:z.files,tree:b,children:ue=>o.jsx(qD,{file:ue,showDirectory:!b,selected:I?.path===ue.path&&I.staged===z.staged,onSelect:()=>fe(ue,z.staged),actions:o.jsxs(o.Fragment,{children:[!z.staged&&o.jsx(Ko,{title:r(ue.status==="untracked"?"Delete untracked file":"Discard changes"),disabled:ke||ue.status==="conflicted",onClick:()=>D(ue),children:o.jsx(ra,{className:"size-3.5"})}),o.jsx(Ko,{title:r(z.staged?"Unstage":"Stage"),disabled:ke,onClick:()=>{pe(z.staged?"Unstage":"Stage",()=>window.electronAPI.git[z.staged?"unstage":"stage"]({...a,paths:[ue.path]}))},children:z.staged?o.jsx(Ov,{className:"size-3.5"}):o.jsx(ps,{className:"size-3.5"})})]})})},U)]},z.id)),Y===0&&o.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-5 text-center text-xs text-muted-foreground",children:r(l.staged.length+l.unstaged.length===0?"Working tree clean.":"No matching files.")})]}),o.jsxs("div",{className:"flex shrink-0 items-end gap-1.5 border-t p-2",children:[o.jsx(Ys,{size:"sm",rows:3,value:j,"aria-label":r("Commit message"),placeholder:r("Enter commit message…"),className:"min-w-0 flex-1 text-xs [&_textarea]:max-h-[calc(6lh+0.5rem)] [&_textarea]:min-h-[calc(3lh+0.5rem)] [&_textarea]:resize-none [&_textarea]:overflow-auto",disabled:g!==null,onChange:z=>N(z.target.value),onKeyDown:z=>{(z.ctrlKey||z.metaKey)&&z.key==="Enter"&&!z.nativeEvent.isComposing&&(z.preventDefault(),X())}}),o.jsxs(le,{size:"xs",className:"mb-0.5 shrink-0",title:r("{{count}} staged files",{count:l.staged.length}),"aria-label":r("Commit"),disabled:!Me,onClick:X,children:[o.jsx(jB,{className:"size-3.5"}),r("Commit"),l.staged.length>0&&o.jsx("span",{className:"font-mono text-[11px]",children:l.staged.length})]})]})]}),children:[I&&o.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:I.path,children:[r(I.staged?"Staged changes":"Unstaged changes")," · ",I.path]}),o.jsx(WD,{result:W,loading:I!==null&&O})]})}),o.jsx(hs,{open:A!==null&&!ke,onOpenChange:z=>{z||D(null)},title:r(A?.status==="untracked"?"Delete untracked file":"Discard changes"),description:A?.status==="untracked"?r("Delete untracked file {{path}} permanently?",{path:A.path}):r("Restore {{path}} to its staged version? Unstaged changes will be lost.",{path:A?.path??""}),confirmLabel:r(A?.status==="untracked"?"Delete":"Discard"),onConfirm:()=>{A&&pe("Discard",()=>window.electronAPI.git.discard({...a,paths:[A.path],confirmUntracked:A.status==="untracked"}))}})]})}function Ko({title:e,disabled:t,onClick:n,children:s}){return o.jsx(le,{variant:"ghost",size:"icon-xs",title:e,"aria-label":e,disabled:t,onClick:n,children:s})}const XD=28,Rne={theme:ha,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0,itemMetrics:{diffHeaderHeight:XD}},Lne={height:"max-content",overflow:"auto"},One={files:[],snapshots:{}},iC=[];function zne(e,t){return t?t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)?t:e?`${e.replace(/[/\\]+$/,"")}/${t}`:null:null}function Gne({conversationId:e,projectId:t}){const{t:n}=te(),s=Jl(Rne),i=pn(Q=>Q.changesModeByConversation[e])??"all",r=pn(Q=>Q.setChangesMode),a=m.useRef(null),l=m.useRef(null),c=m.useRef(!1);m.useLayoutEffect(()=>{const Q=a.current,V=l.current,H=Q?.querySelector('[aria-selected="true"]');!Q||!V||!H||(c.current||(V.style.transition="none"),V.style.transform=`translate(${H.offsetLeft}px, ${H.offsetTop}px)`,V.style.width=`${H.offsetWidth}px`,V.style.height=`${H.offsetHeight}px`,c.current||(V.offsetWidth,V.style.transition="",c.current=!0))},[i]);const d=pn(Q=>Q.snapshotsByConversation[e]),u=pn(Q=>Q.saveSnapshots),h=pn(Q=>Q.loadSnapshots),p=ie(Q=>Qk(Q.conversations[e]?.messages??iC)),f=ie(Q=>Q.workspaceRevisionByConversation[e]??0),x=ie(Q=>!!Q.conversations[e]?.workspaceMigrating),g=xe(Q=>Q.projects.find(V=>V.id===t)),v=ie(Q=>g?.kind==="scratch"?lg({kind:"scratch",canonicalPath:g.path,conversationId:e})??void 0:Q.conversations[e]?.worktree?.path??g?.path),w=ie(Q=>Q.conversations[e]?.status==="running"),y=m.useRef([]),b=m.useMemo(()=>{const Q=ie.getState().conversations[e],H=hr(Q?.messages??iC,w,Q?.customEntries??[],v).flatMap(ne=>ne.kind!=="tool"?[]:ne.name==="apply_patch"?(ne.fileChanges??[]).map(he=>({path:he.path,edits:null,writeContent:null,fileChange:he})):ne.state!=="ok"||ne.name!=="edit"&&ne.name!=="write"?[]:ne.summary?ne.name==="edit"&&!(ne.edits&&ne.edits.length>0)?[]:ne.name==="write"&&ne.writeContent==null?[]:[{path:ne.summary,edits:ne.edits,writeContent:ne.writeContent}]:[]);return _8(y.current,H)?y.current:(y.current=H,H)},[e,p,v,w]),[_,j]=m.useState(!1),[N,C]=m.useState({});m.useEffect(()=>{let Q=!0;return Qr().then(()=>{Q&&j(!0)}),()=>{Q=!1}},[]),m.useEffect(()=>{i==="all"&&h(e)},[e,h,i]),m.useEffect(()=>{if(i!=="all"||x)return;const Q=[...new Set(b.map(H=>H.path))];let V=!0;return Promise.all(Q.map(async H=>{const ne=zne(v,H),he=ne?await window.electronAPI.files.read(ne):null;return[H,he]})).then(H=>{if(!V)return;const ne=Object.fromEntries(H);C(he=>j8(he,ne)?he:ne)}),()=>{V=!1}},[i,v,b,x,f]);const k=m.useMemo(()=>d?N8({tools:b,snapshots:d,currentByPath:N}):One,[b,d,N]);m.useEffect(()=>{if(i!=="all"||!d)return;const Q=k.snapshots,V=Object.keys(Q);V.length===Object.keys(d).length&&V.every(H=>d[H]===Q[H])||u(e,Q)},[k.snapshots,e,i,u,d]);const E=k.files,I=k.incompletePaths??[],[T,A]=m.useState(()=>new Set),D=m.useCallback(Q=>{A(V=>{const H=new Set(V);return H.delete(Q)||H.add(Q),H})},[]),W=m.useRef(new Map),J=m.useMemo(()=>$D(E,T,W.current),[E,T]),O=J.length>0&&J.every(Q=>Q.collapsed),B=()=>A(O?new Set:new Set(J.map(Q=>Q.id))),L=m.useCallback(Q=>o.jsx(Fne,{item:Q,onToggle:()=>D(Q.id)}),[D]),se=!_||!d;return o.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[o.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[o.jsxs("div",{ref:a,role:"tablist",className:"t-tabs",children:[o.jsx("span",{ref:l,"aria-hidden":"true",className:"t-tabs-pill"}),o.jsx(oC,{active:i==="all",onClick:()=>r(e,"all"),children:n("Session")}),o.jsx(oC,{active:i==="git",onClick:()=>r(e,"git"),children:n("Git")})]}),i==="all"&&J.length>0&&o.jsx("button",{type:"button",onClick:B,title:n(O?"Expand all":"Collapse all"),className:"ml-auto inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:bg-muted/50 hover:text-foreground",children:O?o.jsx(Sk,{className:"h-3.5 w-3.5"}):o.jsx(MH,{className:"h-3.5 w-3.5"})})]}),o.jsx("div",{className:"min-h-0 flex-1",children:i==="git"?o.jsx(Mne,{conversationId:e,projectId:t,disabled:x,unavailable:g?.kind==="ssh",editWriteKey:p},`${e}:${v}:${f}`):se||E.length===0&&I.length===0?o.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center text-sm text-muted-foreground",children:n(se?"Loading...":"No file changes in this conversation yet.")}):o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[I.map(Q=>o.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:[o.jsx(ur,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"truncate font-mono text-foreground",title:Q,children:Q}),o.jsx("div",{children:n("Diff unavailable because the original snapshot was truncated.")})]})]},Q)),E.length>0&&o.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:o.jsx(_N,{className:"min-h-0 w-full",items:J,style:Lne,options:s,renderCustomHeader:L})})]})})]})}function Fne({item:e,onToggle:t}){const n=e.type==="diff"?e.fileDiff:null;let s=0,i=0;for(const a of n?.hunks??[])s+=a.additionLines,i+=a.deletionLines;const r=n?.name??(e.type==="file"?e.file.name:"");return o.jsxs("button",{type:"button",onClick:t,style:{height:XD},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?o.jsx(kn,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):o.jsx($n,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",title:r,children:r}),i>0&&o.jsxs("span",{className:"shrink-0 text-red-500",children:["-",i]}),s>0&&o.jsxs("span",{className:"shrink-0 text-green-600",children:["+",s]})]})}function oC({active:e,onClick:t,children:n}){return o.jsx("button",{type:"button",role:"tab",onClick:t,"aria-selected":e,className:q("t-tab rounded-md px-2 py-1 text-xs transition-colors",e?"font-medium":"text-muted-foreground hover:bg-muted/50"),children:n})}function Hne({conversationId:e,projectId:t,onOpenFile:n,onClose:s,menu:i}){const{t:r}=te(),a=m.useRef(0),[l,c]=m.useState(""),[d,u]=m.useState("names"),[h,p]=m.useState(null),[f,x]=m.useState(!1);return m.useEffect(()=>{if(!l.trim()){a.current+=1,p(null),x(!1);return}const v=++a.current;x(!0);const w=setTimeout(()=>{window.electronAPI.workspaceFiles.search({conversationId:e,projectId:t,query:l,mode:d}).then(y=>{v===a.current&&(p(y),x(!1))})},150);return()=>clearTimeout(w)},[e,d,t,l]),o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[o.jsxs("div",{className:"flex flex-col gap-1 px-1 pb-1",children:[o.jsx(Wt,{size:"sm",autoFocus:!0,value:l,onChange:g=>c(g.target.value),onKeyDown:g=>{g.key==="Escape"&&s()},placeholder:r(d==="names"?"Search file names":"Search file contents"),"aria-label":r("Search")}),o.jsxs("div",{className:"flex gap-0.5",children:[o.jsx(aC,{active:d==="names",onClick:()=>u("names"),label:r("File name"),icon:P2}),o.jsx(aC,{active:d==="content",onClick:()=>u("content"),label:r("Content"),icon:go})]})]}),o.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-1 pb-1",children:l.trim()?f&&!h?o.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Searching…")}):h&&!h.ok?o.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r(h.error==="unsupported"?"Search is not available for SSH workspaces.":"Could not complete the file action.")}):h?.ok&&h.hits.length===0?o.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("No results")}):h?.ok&&h.mode==="names"?h.hits.map(g=>{const v=gc(g.name,!1);return o.jsx(rC,{rel:g.relativePath,name:g.name,menu:i,onOpenFile:n,children:o.jsxs("button",{type:"button","data-search-hit":g.relativePath,className:"flex w-full items-start gap-1 rounded-sm px-1 py-0.5 text-left hover:bg-muted",onClick:()=>n(g.relativePath),children:[o.jsx(v,{className:q("mt-0.5 size-3.5 shrink-0",xc(g.name,!1))}),o.jsxs("span",{className:"min-w-0",children:[o.jsx("span",{className:"block truncate text-xs",children:g.name}),o.jsx("span",{className:"block truncate text-[10px] text-muted-foreground",children:g.relativePath})]})]})},g.relativePath)}):h?.ok&&h.mode==="content"?h.hits.map(g=>{const v=g.relativePath.split("/").pop()||g.relativePath;return o.jsx(rC,{rel:g.relativePath,name:v,menu:i,onOpenFile:n,children:Bne(g,n)},JD(g))}):null:o.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Type to search this workspace.")})})]})}function JD(e){return`${e.relativePath}:${e.line}:${e.column}`}function Bne(e,t){const n=e.relativePath.split("/").pop()||e.relativePath,s=gc(n,!1);return o.jsxs("button",{type:"button","data-search-hit":JD(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:[o.jsx(s,{className:q("mt-0.5 size-3.5 shrink-0",xc(n,!1))}),o.jsxs("span",{className:"min-w-0",children:[o.jsxs("span",{className:"block truncate text-xs",children:[n,o.jsxs("span",{className:"text-muted-foreground",children:[":",e.line]})]}),o.jsx("span",{className:"block truncate font-mono text-[10px] text-muted-foreground",children:e.content.trim()})]})]})}function rC({rel:e,name:t,menu:n,onOpenFile:s,children:i}){return o.jsx(Vu,{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:i})}function aC({active:e,onClick:t,label:n,icon:s}){return o.jsxs(le,{type:"button",variant:"ghost",size:"sm",className:q("h-6 flex-1 px-1 text-xs",e&&"bg-muted"),"aria-pressed":e,onClick:t,children:[o.jsx(s,{className:"size-3.5"}),n]})}const Vne=/^data:image\/(png|jpe?g|gif|webp|bmp|x-icon|svg\+xml);/i;function $ne(){return{...yc,attributes:{...yc.attributes,source:[]},protocols:{...yc.protocols,src:[...yc.protocols?.src??[],"data"]}}}function Wne(){return e=>{E2(e,"element",t=>{if(t.tagName!=="img")return;const n=t.properties?.src;typeof n!="string"||!n.startsWith("data:")||Vne.test(n)||delete t.properties.src})}}const Une=[z2],Kne=$ne(),qne=[L2,[O2,Kne],Wne],Yne=({children:e,node:t,...n})=>o.jsx("p",{className:"my-1.5 leading-relaxed first:mt-0 last:mb-0",...n,children:e}),Xne=({children:e,node:t,...n})=>o.jsx("h1",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),Jne=({children:e,node:t,...n})=>o.jsx("h2",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),Zne=({children:e,node:t,...n})=>o.jsx("h3",{className:"mt-2 mb-1 text-sm font-semibold",...n,children:e}),Qne=({children:e,node:t,...n})=>o.jsx("ul",{className:"my-1.5 list-disc pl-5 space-y-0.5",...n,children:e}),ese=({children:e,node:t,...n})=>o.jsx("ol",{className:"my-1.5 list-decimal pl-5 space-y-0.5",...n,children:e}),tse=({children:e,node:t,...n})=>o.jsx("th",{className:"whitespace-nowrap border-b border-border px-2 py-1 text-left font-medium",...n,children:e}),nse=({children:e,node:t,...n})=>o.jsx("td",{className:"whitespace-nowrap border-b border-border/50 px-2 py-1",...n,children:e}),sse={p:Yne,h1:Xne,h2:Jne,h3:Zne,ul:Qne,ol:ese,th:tse,td:nse};function ise({text:e,baseDirRel:t,resolveImage:n,resolveRemoteImage:s}){const i=m.useRef(new Map),r=m.useMemo(()=>({...A2,...sse,img:({node:c,src:d,alt:u,...h})=>o.jsx(ose,{src:typeof d=="string"?d:void 0,alt:u,rest:h,baseDirRel:t,resolveImage:n,resolveRemoteImage:s,cache:i.current})}),[t,n,s]),a=m.useMemo(()=>({text:e,streaming:!1,searchQuery:"",activeNth:-1}),[e]);return o.jsx(M2.Provider,{value:a,children:o.jsx(R2,{remarkPlugins:Une,rehypePlugins:qne,components:r,urlTransform:l=>l,children:e})})}function ose({src:e,alt:t,rest:n,baseDirRel:s,resolveImage:i,resolveRemoteImage:r,cache:a}){const l=e?G2(e):"unsupported",c=l==="local"&&e?`local:${zv(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 x=zv(s,e);return x?i(x):Promise.resolve(null)})():r(F2(e))).then(x=>{p&&(x&&c&&a.set(c,x),u(x))}),()=>{p=!1}},[e,l,s,i,r,a,c]),d?o.jsx("img",{...n,src:d,alt:t,className:"max-w-full rounded",loading:"lazy"}):null}function ZD(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 od(e){const t=ZD(e);if(!t)return[];const n=t.split("/");if(n.length<=1)return[];const s=[];let i="";for(let r=0;r<n.length-1;r++)i=i?`${i}/${n[r]}`:n[r],s.push(i);return s}function rse(e,t,n=!0){if(!n)return{refreshRels:[],nextSeen:null};const s=[],i=a=>{for(const l of a){if(l.kind==="tool-group"){i(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:ZD(l.summary)})}};i(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 iv="\0preview";function QD(e){return`${e}${iv}`}function eP(e){return e.endsWith(iv)}function $r(e){return eP(e)?e.slice(0,-iv.length):e}function ase(e,t){return e===t||e.startsWith(`${t}/`)}function Rm(e,t){return ase($r(e),t)}function lse(e,t){const n=e.trim();return!n||n===t?"cancel":"commit"}function rd(e,t,n){const s=eP(e),i=$r(e);let r=null;return i===t?r=n:i.startsWith(`${t}/`)&&(r=n+i.slice(t.length)),r==null?null:s?QD(r):r}function cse(e){return e==="preview"?"source":"preview"}function ad(e,t,n){return e.some(s=>s.epoch>n&&Rm(t,s.rel))}async function dse(e,t){const{revision:n,migrating:s}=t();if(s)return null;const i=await e(),r=t();return r.migrating||r.revision!==n?null:i}function lC(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 Lm(e,t,n,s){const i=e.indexOf(t);if(i<0)return[];switch(n){case"self":return[t];case"others":return e.filter(r=>r!==t);case"right":return e.slice(i+1);case"saved":return e.filter(r=>!0);case"all":return[...e]}}const use={theme:ha,disableFileHeader:!0,overflow:"scroll",preferredHighlighter:"shiki-js"};function hse(e){return new q2(e)}function pse(e,t){return e?`${e}/${t}`:t}function Er(e){return e.split("/").pop()||e}function fse(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}const Wp=[];function mse({conversationId:e,projectId:t}){const{t:n}=te(),s=Jl(use),i=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),r=ie(K=>K.workspaceRevisionByConversation[e]??0),a=ie(K=>!!K.conversations[e]?.workspaceMigrating),l=m.useCallback(K=>dse(()=>window.electronAPI.workspaceFiles.read({...i,rel:K}),()=>{const be=ie.getState();return{revision:be.workspaceRevisionByConversation[e]??0,migrating:!!be.conversations[e]?.workspaceMigrating}}),[e,i]),[c,d]=m.useState(!1),[u,h]=m.useState([]),[p,f]=m.useState(null),x=fa(),[g,v]=m.useState(!0),w=m.useCallback(K=>{f(K),v(!1)},[]);m.useEffect(()=>{p||v(!0)},[p]);const[y,b]=m.useState(0),[_,j]=m.useState(()=>new Set),[N,C]=m.useState(!1),[k,E]=m.useState(null),[I,T]=m.useState(null),[A,D]=m.useState(null),W=xe(K=>K.projects.find(be=>be.id===t)),J=W?.kind!=="ssh",O=m.useRef(u);O.current=u;const B=m.useRef(p);B.current=p;const L=m.useRef(null),se=m.useRef(null),Q=m.useRef(null),V=m.useRef(0),H=m.useRef([]),ne=m.useCallback(K=>{V.current+=1,H.current.push({epoch:V.current,rel:K}),H.current.length>200&&H.current.splice(0,100)},[]);m.useEffect(()=>{const K=Q.current;if(!K||!p)return;K.querySelector(`[data-file-tab="${CSS.escape(p)}"]`)?.scrollIntoView({inline:"nearest",block:"nearest"})},[p]),m.useEffect(()=>{let K=!0;return Qr().then(()=>{K&&d(!0)}),()=>{K=!1}},[]);const he=m.useCallback((K,be)=>{h(Re=>Re.map(Ve=>Ve.rel===K?lC(Ve,be):Ve))},[]),pe=m.useCallback(K=>{We({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]),ke=m.useCallback(async(K,be)=>{if(O.current.find(nt=>nt.rel===K)){be&&h(nt=>nt.map(ge=>ge.rel===K?{...ge,viewMode:be}:ge)),w(K);return}const Ve=V.current,Ke=await l(K);if(!(!Ke||ad(H.current,K,Ve))){if(!Ke.ok){if(Ke.error!=="too-large"){pe(Ke.error);return}h(nt=>[...nt,{rel:K,contents:"",draft:"",version:0,dirty:!1,conflict:!1,tooLarge:!0}]),w(K);return}h(nt=>[...nt,{rel:K,contents:Ke.content,draft:Ke.content,version:0,dirty:!1,conflict:!1,viewMode:be}]),w(K),window.electronAPI.workspaceFiles.watchStart({...i,rel:K})}},[pe,l,i,w]),[Me,fe]=m.useState(null),F=m.useCallback(K=>{const be=O.current,Re=be.filter(Ve=>!K(Ve.rel));for(const Ve of be)K(Ve.rel)&&window.electronAPI.workspaceFiles.watchStop({...i,rel:Ve.rel});h(Re),f(Ve=>Ve&&Re.some(Ke=>Ke.rel===Ve)?Ve:Re.at(-1)?.rel??null)},[i]),U=m.useCallback(K=>{F(be=>be===K)},[F]),de=m.useCallback(K=>{if(O.current.find(Re=>Re.rel===K)?.dirty){fe({kind:"one",rel:K});return}U(K)},[U]);m.useEffect(()=>H2(e,()=>{const K=B.current;return!K||O.current.length===0?!1:(de(K),!0)}),[e,de]),m.useEffect(()=>()=>{for(const K of O.current)window.electronAPI.workspaceFiles.watchStop({...i,rel:K.rel})},[i]),m.useEffect(()=>{let K=!0;const be=window.electronAPI.workspaceFiles.onChange(Re=>{Re.conversationId!==e||!O.current.find(Ke=>Ke.rel===Re.rel)||l(Re.rel).then(Ke=>{K&&Ke?.ok&&he(Re.rel,Ke.content)})});return()=>{K=!1,be()}},[he,e,l]);const Y=ie(K=>K.conversations[e]?.status==="running"),X=ie(K=>W?.kind==="scratch"?lg({kind:"scratch",canonicalPath:W.path,conversationId:e})??void 0:K.conversations[e]?.worktree?.path??W?.path),z=ie(K=>K.conversations[e]?.historyBaseIndex),ue=ie(K=>Qk(K.conversations[e]?.messages??Wp)),_e=m.useMemo(()=>{const K=ie.getState().conversations[e];return hr(K?.messages??Wp,Y,K?.customEntries??[],X).flatMap(be=>be.kind!=="tool"||be.state!=="ok"?[]:be.name!=="edit"&&be.name!=="write"?[]:be.summary?[be.summary]:[]).join(`
111
- `)},[e,ue,X,Y]);m.useEffect(()=>{let K=!0;const be=new Set(_e?_e.split(`
112
- `):[]);for(const Re of be)O.current.some(Ve=>Ve.rel===Re)&&l(Re).then(Ve=>{K&&Ve?.ok&&he(Re,Ve.content)});return()=>{K=!1}},[he,l,_e]);const Ee=m.useRef(null),Be=m.useRef(e),De=m.useRef(z),Ue=m.useCallback(()=>b(K=>K+1),[]);m.useEffect(()=>{if(r===0||a)return;let K=!0;Ue();for(const be of O.current){const Re=$r(be.rel),Ve=V.current;l(Re).then(Ke=>{!K||!Ke||ad(H.current,Re,Ve)||h(nt=>nt.map(ge=>ge.rel===be.rel?lC(ge,Ke.ok?Ke.content:null):ge))})}return()=>{K=!1}},[Ue,l,a,r]);const St=m.useCallback(K=>{K&&j(be=>{if(be.has(K))return be;const Re=new Set(be);return Re.add(K),Re})},[]),Ut=m.useCallback(K=>{K.length!==0&&j(be=>{let Re=!1;const Ve=new Set(be);for(const Ke of K)!Ke||Ve.has(Ke)||(Ve.add(Ke),Re=!0);return Re?Ve:be})},[]);m.useEffect(()=>{const K=ie.getState().conversations[e],be=z;(Be.current!==e||De.current!==be)&&(Be.current=e,De.current=be,Ee.current=null);const Re=hr(K?.messages??Wp,Y,K?.customEntries??[],X),{refreshRels:Ve,nextSeen:Ke}=rse(Re,Ee.current,B2(K?.messages??[]));Ee.current=Ke,Ve.length!==0&&(Ut(Ve.flatMap(od)),Ue())},[Ue,e,ue,Ut,z,X,Y]);const tn=m.useCallback(K=>{j(be=>{const Re=new Set(be);return Re.has(K)?Re.delete(K):Re.add(K),Re})},[]),Ne=m.useCallback(K=>{St(K),E({parent:K,kind:"file"})},[St]),Z=m.useCallback(K=>{St(K),E({parent:K,kind:"dir"})},[St]),je=m.useCallback(async(K,be=!1)=>{if(be){await ke(K,"preview");return}const Re=QD(K);if(O.current.find(ge=>ge.rel===Re)){w(Re);return}const Ke=V.current,nt=await l(K);if(!(!nt||ad(H.current,K,Ke))){if(!nt.ok){pe(nt.error);return}h(ge=>[...ge,{rel:Re,contents:nt.content,draft:nt.content,version:0,dirty:!1,conflict:!1,preview:!0}]),w(Re)}},[pe,l,ke,w]);m.useEffect(()=>V2(e,(K,be,Re)=>{L.current=be?{rel:K,line:be}:null;const Ve=se.current,Ke=O.current.find(nt=>nt.rel===K);if(be&&Ve?.rel===K&&B.current===K&&Ke?.viewMode!=="preview"){L.current=null,Ve.editor.focus({lineNumber:be});return}Re==="markdown"&&!be?je(K,!0):ke(K,"source")}),[e,ke,je]);const tt=m.useCallback(K=>window.electronAPI.workspaceFiles.readImage({...i,rel:K}).then(be=>be.ok?be.dataUrl:null),[i]),Et=m.useCallback(K=>window.electronAPI.workspaceFiles.fetchRemoteImage({...i,url:K}).then(be=>be.ok?be.dataUrl:null),[i]),zt=m.useCallback(async K=>{const be=await window.electronAPI.workspaceFiles.absPath({...i,rel:K});if(!be.ok||!be.local||!be.fileUrl){pe(be.ok?"unsupported":be.error);return}const Re=`browser:file:${e}:${K}`;ag({conversationId:e,tabId:Re,title:Er(K)});const Ve=await window.electronAPI.browser.navigate(Re,e,be.fileUrl);Ve.ok||pe(Ve.error)},[e,pe,i]),we=m.useCallback(async K=>{if(ie.getState().conversations[e]?.workspaceMigrating){We({type:"error",title:n("Wait for the workspace operation to finish before saving.")});return}const be=O.current.find(nt=>nt.rel===K);if(!be||be.preview)return;const Re=be.draft,Ve=V.current,Ke=await window.electronAPI.workspaceFiles.write({...i,rel:K,content:Re});if(!ad(H.current,K,Ve)){if(!Ke.ok){pe(Ke.error);return}h(nt=>nt.map(ge=>ge.rel===K?{...ge,contents:Re,dirty:ge.draft!==Re,conflict:!1}:ge))}},[e,pe,i,n]),ft=m.useCallback(K=>{h(be=>be.map(Re=>Re.rel===K?{...Re,viewMode:cse(Re.viewMode)}:Re))},[]);m.useEffect(()=>{const K=be=>{!(be.metaKey||be.ctrlKey)||be.key.toLowerCase()!=="s"||p&&(be.preventDefault(),we(p))};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[p,we]);const mt=u.find(K=>K.rel===p)??null,ze=m.useMemo(()=>({enabledSelectionAction:!0,renderSelectionAction(K){const be=document.createElement("button");return be.type="button",be.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",be.textContent=n("Send to conversation"),be.addEventListener("mouseenter",()=>{be.style.background="color-mix(in lab, currentColor 8%, transparent)"}),be.addEventListener("mouseleave",()=>{be.style.background="transparent"}),be.addEventListener("mousedown",Re=>Re.preventDefault()),be.addEventListener("click",()=>{const Re=K.getSelectionText().trim(),Ve=p;if(!Re||!Ve){K.close();return}const Ke=K.selection.start.line+1;let nt=K.selection.end.line+1;K.selection.end.character===0&&nt>Ke&&(nt-=1);const ge=Ke===nt?`L${Ke}`:`L${Ke}-L${nt}`;Vl({kind:"file",id:`${Ve}#${ge}`,label:`${Er(Ve)}#${ge}`,relativePath:`${Ve}#${ge}`}),wr(),K.close()}),be},onChange(K){const be=p;if(!be)return;const Re=K.contents;h(Ve=>Ve.map(Ke=>Ke.rel===be?{...Ke,draft:Re,dirty:Re!==Ke.contents}:Ke))},onAttach(K){if(!p)return;se.current={rel:p,editor:K};const be=L.current;be?.rel===p&&(L.current=null,K.focus({lineNumber:be.line}))}}),[p,n]),Ct=m.useCallback(async(K,be)=>{const Re=await window.electronAPI.workspaceFiles.rename({...i,rel:K,name:be});if(!Re.ok){pe(Re.error);return}T(null);const Ve=Re.rel;if(Ve){ne(K);for(const Ke of O.current){if(Ke.preview||Ke.tooLarge)continue;const nt=rd(Ke.rel,K,Ve);nt!=null&&(window.electronAPI.workspaceFiles.watchStop({...i,rel:Ke.rel}),window.electronAPI.workspaceFiles.watchStart({...i,rel:nt}))}h(Ke=>Ke.map(nt=>{const ge=rd(nt.rel,K,Ve);return ge==null?nt:{...nt,rel:ge}})),f(Ke=>Ke==null?Ke:rd(Ke,K,Ve)??Ke),j(Ke=>{let nt=!1;const ge=new Set;for(const $e of Ke){const it=rd($e,K,Ve)??$e;it!==$e&&(nt=!0),ge.add(it)}return nt?ge:Ke})}Ue()},[Ue,pe,ne,i]);return o.jsxs($2,{createEditor:hse,children:[o.jsxs("div",{className:"flex h-full min-h-0 bg-background",children:[o.jsxs("div",{className:q("flex shrink-0 flex-col overflow-hidden text-sm",x?g?"w-full":"hidden":"w-56 border-r"),children:[o.jsxs("div",{className:"flex justify-end gap-0.5 px-1 py-0.5",children:[o.jsx(le,{variant:"ghost",size:"icon-sm",onClick:()=>C(K=>!K),"aria-label":n("Search"),"aria-pressed":N,children:o.jsx(Js,{})}),o.jsx(le,{variant:"ghost",size:"icon-sm",onClick:Ue,"aria-label":n("Refresh"),children:o.jsx(Mo,{})})]}),N?o.jsx(Hne,{conversationId:e,projectId:t,onOpenFile:K=>{ke(K)},onClose:()=>C(!1),menu:{local:J,onPreview:K=>{je(K)},onBrowser:K=>{zt(K)},onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...i,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...i,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...i,rel:K}).then(be=>{be.ok||pe(be.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...i,rel:K})},onNewFile:K=>{C(!1),Ut(od(K)),Ne(K)},onNewFolder:K=>{C(!1),Ut(od(K)),Z(K)},onRename:(K,be)=>{C(!1),Ut(od(K)),T({rel:K,name:be,at:"tree"})},onDelete:(K,be)=>D({rel:K,name:be}),onSend:(K,be)=>{Vl({kind:"file",id:K,label:be,relativePath:K})}}}):o.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:o.jsx(Vu,{target:{kind:"blank"},local:J,onNewFile:Ne,onNewFolder:Z,onCopyPath:()=>{},onCopyRel:()=>{},children:o.jsx("div",{className:"min-h-full",children:o.jsx(tP,{rel:"",depth:0,conversationId:e,projectId:t,treeEpoch:y,draft:k,renaming:I,local:J,expandedDirs:_,onToggleDir:tn,onOpen:ke,onPreview:je,onBrowser:zt,onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...i,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...i,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...i,rel:K}).then(be=>{be.ok||pe(be.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...i,rel:K})},onNewFile:Ne,onNewFolder:Z,onRenameStart:(K,be)=>T({rel:K,name:be,at:"tree"}),onDelete:(K,be)=>D({rel:K,name:be}),onDraftCancel:()=>E(null),onRenameCancel:()=>T(null),onDraftCommit:async(K,be,Re)=>{const Ke=await(be==="dir"?window.electronAPI.workspaceFiles.mkdir:window.electronAPI.workspaceFiles.createFile)({...i,rel:K||void 0,name:Re});if(!Ke.ok){pe(Ke.error);return}E(null),Ue(),be==="file"&&Ke.rel&&ke(Ke.rel)},onRenameCommit:(K,be)=>{Ct(K,be)}})})})})]}),o.jsxs("div",{className:q("flex min-w-0 flex-1 flex-col",x&&g&&"hidden"),children:[u.length>0&&o.jsxs("div",{ref:Q,className:"flex h-[36px] shrink-0 items-center gap-1 overflow-x-auto border-b px-2",children:[x&&o.jsx("button",{type:"button",className:"flex shrink-0 items-center rounded-md px-1 text-muted-foreground hover:bg-muted/50",onClick:()=>v(!0),"aria-label":n("Files"),title:n("Files"),children:o.jsx(W2,{className:"h-4 w-4"})}),u.map(K=>{const be=I?.rel===K.rel&&I.at==="tab"&&!K.preview,Re=o.jsxs("button",{type:"button","data-file-tab":K.rel,className:q("flex items-center gap-1.5 rounded-md px-2 py-1 text-xs",K.rel===p?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:()=>{be||f(K.rel)},onDoubleClick:Ve=>{K.preview||(Ve.preventDefault(),Ve.stopPropagation(),T({rel:K.rel,name:Er(K.rel),at:"tab"}))},children:[be?o.jsx(Tu,{depth:0,kind:"file",variant:"tab",initial:I.name,onCancel:()=>T(null),onCommit:Ve=>{Ct(K.rel,Ve)}}):o.jsxs("span",{className:"max-w-36 truncate",children:[Er(K.preview?$r(K.rel):K.rel),K.preview?` ${n("Preview")}`:"",K.dirty?"*":""]}),o.jsx("button",{type:"button",className:"text-muted-foreground hover:text-destructive",onClick:Ve=>{Ve.stopPropagation(),de(K.rel)},children:"×"})]});return o.jsxs(ao,{children:[o.jsx(lo,{render:Re}),o.jsxs(co,{className:"min-w-40",children:[!K.preview&&o.jsx(Ht,{onClick:()=>T({rel:K.rel,name:Er(K.rel),at:"tab"}),children:n("Rename")}),o.jsx(Ht,{onClick:()=>de(K.rel),children:n("Close")}),o.jsx(Ht,{onClick:()=>{const Ve=O.current,Ke=K.rel,nt=Ve.some(ge=>ge.rel!==Ke&&ge.dirty);F(ge=>ge!==Ke&&!Ve.find($e=>$e.rel===ge)?.dirty),nt&&fe({kind:"others",rel:Ke})},children:n("Close others")}),o.jsx(Ht,{onClick:()=>{const Ve=O.current,Ke=Lm(Ve.map(ge=>ge.rel),K.rel,"right"),nt=Ke.some(ge=>Ve.find($e=>$e.rel===ge)?.dirty);F(ge=>Ke.includes(ge)&&!Ve.find($e=>$e.rel===ge)?.dirty),nt&&fe({kind:"right",rel:K.rel})},children:n("Close tabs to the right")}),o.jsx(Ht,{onClick:()=>{const Ve=O.current;F(Ke=>!Ve.find(nt=>nt.rel===Ke)?.dirty)},children:n("Close saved")}),o.jsx(Ht,{onClick:()=>{const Ve=O.current,Ke=Ve.some(nt=>nt.dirty);F(nt=>!Ve.find(ge=>ge.rel===nt)?.dirty),Ke&&fe({kind:"all"})},children:n("Close all")}),o.jsx(Ht,{onClick:()=>F(Ve=>Ve!==K.rel),children:n("Force close others")}),o.jsx(Ht,{onClick:()=>F(()=>!0),children:n("Force close all")})]})]},K.rel)})]}),mt?.conflict&&o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b px-2 py-1 text-[11px]",children:[o.jsx("span",{children:n("This file changed on disk.")}),o.jsx("button",{type:"button",className:"underline",disabled:a,onClick:()=>{l($r(mt.rel)).then(K=>{K?.ok&&h(be=>be.map(Re=>Re.rel===mt.rel?{...Re,contents:K.content,draft:K.content,version:Re.version+1,dirty:!1,conflict:!1}:Re))})},children:n("Reload")})]}),o.jsxs("div",{className:"relative min-h-0 flex-1",children:[mt&&!mt.preview&&!mt.tooLarge&&Gv(mt.rel)&&o.jsx("div",{className:"absolute top-2 right-2 z-10",children:o.jsxs(le,{type:"button",variant:"outline",size:"sm","aria-label":mt.viewMode==="preview"?n("View Source"):n("Preview"),onClick:()=>ft(mt.rel),children:[mt.viewMode==="preview"?o.jsx(u1,{className:"h-3.5 w-3.5"}):o.jsx(U2,{className:"h-3.5 w-3.5"}),mt.viewMode==="preview"?n("View Source"):n("Preview")]})}),!c||!mt?o.jsx("div",{className:"flex h-full items-center justify-center px-3 text-center text-sm text-muted-foreground",children:n(c?"Open a file from the tree.":"Loading...")}):mt.tooLarge?o.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.")}):mt.preview||mt.viewMode==="preview"&&Gv(mt.rel)?o.jsx("div",{className:"h-full overflow-auto px-3 py-2 text-sm",children:o.jsx(ise,{text:mt.preview?mt.contents:mt.draft,baseDirRel:fse($r(mt.rel)),resolveImage:tt,resolveRemoteImage:Et})}):o.jsx(K2,{style:{height:"100%",overflow:"auto"},children:o.jsx(HC,{file:{name:Er(mt.rel),contents:mt.draft},disableWorkerPool:!0,edit:!0,editorOptions:ze,options:s},`${mt.rel}:${mt.version}`)})]})]})]}),o.jsx(hs,{open:Me!==null,onOpenChange:K=>{K||fe(null)},title:n("Unsaved changes"),description:Me?.kind==="one"?n("This file has unsaved changes. Close anyway?"):n("Some files have unsaved changes. Close anyway?"),confirmLabel:n("Close"),onConfirm:()=>{if(Me){if(Me.kind==="one"&&Me.rel)U(Me.rel);else if(Me.kind==="others"&&Me.rel){const K=Me.rel;F(be=>be!==K)}else if(Me.kind==="right"&&Me.rel){const K=Me.rel,be=new Set(Lm(O.current.map(Re=>Re.rel),K,"right"));F(Re=>be.has(Re))}else F(()=>!0);fe(null)}}}),o.jsx(hs,{open:A!==null,onOpenChange:K=>{K||D(null)},title:n("Delete"),description:n("Delete {{name}} permanently?",{name:A?.name??""}),confirmLabel:n("Delete"),onConfirm:()=>{if(!A)return;const{rel:K}=A;window.electronAPI.workspaceFiles.remove({...i,rel:K}).then(be=>{if(!be.ok){pe(be.error);return}ne(K),F(Re=>Rm(Re,K)),j(Re=>{let Ve=!1;const Ke=new Set;for(const nt of Re){if(Rm(nt,K)){Ve=!0;continue}Ke.add(nt)}return Ve?Ke:Re}),D(null),Ue()})}})]})}function Tu({depth:e,kind:t,initial:n,onCancel:s,onCommit:i,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 x=c.current;x&&(x.focus(),x.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"&&lse(a,n)==="commit"){u.current=!0,i(a.trim());return}u.current=!0,s()}};return o.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 tP({rel:e,depth:t,conversationId:n,projectId:s,treeEpoch:i,...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,i]),!a)return o.jsx("div",{className:"px-2 py-1 text-muted-foreground",children:"…"});const c=r.draft?.parent===e;return o.jsxs("div",{children:[a.map(d=>{const u=pse(e,d.name),h=r.expandedDirs.has(u);if(d.kind==="dir"){const f=r.renaming?.rel===u&&r.renaming.at==="tree"?o.jsx(Tu,{depth:t,kind:"dir",initial:d.name,onCancel:r.onRenameCancel,onCommit:x=>r.onRenameCommit(u,x)}):o.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:[o.jsx(kn,{className:q("h-3.5 w-3.5 shrink-0",h&&"rotate-90")}),(()=>{const x=gc(d.name,!0,h);return o.jsx(x,{className:q("h-4 w-4 shrink-0",xc(d.name,!0))})})(),o.jsx("span",{className:"truncate",children:d.name})]});return o.jsxs("div",{children:[o.jsx(Vu,{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&&o.jsx(tP,{rel:u,depth:t+1,conversationId:n,projectId:s,treeEpoch:i,...r})]},u)}return o.jsx(gse,{rel:u,name:d.name,depth:t,renaming:r.renaming?.rel===u&&r.renaming.at==="tree",handlers:r},u)}),c&&r.draft&&o.jsx(Tu,{depth:t,kind:r.draft.kind,initial:"",onCancel:r.onDraftCancel,onCommit:d=>r.onDraftCommit(e,r.draft.kind,d)})]})}function gse({rel:e,name:t,depth:n,renaming:s,handlers:i}){const{setNodeRef:r,listeners:a,isDragging:l}=gg({id:`workspace-file:${e}`,data:{type:"workspace-file",relativePath:e,name:t}}),c=s?o.jsx(Tu,{depth:n,kind:"file",initial:t,onCancel:i.onRenameCancel,onCommit:d=>i.onRenameCommit(e,d)}):o.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:()=>i.onOpen(e),children:[(()=>{const d=gc(t,!1);return o.jsx(d,{className:q("h-4 w-4 shrink-0",xc(t,!1))})})(),o.jsx("span",{className:"truncate",children:t})]});return o.jsx(Vu,{target:{kind:"file",rel:e,name:t},local:i.local,onNewFile:i.onNewFile,onNewFolder:i.onNewFolder,onView:i.onOpen,onPreview:i.onPreview,onBrowser:i.onBrowser,onCopyPath:i.onCopyPath,onCopyRel:i.onCopyRel,onCopyFile:i.onCopyFile,onReveal:i.onReveal,onRename:i.onRenameStart,onDelete:i.onDelete,onSend:(d,u)=>{Vl({kind:"file",id:d,label:u,relativePath:d})},children:c})}function xse({open:e,onClose:t,onFindNext:n,onFindPrevious:s,onClear:i,theme:r}){const{t:a}=te(),l=m.useRef(null),[c,d]=m.useState(""),[u,h]=m.useState(!1),[p,f]=m.useState(!1),[x,g]=m.useState(!1),[v,w]=m.useState(null);m.useEffect(()=>{e?(l.current?.focus(),l.current?.select()):(i(),w(null))},[e,i]);const y=()=>({caseSensitive:u,wholeWord:p,regex:x}),b=N=>{if(!c){w(null);return}w(N==="next"?n(c,y()):s(c,y()))};if(!e)return null;const _=r?.background??"#1e1e1e",j=r?.foreground??"#d4d4d4";return o.jsxs("div",{className:"absolute top-2 right-2 z-10 flex items-center gap-1 rounded-md border px-2 py-1 shadow-lg",style:{backgroundColor:_,borderColor:`${j}30`},children:[o.jsx("input",{ref:l,value:c,onChange:N=>{const C=N.target.value;d(C),C?w(n(C,y())):(i(),w(null))},onKeyDown:N=>{N.key==="Enter"?(N.preventDefault(),b(N.shiftKey?"prev":"next")):N.key==="Escape"&&(N.preventDefault(),t())},placeholder:a("Search..."),className:q("w-40 bg-transparent text-sm outline-none placeholder:opacity-50",v===!1&&c&&"text-red-400"),style:{color:j}}),o.jsx("button",{type:"button",onClick:()=>h(N=>!N),className:q("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",u?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:j},title:a("Case sensitive"),children:"Aa"}),o.jsx("button",{type:"button",onClick:()=>f(N=>!N),className:q("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",p?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:j},title:a("Whole word"),children:"W"}),o.jsx("button",{type:"button",onClick:()=>g(N=>!N),className:q("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",x?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:j},title:a("Regular expression"),children:".*"}),o.jsx("div",{className:"mx-1 h-4 w-px",style:{backgroundColor:`${j}30`}}),o.jsx("button",{type:"button",onClick:()=>b("prev"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:j},title:a("Previous match"),children:o.jsx(Ik,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",onClick:()=>b("next"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:j},title:a("Next match"),children:o.jsx($n,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",onClick:t,className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:j},title:a("Close"),children:o.jsx(ln,{className:"h-4 w-4"})})]})}function cC(e,t){const n=Eu(e);return t?Q2(n):n}function vse({termId:e,conversationId:t,projectId:n,onTitle:s}){const{t:i}=te(),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=xe(T=>T.terminalTheme),x=xe(T=>T.terminalFontFamily),g=xe(T=>T.terminalFontSize),v=xe(T=>T.backgroundImageEnabled),[w,y]=m.useState(!1);m.useEffect(()=>{const T=r.current;if(!T)return;let A=!1,D=0,W;const J=()=>{if(A)return;if(!T.isConnected||T.clientWidth===0||T.clientHeight===0){D=requestAnimationFrame(J);return}const B=xe.getState(),L=Z2(e,T,{theme:cC(B.terminalTheme,B.backgroundImageEnabled),fontFamily:B.terminalFontFamily,fontSize:B.terminalFontSize});if(!L.opened){D=requestAnimationFrame(J);return}L.onTitle=Q=>p.current?.(Q);const se=()=>{!T.isConnected||T.clientWidth===0||(L.fit.fit(),window.electronAPI.terminal.resize(e,L.term.cols,L.term.rows))};se(),window.electronAPI.terminal.create({termId:e,conversationId:u.current,projectId:h.current,cols:L.term.cols,rows:L.term.rows}),L.term.focus(),a.current=L.term,W=new ResizeObserver(se),W.observe(T)};document.fonts.load('14px "Enso Nerd Symbols"',"").then(J,B=>{console.warn("Failed to load terminal icon font",B),J()});const O=B=>{(B.metaKey||B.ctrlKey)&&B.key==="f"&&(B.preventDefault(),B.stopPropagation(),y(!0))};return T.addEventListener("keydown",O,!0),()=>{A=!0,cancelAnimationFrame(D),W?.disconnect(),T.removeEventListener("keydown",O,!0),a.current=null,Y2(e)}},[e]),m.useEffect(()=>{X2(cC(f,v),x,g)},[f,x,g,v]);const b=m.useCallback((T,A)=>Fv(e,T,"next",A),[e]),_=m.useCallback((T,A)=>Fv(e,T,"prev",A),[e]),j=m.useCallback(()=>J2(e),[e]),N=()=>{const T=a.current?.getSelection().trim()??"";l.current=T,d(T.length>0)},C=()=>{const T=l.current||a.current?.getSelection().trim()||"";T&&(dh(T),wr(),a.current?.clearSelection(),d(!1))},k=()=>{const T=l.current||a.current?.getSelection().trim()||"";T&&navigator.clipboard.writeText(T)},E=Eu(f),I=o.jsx("div",{ref:r,"data-slot":"terminal-pane",className:"relative h-full w-full overflow-hidden p-2",style:{backgroundColor:E?.background,"--terminal-bg":E?.background},onContextMenu:N,children:o.jsx(xse,{open:w,onClose:()=>y(!1),onFindNext:b,onFindPrevious:_,onClear:j,theme:E})});return o.jsxs(ao,{children:[o.jsx(lo,{render:I}),o.jsxs(co,{className:"min-w-40",children:[o.jsx(Ht,{disabled:!c,onClick:k,children:i("Copy")}),o.jsx(Ht,{disabled:!c,onClick:C,children:i("Send to conversation")})]})]})}const nP={running:"bg-amber-500",completed:"bg-emerald-500",failed:"bg-destructive",cancelled:"bg-muted-foreground"},bse=[],wse={project:"Project",custom:"Custom",global:"Global",builtin:"Built-in"};function yse(e,t,n,s){const i=ie.getState(),r=i.conversations[e],a=xe.getState(),l=a.projects.find(u=>u.id===r?.projectId);if(!r||!l)return!1;const c=jl({defaultModel:a.defaultModel,...Fd(l,a.projectGroups),lastProviderId:r.lastProviderId,lastModelId:r.lastModelId,providers:e_(),credentials:na(Ao.getState().snapshot),virtualModels:a.virtualModels});if(c.source==="none")return We({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 i.send(eL({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 Sse({conversationId:e,preset:t,open:n,onToggle:s}){const{t:i}=te(),[r,a]=m.useState({}),l=t.args.some(u=>u.required&&!u.default?.trim()&&!r[u.key]?.trim()),c=t.source==="builtin"?i(t.name):t.name,d=t.source==="builtin"?i(t.description):t.description;return o.jsxs("li",{className:"rounded-md border",children:[o.jsxs("button",{type:"button",className:"w-full px-2 py-1.5 text-left text-xs hover:bg-muted/60",onClick:s,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:c}),o.jsx("span",{className:"shrink-0 text-muted-foreground",children:i(wse[t.source])})]}),o.jsx("p",{className:"mt-0.5 line-clamp-2 text-muted-foreground",children:d})]}),n?o.jsxs("form",{className:"space-y-2 border-t px-2 py-2",onSubmit:u=>{u.preventDefault(),!(l||!yse(e,t,r,i))&&(a({}),s())},children:[t.args.map(u=>o.jsxs("label",{className:"block text-xs",children:[o.jsxs("span",{className:"text-muted-foreground",children:[t.source==="builtin"?i(u.label):u.label,u.required?" *":""]}),o.jsx(Wt,{size:"sm",className:"mt-1",value:r[u.key]??"",placeholder:u.default,onChange:h=>a(p=>({...p,[u.key]:h.target.value}))})]},u.key)),o.jsx("div",{className:"flex justify-end",children:o.jsxs(le,{type:"submit",size:"xs",disabled:l,children:[o.jsx($m,{}),i("Run")]})})]}):null]})}function Cse({conversationId:e}){const{t}=te(),[n,s]=m.useState([]),[i,r]=m.useState(null),a=xe(d=>d.disabledWorkflowPresets),l=m.useCallback(()=>{let d=!1;return window.electronAPI.assets.listWorkflowPresets(e).then(u=>{d||s(u)}).catch(()=>{d||s([])}),()=>{d=!0}},[e]);m.useEffect(l,[l]);const c=n.filter(d=>d.source!=="builtin"||!a.includes(d.id));return o.jsxs("section",{children:[o.jsxs("div",{className:"mb-1.5 flex items-center gap-2",children:[o.jsx("h3",{className:"flex-1 text-xs font-medium text-muted-foreground",children:t("Presets")}),o.jsx(le,{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:o.jsx(Ok,{})}),o.jsx(le,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Refresh"),onClick:()=>l(),children:o.jsx(Mo,{})})]}),o.jsx("ul",{className:"space-y-1.5",children:c.map(d=>o.jsx(Sse,{conversationId:e,preset:d,open:i===d.id,onToggle:()=>r(u=>u===d.id?null:d.id)},`${d.source}:${d.id}`))})]})}function kse(e,t){const n=ie.getState();n.activeId!==e&&n.selectConversation(e),n.selectTab(e,t)}function _se({conversationId:e,member:t}){const{t:n}=te(),s=o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",nP[t.status])}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),o.jsx("span",{className:"text-muted-foreground",children:n(t.status)})]}),t.prompt?o.jsx("p",{className:"mt-0.5 truncate pl-3.5 text-muted-foreground",children:t.prompt}):null,t.result?o.jsx("p",{className:"mt-0.5 line-clamp-3 whitespace-pre-wrap pl-3.5 text-foreground/80",children:t.result}):null]}),i=t.childId;return i?o.jsx("li",{children:o.jsx("button",{type:"button",className:"w-full rounded px-1 py-0.5 text-left text-xs hover:bg-muted/60",onClick:()=>kse(e,i),children:s})}):o.jsx("li",{className:"text-xs",children:s})}function jse({conversationId:e}){const{t}=te(),n=af(r=>r.byConversation[e])??bse,s=af(r=>r.clearFinished),i=n.some(r=>r.status!=="running");return o.jsx("div",{className:"h-full overflow-auto bg-background p-3",children:o.jsxs("div",{className:"space-y-3",children:[o.jsx(Cse,{conversationId:e}),i?o.jsx("div",{className:"flex justify-end",children:o.jsxs(le,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>s(e),children:[o.jsx(rg,{}),t("Clear finished runs")]})}):null,n.length===0?o.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:t("No workflow runs")}):null,n.map(r=>o.jsxs("section",{className:"rounded-md border px-3 py-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:q("h-2 w-2 shrink-0 rounded-full",nP[r.status])}),o.jsx("h3",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:r.name}),o.jsx("span",{className:"text-xs text-muted-foreground",children:t(r.status)}),r.status==="running"?o.jsx(le,{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:o.jsx(Mu,{})}):null]}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r.description}),o.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:t("{{count}} agents",{count:r.members.length})}),o.jsx("div",{className:"mt-2 space-y-2",children:DV(r.members).map((a,l,c)=>{const d=!!a.phase&&a.phase!==c[l-1]?.phase;return o.jsxs("div",{children:[o.jsxs("div",{className:"mb-1 flex items-center gap-2 text-xs",children:[d?o.jsx("span",{className:"font-medium",children:a.phase}):null,a.members.length>1?o.jsx("span",{className:"text-muted-foreground",children:t("Parallel")}):null]}),o.jsx("ul",{className:"space-y-1",children:a.members.map(u=>o.jsx(_se,{conversationId:e,member:u},u.seq))})]},`${a.batch}:${a.phase??""}`)})}),r.error?o.jsx("p",{className:"mt-2 text-xs text-destructive",children:r.error}):null,r.logs.length>0?o.jsx("p",{className:"mt-2 whitespace-pre-wrap text-xs text-muted-foreground",children:r.logs.join(`
113
- `)}):null]},r.runId))]})})}const ov=m.createContext({}),sP=m.createContext(!1);function Nse(e,t){const[n,s]=m.useState(!t);return m.useEffect(()=>{if(!t)return;const i=()=>{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)};i();const r=e.onDidLayoutChange(i);return()=>r.dispose()},[e,t]),n}function iP(e,t){const n=e.panels.length;return n===0?t:`${t} ${n+1}`}function oP(e,t,n,s){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:iP(e,s),params:{conversationId:t,projectId:n}})}function rP(e,t,n,s){const i=e.getPanel("changes");if(i){i.focus();return}e.addPanel({id:"changes",component:"changes",title:s,params:{conversationId:t,projectId:n}})}function Tse(e){return o.jsx(vse,{termId:e.api.id,conversationId:e.params.conversationId,projectId:e.params.projectId,onTitle:t=>e.api.setTitle(t)})}function Ise(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:o.jsx(Gne,{conversationId:t,projectId:n})}function aP(e,t,n,s){const i=e.getPanel("files");if(i){i.focus();return}e.addPanel({id:"files",component:"files",title:s,params:{conversationId:t,projectId:n}})}function Dse(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:o.jsx(mse,{conversationId:t,projectId:n})}function lP(e,t,n,s){const i=e.panels.filter(r=>r.id.startsWith("btw:")).length;e.addPanel({id:`btw:${crypto.randomUUID()}`,component:"btw",title:i===0?s:`${s} ${i+1}`,params:{conversationId:t,projectId:n}})}function Pse(e){const{conversationId:t}=e.params;return t?o.jsx(Tne,{conversationId:t,panelApi:e.api}):null}function cP(e,t,n,s,i){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 Ese(e){const{conversationId:t}=e.params;return t?o.jsx(ZN,{conversationId:t,panelApi:e.api}):null}function dP(e,t,n,s){const i=e.getPanel("workflow");if(i){i.focus();return}e.addPanel({id:"workflow",component:"workflow",title:s,params:{conversationId:t,projectId:n}})}function rv(e){return xe(t=>iL(t,e))}function uP(e,t,n,s,i){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",...i?{position:{referenceGroup:i}}:{}})}function Ase(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:o.jsx(Nne,{pluginId:n,viewId:s,sessionId:t??null})}function Mse(e){const{conversationId:t}=e.params;return t?o.jsx(jse,{conversationId:t}):null}function ld(e,t){const n=e.group.panels.map(i=>i.id),s=new Set(Lm(n,e.id,t));for(const i of[...e.group.panels])s.has(i.id)&&i.api.close()}function Rse(e){const{t}=te(),[n,s]=m.useState(e.api.isActive),[i,r]=m.useState(e.api.title??""),[a,l]=m.useState(e.params.favicon??null),[c,d]=m.useState(!1);m.useEffect(()=>{const p=e.api.onDidActiveChange(()=>s(e.api.isActive)),f=e.api.onDidTitleChange(()=>r(e.api.title??"")),x=e.api.onDidParametersChange(g=>{const v=g&&typeof g=="object"&&"favicon"in g?g.favicon??null:e.api.getParameters()?.favicon??null;l(v??null),d(!1)});return()=>{p.dispose(),f.dispose(),x.dispose()}},[e.api]);const u=e.api.id==="browser"||e.api.id.startsWith("browser:"),h=o.jsxs("div",{"data-side-tab":!0,"data-active":n||void 0,className:q("group/tab relative flex min-w-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",n?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),children:[e.api.id==="changes"?o.jsx(Ug,{className:"h-3 w-3 shrink-0"}):e.api.id==="files"?o.jsx(Qs,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("btw:")?o.jsx(pr,{className:"h-3 w-3 shrink-0"}):e.api.id==="workflow"?o.jsx(Hm,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("plugin:")?o.jsx(Fm,{pluginId:e.api.id.split(":")[1]??"",className:"h-3 w-3 shrink-0"}):u&&a&&!c?o.jsx("img",{src:a,alt:"",className:"h-3 w-3 shrink-0",onError:()=>d(!0)}):u?o.jsx(uo,{className:"h-3 w-3 shrink-0"}):o.jsx(Eo,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"max-w-32 truncate",children:i}),o.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/tab:opacity-100",onPointerDown:p=>p.stopPropagation(),onClick:p=>{p.stopPropagation(),e.api.close()},children:o.jsx(ln,{className:"h-3 w-3"})})]});return o.jsxs(ao,{children:[o.jsx(lo,{render:h}),o.jsxs(co,{className:"min-w-40",children:[o.jsx(Ht,{onClick:()=>ld(e.api,"self"),children:t("Close")}),o.jsx(Ht,{onClick:()=>ld(e.api,"others"),children:t("Close others")}),o.jsx(Ht,{onClick:()=>ld(e.api,"right"),children:t("Close tabs to the right")}),o.jsx(Ht,{onClick:()=>ld(e.api,"all"),children:t("Close all")})]})]})}function hP({onNewTerminal:e,onNewChanges:t,onNewFiles:n,onNewBrowser:s,onNewBtw:i,onNewWorkflow:r,onNewPluginView:a,compact:l}){const{t:c}=te(),d=Zk();return o.jsxs(zi,{children:[o.jsxs(Gi,{className:q("flex items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",l?"h-6 w-6 rounded p-1 hover:bg-muted":"h-8 gap-1.5 border border-dashed px-3 text-sm hover:border-solid"),"aria-label":c("New tab"),children:[o.jsx(ps,{className:"h-4 w-4"}),!l&&o.jsx("span",{children:c("New tab")})]}),o.jsxs(Fi,{align:l?"end":"center",className:"min-w-36",children:[o.jsxs(dn,{onClick:e,children:[o.jsx(Eo,{className:"h-4 w-4"}),c("Terminal")]}),o.jsxs(dn,{onClick:t,children:[o.jsx(Ug,{className:"h-4 w-4"}),c("Changes")]}),o.jsxs(dn,{onClick:n,children:[o.jsx(Qs,{className:"h-4 w-4"}),c("Files")]}),o.jsxs(dn,{onClick:s,children:[o.jsx(uo,{className:"h-4 w-4"}),c("Browser")]}),o.jsxs(dn,{onClick:i,children:[o.jsx(pr,{className:"h-4 w-4"}),c("Btw")]}),r?o.jsxs(dn,{onClick:r,children:[o.jsx(Hm,{className:"h-4 w-4"}),c("Workflow")]}):null,a?d.map(u=>o.jsxs(dn,{onClick:()=>a(u),children:[o.jsx(Fm,{pluginId:u.pluginId,className:"h-4 w-4"}),u.title]},`${u.pluginId}:${u.id}`)):null]})]})}function pP({containerApi:e,group:t}){const{t:n}=te(),{conversationId:s,projectId:i}=m.useContext(ov),r=pn(f=>f.fullscreen),a=pn(f=>f.toggleFullscreen),l=rv(i),c=fa(),d=m.useContext(sP),u=Nse(e,t),h=pn(f=>f.toggleOpen),p=Hu()==="windows";return o.jsxs("div",{className:"flex h-full items-center gap-0.5",children:[o.jsx(hP,{compact:!0,onNewTerminal:()=>{if(t){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:iP(e,n("Terminal")),params:{conversationId:s,projectId:i},position:{referenceGroup:t}});return}oP(e,s,i,n("Terminal"))},onNewChanges:()=>rP(e,s,i,n("Changes")),onNewFiles:()=>aP(e,s,i,n("Files")),onNewBrowser:()=>cP(e,s,i,n("Browser")),onNewBtw:()=>{if(t){const f=e.panels.filter(x=>x.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:i},position:{referenceGroup:t}});return}lP(e,s,i,n("Btw"))},onNewWorkflow:l?()=>dP(e,s,i,n("Workflow")):void 0,onNewPluginView:f=>uP(e,s,i,f,t)}),o.jsx("button",{type:"button",className:q("flex h-6 w-6 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",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?o.jsx(aL,{className:"h-3.5 w-3.5"}):o.jsx(lL,{className:"h-3.5 w-3.5"})}),d&&u&&o.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:o.jsx(f1,{className:"h-4 w-4"})}),d&&u&&p&&o.jsx("span",{"aria-hidden":!0,className:"shrink-0",style:{width:`calc(100vw - env(titlebar-area-width, calc(100vw - ${cL}px)) - 19px)`}})]})}function Lse(e){const{t}=te(),{conversationId:n,projectId:s}=m.useContext(ov),i=rv(s);return o.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o.jsx("div",{className:"enso-side-dock-header flex shrink-0 items-center justify-end border-b bg-background px-2 py-1",children:o.jsx(pP,{containerApi:e.containerApi})}),o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-3 bg-background px-6 text-center",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:t("No tabs yet. Create one to get started.")}),o.jsx(hP,{onNewTerminal:()=>oP(e.containerApi,n,s,t("Terminal")),onNewChanges:()=>rP(e.containerApi,n,s,t("Changes")),onNewFiles:()=>aP(e.containerApi,n,s,t("Files")),onNewBrowser:()=>cP(e.containerApi,n,s,t("Browser")),onNewBtw:()=>lP(e.containerApi,n,s,t("Btw")),onNewWorkflow:i?()=>dP(e.containerApi,n,s,t("Workflow")):void 0,onNewPluginView:r=>uP(e.containerApi,n,s,r)})]})]})}function Ose(e){return o.jsx(pP,{containerApi:e.containerApi,group:e.group})}const dC={terminal:Tse,changes:Ise,files:Dse,browser:Ese,btw:Pse,workflow:Mse,plugin:Ase};function zse(){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 Gse({conversationId:e,hidden:t}){const n=ie(s=>s.conversations[e]?.projectId);return n?o.jsx("div",{className:q("absolute inset-0",t&&"hidden"),children:o.jsx(Fse,{conversationId:e,projectId:n})}):null}function Fse({conversationId:e,projectId:t}){const n=zse(),s=rv(t),[i,r]=m.useState(null);m.useEffect(()=>{s||i?.getPanel("workflow")?.api.close()},[i,s]);const a=l=>{oL(e,l.api);const c=pn.getState().layouts[e],d=bne(c,new Set(Object.keys(dC)));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,pn.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:")){ie.getState().disposeBtwConversation(h.id.slice(4));return}rL(h.id),window.electronAPI.terminal.dispose(h.id)}}),r(l.api)};return o.jsx(ov.Provider,{value:{conversationId:e,projectId:t},children:o.jsx("div",{className:"enso-side-dock h-full",children:o.jsx(BD,{components:dC,defaultTabComponent:Rse,watermarkComponent:Lse,rightHeaderActionsComponent:Ose,theme:n?Yee:Xee,onReady:a})})})}function Hse({width:e,resizing:t=!1,card:n=!1,titleRow:s=!1}){const{t:i}=te(),r=ie(D=>D.activeId),a=pn(D=>r?!!D.uiByConversation[r]?.open:!1),l=fa(),d=pn(D=>D.fullscreen)||l&&a;m.useEffect(()=>{const D=window.electronAPI.browser.onReveal(J=>{Jk(J.conversationId)||ag({conversationId:J.conversationId,tabId:J.tabId})}),W=window.electronAPI.browser.onTabClosed(J=>{tL(J.conversationId,J.tabId)});return window.electronAPI.browser.restoreTabs(),()=>{D(),W()}},[]),m.useEffect(()=>af.subscribe((D,W)=>{for(const[J,O]of Object.entries(D.byConversation)){if(W.byConversation[J]===O)continue;const B=O.find(L=>L.status==="running");B&&nL({conversationId:J,runId:B.runId,title:i("Workflow")})}}),[i]),m.useEffect(()=>ie.subscribe((D,W)=>{for(const J of Object.keys(W.conversations))D.conversations[J]||sL(J)}),[]);const u=ie(D=>D.activeId),[h,p]=m.useState([]),f=ie(D=>h.filter(W=>!!D.conversations[W]).join(`
114
- `)),[x,g]=m.useState(d),[v,w]=m.useState(0),y=n&&!s?t_:Qm,b=wk(e,v,y),_=m.useRef(null),[j,N]=m.useState({id:u,from:u});u!==j.id&&N({id:u,from:j.id}),d&&!x&&g(!0),m.useEffect(()=>{const D=_.current?.parentElement;if(!D)return;const W=()=>{const O=getComputedStyle(D);w(D.clientWidth-parseFloat(O.paddingLeft)-parseFloat(O.paddingRight))};W();const J=new ResizeObserver(W);return J.observe(D),()=>J.disconnect()},[]),m.useEffect(()=>{j.from!==j.id&&N(D=>D.from===D.id?D:{...D,from:D.id})},[j.from,j.id]);const C=x?void 0:Math.max(0,b-(a&&!n?1:0)),k=u,E=q7({resizing:t,conversationId:j.id??void 0,previousConversationId:j.from??void 0}),I=d?v||b:a?b:0,T=!!s&&!l;k&&!h.includes(k)&&p(D=>D.includes(k)?D:[...D,k]);const A=f===""?[]:f.split(`
115
- `);return o.jsxs(o.Fragment,{children:[x&&!l?o.jsx("div",{className:"shrink-0",style:{width:b},"aria-hidden":!0}):null,o.jsxs(Es.aside,{ref:_,"data-slot":"side-panel",initial:!1,animate:{width:I},style:x?void 0:{maxWidth:`max(0px, calc(100% - ${bk+y}px))`},transition:qN({skip:E,cover:x,targetW:I}),onAnimationComplete:()=>{d||g(!1)},className:q("flex min-h-0 flex-col",T&&a?"overflow-clip [overflow-clip-margin:4px]":"overflow-hidden",a&&(T||!x)?"bg-transparent":T?"":"bg-background",x?T?"absolute top-px right-[8px] bottom-[8px]":n?"absolute top-0 right-[8px] bottom-[8px]":"absolute inset-y-0 right-0":"relative shrink-0",T?q("no-drag -mt-[44px]",x?"rounded-b-[10px]":"rounded-br-[10px]"):n?q("rounded-[10px]",a&&"shadow-surface"):a&&"border-l"),"data-enso":"side-panel","data-title-row":T||void 0,children:[a&&(T||!x)?o.jsx($se,{titleRow:T,full:x}):null,a&&!x&&C!==void 0?o.jsx("div",{"aria-hidden":!0,className:q("pointer-events-none absolute right-0 bottom-0 bg-background",s?"top-[44px]":"top-0"),style:{left:C}}):null,o.jsx("div",{className:q("relative flex h-full min-h-0 flex-col",x&&"w-full",!a&&"invisible"),style:{width:C,clipPath:T?x?Vse:Bse:void 0},children:A.length>0?o.jsx("div",{className:"relative min-h-0 flex-1",children:o.jsx(sP.Provider,{value:T,children:A.map(D=>o.jsx(Gse,{conversationId:D,hidden:D!==k},D))})}):o.jsx("div",{className:"flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground",children:i("Select a conversation to use the side panel.")})})]})]})}const Bse="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)",Vse="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 $se({titleRow:e,full:t}){const n=m.useRef(null),s=pn(i=>i.browserHoles);return m.useLayoutEffect(()=>{const i=n.current;if(!i)return;const{left:r,top:a}=i.getBoundingClientRect(),l=Object.values(s).map(c=>({...c,x:c.x-r,y:c.y-a}));i.style.clipPath=b1(l)??""},[s]),o.jsxs(o.Fragment,{children:[e&&o.jsx("div",{"aria-hidden":!0,className:q("pointer-events-none absolute inset-x-0 top-[44px] bottom-0 shadow-surface",t?"rounded-[10px]":"rounded-r-[10px]"),style:t?void 0:{clipPath:"inset(-24px -24px -24px 0)"}}),o.jsx("div",{ref:n,"aria-hidden":!0,className:q("pointer-events-none absolute inset-x-0 bottom-0 bg-background",e?q("top-[44px]",t?"rounded-[10px]":"rounded-r-[10px]"):"top-0")})]})}function av(){return tr()&&ie.persist.hasHydrated()&&xe.persist.hasHydrated()}function uC(e,t){av()&&e>0&&(async()=>(t&&await ie.getState().refreshWorktreeStatuses(),await ie.getState().autoArchiveStaleConversations()))()}function hC(e){!av()||!(e>0)||ie.getState().autoDeleteStaleArchived()}function Wse(){const e=xe(s=>s.autoArchiveIdleDays),t=xe(s=>s.autoArchiveMergedWorktrees),n=xe(s=>s.autoDeleteArchivedDays);m.useEffect(()=>{if(av()){uC(e,t),hC(n);return}const s=()=>{uC(e,t),hC(n)},i=[ie.persist.onFinishHydration(s),xe.persist.onFinishHydration(s)];return()=>{for(const r of i)r()}},[e,t,n])}function Use(){const e=xe(i=>i.backgroundImageEnabled),t=xe(i=>i.backgroundOpacity),n=xe(i=>i.backgroundComposerOpacity),s=xe(i=>i.backgroundCodeOpacity);m.useEffect(()=>{const i=document.documentElement,r=()=>{i.classList.remove("bg-image-enabled"),i.style.removeProperty("--bg-panel-alpha"),i.style.removeProperty("--bg-popover-alpha"),i.style.removeProperty("--bg-border-alpha"),i.style.removeProperty("--bg-code-alpha"),i.style.removeProperty("--bg-composer-alpha")};if(!e){r();return}const a=Math.min(1,Math.max(0,1-t));return i.classList.add("bg-image-enabled"),i.style.setProperty("--bg-panel-alpha",String(a)),i.style.setProperty("--bg-popover-alpha",String(Math.max(a,.92))),i.style.setProperty("--bg-border-alpha",String(Math.min(1,a+.25))),i.style.setProperty("--bg-code-alpha",String(s)),i.style.setProperty("--bg-composer-alpha",String(n)),r},[e,t,n,s])}function Kse(){const e=ie(t=>Math.min(999,dL(t.order,Rx(t.conversations))));m.useEffect(()=>{window.electronAPI.app.setBadgeCount(e)},[e])}function qse(){const e=xe(n=>n.generationStallTimeoutMin),{t}=te();m.useEffect(()=>{if(e<=0)return;const n=new Set,s=new Set,i=new Map,r=setInterval(()=>{if(!tr())return;const a=e*6e4,l=Date.now(),c=ie.getState();for(const d of Object.values(c.conversations)){d.status==="running"&&d.lastOutputAt&&i.delete(d.id);const u=(d.coworkerIds??[]).some(p=>!!c.conversations[p]?.spawning),h=uL({shouldAbort:hL({status:d.status,spawning:d.spawning,lastOutputAt:mL(d,c.conversations),now:l,timeoutMs:a,hasLiveWork:pL({...fL(d),spawningCoworker:u})}),status:d.status,spawning:d.spawning,pendingRetry:s.has(d.id),attempts:i.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)}),We(pC(d,t("No output for {{minutes}} minutes — retrying",{minutes:e})));continue}if(h==="retry"){s.delete(d.id),i.set(d.id,(i.get(d.id)??0)+1),c.retry(d.id);continue}h==="give-up"&&(s.delete(d.id),i.delete(d.id),We(pC(d,t("Stopped after repeated stalls"))))}},1e3);return()=>clearInterval(r)},[e,t])}function pC(e,t){const n=(e.coworkerName||e.title).split(`
116
- `)[0].trim();return n?{type:"warning",title:n,description:t}:{type:"warning",title:t}}const fC="enso-win",fP="enso-win-flush",cd="enso-win-pending",mC="enso-win-native";function Yse(e,t,n){return{maximized:n.maximized?e.maximized:t.maximized,fullscreen:n.fullscreen?e.fullscreen:t.fullscreen}}function Xse(e,t){return e||t}function Jse(e,t){document.documentElement.classList.toggle(fP,Xse(e,t))}function Zse(){m.useEffect(()=>{if(window.electronAPI?.env.platform!=="win32")return;const e=document.documentElement;e.classList.add(fC,cd),e.classList.add(mC);let t={maximized:!1,fullscreen:!1};const n={maximized:0,fullscreen:0};let s=!1,i=0,r;const a=()=>Jse(t.maximized,t.fullscreen),l=window.electronAPI.window,c=()=>{const p=++i,f={...n};Promise.all([l.isMaximized(),l.isFullScreen()]).then(([x,g])=>{s||p!==i||(t=Yse(t,{maximized:x,fullscreen:g},{maximized:n.maximized!==f.maximized,fullscreen:n.fullscreen!==f.fullscreen}),e.classList.remove(cd),a())}).catch(()=>{!s&&p===i&&e.classList.remove(cd)})};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(fC,fP,cd,mC)}},[])}function Qse(e,t){const n=new Set,s=[];for(const i of e)for(const r of i.interceptBreakers??[]){const a=`${i.id}:${r.event}:${r.until}`;n.add(a),t.has(a)||s.push({pluginName:i.name,event:r.event})}t.clear();for(const i of n)t.add(i);return s}function gC(e){const t=e.permissions.includes("composer.draft")?"1":"0";return`${e.id}\0${e.version}\0${e.build}\0${e.renderer??""}\0${t}`}async function eie(e,t,n,s){if(!s())return;const i=new Map;for(const a of t)a.state==="enabled"&&a.renderer&&i.set(a.id,{...a,renderer:a.renderer});const r=[];for(const[a,l]of e){const c=i.get(a);(!c||gC(c)!==l.key)&&r.push(a)}for(const a of r)e.get(a)?.dispose(),e.delete(a);await Promise.allSettled([...i.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=gC(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 Ar=(e,t)=>({ok:!1,code:e,error:t});async function tie(e,t){if(e.op==="focusSession"){const r=e.payload.sessionId,a=typeof r=="string"?t.conversation(r):null;return typeof r!="string"||!a?Ar("NOT_FOUND","会话不在本窗口"):(t.focus(a.parentId??r,r),{ok:!0,value:null})}if(e.op==="ensureSession"){const r=t.conversation(e.sessionId);if(!r)return Ar("NOT_FOUND","会话不在本窗口");if(r.parentId)return Ar("UNSUPPORTED","子会话随主会话恢复");const a=await t.ensure(e.sessionId);return a?Ar("SESSION_FAILED",a):{ok:!0,value:null}}const n=t.conversation(e.sessionId);if(!n)return Ar("NO_SESSION","发起调用的会话不在本窗口");const s=await t.create(n.projectId);if(!s)return Ar("CREATE_FAILED","新建会话失败");const i=e.payload.text;return typeof i=="string"&&i&&t.prefill(s,i),{ok:!0,value:{sessionId:s}}}const nie={conversation:e=>ie.getState().conversations[e]??null,focus:(e,t)=>{const n=ie.getState();n.selectConversation(e),t!==e&&n.selectTab(e,t)},create:e=>ie.getState().newConversation(e),prefill:vL,ensure:async e=>{const t=ie.getState(),n=t.conversations[e];if(n?.started||n?.spawning)return null;await t.resumeConversation(e,{fresh:!0});const s=ie.getState().conversations[e];return s?.started||s?.spawning?null:s?.error??"无法启动会话:请检查默认模型与登录状态"}};function sie(){return m.useEffect(()=>{const e=wL(()=>OY(ie.getState()));let t=0;const n=new Map,s=new Set,i=()=>{const l=++t;window.electronAPI.extensionPlugins.list().then(async c=>{if(l!==t)return;for(const{pluginName:u,event:h}of Qse(c,s))We({type:"warning",title:`插件 ${u} 的检查连续失败,已临时放行`,description:`${h} 事件 30 秒内不再经过该插件;详情见设置里的插件日志`});const d=c.filter(u=>u.state==="enabled");xL(Object.fromEntries(c.flatMap(u=>u.icon?[[u.id,u.icon]]:[]))),Ly(d.flatMap(u=>WY(u.commands,u.dynamicCommands).map(h=>({pluginId:u.id,pluginName:u.name,...h})))),Hv(d.flatMap(u=>u.views.map(h=>({pluginId:u.id,pluginName:u.name,...h})))),Gy(d.flatMap(u=>u.triggers.filter(h=>h.symbol==="#").map(h=>({pluginId:u.id,name:h.name})))),await eie(n,c,u=>bL(u.id,u.renderer,e,{draft:u.permissions.includes("composer.draft")}),()=>l===t)})};i();const r=window.electronAPI.extensionPlugins.onChanged(i),a=window.electronAPI.extensionPlugins.onDraftRequest(l=>{if(l.op==="focusSession"||l.op==="createSession"||l.op==="ensureSession"){tie(l,nie).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,...gL(l)})});return()=>{t+=1,r(),a(),Ly([]),Gy([]),Hv([]);for(const l of n.values())l.dispose();n.clear()}},[]),null}function iie(e,t=[]){return JSON.stringify({pinnedOrder:t,entries:e.map(n=>{const{updatedAt:s,...i}=n;return i})})}function oie(e){return JSON.stringify(e)}function rie(e,t,n=[]){const s=yL(e,t).map(r=>({id:r.id,name:r.name,models:r.models.map(a=>({id:a.id,...a.label?{label:a.label}:{}}))})),i=n.filter(r=>r.enabled&&s.some(a=>a.id===r.primary.providerId&&a.models.some(l=>l.id===r.primary.modelId)));return i.length>0&&s.unshift({id:Lk,name:"Auto",models:i.map(r=>({id:r.id,label:r.name}))}),s}function aie(e,t,n=[]){const s=rie(e,t,n),i=t.availability.status,r=i==="unloaded"||i==="loading",a=e.some(l=>l.enabled&&l.oauthAccountKey);return{entries:s,settled:!(r&&a&&s.length===0)}}const lie=300;let dd=null,xC=!1,Om=null;function cie(){const e=xe.getState(),t=ie.getState(),n=Vx(e.projects,rr(Rd)),s=new Set(e.projects.filter(b=>b.kind==="scratch").map(b=>b.id)),i=n.filter(b=>b.kind!=="scratch"),r=new Set(rr(qa)),a=kL(_L(e.language),"Temporary chats"),l=new Map(e.projects.map(b=>[b.id,b.kind==="scratch"?a:jo(b)])),c=new Map(e.projects.map(b=>[b.id,b.path])),d=new Map(e.projects.map(b=>[b.id,b.kind])),u=b=>{const _=(b.parentId?t.conversations[b.parentId]:void 0)??b;return d.get(_.projectId)==="scratch"?lg({kind:"scratch",canonicalPath:c.get(_.projectId)??"",conversationId:_.id})??void 0:_.worktree?.path??c.get(b.projectId)},h=e.skills.filter(b=>b.enabled!==!1).map(b=>({name:`/skill:${b.name}`,description:b.description})),p=b=>{const _=_I(b.occupancy,b.contextWindow);return{id:b.id,title:b.parentId&&b.coworkerName||b.title,projectName:l.get(b.projectId)??"",projectId:b.projectId,...u(b)?{cwd:u(b)}:{},status:b.spawning?"running":b.status,updatedAt:n_(b),...b.parentId?{parentId:b.parentId}:{},...b.pinned===!0?{pinned:!0}:{},...b.archived===!0?{archived:!0}:{},...b.lastProviderId?{providerId:b.lastProviderId}:{},...b.lastModelId?{modelId:b.lastModelId}:{},...b.reasoningEnabled!==void 0?{reasoningEnabled:b.reasoningEnabled}:{},...b.thinkingLevel?{thinkingLevel:b.thinkingLevel}:{},...b.unread===!0?{unread:!0}:{},...b.pendingAsks&&b.pendingAsks.length>0?{pendingAskCount:b.pendingAsks.length}:{},...b.pendingApprovals&&b.pendingApprovals.length>0?{pendingApprovalCount:b.pendingApprovals.length}:{},...b.queuedMessages?.length?{queued:b.queuedMessages.map(j=>({id:j.id,text:j.text,...j.images?.length?{hasImages:!0}:{}}))}:{},...b.goal?{goal:{text:b.goal.text,status:b.goal.status,...b.goal.note?{note:b.goal.note}:{},autoTurns:b.goal.autoTurns}}:{},...h.length?{slashCommands:h}:{},..._?{context:_}:{},...b.usageTotals?{usageTotals:b.usageTotals}:{}}},f=t.order.map(b=>t.conversations[b]).filter(b=>!!b),x=new Set(t.order),g=Object.values(t.conversations).filter(b=>!!(b?.parentId&&x.has(b.parentId))),v=[...f,...g].map(p),w=e.scratchSessionsEnabled?v:v.filter(b=>!s.has(b.projectId)),y=aie(e_(),Ao.getState().snapshot,e.virtualModels);return{catalog:w,pinnedOrder:rr(wm),projects:i.map(b=>({...UZ(b),...r.has(b.id)?{archived:!0}:{}})),projectGroups:e.projectGroups,providers:y.entries,providersSettled:y.settled,projectPaths:e.projects.map(b=>({id:b.id,path:b.path})),theme:e.theme,terminal:Eu(e.terminalTheme),terminalFontFamily:e.terminalFontFamily,compactReadOnlyTools:e.compactReadOnlyTools,expandLiveEdits:e.expandLiveEdits,expandLiveReasoning:e.expandLiveReasoning,autoCollapseTurns:e.autoCollapseTurns,collapseCompletedActivity:e.collapseCompletedActivity,pinUnfinishedTodos:e.pinUnfinishedTodos}}function die(e){return oie({catalog:iie(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,pinUnfinishedTodos:e.pinUnfinishedTodos})}function uie(){return ie.persist.hasHydrated()&&xe.persist.hasHydrated()}function Xi(){dd&&clearTimeout(dd),dd=setTimeout(()=>{if(dd=null,!tr()||!uie())return;const e=cie(),t=die(e);t!==Om&&(Om=t,window.electronAPI.pair.pushCatalog(e))},lie)}function hie(){xC||(xC=!0,Xi(),ie.persist.onFinishHydration(Xi),xe.persist.onFinishHydration(Xi),ie.subscribe((e,t)=>{(e.conversations!==t.conversations||e.order!==t.order)&&Xi()}),Ao.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Xi()}),SL.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Xi()}),xe.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.pinUnfinishedTodos!==t.pinUnfinishedTodos||e.skills!==t.skills)&&Xi()}),DZ(Xi),CL(e=>{e&&(Om=null,Xi())}),window.electronAPI.pair.onResumeSession(e=>{Bv(e),tr()&&(ie.getState().markConversationRead(e),ie.getState().resumeConversation(e))}),window.electronAPI.pair.onSessionCreated(e=>{Bv(e.sessionId),tr()&&ie.getState().adoptPairSession(e)}),window.electronAPI.pair.onSessionConfig(e=>{if(!tr())return;const t=ie.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(!tr())return;const t=ie.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 pie=3e4;async function fie(e,t=Date.now()){const{order:n,conversations:s,activeId:i}=ie.getState(),r=n.flatMap(u=>{const h=s[u];return!h||h.parentId?[]:(u===i||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:n_(h)}]}),a=jL(r,e,t),l=ie.getState();for(const u of a)l.removeConversation(u);const c=Date.now()+pie,d=()=>a.filter(u=>ie.getState().conversations[u]);for(;d().length>0&&Date.now()<c;)await new Promise(u=>setTimeout(u,200));return a.length-d().length}const mie=e=>{const t=hO(e);return t.length>0?t:a_(e)},vC="enso-sidebar-width",bC="enso-sidebar-collapsed";function Up(){const e=ie.getState(),n=(e.activeId?e.conversations[e.activeId]:null)?.projectId??xe.getState().projects[0]?.id;n&&e.newConversation(n)}const ud="no-drag flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",wC=200,yC=420;function gie(){const e=xe(z=>z.onboarded),t=m.useSyncExternalStore(z=>xe.persist?.onFinishHydration?.(z)??(()=>{}),()=>xe.persist?.hasHydrated?.()??!0);Use(),qse(),Wse(),Kse();const[n,s]=m.useState(!1),[i,r]=m.useState(null);Zse();const[a,l]=m.useState(()=>{const z=Number(localStorage.getItem(vC));return Number.isFinite(z)&&z>=wC?Math.min(z,yC):280}),[c,d]=m.useState(()=>localStorage.getItem(bC)==="1"),u=fa(),h=NL(),[p,f]=m.useState(!1),x=m.useCallback(()=>f(!1),[]);m.useEffect(()=>{u||f(!1)},[u]),m.useEffect(()=>ie.subscribe((z,ue)=>{z.activeId!==ue.activeId&&f(!1)}),[]);const{t:g}=te(),v=xe(z=>z.chatWide),w=ie(z=>z.activeId),y=pn(z=>w?!!z.uiByConversation[w]?.open:!1),b=pn(z=>z.uiByConversation[w??""]?.width??z.lastWidth),_=pn(z=>z.fullscreen),j=pn(z=>z.toggleOpen),N=re(z=>z.panelOpen),C=re(z=>z.togglePanel);m.useEffect(()=>{_&&!y&&pn.getState().setFullscreen(!1)},[y,_]),m.useEffect(()=>(document.documentElement.classList.add("enso-main-shell"),()=>document.documentElement.classList.remove("enso-main-shell")),[]),m.useEffect(()=>window.electronAPI.app.onCloseRequest(r),[]),m.useEffect(()=>window.electronAPI.app.onFlushPersist(z=>{TL().finally(()=>{window.electronAPI.app.respondFlushPersist(z)})}),[]);const k=z=>{const ue=i;ue&&(r(null),window.electronAPI.app.respondCloseRequest(ue,{action:z}))},[E,I]=m.useState(!1),T=m.useRef(null);m.useEffect(()=>{localStorage.setItem(vC,String(a))},[a]),m.useEffect(()=>{localStorage.setItem(bC,c?"1":"0")},[c]),m.useEffect(()=>window.electronAPI.window.onAgentComposerPrefill(z=>{ie.getState().prefillAgent(z.typeKey,z.prompt)}),[]),m.useEffect(()=>window.electronAPI.resources.onSessionsCleanRequest(({requestId:z,request:ue})=>{fie(ue).catch(()=>0).then(_e=>window.electronAPI.resources.sessionsCleanDone(z,_e))}),[]),m.useEffect(()=>{hie()},[]),m.useEffect(()=>es.getState().bind(),[]);const A=es(z=>z.activeNodeId),D=A!=="local",W=CY(),J=xe(z=>z.botModeEnabled),O=oo(z=>z.mode);m.useEffect(()=>{const z=xe.persist?.hasHydrated?.()??!0;O==="bot"&&(z&&!J||D)&&oo.getState().setMode("code")},[O,J,D]),m.useEffect(()=>{if(!J)return;const z=re.getState().bind(),ue=window.electronAPI.bots.onEvent(_e=>{_e.kind==="open"&&kY(_e)});return()=>{z(),ue()}},[J]),m.useEffect(()=>window.electronAPI.agent.onFocusSession(z=>{ie.getState().conversations[z]&&_Y()}),[]);const B=m.useCallback(z=>{l(ue=>Math.min(yC,Math.max(wC,ue+z)))},[]),L=xe(z=>z.keybindings);m.useEffect(()=>{const z=Ii(L),ue=Ee=>{const Be=ie.getState(),De=Be.activeId?Be.conversations[Be.activeId]:null;if(!De)return;const Ue=[void 0,...De.coworkerIds??[]];if(Ue.length<=1)return;const St=Ue.indexOf(De.activeTabId);Be.selectTab(De.id,Ue[(St+Ee+Ue.length)%Ue.length])},_e=Ee=>{const Be=Cl(Ee);if(!Be)return;if(Be===z["toggle-app-mode"]){if(!xe.getState().botModeEnabled||es.getState().activeNodeId!=="local")return;Ee.preventDefault();const St=oo.getState();St.setMode(St.mode==="bot"?"code":"bot");return}const De=es.getState().activeNodeId!=="local"||Bc();if(Bc()&&Be===z["toggle-side-panel"]){Ee.preventDefault(),re.getState().togglePanel();return}if(Bc()&&Be===z["search-workspace"]){Ee.preventDefault(),re.getState().setSearchOpen(!0);return}De&&["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(Ue=>Be===z[Ue])||(Be===z["toggle-sidebar"]?(Ee.preventDefault(),AL(window.innerWidth)?f(Ue=>!Ue):d(Ue=>!Ue)):Be===z["open-settings"]?(Ee.preventDefault(),window.electronAPI.window.openSettings()):Be===z["new-conversation"]?(Ee.preventDefault(),Up()):Be===z["new-side-tab"]?(Ee.preventDefault(),ML(Ee.target)?RL():Up()):Be===z["new-btw-tab"]?(Ee.preventDefault(),LL()):Be===z["next-tab"]?(Ee.preventDefault(),ue(1)):Be===z["prev-tab"]?(Ee.preventDefault(),ue(-1)):Be===z["toggle-side-panel"]?(Ee.preventDefault(),pn.getState().toggleOpen()):Be===z["toggle-side-panel-fullscreen"]?(Ee.preventDefault(),pn.getState().toggleFullscreen()):Be===z["close-side-tab"]?(Ee.preventDefault(),OL()):Be===z["focus-composer"]?(Ee.preventDefault(),wr()):Be===z["find-in-chat"]?(Ee.preventDefault(),aI()):Be===z["search-workspace"]&&(Ee.preventDefault(),s(!0)))};return window.addEventListener("keydown",_e),()=>window.removeEventListener("keydown",_e)},[L]),m.useEffect(()=>{if(!y||!_)return;const z=ue=>{ue.key==="Escape"&&es.getState().activeNodeId==="local"&&(Bc()||(ue.preventDefault(),pn.getState().setFullscreen(!1)))};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[y,_]);const se=sO(nO(fg,{activationConstraint:{distance:6}})),Q=Hu(),V=Q!=="mobile"&&!D&&!W,H=m.useCallback(z=>{const ue=T.current;if(!ue)return;const _e=getComputedStyle(ue),Ee=ue.clientWidth-parseFloat(_e.paddingLeft)-parseFloat(_e.paddingRight);pn.getState().nudgeWidth(-z,Ee,V?t_:Qm)},[V]),[ne,he]=m.useState(null),[pe,ke]=m.useState(null);m.useEffect(()=>{const z=ne;if(!z){ke(null);return}const ue=()=>{const Ee=z.getBoundingClientRect();ke(Be=>Be&&Be.left===Ee.left&&Be.right===Ee.right?Be:{left:Ee.left,right:Ee.right})};ue();const _e=new ResizeObserver(ue);return _e.observe(z),window.addEventListener("resize",ue),()=>{_e.disconnect(),window.removeEventListener("resize",ue)}},[ne]);const Me=J&&!D?o.jsx(DY,{}):null,fe=V&&(Q==="mac"||Q==="windows"),F=fe&&y&&!u&&!W&&!D,U=D?null:o.jsx("button",{type:"button",className:q("flex items-center justify-center rounded-md transition-colors hover:bg-accent/50",u?"h-9 w-9":V?ud:"h-7 w-7",(W?N:y)?"text-foreground":"text-muted-foreground"),onClick:W?C:j,"aria-label":g("Toggle side panel"),title:g("Toggle side panel"),children:o.jsx(f1,{className:"h-4 w-4"})}),de=o.jsx("button",{type:"button",className:q("flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-accent/50",v?"text-foreground":"text-muted-foreground",u&&"hidden"),onClick:()=>xe.getState().setChatWide(!v),"aria-label":g(v?"Use reading width":"Use full chat width"),title:g(v?"Use reading width":"Use full chat width"),children:v?o.jsx(mB,{className:"h-4 w-4"}):o.jsx(bV,{className:"h-4 w-4"})}),Y=o.jsxs(o.Fragment,{children:[de,U]}),X=V?{trailing:de}:null;return o.jsxs("div",{"data-enso":"canvas",className:q("relative isolate flex flex-col",u?"h-dvh":"h-screen"),children:[o.jsx(IL,{}),o.jsx(QV,{}),o.jsx(DL,{}),Q!=="mobile"?o.jsx(Vv,{leading:o.jsxs("div",{className:"flex items-center gap-0.5",children:[!D&&o.jsx("div",{className:q(Q!=="mac"&&"flex justify-center",Q!=="mac"&&(V?"w-[48px]":"w-12")),children:o.jsx("button",{type:"button",className:ud,onClick:()=>d(z=>!z),title:g(c?"Expand sidebar":"Collapse sidebar"),children:c?o.jsx(p1,{className:"h-4 w-4"}):o.jsx(Xg,{className:"h-4 w-4"})})}),V&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:ud,onClick:()=>s(!0),title:g("Search anything"),children:o.jsx(Js,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",className:ud,onClick:Up,title:g("New conversation"),children:o.jsx(g1,{className:"h-4 w-4"})})]})]}),centered:(F&&_?null:Me)??void 0,centerOver:V?pe:void 0,className:q(Q!=="mac"&&!D&&"pl-0",V&&"border-b-0",V&&(Q==="windows"?"bg-canvas":"bg-transparent"),V&&Q==="mac"&&"pr-4"),actions:V?F?void 0:U:Y}):o.jsx(Vv,{title:"EnsoCode",centered:Me??void 0,leading:u&&!D&&!W?o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("button",{type:"button",className:"-ml-1.5 flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",onClick:()=>f(!0),"aria-label":g("Conversations"),title:g("Conversations"),children:o.jsx(VB,{className:"h-5 w-5"})}),!Me&&o.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"EnsoCode"})]}):void 0,actions:Y}),!V&&o.jsx(Ib,{}),o.jsx("div",{className:"flex min-h-0 flex-1",children:D?o.jsx(eQ,{nodeId:A,sidebarWidth:a}):W?o.jsx(SY,{sidebarWidth:a,collapsed:c,onToggleCollapse:()=>d(z=>!z),onResize:B}):o.jsxs(i5,{sensors:se,collisionDetection:mie,children:[u?o.jsxs(o.Fragment,{children:[o.jsx(rl,{children:p&&o.jsx(Es.div,{className:"fixed inset-0 bg-black/40",style:{zIndex:yn.MOBILE_DRAWER},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:x},"drawer-backdrop")}),o.jsx(Es.div,{className:"fixed inset-y-0 left-0 flex bg-background shadow-xl",style:{zIndex:yn.MOBILE_DRAWER},initial:!1,animate:{x:p?0:"-105%"},transition:Yr,inert:!p,children:o.jsx(dS,{width:Math.min(320,Math.round(h*.85)),collapsed:!1,onToggleCollapse:x,onOpenSearch:()=>s(!0),onNavigate:x})})]}):o.jsxs(o.Fragment,{children:[o.jsx(dS,{width:c?void 0:a,collapsed:c,onToggleCollapse:()=>d(z=>!z),onOpenSearch:()=>s(!0)}),!c&&o.jsx(cu,{edge:V,onResize:B})]}),o.jsxs("div",{ref:T,className:q("relative flex min-h-0 min-w-0 flex-1",fe?"overflow-x-clip":"overflow-hidden",V&&"-mt-px -ml-px pt-px pr-[8px] pb-[8px] pl-px"),children:[o.jsxs("div",{ref:he,"data-enso":"main",className:q("flex min-h-0 min-w-0 flex-1 flex-col bg-background",V&&"overflow-hidden rounded-[10px] shadow-surface",F&&"rounded-r-none"),style:y&&_?{visibility:"hidden",transition:`visibility 0s ${mu.duration}s`}:void 0,children:[o.jsx(sie,{}),o.jsx(PL.Provider,{value:X,children:o.jsx(YJ,{})}),V&&o.jsx(Ib,{})]}),y&&!_&&!u&&o.jsx(cu,{gap:V&&!F,onResize:H,onResizingChange:I}),o.jsx(Hse,{width:b,resizing:E,card:V,titleRow:fe})]})]})}),t&&!e&&!window.electronAPI.remote&&o.jsx(nQ,{}),o.jsx(_Q,{open:n,onOpenChange:s}),o.jsx(Gk,{open:i!==null,onOpenChange:z=>{!z&&i&&k("cancel")},children:o.jsxs(Fk,{className:"sm:max-w-sm",children:[o.jsxs(Hk,{children:[o.jsx(Bk,{className:"text-base",children:g("Confirm exit")}),o.jsx(Vk,{children:g("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.")})]}),o.jsxs($k,{variant:"bare",children:[o.jsx(EL,{render:o.jsx(le,{variant:"outline",size:"sm"}),children:g("Cancel")}),o.jsx(le,{size:"sm",onClick:()=>k("tray"),children:g("Minimize to tray")}),o.jsx(le,{variant:"destructive",size:"sm",onClick:()=>k("quit"),children:g("Exit")})]})]})})]})}function xie(e){return new Worker(""+new URL("worker-DsKBD11i.js",import.meta.url).href,{type:"module",name:e?.name})}const vie={workerFactory:()=>new xie,poolSize:2},bie={theme:ha,langs:[...GL],preferredHighlighter:"shiki-js"};function wie({children:e}){return o.jsx(zL,{poolOptions:vie,highlighterOptions:bie,children:e})}FL();HL();XC();BL.createRoot(document.getElementById("root")).render(o.jsx(m.StrictMode,{children:o.jsx(wie,{children:o.jsx(gie,{})})}));