@ensocode/server 0.3.7 → 0.3.9

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 (176) hide show
  1. package/out/phone/assets/{abnfDiagram-VCTEODGH-2-rZfXru.js → abnfDiagram-VCTEODGH-CBVQuFGg.js} +1 -1
  2. package/out/phone/assets/architecture-7GRP2DOG-DOA5Bycz.js +1 -0
  3. package/out/phone/assets/{architectureDiagram-5GKGNRK7-vlXme2Q3.js → architectureDiagram-5GKGNRK7-Uwi4Yp3N.js} +1 -1
  4. package/out/phone/assets/{blockDiagram-I7D4REHJ-BD1NeeU7.js → blockDiagram-I7D4REHJ-Dee88kBX.js} +1 -1
  5. package/out/phone/assets/{c4Diagram-7LVT6UL2-BLQd5mqT.js → c4Diagram-7LVT6UL2-CPVctMym.js} +1 -1
  6. package/out/phone/assets/channel-DKcROQS8.js +1 -0
  7. package/out/phone/assets/{chunk-4HAMMTFA-CxF_O9R8.js → chunk-4HAMMTFA-DdHZ8tzu.js} +1 -1
  8. package/out/phone/assets/{chunk-75Z2AOVW-DmshWRC4.js → chunk-75Z2AOVW-CXd1zaQL.js} +1 -1
  9. package/out/phone/assets/{chunk-DU6HZSFF-CZrdwMNN.js → chunk-DU6HZSFF-K72dP1XP.js} +1 -1
  10. package/out/phone/assets/{chunk-F27PBJKO-ColBn-9C.js → chunk-F27PBJKO-JZyoOZLJ.js} +1 -1
  11. package/out/phone/assets/{chunk-GMAD6QVW-CJN3ap1i.js → chunk-GMAD6QVW-O3x_QcGA.js} +1 -1
  12. package/out/phone/assets/{chunk-GVQU2GXP-h3qKgG9R.js → chunk-GVQU2GXP-g5OZYD2B.js} +1 -1
  13. package/out/phone/assets/{chunk-IMKFNOWR-CZRKz_sn.js → chunk-IMKFNOWR-r0ScpN_y.js} +1 -1
  14. package/out/phone/assets/{chunk-L3NEJ4N5-CMO7DEvv.js → chunk-L3NEJ4N5-O-r4RmZJ.js} +1 -1
  15. package/out/phone/assets/{chunk-OSK3NFVY-C5uece6k.js → chunk-OSK3NFVY-ramCCXI9.js} +1 -1
  16. package/out/phone/assets/{chunk-P2QGCYS3-WgQBUDEk.js → chunk-P2QGCYS3-DD3uRJ3h.js} +1 -1
  17. package/out/phone/assets/{chunk-POPQ4Y6H-VHLT_ckM.js → chunk-POPQ4Y6H-RiL5jwG6.js} +1 -1
  18. package/out/phone/assets/{chunk-PWAF6VOD-AIbXljX0.js → chunk-PWAF6VOD-YKF2LrOr.js} +1 -1
  19. package/out/phone/assets/{chunk-SHT3W25Y-Bxg4nJYZ.js → chunk-SHT3W25Y-NK2MDUJG.js} +1 -1
  20. package/out/phone/assets/{chunk-SVP7TREG-C4_nxyeQ.js → chunk-SVP7TREG-7bCZBtZP.js} +1 -1
  21. package/out/phone/assets/{chunk-TICWLB2K-B5wDGVGC.js → chunk-TICWLB2K-DkVtQtfm.js} +1 -1
  22. package/out/phone/assets/classDiagram-ZZMXUADV-CrpQDbmR.js +1 -0
  23. package/out/phone/assets/classDiagram-v2-VYDZK3BY-CrpQDbmR.js +1 -0
  24. package/out/phone/assets/{cynefin-OW5HDTMX-IUYlkNoA.js → cynefin-OW5HDTMX-C3bBDDKw.js} +1 -1
  25. package/out/phone/assets/{cynefinDiagram-5FMLGOSQ-ciimhepC.js → cynefinDiagram-5FMLGOSQ-B1KRMzP2.js} +1 -1
  26. package/out/phone/assets/{dagre-GXQ25YYZ-Dk3tslas.js → dagre-GXQ25YYZ-NLxwj9wy.js} +1 -1
  27. package/out/phone/assets/desk-DfeUjqmj.js +2 -0
  28. package/out/phone/assets/{diagram-S7CK7UJ4-BhDokNwG.js → diagram-S7CK7UJ4-DfcfBkAs.js} +1 -1
  29. package/out/phone/assets/{diagram-UQ7AKVKN-CciyntsZ.js → diagram-UQ7AKVKN-DCvI1s7K.js} +1 -1
  30. package/out/phone/assets/{diagram-VSXAHHWV-BG3YhyOX.js → diagram-VSXAHHWV-Bm1zOS5P.js} +1 -1
  31. package/out/phone/assets/{diagram-VX7I27RA-Wx7x7olQ.js → diagram-VX7I27RA-BQuZufNO.js} +1 -1
  32. package/out/phone/assets/{diagram-Z3DM3KII-CcI8MVzR.js → diagram-Z3DM3KII-DBIMQQh6.js} +1 -1
  33. package/out/phone/assets/{ebnfDiagram-PWID7BFC-Cug1-9Ha.js → ebnfDiagram-PWID7BFC-tVvJnbJ2.js} +1 -1
  34. package/out/phone/assets/{erDiagram-RLTQ6QDP-kjxgMXRS.js → erDiagram-RLTQ6QDP-BSiTfV80.js} +1 -1
  35. package/out/phone/assets/eventmodeling-NTZA5JFV-DiyOQMrF.js +1 -0
  36. package/out/phone/assets/flowDiagram-HODETNUW-_UpaA-So.js +1 -0
  37. package/out/phone/assets/{ganttDiagram-EL5Y4UJY-Ci67p8ni.js → ganttDiagram-EL5Y4UJY-DTQdTWJN.js} +1 -1
  38. package/out/phone/assets/{gitGraph-4MIJSDKK-Bq5w_SFd.js → gitGraph-4MIJSDKK-DP-rU0q-.js} +1 -1
  39. package/out/phone/assets/{gitGraphDiagram-WWUBYQGX-6MPAWIQP.js → gitGraphDiagram-WWUBYQGX-v56Bt0O6.js} +1 -1
  40. package/out/phone/assets/{info-A6RAGUB7-D05oiQx3.js → info-A6RAGUB7-CAQE0Hfy.js} +1 -1
  41. package/out/phone/assets/{infoDiagram-27XIBGKW-DEMR262W.js → infoDiagram-27XIBGKW-CSXtf5Fo.js} +1 -1
  42. package/out/phone/assets/{ishikawaDiagram-5VMMS53U-D54EdxMb.js → ishikawaDiagram-5VMMS53U-CclPV6gG.js} +1 -1
  43. package/out/phone/assets/{journeyDiagram-3NMN7TZE-BIEdfqGB.js → journeyDiagram-3NMN7TZE-BIkpYm1f.js} +1 -1
  44. package/out/phone/assets/{kanban-definition-UXKFOSKX-Ps-NZDsh.js → kanban-definition-UXKFOSKX-yepY9S2l.js} +1 -1
  45. package/out/phone/assets/{line-DGUUioP5.js → line-BeTXpSNc.js} +1 -1
  46. package/out/phone/assets/main-CGpGZfti.css +1 -0
  47. package/out/phone/assets/main-DW3B3ovc.js +1658 -0
  48. package/out/phone/assets/{mermaid-parser.core-BkNZLgza.js → mermaid-parser.core-nw37szCl.js} +3 -3
  49. package/out/phone/assets/{mermaid.core-nEcMItTa.js → mermaid.core-DdSdNZO_.js} +4 -4
  50. package/out/phone/assets/{mindmap-definition-YA3MSWOX-DZvLJVDS.js → mindmap-definition-YA3MSWOX-CiQWyjG5.js} +1 -1
  51. package/out/phone/assets/{packet-AYTQ26CC-BORABWaG.js → packet-AYTQ26CC-MFESxWKw.js} +1 -1
  52. package/out/phone/assets/{pegDiagram-XKGWAZYB-CGyyPNG0.js → pegDiagram-XKGWAZYB-BM9Ofbc8.js} +1 -1
  53. package/out/phone/assets/{pie-WAS4IAKB-DXKTNLO7.js → pie-WAS4IAKB-BX8j-oF_.js} +1 -1
  54. package/out/phone/assets/{pieDiagram-E7YTZNPT-BHlAnBZb.js → pieDiagram-E7YTZNPT-1KLqp5sl.js} +1 -1
  55. package/out/phone/assets/{quadrantDiagram-AXDQQJYC-CYx8zP0Z.js → quadrantDiagram-AXDQQJYC-wqwWQyRe.js} +1 -1
  56. package/out/phone/assets/{radar-RG4KPBEZ-mYzEXGPZ.js → radar-RG4KPBEZ-jaQ0-Att.js} +1 -1
  57. package/out/phone/assets/{railroad-74A4TZTK-BpSoFKZI.js → railroad-74A4TZTK-BBOWTcMX.js} +1 -1
  58. package/out/phone/assets/railroad-abnf-HS5TGJTU-DfD2cpkN.js +1 -0
  59. package/out/phone/assets/railroad-ebnf-LZEXJU2U-BAwl_fDM.js +1 -0
  60. package/out/phone/assets/railroad-peg-WCYAUIDC-MbpAQZum.js +1 -0
  61. package/out/phone/assets/{railroadDiagram-O6MQD6OU-BAlwhvnj.js → railroadDiagram-O6MQD6OU-DJQ-7iWl.js} +1 -1
  62. package/out/phone/assets/{requirementDiagram-BXWQKSXE-C2R7ulaS.js → requirementDiagram-BXWQKSXE-D4dveBtm.js} +1 -1
  63. package/out/phone/assets/{sankeyDiagram-P5KCCOFB-c0sv5hNV.js → sankeyDiagram-P5KCCOFB-Xi3vzQcH.js} +1 -1
  64. package/out/phone/assets/{sequenceDiagram-WJ2MYXX4-Cz6Zq57N.js → sequenceDiagram-WJ2MYXX4-DJu7wXTv.js} +1 -1
  65. package/out/phone/assets/{stateDiagram-D77RDMKH-DZhgDUa6.js → stateDiagram-D77RDMKH-BY7kdvUZ.js} +1 -1
  66. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-DDqCllzv.js +1 -0
  67. package/out/phone/assets/storage-dUWOZ2xo.js +36 -0
  68. package/out/phone/assets/{swimlanes-42K2YHIH-ByNqwNMl.js → swimlanes-42K2YHIH-CIxzAE5G.js} +1 -1
  69. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-Cu8_tU2m.js +8 -0
  70. package/out/phone/assets/{timeline-definition-24CTP7MA-CSFOYvnV.js → timeline-definition-24CTP7MA-e-O3IHwG.js} +1 -1
  71. package/out/phone/assets/{treeView-Q6P3EWNA-CDqEDufz.js → treeView-Q6P3EWNA-Bhtyuzk0.js} +1 -1
  72. package/out/phone/assets/{treemap-WGGIJYW6-DfjCLTFL.js → treemap-WGGIJYW6-B_tM9CqS.js} +1 -1
  73. package/out/phone/assets/{vennDiagram-4TSXK5OY-CjV_vvWy.js → vennDiagram-4TSXK5OY-9npu53KS.js} +1 -1
  74. package/out/phone/assets/{wardley-WFR3VGLG-Df2M8YsO.js → wardley-WFR3VGLG-Dtb3_st-.js} +1 -1
  75. package/out/phone/assets/{wardleyDiagram-VM6X3IG4-B2bcg9of.js → wardleyDiagram-VM6X3IG4-DCBObiQg.js} +1 -1
  76. package/out/phone/assets/{xychartDiagram-S5SC5T6Z-Fq1wBYKM.js → xychartDiagram-S5SC5T6Z-BAHqVoN1.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-DMPmG_xF.js → abnfDiagram-VCTEODGH-ClaZATP-.js} +1 -1
  80. package/out/renderer/assets/{arc-DjMiWCQZ.js → arc-B0Ue52gX.js} +1 -1
  81. package/out/renderer/assets/{architectureDiagram-5GKGNRK7-Dy1W4IYD.js → architectureDiagram-5GKGNRK7-CbmNLvfJ.js} +1 -1
  82. package/out/renderer/assets/{blockDiagram-I7D4REHJ-B8zx5UuN.js → blockDiagram-I7D4REHJ-crBSO4mg.js} +1 -1
  83. package/out/renderer/assets/{c4Diagram-7LVT6UL2-D7MZ3XeI.js → c4Diagram-7LVT6UL2-BhASES00.js} +1 -1
  84. package/out/renderer/assets/channel-DAEAroq1.js +1 -0
  85. package/out/renderer/assets/{chunk-2Q5K7J3B-BEMGeNvl.js → chunk-2Q5K7J3B-CCY1-54C.js} +1 -1
  86. package/out/renderer/assets/{chunk-5VM5RSS4-CTB_kPAW.js → chunk-5VM5RSS4-MmFztUTQ.js} +1 -1
  87. package/out/renderer/assets/{chunk-F27PBJKO-CDc0IpL4.js → chunk-F27PBJKO-CemaMYDJ.js} +1 -1
  88. package/out/renderer/assets/{chunk-IMKFNOWR-5NElfs8W.js → chunk-IMKFNOWR-DctUdkub.js} +1 -1
  89. package/out/renderer/assets/{chunk-JWPE2WC7-DfZ55eH3.js → chunk-JWPE2WC7-DCjmZlft.js} +1 -1
  90. package/out/renderer/assets/{chunk-POPQ4Y6H-BK1Mb8zQ.js → chunk-POPQ4Y6H-D-KxWwr4.js} +1 -1
  91. package/out/renderer/assets/{chunk-SVP7TREG-BTCzRhBg.js → chunk-SVP7TREG-CGc3VMbe.js} +1 -1
  92. package/out/renderer/assets/{chunk-TICWLB2K-BIdRdQio.js → chunk-TICWLB2K-BwI6l28m.js} +1 -1
  93. package/out/renderer/assets/{chunk-XXDRQBXY-xdEJ7eED.js → chunk-XXDRQBXY-C3lgg1-4.js} +1 -1
  94. package/out/renderer/assets/classDiagram-ZZMXUADV-BHNNTKj0.js +1 -0
  95. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-BHNNTKj0.js +1 -0
  96. package/out/renderer/assets/{cose-bilkent-JH36ORCC-Dbeuy5zT.js → cose-bilkent-JH36ORCC-DqGFhKtY.js} +1 -1
  97. package/out/renderer/assets/{cynefin-OW5HDTMX-DYk68iql.js → cynefin-OW5HDTMX-BpknO3Y_.js} +1 -1
  98. package/out/renderer/assets/{cynefinDiagram-5FMLGOSQ-CW9N3zhw.js → cynefinDiagram-5FMLGOSQ-DS1vS0h7.js} +1 -1
  99. package/out/renderer/assets/{cytoscape-fcose-BtmodGyv.js → cytoscape-fcose-DeHY1J1u.js} +1 -1
  100. package/out/renderer/assets/{dagre-GXQ25YYZ-xTaBduGi.js → dagre-GXQ25YYZ-DxScp9AG.js} +1 -1
  101. package/out/renderer/assets/{diagram-S7CK7UJ4-Okomm8Ap.js → diagram-S7CK7UJ4-Djlu9ceY.js} +1 -1
  102. package/out/renderer/assets/{diagram-UQ7AKVKN-CvzlGwuY.js → diagram-UQ7AKVKN-BK3mHHvd.js} +1 -1
  103. package/out/renderer/assets/{diagram-VSXAHHWV-BJtbgGmH.js → diagram-VSXAHHWV-Bg9tDRjc.js} +1 -1
  104. package/out/renderer/assets/{diagram-VX7I27RA-vefJMKYp.js → diagram-VX7I27RA-DrWUeEXG.js} +1 -1
  105. package/out/renderer/assets/{diagram-Z3DM3KII-ChsgoF9h.js → diagram-Z3DM3KII-BxPy8fU9.js} +1 -1
  106. package/out/renderer/assets/{ebnfDiagram-PWID7BFC-D9X9DUcr.js → ebnfDiagram-PWID7BFC-BWqMH4I8.js} +1 -1
  107. package/out/renderer/assets/{erDiagram-RLTQ6QDP-C024iQV7.js → erDiagram-RLTQ6QDP-DTdklRgf.js} +1 -1
  108. package/out/renderer/assets/{flowDiagram-HODETNUW-CPVYCBuI.js → flowDiagram-HODETNUW-BKIZ7ju6.js} +1 -1
  109. package/out/renderer/assets/{ganttDiagram-EL5Y4UJY-C65Z220Q.js → ganttDiagram-EL5Y4UJY-BxvJsq6b.js} +1 -1
  110. package/out/renderer/assets/{gitGraphDiagram-WWUBYQGX-B2ZCfyVT.js → gitGraphDiagram-WWUBYQGX-CKYXaYvq.js} +1 -1
  111. package/out/renderer/assets/globals-DoK2OLv9.css +1 -0
  112. package/out/renderer/assets/globals-kfeSrZZh.js +2603 -0
  113. package/out/renderer/assets/{index-B49rZgqC.css → index-F_0FxVZ_.css} +1 -1
  114. package/out/renderer/assets/index-oWFcXlIg.js +133 -0
  115. package/out/renderer/assets/{infoDiagram-27XIBGKW-D7RgOT5Z.js → infoDiagram-27XIBGKW-B79kbTEz.js} +1 -1
  116. package/out/renderer/assets/{ishikawaDiagram-5VMMS53U-CEyzfHnV.js → ishikawaDiagram-5VMMS53U-7A2txHe5.js} +1 -1
  117. package/out/renderer/assets/{journeyDiagram-3NMN7TZE-C1GjLzvL.js → journeyDiagram-3NMN7TZE-JNKKQMwS.js} +1 -1
  118. package/out/renderer/assets/{kanban-definition-UXKFOSKX-umALrvd6.js → kanban-definition-UXKFOSKX-dK6zSfqM.js} +1 -1
  119. package/out/renderer/assets/{layout-CPiirD-6.js → layout-MfkXYuHA.js} +1 -1
  120. package/out/renderer/assets/{linear-DeKsEgmD.js → linear-DUiegqFS.js} +1 -1
  121. package/out/renderer/assets/{mermaid.core-upLR8Tou.js → mermaid.core-Dn6T9UVK.js} +5 -5
  122. package/out/renderer/assets/{mindmap-definition-YA3MSWOX-CDpc91To.js → mindmap-definition-YA3MSWOX-Du0yA8rg.js} +1 -1
  123. package/out/renderer/assets/{pegDiagram-XKGWAZYB-ZWCzr3Tm.js → pegDiagram-XKGWAZYB-DaRtM-Te.js} +1 -1
  124. package/out/renderer/assets/{pieDiagram-E7YTZNPT-Cli5NL_V.js → pieDiagram-E7YTZNPT-Bsf9CqyI.js} +1 -1
  125. package/out/renderer/assets/{quadrantDiagram-AXDQQJYC-DyHSkgko.js → quadrantDiagram-AXDQQJYC-Diojakd2.js} +1 -1
  126. package/out/renderer/assets/{railroadDiagram-O6MQD6OU-BifUAJjm.js → railroadDiagram-O6MQD6OU-BMREAMLm.js} +1 -1
  127. package/out/renderer/assets/{requirementDiagram-BXWQKSXE-4vjbe8oI.js → requirementDiagram-BXWQKSXE-KYN9y0mn.js} +1 -1
  128. package/out/renderer/assets/{sankeyDiagram-P5KCCOFB-BDHiusDD.js → sankeyDiagram-P5KCCOFB-BOarV1lP.js} +1 -1
  129. package/out/renderer/assets/{sequenceDiagram-WJ2MYXX4-CfTMNjuO.js → sequenceDiagram-WJ2MYXX4-CLvIIq-e.js} +1 -1
  130. package/out/renderer/assets/settings-C1ake4C5.js +27 -0
  131. package/out/renderer/assets/{sizeCapture-INFHLROL-BInsctow.js → sizeCapture-INFHLROL-BZp_C1e1.js} +1 -1
  132. package/out/renderer/assets/{stateDiagram-D77RDMKH-3R4s4xE6.js → stateDiagram-D77RDMKH-CZYezuvN.js} +1 -1
  133. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-BZR_zNTR.js +1 -0
  134. package/out/renderer/assets/{swimlanes-42K2YHIH-CHnfm1qW.js → swimlanes-42K2YHIH-BzLF-RZ8.js} +1 -1
  135. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-CguqA7f1.js +8 -0
  136. package/out/renderer/assets/{timeline-definition-24CTP7MA-BSOSQ438.js → timeline-definition-24CTP7MA-uG42f1oC.js} +1 -1
  137. package/out/renderer/assets/{vennDiagram-4TSXK5OY-Bw_mOynV.js → vennDiagram-4TSXK5OY-DTog5Yh9.js} +1 -1
  138. package/out/renderer/assets/{wardleyDiagram-VM6X3IG4-DZF4RS4h.js → wardleyDiagram-VM6X3IG4-BgQ7fmC4.js} +1 -1
  139. package/out/renderer/assets/{xychartDiagram-S5SC5T6Z-DwVUcf5G.js → xychartDiagram-S5SC5T6Z-BerG1RDT.js} +1 -1
  140. package/out/renderer/index.html +4 -4
  141. package/out/renderer/settings.html +4 -4
  142. package/out/renderer/web-preload.js +51 -1
  143. package/out/server/agent.js +1831 -355
  144. package/out/server/chunks/{agent-BlAuVqNp.js → agent-BbLTL3oo.js} +760 -191
  145. package/out/server/chunks/conversationsMove-CJZfkj55.js +57 -0
  146. package/out/server/chunks/{gpuBackendInstall-C0fP_8jk.js → gpuBackendInstall-DUOvnlWd.js} +5 -5
  147. package/out/server/chunks/{loadProvider-1NxA7GHt.js → loadProvider-79AJEjnd.js} +2 -2
  148. package/out/server/chunks/{manifest-CojWIAHB.js → manifest-DjsZzZuh.js} +63 -6
  149. package/out/server/chunks/{workflowPresets-COTLnY4e.js → workflowPresets-Di8u79iQ.js} +761 -298
  150. package/out/server/index.js +56416 -39536
  151. package/out/server/plugin-host.js +110 -3
  152. package/package.json +1 -1
  153. package/out/phone/assets/architecture-7GRP2DOG-yfAdIxfu.js +0 -1
  154. package/out/phone/assets/channel-D8BkMJGk.js +0 -1
  155. package/out/phone/assets/classDiagram-ZZMXUADV-CIHzXafb.js +0 -1
  156. package/out/phone/assets/classDiagram-v2-VYDZK3BY-CIHzXafb.js +0 -1
  157. package/out/phone/assets/desk-9dPB4fYu.js +0 -2
  158. package/out/phone/assets/eventmodeling-NTZA5JFV-CTu3xjKC.js +0 -1
  159. package/out/phone/assets/flowDiagram-HODETNUW-EMW1nWtZ.js +0 -1
  160. package/out/phone/assets/main-DYdpq0Gx.css +0 -1
  161. package/out/phone/assets/main-Do_3fZm7.js +0 -1643
  162. package/out/phone/assets/railroad-abnf-HS5TGJTU-C8SKwwnT.js +0 -1
  163. package/out/phone/assets/railroad-ebnf-LZEXJU2U-RhLt9QbJ.js +0 -1
  164. package/out/phone/assets/railroad-peg-WCYAUIDC-_H7Uu52_.js +0 -1
  165. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-nNiD0itH.js +0 -1
  166. package/out/phone/assets/storage-p-WxHA1h.js +0 -1
  167. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-Dz8lzRW1.js +0 -8
  168. package/out/renderer/assets/channel-BCPz1zGb.js +0 -1
  169. package/out/renderer/assets/classDiagram-ZZMXUADV-D5itFA4H.js +0 -1
  170. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-D5itFA4H.js +0 -1
  171. package/out/renderer/assets/globals-B4auqknW.js +0 -2539
  172. package/out/renderer/assets/globals-biae1A0_.css +0 -1
  173. package/out/renderer/assets/index-XLAcGpdw.js +0 -117
  174. package/out/renderer/assets/settings-B1-ZqHbd.js +0 -34
  175. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-DqJbnbM3.js +0 -1
  176. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-Gz8US82e.js +0 -8
@@ -1,117 +0,0 @@
1
- import{r as m,eP as _e,eQ as qs,j as i,c as rt,eR as u0,eS as h0,eT as _A,eU as Zk,eV as NA,bi as Qk,q as we,eW as fn,eX as op,eY as Mf,eZ as TA,e_ as IA,p as ne,e as W,cT as Qu,e$ as Lg,dq as ie,cO as ti,bt as as,f0 as eh,f1 as DA,f2 as Qr,cA as os,f3 as ue,f4 as EA,f5 as Og,Z as yn,J as ze,dj as ej,au as cc,X as dn,aQ as PA,d2 as tj,cj as Uo,aB as ca,f6 as AA,f7 as MA,f8 as nj,cm as p0,bd as un,f9 as sj,cn as Sa,bQ as da,dv as ko,fa as RA,ax as zg,fb as Gg,fc as LA,fd as OA,fe as zA,ff as GA,fg as Ml,fh as Ca,fi as mo,fj as FA,fk as HA,fl as BA,fm as vs,fn as Ed,fo as VA,fp as $A,fq as Rl,fr as Ll,fs as Li,ft as rp,fu as WA,fv as Pd,fw as Pr,fx as UA,fy as KA,fz as qA,fA as YA,fB as XA,fC as JA,fD as ap,fE as Ur,fF as f0,fG as ij,fH as m0,fI as ZA,fJ as QA,fK as ea,fL as eM,fM as ci,fN as tM,fO as hr,fP as oj,fQ as g0,fR as ua,fS as nM,fT as Lc,fU as sM,fV as iM,fW as oM,fX as rM,fY as x0,fZ as rj,f_ as Rf,f$ as aM,g0 as lM,g1 as aj,g2 as cM,g3 as v0,g4 as lj,g5 as dM,g6 as uM,g7 as Lf,g8 as hM,g9 as cj,ga as pM,gb as fM,gc as mM,gd as gM,ge as xM,gf as b0,gg as vM,gh as bM,gi as wM,gj as w0,gk as lp,gl as yM,gm as SM,gn as CM,go as dj,gp as Br,gq as nl,gr as ur,gs as uj,gt as cp,gu as Of,gv as kM,gw as th,gx as jM,gy as _M,gz as NM,gA as Oa,gB as TM,gC as IM,gD as DM,gE as hj,gF as EM,gG as PM,gH as AM,gI as MM,gJ as RM,gK as pj,gL as fj,gM as ro,gN as LM,gO as OM,gP as y0,gQ as zM,gR as nh,gS as mj,cW as ha,cU as dc,cV as ka,bu as pa,eA as Ws,$ as uc,gT as GM,gU as FM,gV as HM,gW as BM,gX as VM,gY as $M,gZ as WM,g_ as UM,g$ as KM,h0 as qM,h1 as YM,h2 as XM,a5 as Fg,ah as JM,h3 as ZM,h4 as QM,h5 as eR,h6 as tR,h7 as nR,h8 as sR,h9 as iR,a6 as gj,ha as oR,hb as rR,hc as aR,hd as lR,b as hc,he as cR,hf as dR,hg as uR,hh as hR,hi as pR,hj as fR,d as mR,hk as gR,hl as xR,hm as vR,hn as bR,dr as wR,ct as xj,eB as sh,ho as yR,cZ as vj,hp as Qn,cz as Yn,bN as ih,e7 as ii,hq as Ts,hr as qn,hs as SR,bb as oh,ba as CR,co as bj,bZ as $n,ht as go,hu as xo,hv as vo,hw as $t,hx as kR,aC as yr,hy as jR,hz as _R,di as rh,ch as wj,bk as Ko,hA as S0,ci as NR,hB as TR,at as Xt,hC as C0,hD as yj,hE as Sj,hF as IR,hG as DR,hH as Cj,hI as ER,hJ as PR,hK as AR,hL as MR,hM as RR,hN as LR,hO as OR,hP as zR,hQ as GR,hR as FR,hS as HR,hT as Oc,hU as vi,hV as bi,hW as wi,aR as gs,hX as BR,hY as VR,hZ as $R,h_ as WR,h$ as k0,bP as UR,i0 as KR,i1 as kj,i2 as qR,cp as Hg,i3 as YR,i4 as jj,i5 as XR,cH as jo,s as xn,i6 as JR,v as vn,x as bn,y as wn,E as An,i7 as j0,i8 as ZR,i9 as QR,eD as _j,ia as e2,ib as t2,ic as n2,B as me,id as ah,ew as mi,b4 as zf,em as _0,bJ as Bg,bf as za,bj as oi,dg as Nj,ie as s2,ig as Tj,ih as i2,ii as o2,ij as r2,ik as a2,il as Gf,im as Ij,io as l2,ip as c2,bv as Vs,iq as d2,ir as u2,is as h2,it as p2,iu as f2,iv as m2,iw as g2,ix as Dj,iy as N0,iz as T0,iA as x2,iB as I0,iC as Ff,iD as Hf,iE as Kr,iF as v2,iG as b2,iH as w2,iI as D0,iJ as y2,iK as S2,iL as C2,iM as E0,iN as k2,iO as dp,iP as up,iQ as j2,df as pc,el as Ej,iR as fc,iS as mc,bM as $s,iT as _2,iU as N2,iV as T2,iW as I2,iX as D2,iY as E2,iZ as P2,cl as bo,i_ as A2,i$ as Pj,j0 as M2,j1 as nu,j2 as Aj,j3 as su,ei as R2,j4 as L2,ey as Mj,de as vr,cQ as Ol,j5 as O2,j6 as Rj,j7 as P0,cJ as Fi,j8 as z2,j9 as G2,ja as F2,jb as Lj,bI as tn,jc as Oj,jd as H2,je as B2,jf as wo,jg as V2,jh as zj,ji as Gj,jj as Fj,jk as zl,jl as $2,jm as W2,jn as U2,jo as Bf,jp as K2,jq as q2,jr as Y2,js as X2,jt as J2,ju as Z2,jv as Q2,jw as eL,jx as tL,jy as nL,z as Rs,bh as sL,G as ls,jz as iL,bX as Yt,bg as Vg,c2 as Hj,aS as pi,I as Zt,jA as A0,jB as M0,jC as R0,F as gc,jD as Gl,cd as hp,eb as pp,c3 as ni,jE as oL,jF as Bj,jG as rL,jH as Cs,jI as aL,ek as $g,O as bs,P as ws,Q as ys,R as Ss,T as rs,bW as Wg,jJ as Vf,jK as $f,jL as Wf,bE as lh,bF as ch,bG as Ps,bH as lo,c1 as Vj,jM as $j,jN as Wj,jO as dl,jP as iu,jQ as Uj,jR as lL,jS as cL,jT as dL,jU as Ug,jV as uL,jW as hL,jX as Kj,d_ as $i,d$ as Wi,e1 as Ui,e5 as mn,jY as qj,jZ as Yj,j_ as Xj,e3 as ja,cr as Kg,j$ as Jj,k0 as dh,k1 as Ns,k2 as Is,b_ as Zj,bT as pL,bU as fL,c4 as mL,k3 as gL,c6 as xL,k4 as vL,k5 as Qj,k6 as bL,k7 as wL,k8 as yL,k9 as SL,ka as e_,kb as CL,kc as kL,kd as jL,ke as Sr,kf as qg,kg as sl,kh as Yg,ki as Xg,d7 as uh,d9 as hh,ck as si,d8 as ph,ej as t_,ep as _a,kj as _L,kk as n_,kl as s_,km as NL,kn as ul,av as fh,ko as i_,kp as Jg,kq as o_,cu as Na,kr as r_,ks as TL,db as IL,da as DL,kt as EL,A as PL,ku as AL,kv as ML,n as RL,kw as LL,kx as OL,ky as zL,m as GL,kz as FL,kA as HL,C as BL,f as a_,h as VL,i as $L,k as WL,S as UL,l as KL,o as qL,kB as YL,kC as XL,kD as JL,kE as ZL,kF as QL,kG as e5,kH as l_,cN as di,kI as t5,cq as fa,eF as Uf,kJ as n5,kK as s5,kL as Zg,kM as c_,kN as d_,kO as u_,kP as mh,kQ as i5,kR as o5,kS as r5,bD as h_,bL as rr,bC as a5,kT as l5,kU as p_,kV as Ar,bK as L0,bS as c5,kW as d5,b$ as O0,es as gh,kX as z0,eE as u5,kY as f_,kZ as m_,dP as h5,k_ as g_,k$ as p5,l0 as f5,l1 as m5,l2 as x_,l3 as v_,l4 as Qg,ex as g5,l5 as x5,l6 as v5,l7 as b5,l8 as w5,l9 as fp,la as G0,lb as y5,et as b_,lc as S5,ld as ex,en as C5,cE as Gs,cF as Fs,le as w_,lf as k5,lg as j5,lh as _5,li as N5,lj as T5,ez as ou,lk as I5,ll as D5,lm as E5,ln as P5,lo as y_,lp as A5,lq as M5,cw as R5,lr as L5,dI as S_,ls as tx,lt as O5,dl as C_,lu as z5,lv as F0,lw as G5,lx as F5,d5 as H5,d4 as B5,dh as V5,eC as $5,ly as k_,lz as Kf,aD as j_,aE as __,aF as N_,aG as T_,aH as I_,aI as D_,lA as Ad,lB as E_,er as W5,lC as qf,lD as U5,aK as nx,lE as ru,lF as au,lG as Fl,dG as Yf,lH as K5,lI as q5,lJ as Y5,aN as xh,e9 as H0,e8 as X5,lK as ps,lL as In,lM as Oo,lN as P_,aO as J5,lO as lu,ce as Z5,cD as Q5,lP as eO,lQ as A_,lR as Vr,lS as tO,lT as M_,lU as nO,lV as sO,lW as iO,lX as oO,cy as B0,lY as rO,lZ as R_,l_ as V0,cs as Xf,e0 as sx,l$ as aO,cG as lO,m0 as cO,m1 as dO,m2 as Jf,m3 as uO,b3 as hO,cC as pO,m4 as fO,eo as mO,dx as gO,m5 as xO,dR as vO,dS as bO,cI as wO,m6 as yO,eq as SO,ea as CO,m7 as kO,m8 as jO,m9 as L_,ma as ix,mb as O_,mc as _O,md as NO,me as TO,mf as IO,mg as DO,mh as EO,mi as PO,mj as $0,mk as z_,ml as ox,dk as AO,mm as vh,mn as zc,mo as MO,mp as RO,mq as LO,mr as OO,ms as zO,mt as GO,mu as FO,mv as HO,mw as BO,mx as VO,my as W0,mz as $O,mA as WO,mB as UO,cX as KO,bc as qO,mC as YO,mD as mp,bO as U0,cY as XO,c_ as JO,mE as ZO,mF as QO,mG as K0,mH as ez,mI as tz,mJ as nz,mK as Zf,mL as G_,mM as sz,mN as iz,mO as oz,mP as rz,mQ as F_,mR as az,mS as lz,mT as cz,mU as dz,mV as uz,mW as hz,mX as uo,mY as pz,mZ as fz,m_ as mz,m$ as gz,n0 as xz,n1 as vz,n2 as bz,n3 as q0,n4 as Y0,n5 as wz,cS as yz,n6 as Sz,n7 as Cz,n8 as kz,n9 as jz,na as _z,dy as Nz,nb as Tz,nc as X0,nd as Iz,ne as Dz,nf as H_,e6 as Ez,ng as Pz,nh as Az,ni as Mz,eM as Rz,eN as Lz,eJ as Oz,eO as J0,eK as zz,aJ as Gz,nj as Fz,nk as Hz,nl as Bz,nm as Vz,nn as $z,cP as Wz,no as Uz,np as Kz,eG as qz,eH as Yz,eI as Xz}from"./globals-B4auqknW.js";function Jz(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return m.useMemo(()=>s=>{t.forEach(o=>o(s))},t)}const bh=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Ta(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function rx(e){return"nodeType"in e}function Ds(e){var t,n;return e?Ta(e)?e:rx(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function ax(e){const{Document:t}=Ds(e);return e instanceof t}function xc(e){return Ta(e)?!1:e instanceof Ds(e).HTMLElement}function B_(e){return e instanceof Ds(e).SVGElement}function Ia(e){return e?Ta(e)?e.document:rx(e)?ax(e)?e:xc(e)||B_(e)?e.ownerDocument:document:document:document}const yi=bh?m.useLayoutEffect:m.useEffect;function wh(e){const t=m.useRef(e);return yi(()=>{t.current=e}),m.useCallback(function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];return t.current==null?void 0:t.current(...s)},[])}function Zz(){const e=m.useRef(null),t=m.useCallback((s,o)=>{e.current=setInterval(s,o)},[]),n=m.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Hl(e,t){t===void 0&&(t=[e]);const n=m.useRef(e);return yi(()=>{n.current!==e&&(n.current=e)},t),n}function vc(e,t){const n=m.useRef();return m.useMemo(()=>{const s=e(n.current);return n.current=s,s},[...t])}function cu(e){const t=wh(e),n=m.useRef(null),s=m.useCallback(o=>{o!==n.current&&t?.(o,n.current),n.current=o},[]);return[n,s]}function du(e){const t=m.useRef();return m.useEffect(()=>{t.current=e},[e]),t.current}let gp={};function bc(e,t){return m.useMemo(()=>{if(t)return t;const n=gp[e]==null?0:gp[e]+1;return gp[e]=n,e+"-"+n},[e,t])}function V_(e){return function(t){for(var n=arguments.length,s=new Array(n>1?n-1:0),o=1;o<n;o++)s[o-1]=arguments[o];return s.reduce((r,a)=>{const l=Object.entries(a);for(const[c,d]of l){const u=r[c];u!=null&&(r[c]=u+e*d)}return r},{...t})}}const ta=V_(1),uu=V_(-1);function Qz(e){return"clientX"in e&&"clientY"in e}function yh(e){if(!e)return!1;const{KeyboardEvent:t}=Ds(e.target);return t&&e instanceof t}function e3(e){if(!e)return!1;const{TouchEvent:t}=Ds(e.target);return t&&e instanceof t}function hu(e){if(e3(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 Qz(e)?{x:e.clientX,y:e.clientY}:null}const Bi=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[Bi.Translate.toString(e),Bi.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:s}=e;return t+" "+n+"ms "+s}}}),Z0="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function t3(e){return e.matches(Z0)?e:e.querySelector(Z0)}const n3={display:"none"};function s3(e){let{id:t,value:n}=e;return _e.createElement("div",{id:t,style:n3},n)}function i3(e){let{id:t,announcement:n,ariaLiveType:s="assertive"}=e;const o={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return _e.createElement("div",{id:t,style:o,role:"status","aria-live":s,"aria-atomic":!0},n)}function o3(){const[e,t]=m.useState("");return{announce:m.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const $_=m.createContext(null);function W_(e){const t=m.useContext($_);m.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function r3(){const[e]=m.useState(()=>new Set),t=m.useCallback(s=>(e.add(s),()=>e.delete(s)),[e]);return[m.useCallback(s=>{let{type:o,event:r}=s;e.forEach(a=>{var l;return(l=a[o])==null?void 0:l.call(a,r)})},[e]),t]}const a3={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
- `},l3={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 c3(e){let{announcements:t=l3,container:n,hiddenTextDescribedById:s,screenReaderInstructions:o=a3}=e;const{announce:r,announcement:a}=o3(),l=bc("DndLiveRegion"),[c,d]=m.useState(!1);if(m.useEffect(()=>{d(!0)},[]),W_(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=_e.createElement(_e.Fragment,null,_e.createElement(s3,{id:s,value:o.draggable}),_e.createElement(i3,{id:l,announcement:a}));return n?qs.createPortal(u,n):u}var es;(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"})(es||(es={}));function pu(){}function d3(e,t){return m.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function u3(){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 Si=Object.freeze({x:0,y:0});function h3(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function p3(e,t){const n=hu(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 f3(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return n-s}function m3(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return s-n}function g3(e){let{left:t,top:n,height:s,width:o}=e;return[{x:t,y:n},{x:t+o,y:n},{x:t,y:n+s},{x:t+o,y:n+s}]}function x3(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function v3(e,t){const n=Math.max(t.top,e.top),s=Math.max(t.left,e.left),o=Math.min(t.left+t.width,e.left+e.width),r=Math.min(t.top+t.height,e.top+e.height),a=o-s,l=r-n;if(s<o&&n<r){const c=t.width*t.height,d=e.width*e.height,u=a*l,h=u/(c+d-u);return Number(h.toFixed(4))}return 0}const U_=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:s}=e;const o=[];for(const r of s){const{id:a}=r,l=n.get(a);if(l){const c=v3(l,t);c>0&&o.push({id:a,data:{droppableContainer:r,value:c}})}}return o.sort(m3)};function b3(e,t){const{top:n,left:s,bottom:o,right:r}=t;return n<=e.y&&e.y<=o&&s<=e.x&&e.x<=r}const w3=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:s}=e;if(!s)return[];const o=[];for(const r of t){const{id:a}=r,l=n.get(a);if(l&&b3(s,l)){const d=g3(l).reduce((h,p)=>h+h3(s,p),0),u=Number((d/4).toFixed(4));o.push({id:a,data:{droppableContainer:r,value:u}})}}return o.sort(f3)};function y3(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function K_(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Si}function S3(e){return function(n){for(var s=arguments.length,o=new Array(s>1?s-1:0),r=1;r<s;r++)o[r-1]=arguments[r];return o.reduce((a,l)=>({...a,top:a.top+e*l.y,bottom:a.bottom+e*l.y,left:a.left+e*l.x,right:a.right+e*l.x}),{...n})}}const C3=S3(1);function q_(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 k3(e,t,n){const s=q_(t);if(!s)return e;const{scaleX:o,scaleY:r,x:a,y:l}=s,c=e.left-a-(1-o)*parseFloat(n),d=e.top-l-(1-r)*parseFloat(n.slice(n.indexOf(" ")+1)),u=o?e.width/o:e.width,h=r?e.height/r:e.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}const j3={ignoreTransform:!1};function Da(e,t){t===void 0&&(t=j3);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Ds(e).getComputedStyle(e);d&&(n=k3(n,d,u))}const{top:s,left:o,width:r,height:a,bottom:l,right:c}=n;return{top:s,left:o,width:r,height:a,bottom:l,right:c}}function Q0(e){return Da(e,{ignoreTransform:!0})}function _3(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function N3(e,t){return t===void 0&&(t=Ds(e).getComputedStyle(e)),t.position==="fixed"}function T3(e,t){t===void 0&&(t=Ds(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const r=t[o];return typeof r=="string"?n.test(r):!1})}function lx(e,t){const n=[];function s(o){if(t!=null&&n.length>=t||!o)return n;if(ax(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!xc(o)||B_(o)||n.includes(o))return n;const r=Ds(e).getComputedStyle(o);return o!==e&&T3(o,r)&&n.push(o),N3(o,r)?n:s(o.parentNode)}return e?s(e):n}function Y_(e){const[t]=lx(e,1);return t??null}function xp(e){return!bh||!e?null:Ta(e)?e:rx(e)?ax(e)||e===Ia(e).scrollingElement?window:xc(e)?e:null:null}function X_(e){return Ta(e)?e.scrollX:e.scrollLeft}function J_(e){return Ta(e)?e.scrollY:e.scrollTop}function Qf(e){return{x:X_(e),y:J_(e)}}var is;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(is||(is={}));function Z_(e){return!bh||!e?!1:e===document.scrollingElement}function Q_(e){const t={x:0,y:0},n=Z_(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},s={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},o=e.scrollTop<=t.y,r=e.scrollLeft<=t.x,a=e.scrollTop>=s.y,l=e.scrollLeft>=s.x;return{isTop:o,isLeft:r,isBottom:a,isRight:l,maxScroll:s,minScroll:t}}const I3={x:.2,y:.2};function D3(e,t,n,s,o){let{top:r,left:a,right:l,bottom:c}=n;s===void 0&&(s=10),o===void 0&&(o=I3);const{isTop:d,isBottom:u,isLeft:h,isRight:p}=Q_(e),f={x:0,y:0},g={x:0,y:0},x={height:t.height*o.y,width:t.width*o.x};return!d&&r<=t.top+x.height?(f.y=is.Backward,g.y=s*Math.abs((t.top+x.height-r)/x.height)):!u&&c>=t.bottom-x.height&&(f.y=is.Forward,g.y=s*Math.abs((t.bottom-x.height-c)/x.height)),!p&&l>=t.right-x.width?(f.x=is.Forward,g.x=s*Math.abs((t.right-x.width-l)/x.width)):!h&&a<=t.left+x.width&&(f.x=is.Backward,g.x=s*Math.abs((t.left+x.width-a)/x.width)),{direction:f,speed:g}}function E3(e){if(e===document.scrollingElement){const{innerWidth:r,innerHeight:a}=window;return{top:0,left:0,right:r,bottom:a,width:r,height:a}}const{top:t,left:n,right:s,bottom:o}=e.getBoundingClientRect();return{top:t,left:n,right:s,bottom:o,width:e.clientWidth,height:e.clientHeight}}function e1(e){return e.reduce((t,n)=>ta(t,Qf(n)),Si)}function P3(e){return e.reduce((t,n)=>t+X_(n),0)}function A3(e){return e.reduce((t,n)=>t+J_(n),0)}function t1(e,t){if(t===void 0&&(t=Da),!e)return;const{top:n,left:s,bottom:o,right:r}=t(e);Y_(e)&&(o<=0||r<=0||n>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const M3=[["x",["left","right"],P3],["y",["top","bottom"],A3]];class cx{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=lx(n),o=e1(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[r,a,l]of M3)for(const c of a)Object.defineProperty(this,c,{get:()=>{const d=l(s),u=o[r]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class hl{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...n)})},this.target=t}add(t,n,s){var o;(o=this.target)==null||o.addEventListener(t,n,s),this.listeners.push([t,n,s])}}function R3(e){const{EventTarget:t}=Ds(e);return e instanceof t?e:Ia(e)}function vp(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 Ks;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Ks||(Ks={}));function eb(e){e.preventDefault()}function L3(e){e.stopPropagation()}var pn;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(pn||(pn={}));const n1={start:[pn.Space,pn.Enter],cancel:[pn.Esc],end:[pn.Space,pn.Enter,pn.Tab]},O3=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case pn.Right:return{...n,x:n.x+25};case pn.Left:return{...n,x:n.x-25};case pn.Down:return{...n,y:n.y+25};case pn.Up:return{...n,y:n.y-25}}};class s1{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 hl(Ia(n)),this.windowListeners=new hl(Ds(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Ks.Resize,this.handleCancel),this.windowListeners.add(Ks.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Ks.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,s=t.node.current;s&&t1(s),n(Si)}handleKeyDown(t){if(yh(t)){const{active:n,context:s,options:o}=this.props,{keyboardCodes:r=n1,coordinateGetter:a=O3,scrollBehavior:l="smooth"}=o,{code:c}=t;if(r.end.includes(c)){this.handleEnd(t);return}if(r.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:d}=s.current,u=d?{x:d.left,y:d.top}:Si;this.referenceCoordinates||(this.referenceCoordinates=u);const h=a(t,{active:n,context:s.current,currentCoordinates:u});if(h){const p=uu(h,u),f={x:0,y:0},{scrollableAncestors:g}=s.current;for(const x of g){const v=t.code,{isTop:y,isRight:b,isLeft:w,isBottom:C,maxScroll:_,minScroll:N}=Q_(x),k=E3(x),S={x:Math.min(v===pn.Right?k.right-k.width/2:k.right,Math.max(v===pn.Right?k.left:k.left+k.width/2,h.x)),y:Math.min(v===pn.Down?k.bottom-k.height/2:k.bottom,Math.max(v===pn.Down?k.top:k.top+k.height/2,h.y))},A=v===pn.Right&&!b||v===pn.Left&&!w,T=v===pn.Down&&!C||v===pn.Up&&!y;if(A&&S.x!==h.x){const I=x.scrollLeft+p.x,P=v===pn.Right&&I<=_.x||v===pn.Left&&I>=N.x;if(P&&!p.y){x.scrollTo({left:I,behavior:l});return}P?f.x=x.scrollLeft-I:f.x=v===pn.Right?x.scrollLeft-_.x:x.scrollLeft-N.x,f.x&&x.scrollBy({left:-f.x,behavior:l});break}else if(T&&S.y!==h.y){const I=x.scrollTop+p.y,P=v===pn.Down&&I<=_.y||v===pn.Up&&I>=N.y;if(P&&!p.x){x.scrollTo({top:I,behavior:l});return}P?f.y=x.scrollTop-I:f.y=v===pn.Down?x.scrollTop-_.y:x.scrollTop-N.y,f.y&&x.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(t,ta(uu(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()}}s1.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:s=n1,onActivation:o}=t,{active:r}=n;const{code:a}=e.nativeEvent;if(s.start.includes(a)){const l=r.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),o?.({event:e.nativeEvent}),!0)}return!1}}];function tb(e){return!!(e&&"distance"in e)}function nb(e){return!!(e&&"delay"in e)}class dx{constructor(t,n,s){var o;s===void 0&&(s=R3(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=Ia(a),this.documentListeners=new hl(this.document),this.listeners=new hl(s),this.windowListeners=new hl(Ds(a)),this.initialCoordinates=(o=hu(r))!=null?o:Si,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(Ks.Resize,this.handleCancel),this.windowListeners.add(Ks.DragStart,eb),this.windowListeners.add(Ks.VisibilityChange,this.handleCancel),this.windowListeners.add(Ks.ContextMenu,eb),this.documentListeners.add(Ks.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(nb(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(tb(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:s,onPending:o}=this.props;o(s,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Ks.Click,L3,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Ks.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:s,initialCoordinates:o,props:r}=this,{onMove:a,options:{activationConstraint:l}}=r;if(!o)return;const c=(n=hu(t))!=null?n:Si,d=uu(o,c);if(!s&&l){if(tb(l)){if(l.tolerance!=null&&vp(d,l.tolerance))return this.handleCancel();if(vp(d,l.distance))return this.handleStart()}if(nb(l)&&vp(d,l.tolerance))return this.handleCancel();this.handlePending(l,d);return}t.cancelable&&t.preventDefault(),a(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===pn.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const z3={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class ux extends dx{constructor(t){const{event:n}=t,s=Ia(n.target);super(t,z3,s)}}ux.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 G3={move:{name:"mousemove"},end:{name:"mouseup"}};var em;(function(e){e[e.RightClick=2]="RightClick"})(em||(em={}));class F3 extends dx{constructor(t){super(t,G3,Ia(t.event.target))}}F3.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return n.button===em.RightClick?!1:(s?.({event:n}),!0)}}];const bp={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class H3 extends dx{constructor(t){super(t,bp)}static setup(){return window.addEventListener(bp.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(bp.move.name,t)};function t(){}}}H3.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;const{touches:o}=n;return o.length>1?!1:(s?.({event:n}),!0)}}];var pl;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(pl||(pl={}));var fu;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(fu||(fu={}));function B3(e){let{acceleration:t,activator:n=pl.Pointer,canScroll:s,draggingRect:o,enabled:r,interval:a=5,order:l=fu.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:p}=e;const f=$3({delta:h,disabled:!r}),[g,x]=Zz(),v=m.useRef({x:0,y:0}),y=m.useRef({x:0,y:0}),b=m.useMemo(()=>{switch(n){case pl.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case pl.DraggableRect:return o}},[n,o,c]),w=m.useRef(null),C=m.useCallback(()=>{const N=w.current;if(!N)return;const k=v.current.x*y.current.x,S=v.current.y*y.current.y;N.scrollBy(k,S)},[]),_=m.useMemo(()=>l===fu.TreeOrder?[...d].reverse():d,[l,d]);m.useEffect(()=>{if(!r||!d.length||!b){x();return}for(const N of _){if(s?.(N)===!1)continue;const k=d.indexOf(N),S=u[k];if(!S)continue;const{direction:A,speed:T}=D3(N,S,b,t,p);for(const I of["x","y"])f[I][A[I]]||(T[I]=0,A[I]=0);if(T.x>0||T.y>0){x(),w.current=N,g(C,a),v.current=T,y.current=A;return}}v.current={x:0,y:0},y.current={x:0,y:0},x()},[t,C,s,x,r,a,JSON.stringify(b),JSON.stringify(f),g,d,_,u,JSON.stringify(p)])}const V3={x:{[is.Backward]:!1,[is.Forward]:!1},y:{[is.Backward]:!1,[is.Forward]:!1}};function $3(e){let{delta:t,disabled:n}=e;const s=du(t);return vc(o=>{if(n||!s||!o)return V3;const r={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[is.Backward]:o.x[is.Backward]||r.x===-1,[is.Forward]:o.x[is.Forward]||r.x===1},y:{[is.Backward]:o.y[is.Backward]||r.y===-1,[is.Forward]:o.y[is.Forward]||r.y===1}}},[n,t,s])}function W3(e,t){const n=t!=null?e.get(t):void 0,s=n?n.node.current:null;return vc(o=>{var r;return t==null?null:(r=s??o)!=null?r:null},[s,t])}function U3(e,t){return m.useMemo(()=>e.reduce((n,s)=>{const{sensor:o}=s,r=o.activators.map(a=>({eventName:a.eventName,handler:t(a.handler,s)}));return[...n,...r]},[]),[e,t])}var Bl;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Bl||(Bl={}));var tm;(function(e){e.Optimized="optimized"})(tm||(tm={}));const sb=new Map;function K3(e,t){let{dragging:n,dependencies:s,config:o}=t;const[r,a]=m.useState(null),{frequency:l,measure:c,strategy:d}=o,u=m.useRef(e),h=v(),p=Hl(h),f=m.useCallback(function(y){y===void 0&&(y=[]),!p.current&&a(b=>b===null?y:b.concat(y.filter(w=>!b.includes(w))))},[p]),g=m.useRef(null),x=vc(y=>{if(h&&!n)return sb;if(!y||y===sb||u.current!==e||r!=null){const b=new Map;for(let w of e){if(!w)continue;if(r&&r.length>0&&!r.includes(w.id)&&w.rect.current){b.set(w.id,w.rect.current);continue}const C=w.node.current,_=C?new cx(c(C),C):null;w.rect.current=_,_&&b.set(w.id,_)}return b}return y},[e,r,n,h,c]);return m.useEffect(()=>{u.current=e},[e]),m.useEffect(()=>{h||f()},[n,h]),m.useEffect(()=>{r&&r.length>0&&a(null)},[JSON.stringify(r)]),m.useEffect(()=>{h||typeof l!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},l))},[l,h,f,...s]),{droppableRects:x,measureDroppableContainers:f,measuringScheduled:r!=null};function v(){switch(d){case Bl.Always:return!1;case Bl.BeforeDragging:return n;default:return!n}}}function hx(e,t){return vc(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function q3(e,t){return hx(e,t)}function Y3(e){let{callback:t,disabled:n}=e;const s=wh(t),o=m.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:r}=window;return new r(s)},[s,n]);return m.useEffect(()=>()=>o?.disconnect(),[o]),o}function Sh(e){let{callback:t,disabled:n}=e;const s=wh(t),o=m.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:r}=window;return new r(s)},[n]);return m.useEffect(()=>()=>o?.disconnect(),[o]),o}function X3(e){return new cx(Da(e),e)}function ib(e,t,n){t===void 0&&(t=X3);const[s,o]=m.useState(null);function r(){o(c=>{if(!e)return null;if(e.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(e);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const a=Y3({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=Sh({callback:r});return yi(()=>{r(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),s}function J3(e){const t=hx(e);return K_(e,t)}const ob=[];function Z3(e){const t=m.useRef(e),n=vc(s=>e?s&&s!==ob&&e&&t.current&&e.parentNode===t.current.parentNode?s:lx(e):ob,[e]);return m.useEffect(()=>{t.current=e},[e]),n}function Q3(e){const[t,n]=m.useState(null),s=m.useRef(e),o=m.useCallback(r=>{const a=xp(r.target);a&&n(l=>l?(l.set(a,Qf(a)),new Map(l)):null)},[]);return m.useEffect(()=>{const r=s.current;if(e!==r){a(r);const l=e.map(c=>{const d=xp(c);return d?(d.addEventListener("scroll",o,{passive:!0}),[d,Qf(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=xp(c);d?.removeEventListener("scroll",o)})}},[o,e]),m.useMemo(()=>e.length?t?Array.from(t.values()).reduce((r,a)=>ta(r,a),Si):e1(e):Si,[e,t])}function rb(e,t){t===void 0&&(t=[]);const n=m.useRef(null);return m.useEffect(()=>{n.current=null},t),m.useEffect(()=>{const s=e!==Si;s&&!n.current&&(n.current=e),!s&&n.current&&(n.current=null)},[e]),n.current?uu(e,n.current):Si}function eG(e){m.useEffect(()=>{if(!bh)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 tG(e,t){return m.useMemo(()=>e.reduce((n,s)=>{let{eventName:o,handler:r}=s;return n[o]=a=>{r(a,t)},n},{}),[e,t])}function i1(e){return m.useMemo(()=>e?_3(e):null,[e])}const ab=[];function nG(e,t){t===void 0&&(t=Da);const[n]=e,s=i1(n?Ds(n):null),[o,r]=m.useState(ab);function a(){r(()=>e.length?e.map(c=>Z_(c)?s:new cx(t(c),c)):ab)}const l=Sh({callback:a});return yi(()=>{l?.disconnect(),a(),e.forEach(c=>l?.observe(c))},[e]),o}function o1(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return xc(t)?t:e}function sG(e){let{measure:t}=e;const[n,s]=m.useState(null),o=m.useCallback(d=>{for(const{target:u}of d)if(xc(u)){s(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),r=Sh({callback:o}),a=m.useCallback(d=>{const u=o1(d);r?.disconnect(),u&&r?.observe(u),s(u?t(u):null)},[t,r]),[l,c]=cu(a);return m.useMemo(()=>({nodeRef:l,rect:n,setRef:c}),[n,l,c])}const iG=[{sensor:ux,options:{}},{sensor:s1,options:{}}],oG={current:{}},Md={draggable:{measure:Q0},droppable:{measure:Q0,strategy:Bl.WhileDragging,frequency:tm.Optimized},dragOverlay:{measure:Da}};class fl 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 rG={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new fl,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:pu},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Md,measureDroppableContainers:pu,windowRect:null,measuringScheduled:!1},r1={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:pu,draggableNodes:new Map,over:null,measureDroppableContainers:pu},wc=m.createContext(r1),a1=m.createContext(rG);function aG(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new fl}}}function lG(e,t){switch(t.type){case es.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case es.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 es.DragEnd:case es.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case es.RegisterDroppable:{const{element:n}=t,{id:s}=n,o=new fl(e.droppable.containers);return o.set(s,n),{...e,droppable:{...e.droppable,containers:o}}}case es.SetDroppableDisabled:{const{id:n,key:s,disabled:o}=t,r=e.droppable.containers.get(n);if(!r||s!==r.key)return e;const a=new fl(e.droppable.containers);return a.set(n,{...r,disabled:o}),{...e,droppable:{...e.droppable,containers:a}}}case es.UnregisterDroppable:{const{id:n,key:s}=t,o=e.droppable.containers.get(n);if(!o||s!==o.key)return e;const r=new fl(e.droppable.containers);return r.delete(n),{...e,droppable:{...e.droppable,containers:r}}}default:return e}}function cG(e){let{disabled:t}=e;const{active:n,activatorEvent:s,draggableNodes:o}=m.useContext(wc),r=du(s),a=du(n?.id);return m.useEffect(()=>{if(!t&&!s&&r&&a!=null){if(!yh(r)||document.activeElement===r.target)return;const l=o.get(a);if(!l)return;const{activatorNode:c,node:d}=l;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const u of[c.current,d.current]){if(!u)continue;const h=t3(u);if(h){h.focus();break}}})}},[s,t,o,a,r]),null}function l1(e,t){let{transform:n,...s}=t;return e!=null&&e.length?e.reduce((o,r)=>r({transform:o,...s}),n):n}function dG(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 uG(e){let{activeNode:t,measure:n,initialRect:s,config:o=!0}=e;const r=m.useRef(!1),{x:a,y:l}=typeof o=="boolean"?{x:o,y:o}:o;yi(()=>{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=K_(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=Y_(d);p&&p.scrollBy({top:h.y,left:h.x})}},[t,a,l,s,n])}const Ch=m.createContext({...Si,scaleX:1,scaleY:1});var Mo;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(Mo||(Mo={}));const hG=m.memo(function(t){var n,s,o,r;let{id:a,accessibility:l,autoScroll:c=!0,children:d,sensors:u=iG,collisionDetection:h=U_,measuring:p,modifiers:f,...g}=t;const x=m.useReducer(lG,void 0,aG),[v,y]=x,[b,w]=r3(),[C,_]=m.useState(Mo.Uninitialized),N=C===Mo.Initialized,{draggable:{active:k,nodes:S,translate:A},droppable:{containers:T}}=v,I=k!=null?S.get(k):null,P=m.useRef({initial:null,translated:null}),D=m.useMemo(()=>{var K;return k!=null?{id:k,data:(K=I?.data)!=null?K:oG,rect:P}:null},[k,I]),O=m.useRef(null),[z,R]=m.useState(null),[$,X]=m.useState(null),H=Hl(g,Object.values(g)),te=bc("DndDescribedBy",a),V=m.useMemo(()=>T.getEnabled(),[T]),Y=dG(p),{droppableRects:q,measureDroppableContainers:ee,measuringScheduled:ge}=K3(V,{dragging:N,dependencies:[A.x,A.y],config:Y.droppable}),Ce=W3(S,k),Re=m.useMemo(()=>$?hu($):null,[$]),fe=it(),U=q3(Ce,Y.draggable.measure);uG({activeNode:k!=null?S.get(k):null,config:fe.layoutShiftCompensation,initialRect:U,measure:Y.draggable.measure});const oe=ib(Ce,Y.draggable.measure,U),Se=ib(Ce?Ce.parentElement:null),G=m.useRef({activatorEvent:null,active:null,activeNode:Ce,collisionRect:null,collisions:null,droppableRects:q,draggableNodes:S,draggingNode:null,draggingNodeRect:null,droppableContainers:T,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Q=T.getNodeFor((n=G.current.over)==null?void 0:n.id),ae=sG({measure:Y.dragOverlay.measure}),Z=(s=ae.nodeRef.current)!=null?s:Ce,ce=N?(o=ae.rect)!=null?o:oe:null,De=!!(ae.nodeRef.current&&ae.rect),Oe=J3(De?null:oe),Ne=i1(Z?Ds(Z):null),Ze=Z3(N?Q??Ce:null),bt=nG(Ze),Ut=l1(f,{transform:{x:A.x-Oe.x,y:A.y-Oe.y,scaleX:1,scaleY:1},activatorEvent:$,active:D,activeNodeRect:oe,containerNodeRect:Se,draggingNodeRect:ce,over:G.current.over,overlayNodeRect:ae.rect,scrollableAncestors:Ze,scrollableAncestorRects:bt,windowRect:Ne}),Et=Re?ta(Re,A):null,_t=Q3(Ze),B=rb(_t),Te=rb(_t,[oe]),We=ta(Ut,B),kt=ce?C3(ce,Ut):null,Gt=D&&kt?h({active:D,collisionRect:kt,droppableRects:q,droppableContainers:V,pointerCoordinates:Et}):null,de=x3(Gt,"id"),[mt,Lt]=m.useState(null),Fe=De?Ut:ta(Ut,Te),Nt=y3(Fe,(r=mt?.rect)!=null?r:null,oe),Ft=m.useRef(null),on=m.useCallback((K,pe)=>{let{sensor:Ie,options:Ae}=pe;if(O.current==null)return;const He=S.get(O.current);if(!He)return;const nt=K.nativeEvent,be=new Ie({active:O.current,activeNode:He,event:nt,options:Ae,context:G,onAbort(tt){if(!S.get(tt))return;const{onDragAbort:Jt}=H.current,E={id:tt};Jt?.(E),b({type:"onDragAbort",event:E})},onPending(tt,wt,Jt,E){if(!S.get(tt))return;const{onDragPending:M}=H.current,j={id:tt,constraint:wt,initialCoordinates:Jt,offset:E};M?.(j),b({type:"onDragPending",event:j})},onStart(tt){const wt=O.current;if(wt==null)return;const Jt=S.get(wt);if(!Jt)return;const{onDragStart:E}=H.current,L={activatorEvent:nt,active:{id:wt,data:Jt.data,rect:P}};qs.unstable_batchedUpdates(()=>{E?.(L),_(Mo.Initializing),y({type:es.DragStart,initialCoordinates:tt,active:wt}),b({type:"onDragStart",event:L}),R(Ft.current),X(nt)})},onMove(tt){y({type:es.DragMove,coordinates:tt})},onEnd:et(es.DragEnd),onCancel:et(es.DragCancel)});Ft.current=be;function et(tt){return async function(){const{active:Jt,collisions:E,over:L,scrollAdjustedTranslate:M}=G.current;let j=null;if(Jt&&M){const{cancelDrop:F}=H.current;j={activatorEvent:nt,active:Jt,collisions:E,delta:M,over:L},tt===es.DragEnd&&typeof F=="function"&&await Promise.resolve(F(j))&&(tt=es.DragCancel)}O.current=null,qs.unstable_batchedUpdates(()=>{y({type:tt}),_(Mo.Uninitialized),Lt(null),R(null),X(null),Ft.current=null;const F=tt===es.DragEnd?"onDragEnd":"onDragCancel";if(j){const he=H.current[F];he?.(j),b({type:F,event:j})}})}}},[S]),re=m.useCallback((K,pe)=>(Ie,Ae)=>{const He=Ie.nativeEvent,nt=S.get(Ae);if(O.current!==null||!nt||He.dndKit||He.defaultPrevented)return;const be={active:nt};K(Ie,pe.options,be)===!0&&(He.dndKit={capturedBy:pe.sensor},O.current=Ae,on(Ie,pe))},[S,on]),Ue=U3(u,re);eG(u),yi(()=>{oe&&C===Mo.Initializing&&_(Mo.Initialized)},[oe,C]),m.useEffect(()=>{const{onDragMove:K}=H.current,{active:pe,activatorEvent:Ie,collisions:Ae,over:He}=G.current;if(!pe||!Ie)return;const nt={active:pe,activatorEvent:Ie,collisions:Ae,delta:{x:We.x,y:We.y},over:He};qs.unstable_batchedUpdates(()=>{K?.(nt),b({type:"onDragMove",event:nt})})},[We.x,We.y]),m.useEffect(()=>{const{active:K,activatorEvent:pe,collisions:Ie,droppableContainers:Ae,scrollAdjustedTranslate:He}=G.current;if(!K||O.current==null||!pe||!He)return;const{onDragOver:nt}=H.current,be=Ae.get(de),et=be&&be.rect.current?{id:be.id,rect:be.rect.current,data:be.data,disabled:be.disabled}:null,tt={active:K,activatorEvent:pe,collisions:Ie,delta:{x:He.x,y:He.y},over:et};qs.unstable_batchedUpdates(()=>{Lt(et),nt?.(tt),b({type:"onDragOver",event:tt})})},[de]),yi(()=>{G.current={activatorEvent:$,active:D,activeNode:Ce,collisionRect:kt,collisions:Gt,droppableRects:q,draggableNodes:S,draggingNode:Z,draggingNodeRect:ce,droppableContainers:T,over:mt,scrollableAncestors:Ze,scrollAdjustedTranslate:We},P.current={initial:ce,translated:kt}},[D,Ce,Gt,kt,S,Z,ce,q,T,mt,Ze,We]),B3({...fe,delta:A,draggingRect:kt,pointerCoordinates:Et,scrollableAncestors:Ze,scrollableAncestorRects:bt});const dt=m.useMemo(()=>({active:D,activeNode:Ce,activeNodeRect:oe,activatorEvent:$,collisions:Gt,containerNodeRect:Se,dragOverlay:ae,draggableNodes:S,droppableContainers:T,droppableRects:q,over:mt,measureDroppableContainers:ee,scrollableAncestors:Ze,scrollableAncestorRects:bt,measuringConfiguration:Y,measuringScheduled:ge,windowRect:Ne}),[D,Ce,oe,$,Gt,Se,ae,S,T,q,mt,ee,Ze,bt,Y,ge,Ne]),Dt=m.useMemo(()=>({activatorEvent:$,activators:Ue,active:D,activeNodeRect:oe,ariaDescribedById:{draggable:te},dispatch:y,draggableNodes:S,over:mt,measureDroppableContainers:ee}),[$,Ue,D,oe,y,te,S,mt,ee]);return _e.createElement($_.Provider,{value:w},_e.createElement(wc.Provider,{value:Dt},_e.createElement(a1.Provider,{value:dt},_e.createElement(Ch.Provider,{value:Nt},d)),_e.createElement(cG,{disabled:l?.restoreFocus===!1})),_e.createElement(c3,{...l,hiddenTextDescribedById:te}));function it(){const K=z?.autoScrollEnabled===!1,pe=typeof c=="object"?c.enabled===!1:c===!1,Ie=N&&!K&&!pe;return typeof c=="object"?{...c,enabled:Ie}:{enabled:Ie}}}),pG=m.createContext(null),lb="button",fG="Draggable";function px(e){let{id:t,data:n,disabled:s=!1,attributes:o}=e;const r=bc(fG),{activators:a,activatorEvent:l,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:p}=m.useContext(wc),{role:f=lb,roleDescription:g="draggable",tabIndex:x=0}=o??{},v=c?.id===t,y=m.useContext(v?Ch:pG),[b,w]=cu(),[C,_]=cu(),N=tG(a,t),k=Hl(n);yi(()=>(h.set(t,{id:t,key:r,node:b,activatorNode:C,data:k}),()=>{const A=h.get(t);A&&A.key===r&&h.delete(t)}),[h,t]);const S=m.useMemo(()=>({role:f,tabIndex:x,"aria-disabled":s,"aria-pressed":v&&f===lb?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[s,f,x,v,g,u.draggable]);return{active:c,activatorEvent:l,activeNodeRect:d,attributes:S,isDragging:v,listeners:s?void 0:N,node:b,over:p,setNodeRef:w,setActivatorNodeRef:_,transform:y}}function yc(){return m.useContext(a1)}const mG="Droppable",gG={timeout:25};function Sc(e){let{data:t,disabled:n=!1,id:s,resizeObserverConfig:o}=e;const r=bc(mG),{active:a,dispatch:l,over:c,measureDroppableContainers:d}=m.useContext(wc),u=m.useRef({disabled:n}),h=m.useRef(!1),p=m.useRef(null),f=m.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:v}={...gG,...o},y=Hl(x??s),b=m.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(y.current)?y.current:[y.current]),f.current=null},v)},[v]),w=Sh({callback:b,disabled:g||!a}),C=m.useCallback((S,A)=>{w&&(A&&(w.unobserve(A),h.current=!1),S&&w.observe(S))},[w]),[_,N]=cu(C),k=Hl(t);return m.useEffect(()=>{!w||!_.current||(w.disconnect(),h.current=!1,w.observe(_.current))},[_,w]),m.useEffect(()=>(l({type:es.RegisterDroppable,element:{id:s,key:r,disabled:n,node:_,rect:p,data:k}}),()=>l({type:es.UnregisterDroppable,key:r,id:s})),[s]),m.useEffect(()=>{n!==u.current.disabled&&(l({type:es.SetDroppableDisabled,id:s,key:r,disabled:n}),u.current.disabled=n)},[s,r,n,l]),{active:a,rect:p,isOver:c?.id===s,node:_,over:c,setNodeRef:N}}function xG(e){let{animation:t,children:n}=e;const[s,o]=m.useState(null),[r,a]=m.useState(null),l=du(n);return!n&&!s&&l&&o(l),yi(()=>{if(!r)return;const c=s?.key,d=s?.props.id;if(c==null||d==null){o(null);return}Promise.resolve(t(d,r)).then(()=>{o(null)})},[t,s,r]),_e.createElement(_e.Fragment,null,n,s?m.cloneElement(s,{ref:a}):null)}const vG={x:0,y:0,scaleX:1,scaleY:1};function bG(e){let{children:t}=e;return _e.createElement(wc.Provider,{value:r1},_e.createElement(Ch.Provider,{value:vG},t))}const wG={position:"fixed",touchAction:"none"},yG=e=>yh(e)?"transform 250ms ease":void 0,SG=m.forwardRef((e,t)=>{let{as:n,activatorEvent:s,adjustScale:o,children:r,className:a,rect:l,style:c,transform:d,transition:u=yG}=e;if(!l)return null;const h=o?d:{...d,scaleX:1,scaleY:1},p={...wG,width:l.width,height:l.height,top:l.top,left:l.left,transform:Bi.Transform.toString(h),transformOrigin:o&&s?p3(s,l):void 0,transition:typeof u=="function"?u(s):u,...c};return _e.createElement(n,{className:a,style:p,ref:t},r)}),CG=e=>t=>{let{active:n,dragOverlay:s}=t;const o={},{styles:r,className:a}=e;if(r!=null&&r.active)for(const[l,c]of Object.entries(r.active))c!==void 0&&(o[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,c));if(r!=null&&r.dragOverlay)for(const[l,c]of Object.entries(r.dragOverlay))c!==void 0&&s.node.style.setProperty(l,c);return a!=null&&a.active&&n.node.classList.add(a.active),a!=null&&a.dragOverlay&&s.node.classList.add(a.dragOverlay),function(){for(const[c,d]of Object.entries(o))n.node.style.setProperty(c,d);a!=null&&a.active&&n.node.classList.remove(a.active)}},kG=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Bi.Transform.toString(t)},{transform:Bi.Transform.toString(n)}]},jG={duration:250,easing:"ease",keyframes:kG,sideEffects:CG({styles:{active:{opacity:"0"}}})};function _G(e){let{config:t,draggableNodes:n,droppableContainers:s,measuringConfiguration:o}=e;return wh((r,a)=>{if(t===null)return;const l=n.get(r);if(!l)return;const c=l.node.current;if(!c)return;const d=o1(a);if(!d)return;const{transform:u}=Ds(a).getComputedStyle(a),h=q_(u);if(!h)return;const p=typeof t=="function"?t:NG(t);return t1(c,o.draggable.measure),p({active:{id:r,data:l.data,node:c,rect:o.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:a,rect:o.dragOverlay.measure(d)},droppableContainers:s,measuringConfiguration:o,transform:h})})}function NG(e){const{duration:t,easing:n,sideEffects:s,keyframes:o}={...jG,...e};return r=>{let{active:a,dragOverlay:l,transform:c,...d}=r;if(!t)return;const u={x:l.rect.left-a.rect.left,y:l.rect.top-a.rect.top},h={scaleX:c.scaleX!==1?a.rect.width*c.scaleX/l.rect.width:1,scaleY:c.scaleY!==1?a.rect.height*c.scaleY/l.rect.height:1},p={x:c.x-u.x,y:c.y-u.y,...h},f=o({...d,active:a,dragOverlay:l,transform:{initial:c,final:p}}),[g]=f,x=f[f.length-1];if(JSON.stringify(g)===JSON.stringify(x))return;const v=s?.({active:a,dragOverlay:l,...d}),y=l.node.animate(f,{duration:t,easing:n,fill:"forwards"});return new Promise(b=>{y.onfinish=()=>{v?.(),b()}})}}let cb=0;function TG(e){return m.useMemo(()=>{if(e!=null)return cb++,cb},[e])}const IG=_e.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:s,style:o,transition:r,modifiers:a,wrapperElement:l="div",className:c,zIndex:d=999}=e;const{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggableNodes:g,droppableContainers:x,dragOverlay:v,over:y,measuringConfiguration:b,scrollableAncestors:w,scrollableAncestorRects:C,windowRect:_}=yc(),N=m.useContext(Ch),k=TG(h?.id),S=l1(a,{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggingNodeRect:v.rect,over:y,overlayNodeRect:v.rect,scrollableAncestors:w,scrollableAncestorRects:C,transform:N,windowRect:_}),A=hx(p),T=_G({config:s,draggableNodes:g,droppableContainers:x,measuringConfiguration:b}),I=A?v.setRef:void 0;return _e.createElement(bG,null,_e.createElement(xG,{animation:T},h&&k?_e.createElement(SG,{key:k,id:h.id,ref:I,as:l,activatorEvent:u,adjustScale:t,className:c,transition:r,rect:A,style:{zIndex:d,...o},transform:S},n):null))}),fx=m.createContext({});function mx(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const DG=typeof window<"u",mu=DG?m.useLayoutEffect:m.useEffect,kh=m.createContext(null);function gx(e,t){e.indexOf(t)===-1&&e.push(t)}function gu(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const Vi=(e,t,n)=>n>t?t:n<e?e:n;let jh=()=>{};const Go={},c1=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),d1=e=>typeof e=="object"&&e!==null,u1=e=>/^0[^.\s]+$/u.test(e);function h1(e){let t;return()=>(t===void 0&&(t=e()),t)}const Qs=e=>e,Cc=(...e)=>e.reduce((t,n)=>s=>n(t(s))),Vl=(e,t,n)=>{const s=t-e;return s?(n-e)/s:1};class xx{constructor(){this.subscriptions=[]}add(t){return gx(this.subscriptions,t),()=>gu(this.subscriptions,t)}notify(t,n,s){const o=this.subscriptions.length;if(o)if(o===1)this.subscriptions[0](t,n,s);else for(let r=0;r<o;r++){const a=this.subscriptions[r];a&&a(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Hs=e=>e*1e3,Ys=e=>e/1e3,p1=(e,t)=>t?e*(1e3/t):0,f1=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,EG=1e-7,PG=12;function AG(e,t,n,s,o){let r,a,l=0;do a=t+(n-t)/2,r=f1(a,s,o)-e,r>0?n=a:t=a;while(Math.abs(r)>EG&&++l<PG);return a}function kc(e,t,n,s){if(e===t&&n===s)return Qs;const o=r=>AG(r,0,1,e,n);return r=>r===0||r===1?r:f1(o(r),t,s)}const m1=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,g1=e=>t=>1-e(1-t),x1=kc(.33,1.53,.69,.99),vx=g1(x1),v1=m1(vx),b1=e=>e>=1?1:(e*=2)<1?.5*vx(e):.5*(2-Math.pow(2,-10*(e-1))),bx=e=>1-Math.sin(Math.acos(e)),w1=g1(bx),y1=m1(bx),MG=kc(.42,0,1,1),RG=kc(0,0,.58,1),S1=kc(.42,0,.58,1),LG=e=>Array.isArray(e)&&typeof e[0]!="number",C1=e=>Array.isArray(e)&&typeof e[0]=="number",OG={linear:Qs,easeIn:MG,easeInOut:S1,easeOut:RG,circIn:bx,circInOut:y1,circOut:w1,backIn:vx,backInOut:v1,backOut:x1,anticipate:b1},zG=e=>typeof e=="string",db=e=>{if(C1(e)){jh(e.length===4);const[t,n,s,o]=e;return kc(t,n,s,o)}else if(zG(e))return OG[e];return e},Gc=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function GG(e){let t=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function l(d){r.has(d)&&(c.schedule(d),e()),d(a)}const c={schedule:(d,u=!1,h=!1)=>{const f=h&&s?t:n;return u&&r.add(d),f.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0;const u=t;t=n,n=u,t.forEach(l),t.clear(),s=!1,o&&(o=!1,c.process(d))}};return c}const FG=40;function k1(e,t){let n=!1,s=!0;const o={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,a=Gc.reduce((w,C)=>(w[C]=GG(r),w),{}),{setup:l,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:p,render:f,postRender:g}=a,x=()=>{const w=Go.useManualTiming,C=w?o.timestamp:performance.now();n=!1,w||(o.delta=s?1e3/60:Math.max(Math.min(C-o.timestamp,FG),1)),o.timestamp=C,o.isProcessing=!0,l.process(o),c.process(o),d.process(o),u.process(o),h.process(o),p.process(o),f.process(o),g.process(o),o.isProcessing=!1,n&&t&&(s=!1,e(x))},v=()=>{n=!0,s=!0,o.isProcessing||e(x)};return{schedule:Gc.reduce((w,C)=>{const _=a[C];return w[C]=(N,k=!1,S=!1)=>(n||v(),_.schedule(N,k,S)),w},{}),cancel:w=>{for(let C=0;C<Gc.length;C++)a[Gc[C]].cancel(w)},state:o,steps:a}}const{schedule:kn,cancel:Fo,state:us,steps:wp}=k1(typeof requestAnimationFrame<"u"?requestAnimationFrame:Qs,!0);let Rd;function HG(){Rd=void 0}const ks={now:()=>(Rd===void 0&&ks.set(us.isProcessing||Go.useManualTiming?us.timestamp:performance.now()),Rd),set:e=>{Rd=e,queueMicrotask(HG)}},j1=e=>t=>typeof t=="string"&&t.startsWith(e),_1=j1("--"),BG=j1("var(--"),wx=e=>BG(e)?VG.test(e.split("/*")[0].trim()):!1,VG=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function ub(e){return typeof e!="string"?!1:e.split("/*")[0].includes("var(--")}const Ea={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},$l={...Ea,transform:e=>Vi(0,1,e)},Fc={...Ea,default:1},ml=e=>Math.round(e*1e5)/1e5,yx=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function $G(e){return e==null}const WG=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Sx=(e,t)=>n=>!!(typeof n=="string"&&WG.test(n)&&n.startsWith(e)||t&&!$G(n)&&Object.prototype.hasOwnProperty.call(n,t)),N1=(e,t,n)=>s=>{if(typeof s!="string")return s;const[o,r,a,l]=s.match(yx);return{[e]:parseFloat(o),[t]:parseFloat(r),[n]:parseFloat(a),alpha:l!==void 0?parseFloat(l):1}},UG=e=>Vi(0,255,e),yp={...Ea,transform:e=>Math.round(UG(e))},pr={test:Sx("rgb","red"),parse:N1("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+yp.transform(e)+", "+yp.transform(t)+", "+yp.transform(n)+", "+ml($l.transform(s))+")"};function KG(e){let t="",n="",s="",o="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),o=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),o=e.substring(4,5),t+=t,n+=n,s+=s,o+=o),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:o?parseInt(o,16)/255:1}}const nm={test:Sx("#"),parse:KG,transform:pr.transform},jc=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),so=jc("deg"),Hi=jc("%"),xt=jc("px"),qG=jc("vh"),YG=jc("vw"),hb={...Hi,parse:e=>Hi.parse(e)/100,transform:e=>Hi.transform(e*100)},qr={test:Sx("hsl","hue"),parse:N1("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Hi.transform(ml(t))+", "+Hi.transform(ml(n))+", "+ml($l.transform(s))+")"},Un={test:e=>pr.test(e)||nm.test(e)||qr.test(e),parse:e=>pr.test(e)?pr.parse(e):qr.test(e)?qr.parse(e):nm.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?pr.transform(e):qr.transform(e),getAnimatableNone:e=>{const t=Un.parse(e);return t.alpha=0,Un.transform(t)}},XG=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function JG(e){return isNaN(e)&&typeof e=="string"&&(e.match(yx)?.length||0)+(e.match(XG)?.length||0)>0}const T1="number",I1="color",ZG="var",QG="var(",pb="${}",eF=/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 ma(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},o=[];let r=0;const l=t.replace(eF,c=>(Un.test(c)?(s.color.push(r),o.push(I1),n.push(Un.parse(c))):c.startsWith(QG)?(s.var.push(r),o.push(ZG),n.push(c)):(s.number.push(r),o.push(T1),n.push(parseFloat(c))),++r,pb)).split(pb);return{values:n,split:l,indexes:s,types:o}}function tF(e){return ma(e).values}function D1({split:e,types:t}){const n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=t[r];a===T1?o+=ml(s[r]):a===I1?o+=Un.transform(s[r]):o+=s[r]}return o}}function nF(e){return D1(ma(e))}const sF=e=>typeof e=="number"?0:Un.test(e)?Un.getAnimatableNone(e):e,iF=(e,t)=>typeof e=="number"?t?.trim().endsWith("/")?e:0:sF(e);function oF(e){const t=ma(e);return D1(t)(t.values.map((s,o)=>iF(s,t.split[o])))}const gi={test:JG,parse:tF,createTransformer:nF,getAnimatableNone:oF};function Sp(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 rF({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let o=0,r=0,a=0;if(!t)o=r=a=n;else{const l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;o=Sp(c,l,e+1/3),r=Sp(c,l,e),a=Sp(c,l,e-1/3)}return{red:Math.round(o*255),green:Math.round(r*255),blue:Math.round(a*255),alpha:s}}function xu(e,t){return n=>n>0?t:e}const Cn=(e,t,n)=>e+(t-e)*n,Cp=(e,t,n)=>{const s=e*e,o=n*(t*t-s)+s;return o<0?0:Math.sqrt(o)},aF=[nm,pr,qr],lF=e=>aF.find(t=>t.test(e));function fb(e){const t=lF(e);if(!t)return!1;let n=t.parse(e);return t===qr&&(n=rF(n)),n}const mb=(e,t)=>{const n=fb(e),s=fb(t);if(!n||!s)return xu(e,t);const o={...n};return r=>(o.red=Cp(n.red,s.red,r),o.green=Cp(n.green,s.green,r),o.blue=Cp(n.blue,s.blue,r),o.alpha=Cn(n.alpha,s.alpha,r),pr.transform(o))},sm=new Set(["none","hidden"]);function cF(e,t){return sm.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function dF(e,t){return n=>Cn(e,t,n)}function Cx(e){return typeof e=="number"?dF:typeof e=="string"?wx(e)?xu:Un.test(e)?mb:pF:Array.isArray(e)?E1:typeof e=="object"?Un.test(e)?mb:uF:xu}function E1(e,t){const n=[...e],s=n.length,o=e.map((r,a)=>Cx(r)(r,t[a]));return r=>{for(let a=0;a<s;a++)n[a]=o[a](r);return n}}function uF(e,t){const n={...e,...t},s={};for(const o in n)e[o]!==void 0&&t[o]!==void 0&&(s[o]=Cx(e[o])(e[o],t[o]));return o=>{for(const r in s)n[r]=s[r](o);return n}}function hF(e,t){const n=[],s={color:0,var:0,number:0};for(let o=0;o<t.values.length;o++){const r=t.types[o],a=e.indexes[r][s[r]],l=e.values[a]??0;n[o]=l,s[r]++}return n}const pF=(e,t)=>{const n=gi.createTransformer(t),s=ma(e),o=ma(t);return s.indexes.var.length===o.indexes.var.length&&s.indexes.color.length===o.indexes.color.length&&s.indexes.number.length>=o.indexes.number.length?sm.has(e)&&!o.values.length||sm.has(t)&&!s.values.length?cF(e,t):Cc(E1(hF(s,o),o.values),n):xu(e,t)};function P1(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?Cn(e,t,n):Cx(e)(e,t)}const fF=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>kn.update(t,n),stop:()=>Fo(t),now:()=>us.isProcessing?us.timestamp:ks.now()}},A1=(e,t,n=10)=>{let s="";const o=Math.max(Math.round(t/n),2);for(let r=0;r<o;r++)s+=Math.round(e(r/(o-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},vu=2e4;function kx(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<vu;)t+=n,s=e.next(t);return t>=vu?1/0:t}function mF(e,t=100,n){const s=n({...e,keyframes:[0,t]}),o=Math.min(kx(s),vu);return{type:"keyframes",ease:r=>s.next(o*r).value/t,duration:Ys(o)}}const Hn={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 im(e,t){return e*Math.sqrt(1-t*t)}const gF=12;function xF(e,t,n){let s=n;for(let o=1;o<gF;o++)s=s-e(s)/t(s);return s}const kp=.001;function vF({duration:e=Hn.duration,bounce:t=Hn.bounce,velocity:n=Hn.velocity,mass:s=Hn.mass}){let o,r,a=1-t;a=Vi(Hn.minDamping,Hn.maxDamping,a),e=Vi(Hn.minDuration,Hn.maxDuration,Ys(e)),a<1?(o=d=>{const u=d*a,h=u*e,p=u-n,f=im(d,a),g=Math.exp(-h);return kp-p/f*g},r=d=>{const h=d*a*e,p=h*n+n,f=Math.pow(a,2)*Math.pow(d,2)*e,g=Math.exp(-h),x=im(Math.pow(d,2),a);return(-o(d)+kp>0?-1:1)*((p-f)*g)/x}):(o=d=>{const u=Math.exp(-d*e),h=(d-n)*e+1;return-kp+u*h},r=d=>{const u=Math.exp(-d*e),h=(n-d)*(e*e);return u*h});const l=5/e,c=xF(o,r,l);if(e=Hs(e),isNaN(c))return{stiffness:Hn.stiffness,damping:Hn.damping,duration:e};{const d=Math.pow(c,2)*s;return{stiffness:d,damping:a*2*Math.sqrt(s*d),duration:e}}}const bF=["duration","bounce"],wF=["stiffness","damping","mass"];function gb(e,t){return t.some(n=>e[n]!==void 0)}function yF(e){let t={velocity:Hn.velocity,stiffness:Hn.stiffness,damping:Hn.damping,mass:Hn.mass,isResolvedFromDuration:!1,...e};if(!gb(e,wF)&&gb(e,bF))if(t.velocity=0,e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),o=s*s,r=2*Vi(.05,1,1-(e.bounce||0))*Math.sqrt(o);t={...t,mass:Hn.mass,stiffness:o,damping:r}}else{const n=vF({...e,velocity:0});t={...t,...n,mass:Hn.mass},t.isResolvedFromDuration=!0}return t}function bu(e=Hn.visualDuration,t=Hn.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:o}=n;const r=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],l={done:!1,value:r},{stiffness:c,damping:d,mass:u,duration:h,velocity:p,isResolvedFromDuration:f}=yF({...n,velocity:-Ys(n.velocity||0)}),g=p||0,x=d/(2*Math.sqrt(c*u)),v=a-r,y=Ys(Math.sqrt(c/u)),b=Math.abs(v)<5;s||(s=b?Hn.restSpeed.granular:Hn.restSpeed.default),o||(o=b?Hn.restDelta.granular:Hn.restDelta.default);let w,C,_,N,k,S;if(x<1)_=im(y,x),N=(g+x*y*v)/_,w=T=>{const I=Math.exp(-x*y*T);return a-I*(N*Math.sin(_*T)+v*Math.cos(_*T))},k=x*y*N+v*_,S=x*y*v-N*_,C=T=>Math.exp(-x*y*T)*(k*Math.sin(_*T)+S*Math.cos(_*T));else if(x===1){w=I=>a-Math.exp(-y*I)*(v+(g+y*v)*I);const T=g+y*v;C=I=>Math.exp(-y*I)*(y*T*I-g)}else{const T=y*Math.sqrt(x*x-1);w=O=>{const z=Math.exp(-x*y*O),R=Math.min(T*O,300);return a-z*((g+x*y*v)*Math.sinh(R)+T*v*Math.cosh(R))/T};const I=(g+x*y*v)/T,P=x*y*I-v*T,D=x*y*v-I*T;C=O=>{const z=Math.exp(-x*y*O),R=Math.min(T*O,300);return z*(P*Math.sinh(R)+D*Math.cosh(R))}}const A={calculatedDuration:f&&h||null,velocity:T=>Hs(C(T)),next:T=>{if(!f&&x<1){const P=Math.exp(-x*y*T),D=Math.sin(_*T),O=Math.cos(_*T),z=a-P*(N*D+v*O),R=Hs(P*(k*D+S*O));return l.done=Math.abs(R)<=s&&Math.abs(a-z)<=o,l.value=l.done?a:z,l}const I=w(T);if(f)l.done=T>=h;else{const P=Hs(C(T));l.done=Math.abs(P)<=s&&Math.abs(a-I)<=o}return l.value=l.done?a:I,l},toString:()=>{const T=Math.min(kx(A),vu),I=A1(P=>A.next(T*P).value,T,30);return T+"ms "+I},toTransition:()=>{}};return A}bu.applyToOptions=e=>{const t=mF(e,100,bu);return e.ease=t.ease,e.duration=Hs(t.duration),e.type="keyframes",e};const SF=5;function M1(e,t,n){const s=Math.max(t-SF,0);return p1(n-e(s),t-s)}function om({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:o=10,bounceStiffness:r=500,modifyTarget:a,min:l,max:c,restDelta:d=.5,restSpeed:u}){const h=e[0],p={done:!1,value:h},f=S=>l!==void 0&&S<l||c!==void 0&&S>c,g=S=>l===void 0?c:c===void 0||Math.abs(l-S)<Math.abs(c-S)?l:c;let x=n*t;const v=h+x,y=a===void 0?v:a(v);y!==v&&(x=y-h);const b=S=>-x*Math.exp(-S/s),w=S=>y+b(S),C=S=>{const A=b(S),T=w(S);p.done=Math.abs(A)<=d,p.value=p.done?y:T};let _,N;const k=S=>{f(p.value)&&(_=S,N=bu({keyframes:[p.value,g(p.value)],velocity:M1(w,S,p.value),damping:o,stiffness:r,restDelta:d,restSpeed:u}))};return k(0),{calculatedDuration:null,next:S=>{let A=!1;return!N&&_===void 0&&(A=!0,C(S),k(S)),_!==void 0&&S>=_?N.next(S-_):(!A&&C(S),p)}}}function CF(e,t,n){const s=[],o=n||Go.mix||P1,r=e.length-1;for(let a=0;a<r;a++){let l=o(e[a],e[a+1]);if(t){const c=Array.isArray(t)?t[a]||Qs:t;l=Cc(c,l)}s.push(l)}return s}function kF(e,t,{clamp:n=!0,ease:s,mixer:o}={}){const r=e.length;if(jh(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=CF(t,s,o),c=l.length,d=u=>{if(a&&u<e[0])return t[0];let h=0;if(c>1)for(;h<e.length-2&&!(u<e[h+1]);h++);const p=Vl(e[h],e[h+1],u);return l[h](p)};return n?u=>d(Vi(e[0],e[r-1],u)):d}function jF(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const o=Vl(0,t,s);e.push(Cn(n,1,o))}}function _F(e){const t=[0];return jF(t,e.length-1),t}function NF(e,t){return e.map(n=>n*t)}function TF(e,t){return e.map(()=>t||S1).splice(0,e.length-1)}function gl({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const o=LG(s)?s.map(db):db(s),r={done:!1,value:t[0]},a=NF(n&&n.length===t.length?n:_F(t),e),l=kF(a,t,{ease:Array.isArray(o)?o:TF(t,o)});return{calculatedDuration:e,next:c=>(r.value=l(c),r.done=c>=e,r)}}const IF=e=>e!==null;function _h(e,{repeat:t,repeatType:n="loop"},s,o=1){const r=e.filter(IF),l=o<0||t&&n!=="loop"&&t%2===1?0:r.length-1;return!l||s===void 0?r[l]:s}const DF={decay:om,inertia:om,tween:gl,keyframes:gl,spring:bu};function R1(e){typeof e.type=="string"&&(e.type=DF[e.type])}class jx{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 EF=e=>e/100;class wu extends jx{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!==ks.now()&&this.tick(ks.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;R1(t);const{type:n=gl,repeat:s=0,repeatDelay:o=0,repeatType:r,velocity:a=0}=t;let{keyframes:l}=t;const c=n||gl;c!==gl&&typeof l[0]!="number"&&(this.mixKeyframes=Cc(EF,P1(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=kx(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+o,this.totalDuration=this.resolvedDuration*(s+1)-o,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:o,mixKeyframes:r,mirroredGenerator:a,resolvedDuration:l,calculatedDuration:c}=this;if(this.startTime===null)return s.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:p,repeatDelay:f,type:g,onUpdate:x,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-o/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const y=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?y<0:y>o;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=o);let w=this.currentTime,C=s;if(h){const S=Math.min(this.currentTime,o)/l;let A=Math.floor(S),T=S%1;!T&&S>=1&&(T=1),T===1&&A--,A=Math.min(A,h+1),A%2&&(p==="reverse"?(T=1-T,f&&(T-=f/l)):p==="mirror"&&(C=a)),w=Vi(0,1,T)*l}let _;b?(this.delayState.value=u[0],_=this.delayState):_=C.next(w),r&&!b&&(_.value=r(_.value));let{done:N}=_;!b&&c!==null&&(N=this.playbackSpeed>=0?this.currentTime>=o:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return k&&g!==om&&(_.value=_h(u,this.options,v,this.speed)),x&&x(_.value),k&&this.finish(),_}then(t,n){return this.finished.then(t,n)}get duration(){return Ys(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ys(t)}get time(){return Ys(this.currentTime)}set time(t){t=Hs(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 M1(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(ks.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=Ys(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=fF,startTime:n}=this.options;this.driver||(this.driver=t(o=>this.tick(o))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ks.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 PF(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const fr=e=>e*180/Math.PI,rm=e=>{const t=fr(Math.atan2(e[1],e[0]));return am(t)},AF={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:rm,rotateZ:rm,skewX:e=>fr(Math.atan(e[1])),skewY:e=>fr(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},am=e=>(e=e%360,e<0&&(e+=360),e),xb=rm,vb=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),bb=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),MF={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:vb,scaleY:bb,scale:e=>(vb(e)+bb(e))/2,rotateX:e=>am(fr(Math.atan2(e[6],e[5]))),rotateY:e=>am(fr(Math.atan2(-e[2],e[0]))),rotateZ:xb,rotate:xb,skewX:e=>fr(Math.atan(e[4])),skewY:e=>fr(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function lm(e){return e.includes("scale")?1:0}function cm(e,t){if(!e||e==="none")return lm(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,o;if(n)s=MF,o=n;else{const l=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=AF,o=l}if(!o)return lm(t);const r=s[t],a=o[1].split(",").map(LF);return typeof r=="function"?r(a):a[r]}const RF=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return cm(n,t)};function LF(e){return parseFloat(e.trim())}const Pa=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Aa=new Set([...Pa,"pathRotation"]),wb=e=>e===Ea||e===xt,OF=new Set(["x","y","z"]),zF=Pa.filter(e=>!OF.has(e));function GF(e){const t=[];return zF.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const zo={width:({x:e},{paddingLeft:t="0",paddingRight:n="0",boxSizing:s})=>{const o=e.max-e.min;return s==="border-box"?o:o-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t="0",paddingBottom:n="0",boxSizing:s})=>{const o=e.max-e.min;return s==="border-box"?o:o-parseFloat(t)-parseFloat(n)},top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>cm(t,"x"),y:(e,{transform:t})=>cm(t,"y")};zo.translateX=zo.x;zo.translateY=zo.y;const br=new Set;let dm=!1,um=!1,hm=!1;function L1(){if(um){const e=Array.from(br).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const o=GF(s);o.length&&(n.set(s,o),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const o=n.get(s);o&&o.forEach(([r,a])=>{s.getValue(r)?.set(a)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}um=!1,dm=!1,br.forEach(e=>e.complete(hm)),br.clear()}function O1(){br.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(um=!0)})}function FF(){hm=!0,O1(),L1(),hm=!1}class _x{constructor(t,n,s,o,r,a=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=o,this.element=r,this.isAsync=a}scheduleResolve(){this.state="scheduled",this.isAsync?(br.add(this),dm||(dm=!0,kn.read(O1),kn.resolveKeyframes(L1))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:o}=this;if(t[0]===null){const r=o?.get(),a=t[t.length-1];if(r!==void 0)t[0]=r;else if(s&&n){const l=s.readValue(n,a);l!=null&&(t[0]=l)}t[0]===void 0&&(t[0]=a),o&&r===void 0&&o.set(t[0])}PF(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),br.delete(this)}cancel(){this.state==="scheduled"&&(br.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const HF=e=>e.startsWith("--");function z1(e,t,n){HF(t)?e.style.setProperty(t,n):e.style[t]=n}const BF={};function G1(e,t){const n=h1(e);return()=>BF[t]??n()}const VF=G1(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),F1=G1(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),il=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,yb={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:il([0,.65,.55,1]),circOut:il([.55,0,1,.45]),backIn:il([.31,.01,.66,-.59]),backOut:il([.33,1.53,.69,.99])};function H1(e,t){if(e)return typeof e=="function"?F1()?A1(e,t):"ease-out":C1(e)?il(e):Array.isArray(e)?e.map(n=>H1(n,t)||yb.easeOut):yb[e]}function $F(e,t,n,{delay:s=0,duration:o=300,repeat:r=0,repeatType:a="loop",ease:l="easeOut",times:c}={},d=void 0){const u={[t]:n};c&&(u.offset=c);const h=H1(l,o);Array.isArray(h)&&(u.easing=h);const p={delay:s,duration:o,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:r+1,direction:a==="reverse"?"alternate":"normal"};return d&&(p.pseudoElement=d),e.animate(u,p)}function B1(e){return typeof e=="function"&&"applyToOptions"in e}function WF({type:e,...t}){return B1(e)&&F1()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class V1 extends jx{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:n,name:s,keyframes:o,pseudoElement:r,allowFlatten:a=!1,finalKeyframe:l,onComplete:c}=t;this.isPseudoElement=!!r,this.allowFlatten=a,this.options=t,jh(typeof t.type!="string");const d=WF(t);this.animation=$F(n,s,o,d,r),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=_h(o,this.options,l,this.speed);this.updateMotionValue&&this.updateMotionValue(u),z1(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 Ys(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ys(t)}get time(){return Ys(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Hs(t),n&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(t){this.manualStartTime=this.animation.startTime=t}attachTimeline({timeline:t,rangeStart:n,rangeEnd:s,observe:o}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&VF()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),s&&(this.animation.rangeEnd=s),Qs):o(this)}}const $1={anticipate:b1,backInOut:v1,circInOut:y1};function UF(e){return e in $1}function KF(e){typeof e.ease=="string"&&UF(e.ease)&&(e.ease=$1[e.ease])}const jp=10;class qF extends V1{constructor(t){KF(t),R1(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:o,element:r,...a}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const l=new wu({...a,autoplay:!1}),c=Math.max(jp,ks.now()-this.startTime),d=Vi(0,jp,c-jp),u=l.sample(c).value,{name:h}=this.options;r&&h&&z1(r,h,u),n.setWithVelocity(l.sample(Math.max(0,c-d)).value,u,d),l.stop()}}const Sb=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(gi.test(e)||e==="0")&&!e.startsWith("url("));function YF(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function XF(e,t,n,s){const o=e[0];if(o===null)return!1;if(t==="display"||t==="visibility")return!0;const r=e[e.length-1],a=Sb(o,t),l=Sb(r,t);return!a||!l?!1:YF(e)||(n==="spring"||B1(n))&&s}function pm(e){e.duration=0,e.type="keyframes"}const W1=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),JF=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function ZF(e){for(let t=0;t<e.length;t++)if(typeof e[t]=="string"&&JF.test(e[t]))return!0;return!1}const QF=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),eH=h1(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function tH(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:o,damping:r,type:a,keyframes:l}=e,c=t?.owner?.current;if(!(c instanceof HTMLElement)&&!(c instanceof SVGElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return eH()&&n&&(W1.has(n)||QF.has(n)&&ZF(l))&&(n!=="transform"||!u)&&!d&&!s&&o!=="mirror"&&r!==0&&a!=="inertia"}const nH=40;class sH extends jx{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:o=0,repeatDelay:r=0,repeatType:a="loop",keyframes:l,name:c,motionValue:d,element:u,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=ks.now();const p={autoplay:t,delay:n,type:s,repeat:o,repeatDelay:r,repeatType:a,name:c,motionValue:d,element:u,...h},f=u?.KeyframeResolver||_x;this.keyframeResolver=new f(l,(g,x,v)=>this.onKeyframesResolved(g,x,p,!v),c,d,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,o){this.keyframeResolver=void 0;const{name:r,type:a,velocity:l,delay:c,isHandoff:d,onUpdate:u}=s;this.resolvedAt=ks.now();let h=!0;XF(t,r,a,l)||(h=!1,(Go.instantAnimations||!c)&&u?.(_h(t,s,n)),t[0]=t[t.length-1],pm(s),s.repeat=0);const f={startTime:o?this.resolvedAt?this.resolvedAt-this.createdAt>nH?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=h&&!d&&tH(f),x=f.motionValue?.owner?.current;let v;if(g)try{v=new qF({...f,element:x})}catch{v=new wu(f)}else v=new wu(f);v.finished.then(()=>{this.notifyFinished()}).catch(Qs),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(),FF()),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 U1(e,t,n,s=0,o=1){const r=Array.from(e).sort((d,u)=>d.sortNodePosition(u)).indexOf(t),a=e.size,l=(a-1)*s;return typeof n=="function"?n(r,a):o===1?r*s:l-r*s}const Cb=30,iH=e=>!isNaN(parseFloat(e));class oH{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const o=ks.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const r of this.dependents)r.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=ks.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=iH(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 xx);const s=this.events[t].add(n);return t==="change"?()=>{s(),kn.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=ks.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Cb)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Cb);return p1(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 ga(e,t){return new oH(e,t)}function K1(e,t){if(e?.inherit&&t){const{inherit:n,...s}=e;return{...t,...s}}return e}function Nx(e,t){const n=e?.[t]??e?.default??e;return n!==e?K1(n,e):n}const rH={type:"spring",stiffness:500,damping:25,restSpeed:10},aH=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),lH={type:"keyframes",duration:.8},cH={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},dH=(e,{keyframes:t})=>t.length>2?lH:Aa.has(e)?e.startsWith("scale")?aH(t[1]):rH:cH,uH=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function hH(e){for(const t in e)if(!uH.has(t))return!0;return!1}const Tx=(e,t,n,s={},o,r)=>a=>{const l=Nx(s,e)||{},c=l.delay||s.delay||0;let{elapsed:d=0}=s;d=d-Hs(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...l,delay:-d,onUpdate:p=>{t.set(p),l.onUpdate&&l.onUpdate(p)},onComplete:()=>{a(),l.onComplete&&l.onComplete()},name:e,motionValue:t,element:r?void 0:o};hH(l)||Object.assign(u,dH(e,u)),u.duration&&(u.duration=Hs(u.duration)),u.repeatDelay&&(u.repeatDelay=Hs(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(pm(u),u.delay===0&&(h=!0)),(Go.instantAnimations||Go.skipAnimations||o?.shouldSkipAnimations||l.skipAnimations)&&(h=!0,pm(u),u.delay=0),u.allowFlatten=!l.type&&!l.ease,h&&!r&&t.get()!==void 0){const p=_h(u.keyframes,l);if(p!==void 0){kn.update(()=>{u.onUpdate(p),u.onComplete()});return}}return l.isSync?new wu(u):new sH(u)},pH=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function fH(e){const t=pH.exec(e);if(!t)return[,];const[,n,s,o]=t;return[`--${n??s}`,o]}function q1(e,t,n=1){const[s,o]=fH(e);if(!s)return;const r=window.getComputedStyle(t).getPropertyValue(s);if(r){const a=r.trim();return c1(a)?parseFloat(a):a}return wx(o)?q1(o,t,n+1):o}function kb(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function Ix(e,t,n,s){if(typeof t=="function"){const[o,r]=kb(s);t=t(n!==void 0?n:e.custom,o,r)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[o,r]=kb(s);t=t(n!==void 0?n:e.custom,o,r)}return t}function wr(e,t,n){const s=e.getProps();return Ix(s,t,n!==void 0?n:s.custom,e)}const Y1=new Set(["width","height","top","left","right","bottom",...Pa]),fm=e=>Array.isArray(e);function mH(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,ga(n))}function gH(e){return fm(e)?e[e.length-1]||0:e}function xH(e,t){const n=wr(e,t);let{transitionEnd:s={},transition:o={},...r}=n||{};r={...r,...s};for(const a in r){const l=gH(r[a]);mH(e,a,l)}}const hs=e=>!!(e&&e.getVelocity);function vH(e){return!!(hs(e)&&e.add)}function mm(e,t){const n=e.getValue("willChange");if(vH(n))return n.add(t);if(!n&&Go.WillChange){const s=new Go.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function Dx(e){return e.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const bH="framerAppearId",X1="data-"+Dx(bH);function J1(e){return e.props[X1]}const wH=typeof window<"u";function yH({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function Z1(e,t,{delay:n=0,transitionOverride:s,type:o}={}){let{transition:r,transitionEnd:a,...l}=t;const c=e.getDefaultTransition();r=r?K1(r,c):c;const d=r?.reduceMotion,u=r?.skipAnimations;s&&(r=s);const h=[],p=o&&e.animationState&&e.animationState.getState()[o],f=r?.path;f&&f.animateVisualElement(e,l,r,n,h);for(const g in l){const x=e.getValue(g,e.latestValues[g]??null),v=l[g];if(v===void 0||p&&yH(p,g))continue;const y={delay:n,...Nx(r||{},g)};u&&(y.skipAnimations=!0);const b=x.get();if(b!==void 0&&!x.isAnimating()&&!Array.isArray(v)&&v===b&&!y.velocity){kn.update(()=>x.set(v));continue}let w=!1;if(wH&&window.MotionHandoffAnimation){const N=J1(e);if(N){const k=window.MotionHandoffAnimation(N,g,kn);k!==null&&(y.startTime=k,w=!0)}}mm(e,g);const C=d??e.shouldReduceMotion;x.start(Tx(g,x,v,C&&Y1.has(g)?{type:!1}:y,e,w));const _=x.animation;_&&h.push(_)}if(a){const g=()=>kn.update(()=>{a&&xH(e,a)});h.length?Promise.all(h).then(g):g()}return h}function gm(e,t,n={}){const s=wr(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:o=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(o=n.transitionOverride);const r=s?()=>Promise.all(Z1(e,s,n)):()=>Promise.resolve(),a=e.variantChildren&&e.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:h}=o;return SH(e,t,c,d,u,h,n)}:()=>Promise.resolve(),{when:l}=o;if(l){const[c,d]=l==="beforeChildren"?[r,a]:[a,r];return c().then(()=>d())}else return Promise.all([r(),a(n.delay)])}function SH(e,t,n=0,s=0,o=0,r=1,a){const l=[];for(const c of e.variantChildren)c.notify("AnimationStart",t),l.push(gm(c,t,{...a,delay:n+(typeof s=="function"?0:s)+U1(e.variantChildren,c,s,o,r)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(l)}function CH(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const o=t.map(r=>gm(e,r,n));s=Promise.all(o)}else if(typeof t=="string")s=gm(e,t,n);else{const o=typeof t=="function"?wr(e,t,n.custom):t;s=Promise.all(Z1(e,o,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}const kH={test:e=>e==="auto",parse:e=>e},Q1=e=>t=>t.test(e),eN=[Ea,xt,Hi,so,YG,qG,kH],jb=e=>eN.find(Q1(e));function jH(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||u1(e):!0}const _H=new Set(["brightness","contrast","saturate","opacity"]);function NH(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(yx)||[];if(!s)return e;const o=n.replace(s,"");let r=_H.has(t)?1:0;return s!==n&&(r*=100),t+"("+r+o+")"}const TH=/\b([a-z-]*)\(.*?\)/gu,xm={...gi,getAnimatableNone:e=>{const t=e.match(TH);return t?t.map(NH).join(" "):e}},vm={...gi,getAnimatableNone:e=>{const t=gi.parse(e);return gi.createTransformer(e)(t.map(s=>typeof s=="number"?0:typeof s=="object"?{...s,alpha:1}:s))}},_b={...Ea,transform:Math.round},IH={rotate:so,pathRotation:so,rotateX:so,rotateY:so,rotateZ:so,scale:Fc,scaleX:Fc,scaleY:Fc,scaleZ:Fc,skew:so,skewX:so,skewY:so,distance:xt,translateX:xt,translateY:xt,translateZ:xt,x:xt,y:xt,z:xt,perspective:xt,transformPerspective:xt,opacity:$l,originX:hb,originY:hb,originZ:xt},yu={borderWidth:xt,borderTopWidth:xt,borderRightWidth:xt,borderBottomWidth:xt,borderLeftWidth:xt,borderRadius:xt,borderTopLeftRadius:xt,borderTopRightRadius:xt,borderBottomRightRadius:xt,borderBottomLeftRadius:xt,width:xt,maxWidth:xt,height:xt,maxHeight:xt,top:xt,right:xt,bottom:xt,left:xt,inset:xt,insetBlock:xt,insetBlockStart:xt,insetBlockEnd:xt,insetInline:xt,insetInlineStart:xt,insetInlineEnd:xt,padding:xt,paddingTop:xt,paddingRight:xt,paddingBottom:xt,paddingLeft:xt,paddingBlock:xt,paddingBlockStart:xt,paddingBlockEnd:xt,paddingInline:xt,paddingInlineStart:xt,paddingInlineEnd:xt,margin:xt,marginTop:xt,marginRight:xt,marginBottom:xt,marginLeft:xt,marginBlock:xt,marginBlockStart:xt,marginBlockEnd:xt,marginInline:xt,marginInlineStart:xt,marginInlineEnd:xt,fontSize:xt,backgroundPositionX:xt,backgroundPositionY:xt,...IH,zIndex:_b,fillOpacity:$l,strokeOpacity:$l,numOctaves:_b},DH={...yu,color:Un,backgroundColor:Un,outlineColor:Un,fill:Un,stroke:Un,borderColor:Un,borderTopColor:Un,borderRightColor:Un,borderBottomColor:Un,borderLeftColor:Un,filter:xm,WebkitFilter:xm,mask:vm,WebkitMask:vm},tN=e=>DH[e],EH=new Set([xm,vm]);function nN(e,t){let n=tN(e);return EH.has(n)||(n=gi),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const PH=new Set(["auto","none","0"]);function AH(e,t,n){let s=0,o;for(;s<e.length&&!o;){const r=e[s];typeof r=="string"&&!PH.has(r)&&ma(r).values.length&&(o=e[s]),s++}if(o&&n)for(const r of t)e[r]=nN(n,o)}class MH extends _x{constructor(t,n,s,o,r){super(t,n,s,o,r,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let u=0;u<t.length;u++){let h=t[u];if(typeof h=="string"&&(h=h.trim(),wx(h))){const p=q1(h,n.current);p!==void 0&&(t[u]=p),u===t.length-1&&(this.finalKeyframe=h)}}if(this.resolveNoneKeyframes(),!Y1.has(s)||t.length!==2)return;const[o,r]=t,a=jb(o),l=jb(r),c=ub(o),d=ub(r);if(c!==d&&zo[s]){this.needsMeasurement=!0;return}if(a!==l)if(wb(a)&&wb(l))for(let u=0;u<t.length;u++){const h=t[u];typeof h=="string"&&(t[u]=parseFloat(h))}else zo[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let o=0;o<t.length;o++)(t[o]===null||jH(t[o]))&&s.push(o);s.length&&AH(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=zo[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const o=n[n.length-1];o!==void 0&&t.getValue(s,o).jump(o,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const o=t.getValue(n);o&&o.jump(this.measuredOrigin,!1);const r=s.length-1,a=s[r];s[r]=zo[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 Ex=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function sN(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const o=n?.[e]??s.querySelectorAll(e);return o?Array.from(o):[]}return Array.from(e).filter(s=>s!=null)}const bm=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function Ld(e){return d1(e)&&"offsetHeight"in e&&!("ownerSVGElement"in e)}const{schedule:Px}=k1(queueMicrotask,!1),li={x:!1,y:!1};function iN(){return li.x||li.y}function RH(e){return e==="x"||e==="y"?li[e]?null:(li[e]=!0,()=>{li[e]=!1}):li.x||li.y?null:(li.x=li.y=!0,()=>{li.x=li.y=!1})}function oN(e,t){const n=sN(e),s=new AbortController,o={passive:!0,...t,signal:s.signal};return[n,o,()=>s.abort()]}function LH(e){return!(e.pointerType==="touch"||iN())}function OH(e,t,n={}){const[s,o,r]=oN(e,n);return s.forEach(a=>{let l=!1,c=!1,d;const u=()=>{a.removeEventListener("pointerleave",g)},h=v=>{d&&(d(v),d=void 0),u()},p=v=>{l=!1,window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),c&&(c=!1,h(v))},f=()=>{l=!0,window.addEventListener("pointerup",p,o),window.addEventListener("pointercancel",p,o)},g=v=>{if(v.pointerType!=="touch"){if(l){c=!0;return}h(v)}},x=v=>{if(!LH(v))return;c=!1;const y=t(a,v);typeof y=="function"&&(d=y,a.addEventListener("pointerleave",g,o))};a.addEventListener("pointerenter",x,o),a.addEventListener("pointerdown",f,o)}),r}const rN=(e,t)=>t?e===t?!0:rN(e,t.parentElement):!1,Ax=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,zH=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function GH(e){return zH.has(e.tagName)||e.isContentEditable===!0}const FH=new Set(["INPUT","SELECT","TEXTAREA"]);function HH(e){return FH.has(e.tagName)||e.isContentEditable===!0}const Od=new WeakSet;function Nb(e){return t=>{t.key==="Enter"&&e(t)}}function _p(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const BH=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=Nb(()=>{if(Od.has(n))return;_p(n,"down");const o=Nb(()=>{_p(n,"up")}),r=()=>_p(n,"cancel");n.addEventListener("keyup",o,t),n.addEventListener("blur",r,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function Tb(e){return Ax(e)&&!iN()}const Ib=new WeakSet;function VH(e,t,n={}){const[s,o,r]=oN(e,n),a=l=>{const c=l.currentTarget;if(!Tb(l)||Ib.has(l))return;Od.add(c),n.stopPropagation&&Ib.add(l);const d=t(c,l),u={...o,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",p,u),window.removeEventListener("pointercancel",f,u),Od.has(c)&&Od.delete(c),Tb(g)&&typeof d=="function"&&d(g,{success:x})},p=g=>{h(g,c===window||c===document||n.useGlobalTarget||rN(c,g.target))},f=g=>{h(g,!1)};window.addEventListener("pointerup",p,u),window.addEventListener("pointercancel",f,u)};return s.forEach(l=>{(n.useGlobalTarget?window:l).addEventListener("pointerdown",a,o),Ld(l)&&(l.addEventListener("focus",d=>BH(d,o)),!GH(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),r}function Mx(e){return d1(e)&&"ownerSVGElement"in e}const zd=new WeakMap;let Gd;const aN=(e,t,n)=>(s,o)=>o&&o[0]?o[0][e+"Size"]:Mx(s)&&"getBBox"in s?s.getBBox()[t]:s[n],$H=aN("inline","width","offsetWidth"),WH=aN("block","height","offsetHeight");function UH({target:e,borderBoxSize:t}){zd.get(e)?.forEach(n=>{n(e,{get width(){return $H(e,t)},get height(){return WH(e,t)}})})}function KH(e){e.forEach(UH)}function qH(){typeof ResizeObserver>"u"||(Gd=new ResizeObserver(KH))}function YH(e,t){Gd||qH();const n=sN(e);return n.forEach(s=>{let o=zd.get(s);o||(o=new Set,zd.set(s,o)),o.add(t),Gd?.observe(s)}),()=>{n.forEach(s=>{const o=zd.get(s);o?.delete(t),o?.size||Gd?.unobserve(s)})}}const Fd=new Set;let Yr;function XH(){Yr=()=>{const e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Fd.forEach(t=>t(e))},window.addEventListener("resize",Yr)}function JH(e){return Fd.add(e),Yr||XH(),()=>{Fd.delete(e),!Fd.size&&typeof Yr=="function"&&(window.removeEventListener("resize",Yr),Yr=void 0)}}function Db(e,t){return typeof e=="function"?JH(e):YH(e,t)}function ZH(e){return Mx(e)&&e.tagName==="svg"}const QH=[...eN,Un,gi],eB=e=>QH.find(Q1(e)),Eb=()=>({translate:0,scale:1,origin:0,originPoint:0}),Xr=()=>({x:Eb(),y:Eb()}),Pb=()=>({min:0,max:0}),Xn=()=>({x:Pb(),y:Pb()}),tB=new WeakMap;function Nh(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function Wl(e){return typeof e=="string"||Array.isArray(e)}const Rx=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Lx=["initial",...Rx];function Th(e){return Nh(e.animate)||Lx.some(t=>Wl(e[t]))}function lN(e){return!!(Th(e)||e.variants)}function nB(e,t,n){for(const s in t){const o=t[s],r=n[s];if(hs(o))e.addValue(s,o);else if(hs(r))e.addValue(s,ga(o,{owner:e}));else if(r!==o)if(e.hasValue(s)){const a=e.getValue(s);a.liveStyle===!0?a.jump(o):a.hasAnimated||a.set(o)}else{const a=e.getStaticValue(s);e.addValue(s,ga(a!==void 0?a:o,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const Su={current:null},Ox={current:!1},sB=typeof window<"u";function cN(){if(Ox.current=!0,!!sB)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>Su.current=e.matches;e.addEventListener("change",t),t()}else Su.current=!1}const Ab=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Cu={};function dN(e){Cu=e}function iB(){return Cu}class oB{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:o,skipAnimations:r,blockInitialAnimation:a,visualState:l},c={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=_x,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=ks.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,kn.render(this.render,!1,!0))};const{latestValues:d,renderState:u}=l;this.latestValues=d,this.baseTarget={...d},this.initialValues=n.initial?{...d}:{},this.renderState=u,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=o,this.skipAnimationsConfig=r,this.options=c,this.blockInitialAnimation=!!a,this.isControllingVariants=Th(n),this.isVariantNode=lN(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:h,...p}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in p){const g=p[f];d[f]!==void 0&&hs(g)&&g.set(d[f])}}mount(t){if(this.hasBeenMounted)for(const n in this.initialValues)this.values.get(n)?.jump(this.initialValues[n]),this.latestValues[n]=this.initialValues[n];this.current=t,tB.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:(Ox.current||cN(),this.shouldReduceMotion=Su.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(),Fo(this.notifyUpdate),Fo(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&&W1.has(t)&&this.current instanceof HTMLElement){const{factory:a,keyframes:l,times:c,ease:d,duration:u}=n.accelerate,h=new V1({element:this.current,name:t,keyframes:l,times:c,ease:d,duration:Hs(u)}),p=a(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const s=Aa.has(t);s&&this.onBindTransform&&this.onBindTransform();const o=n.on("change",a=>{this.latestValues[t]=a,this.props.onUpdate&&kn.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let r;typeof window<"u"&&window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{o(),r&&r()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in Cu){const n=Cu[t];if(!n)continue;const{isEnabled:s,Feature:o}=n;if(!this.features[t]&&o&&s(this.props)&&(this.features[t]=new o(this)),this.features[t]){const r=this.features[t];r.isMounted?r.update():(r.mount(),r.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Xn()}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<Ab.length;s++){const o=Ab[s];this.propEventSubscriptions[o]&&(this.propEventSubscriptions[o](),delete this.propEventSubscriptions[o]);const r="on"+o,a=t[r];a&&(this.propEventSubscriptions[o]=this.on(o,a))}this.prevMotionValues=nB(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=ga(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"&&(c1(s)||u1(s))?s=parseFloat(s):!eB(s)&&gi.test(n)&&(s=nN(t,n)),this.setBaseTarget(t,hs(s)?s.get():s)),hs(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=Ix(this.props,n,this.presenceContext?.custom);r&&(s=r[t])}if(n&&s!==void 0)return s;const o=this.getBaseTargetFromProps(this.props,t);return o!==void 0&&!hs(o)?o:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new xx),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Px.render(this.render)}}class uN extends oB{constructor(){super(...arguments),this.KeyframeResolver=MH}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;hs(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class qo{constructor(t){this.isMounted=!1,this.node=t}update(){}}function hN({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function rB({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function aB(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 Np(e){return e===void 0||e===1}function wm({scale:e,scaleX:t,scaleY:n}){return!Np(e)||!Np(t)||!Np(n)}function ar(e){return wm(e)||pN(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function pN(e){return Mb(e.x)||Mb(e.y)}function Mb(e){return e&&e!=="0%"}function ku(e,t,n){const s=e-n,o=t*s;return n+o}function Rb(e,t,n,s,o){return o!==void 0&&(e=ku(e,o,s)),ku(e,n,s)+t}function ym(e,t=0,n=1,s,o){e.min=Rb(e.min,t,n,s,o),e.max=Rb(e.max,t,n,s,o)}function fN(e,{x:t,y:n}){ym(e.x,t.translate,t.scale,t.originPoint),ym(e.y,n.translate,n.scale,n.originPoint)}const Lb=.999999999999,Ob=1.0000000000001;function lB(e,t,n,s=!1){const o=n.length;if(!o)return;t.x=t.y=1;let r,a;for(let l=0;l<o;l++){r=n[l],a=r.projectionDelta;const{visualElement:c}=r.options;c&&c.props.style&&c.props.style.display==="contents"||(s&&r.options.layoutScroll&&r.scroll&&r!==r.root&&(Ei(e.x,-r.scroll.offset.x),Ei(e.y,-r.scroll.offset.y)),a&&(t.x*=a.x.scale,t.y*=a.y.scale,fN(e,a)),s&&ar(r.latestValues)&&Hd(e,r.latestValues,r.layout?.layoutBox))}t.x<Ob&&t.x>Lb&&(t.x=1),t.y<Ob&&t.y>Lb&&(t.y=1)}function Ei(e,t){e.min+=t,e.max+=t}function zb(e,t,n,s,o=.5){const r=Cn(e.min,e.max,o);ym(e,t,n,r,s)}function Gb(e,t){return typeof e=="string"?parseFloat(e)/100*(t.max-t.min):e}function Hd(e,t,n){const s=n??e;zb(e.x,Gb(t.x,s.x),t.scaleX,t.scale,t.originX),zb(e.y,Gb(t.y,s.y),t.scaleY,t.scale,t.originY)}function mN(e,t){return hN(aB(e.getBoundingClientRect(),t))}function cB(e,t,n){const s=mN(e,n),{scroll:o}=t;return o&&(Ei(s.x,o.offset.x),Ei(s.y,o.offset.y)),s}const dB={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},uB=Pa.length;function hB(e,t,n){let s="",o=!0;for(let a=0;a<uB;a++){const l=Pa[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=bm(c,yu[l]);if(!d){o=!1;const h=dB[l]||l;s+=`${h}(${u}) `}n&&(t[l]=u)}}const r=e.pathRotation;return r&&(o=!1,s+=`rotate(${bm(r,yu.pathRotation)}) `),s=s.trim(),n?s=n(t,o?"":s):o&&(s="none"),s}function zx(e,t,n){const{style:s,vars:o,transformOrigin:r}=e;let a=!1,l=!1;for(const c in t){const d=t[c];if(Aa.has(c)){a=!0;continue}else if(_1(c)){o[c]=d;continue}else{const u=bm(d,yu[c]);c.startsWith("origin")?(l=!0,r[c]=u):s[c]=u}}if(t.transform||(a||n?s.transform=hB(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 gN(e,{style:t,vars:n},s,o){const r=e.style;let a;for(a in t)r[a]=t[a];o?.applyProjectionStyles(r,s);for(a in n)r.setProperty(a,n[a])}function Fb(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Ga={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(xt.test(e))e=parseFloat(e);else return e;const n=Fb(e,t.target.x),s=Fb(e,t.target.y);return`${n}% ${s}%`}},pB={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,o=gi.parse(e);if(o.length>5)return s;const r=gi.createTransformer(e),a=typeof o[0]!="number"?1:0,l=n.x.scale*t.x,c=n.y.scale*t.y;o[0+a]/=l,o[1+a]/=c;const d=Cn(l,c,.5);return typeof o[2+a]=="number"&&(o[2+a]/=d),typeof o[3+a]=="number"&&(o[3+a]/=d),r(o)}},Sm={borderRadius:{...Ga,applyTo:[...Ex]},borderTopLeftRadius:Ga,borderTopRightRadius:Ga,borderBottomLeftRadius:Ga,borderBottomRightRadius:Ga,boxShadow:pB};function xN(e,{layout:t,layoutId:n}){return Aa.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Sm[e]||e==="opacity")}function Gx(e,t,n){const s=e.style,o=t?.style,r={};if(!s)return r;for(const a in s)(hs(s[a])||o&&hs(o[a])||xN(a,e)||n?.getValue(a)?.liveStyle!==void 0)&&(r[a]=s[a]);return r}function fB(e){return window.getComputedStyle(e)}class mB extends uN{constructor(){super(...arguments),this.type="html",this.renderInstance=gN}mount(t){jh(!!t.style),super.mount(t)}readValueFromInstance(t,n){if(Aa.has(n))return this.projection?.isProjecting?lm(n):RF(t,n);{const s=fB(t),o=(_1(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return mN(t,n)}build(t,n,s){zx(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return Gx(t,n,s)}}const gB={offset:"stroke-dashoffset",array:"stroke-dasharray"},xB={offset:"strokeDashoffset",array:"strokeDasharray"};function vB(e,t,n=1,s=0,o=!0){e.pathLength=1;const r=o?gB:xB;e[r.offset]=`${-s}`,e[r.array]=`${t} ${n}`}const vN=["transform","opacity","offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function bN(e,{attrX:t,attrY:n,attrScale:s,pathLength:o,pathSpacing:r=1,pathOffset:a=0,...l},c,d,u){if(zx(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 vN)h[f]!==void 0&&(p[f]=h[f],delete h[f]);(p.transform||h.transformOrigin)&&(p.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),p.transform&&(p.transformBox=u?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),o!==void 0&&vB(h,o,r,a,!1)}const wN=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"]),yN=e=>typeof e=="string"&&e.toLowerCase()==="svg";function bB(e,t,n,s){gN(e,t,void 0,s);for(const o in t.attrs)e.setAttribute(wN.has(o)?o:Dx(o),t.attrs[o])}function SN(e,t,n){const s=Gx(e,t,n);for(const o in e)if(hs(e[o])||hs(t[o])){const r=Pa.indexOf(o)!==-1?"attr"+o.charAt(0).toUpperCase()+o.substring(1):o;s[r]=e[o]}return s}class wB extends uN{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Xn}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Aa.has(n)){const s=tN(n);return s&&s.default||0}if(vN.includes(n)){const o=getComputedStyle(t)[n];if(typeof o=="string"&&o)return o.trim()}return n=wN.has(n)?n:Dx(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return SN(t,n,s)}build(t,n,s){bN(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,o){bB(t,n,s,o)}mount(t){this.isSVGTag=yN(t.tagName),super.mount(t)}}const yB=Lx.length;function CN(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?CN(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<yB;n++){const s=Lx[n],o=e.props[s];(Wl(o)||o===!1)&&(t[s]=o)}return t}function kN(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 SB=[...Rx].reverse(),CB=Rx.length;function kB(e){return t=>Promise.all(t.map(({animation:n,options:s})=>CH(e,n,s)))}function jB(e){let t=kB(e),n=Hb(),s=!0,o=!1;const r=d=>(u,h)=>{const p=wr(e,h,d==="exit"?e.presenceContext?.custom:void 0);if(p){const{transition:f,transitionEnd:g,...x}=p;u={...u,...x,...g}}return u};function a(d){t=d(e)}function l(d){const{props:u}=e,h=CN(e.parent)||{},p=[],f=new Set;let g={},x=1/0;for(let y=0;y<CB;y++){const b=SB[y],w=n[b],C=u[b]!==void 0?u[b]:h[b],_=Wl(C),N=b===d?w.isActive:null;N===!1&&(x=y);let k=C===h[b]&&C!==u[b]&&_;if(k&&(s||o)&&e.manuallyAnimateOnMount&&(k=!1),w.protectedKeys={...g},!w.isActive&&N===null||!C&&!w.prevProp||Nh(C)||typeof C=="boolean")continue;if(b==="exit"&&w.isActive&&N!==!0){w.prevResolvedValues&&(g={...g,...w.prevResolvedValues});continue}const S=_B(w.prevProp,C);let A=S||b===d&&w.isActive&&!k&&_||y>x&&_,T=!1;const I=Array.isArray(C)?C:[C];let P=I.reduce(r(b),{});N===!1&&(P={});const{prevResolvedValues:D={}}=w,O={...D,...P},z=X=>{A=!0,f.has(X)&&(T=!0,f.delete(X)),w.needsAnimating[X]=!0;const H=e.getValue(X);H&&(H.liveStyle=!1)};for(const X in O){const H=P[X],te=D[X];if(g.hasOwnProperty(X))continue;let V=!1;fm(H)&&fm(te)?V=!kN(H,te)||S:V=H!==te,V?H!=null?z(X):f.add(X):H!==void 0&&f.has(X)?z(X):w.protectedKeys[X]=!0}w.prevProp=C,w.prevResolvedValues=P,w.isActive&&(g={...g,...P}),(s||o)&&e.blockInitialAnimation&&(A=!1);const R=k&&S;A&&(!R||T)&&p.push(...I.map(X=>{const H={type:b};if(typeof X=="string"&&(s||o)&&!R&&e.manuallyAnimateOnMount&&e.parent){const{parent:te}=e,V=wr(te,X);if(te.enteringChildren&&V){const{delayChildren:Y}=V.transition||{};H.delay=U1(te.enteringChildren,e,Y)}}return{animation:X,options:H}}))}if(f.size){const y={};if(typeof u.initial!="boolean"){const b=wr(e,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(y.transition=b.transition)}f.forEach(b=>{const w=e.getBaseTarget(b),C=e.getValue(b);C&&(C.liveStyle=!0),y[b]=w??null}),p.push({animation:y})}let v=!!p.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(v=!1),s=!1,o=!1,v?t(p):Promise.resolve()}function c(d,u){if(n[d].isActive===u)return Promise.resolve();e.variantChildren?.forEach(p=>p.animationState?.setActive(d,u)),n[d].isActive=u;const h=l(d);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:l,setActive:c,setAnimateFunction:a,getState:()=>n,reset:()=>{n=Hb(),o=!0}}}function _B(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!kN(t,e):!1}function nr(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Hb(){return{animate:nr(!0),whileInView:nr(),whileHover:nr(),whileTap:nr(),whileDrag:nr(),whileFocus:nr(),exit:nr()}}function Cm(e,t){e.min=t.min,e.max=t.max}function ri(e,t){Cm(e.x,t.x),Cm(e.y,t.y)}function Bb(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}const jN=1e-4,NB=1-jN,TB=1+jN,_N=.01,IB=0-_N,DB=0+_N;function js(e){return e.max-e.min}function EB(e,t,n){return Math.abs(e-t)<=n}function Vb(e,t,n,s=.5){e.origin=s,e.originPoint=Cn(t.min,t.max,e.origin),e.scale=js(n)/js(t),e.translate=Cn(n.min,n.max,e.origin)-e.originPoint,(e.scale>=NB&&e.scale<=TB||isNaN(e.scale))&&(e.scale=1),(e.translate>=IB&&e.translate<=DB||isNaN(e.translate))&&(e.translate=0)}function xl(e,t,n,s){Vb(e.x,t.x,n.x,s?s.originX:void 0),Vb(e.y,t.y,n.y,s?s.originY:void 0)}function $b(e,t,n,s=0){const o=s?Cn(n.min,n.max,s):n.min;e.min=o+t.min,e.max=e.min+js(t)}function PB(e,t,n,s){$b(e.x,t.x,n.x,s?.x),$b(e.y,t.y,n.y,s?.y)}function Wb(e,t,n,s=0){const o=s?Cn(n.min,n.max,s):n.min;e.min=t.min-o,e.max=e.min+js(t)}function ju(e,t,n,s){Wb(e.x,t.x,n.x,s?.x),Wb(e.y,t.y,n.y,s?.y)}function Ub(e,t,n,s,o){return e-=t,e=ku(e,1/n,s),o!==void 0&&(e=ku(e,1/o,s)),e}function AB(e,t=0,n=1,s=.5,o,r=e,a=e){if(Hi.test(t)&&(t=parseFloat(t),t=Cn(a.min,a.max,t/100)-a.min),typeof t!="number")return;let l=Cn(r.min,r.max,s);e===r&&(l-=t),e.min=Ub(e.min,t,n,l,o),e.max=Ub(e.max,t,n,l,o)}function Kb(e,t,[n,s,o],r,a){AB(e,t[n],t[s],t[o],t.scale,r,a)}const MB=["x","scaleX","originX"],RB=["y","scaleY","originY"];function qb(e,t,n,s){Kb(e.x,t,MB,n?n.x:void 0,s?s.x:void 0),Kb(e.y,t,RB,n?n.y:void 0,s?s.y:void 0)}function Yb(e){return e.translate===0&&e.scale===1}function NN(e){return Yb(e.x)&&Yb(e.y)}function Xb(e,t){return e.min===t.min&&e.max===t.max}function LB(e,t){return Xb(e.x,t.x)&&Xb(e.y,t.y)}function Jb(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function TN(e,t){return Jb(e.x,t.x)&&Jb(e.y,t.y)}function Zb(e){return js(e.x)/js(e.y)}function Qb(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function Di(e){return[e("x"),e("y")]}function OB(e,t,n){let s="";const o=e.x.translate/t.x,r=e.y.translate/t.y,a=n?.z||0;if((o||r||a)&&(s=`translate3d(${o}px, ${r}px, ${a}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:d,rotate:u,pathRotation:h,rotateX:p,rotateY:f,skewX:g,skewY:x}=n;d&&(s=`perspective(${d}px) ${s}`),u&&(s+=`rotate(${u}deg) `),h&&(s+=`rotate(${h}deg) `),p&&(s+=`rotateX(${p}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),x&&(s+=`skewY(${x}deg) `)}const l=e.x.scale*t.x,c=e.y.scale*t.y;return(l!==1||c!==1)&&(s+=`scale(${l}, ${c})`),s||"none"}const zB=Ex.length,ew=e=>typeof e=="string"?parseFloat(e):e,tw=e=>typeof e=="number"||xt.test(e);function GB(e,t,n,s,o,r){o?(e.opacity=Cn(0,n.opacity??1,FB(s)),e.opacityExit=Cn(t.opacity??1,0,HB(s))):r&&(e.opacity=Cn(t.opacity??1,n.opacity??1,s));for(let a=0;a<zB;a++){const l=Ex[a];let c=nw(t,l),d=nw(n,l);if(c===void 0&&d===void 0)continue;c||(c=0),d||(d=0),c===0||d===0||tw(c)===tw(d)?(e[l]=Math.max(Cn(ew(c),ew(d),s),0),(Hi.test(d)||Hi.test(c))&&(e[l]+="%")):e[l]=d}(t.rotate||n.rotate)&&(e.rotate=Cn(t.rotate||0,n.rotate||0,s))}function nw(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const FB=IN(0,.5,w1),HB=IN(.5,.95,Qs);function IN(e,t,n){return s=>s<e?0:s>t?1:n(Vl(e,t,s))}function BB(e,t,n){const s=hs(e)?e:ga(e);return s.start(Tx("",s,t,n)),s.animation}function Ul(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}const VB=(e,t)=>e.depth-t.depth;class $B{constructor(){this.children=[],this.isDirty=!1}add(t){gx(this.children,t),this.isDirty=!0}remove(t){gu(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(VB),this.isDirty=!1,this.children.forEach(t)}}function WB(e,t){const n=ks.now(),s=({timestamp:o})=>{const r=o-n;r>=t&&(Fo(s),e(r-t))};return kn.setup(s,!0),()=>Fo(s)}function Bd(e){return hs(e)?e.get():e}class UB{constructor(){this.members=[]}add(t){gx(this.members,t);for(let n=this.members.length-1;n>=0;n--){const s=this.members[n];if(s===t||s===this.lead||s===this.prevLead)continue;const o=s.instance;(!o||o.isConnected===!1)&&!s.snapshot&&(gu(this.members,s),s.unmount())}t.scheduleRender()}remove(t){if(gu(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){for(let n=this.members.indexOf(t)-1;n>=0;n--){const s=this.members[n];if(s.isPresent!==!1&&s.instance?.isConnected!==!1)return this.promote(s),!0}return!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.updateSnapshot(),t.scheduleRender();const{layoutDependency:o}=s.options,{layoutDependency:r}=t.options;(o===void 0||o!==r)&&(t.resumeFrom=s,n&&(s.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root?.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{t.options.onExitComplete?.(),t.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(t=>t.instance&&t.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}}const Vd={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Tp=["","X","Y","Z"],KB=1e3;let qB=0;function Ip(e,t,n,s){const{latestValues:o}=t;o[e]&&(n[e]=o[e],t.setStaticValue(e,0),s&&(s[e]=0))}function DN(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=J1(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:o,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",kn,!(o||r))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&DN(s)}function EN({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:o}){return class{constructor(a={},l=t?.()){this.id=qB++,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(JB),this.nodes.forEach(sV),this.nodes.forEach(iV),this.nodes.forEach(ZB)},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 $B)}addEventListener(a,l){return this.eventHandlers.has(a)||this.eventHandlers.set(a,new xx),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=Mx(a)&&!ZH(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;kn.read(()=>{h=window.innerWidth}),e(a,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=WB(p,250),Vd.hasAnimatedSinceResize&&(Vd.hasAnimatedSinceResize=!1,this.nodes.forEach(ow)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&d&&(l||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:p,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||cV,{onLayoutAnimationStart:x,onLayoutAnimationComplete:v}=d.getProps(),y=!this.targetLayout||!TN(this.targetLayout,f),b=!h&&p;if(this.options.layoutRoot||this.resumeFrom||b||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...Nx(g,"layout"),onPlay:x,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,b,w.path)}else h||ow(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(),Fo(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(oV),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&&DN(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(eV),this.nodes.forEach(sw);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(iw);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(tV),this.nodes.forEach(nV),this.nodes.forEach(YB),this.nodes.forEach(XB)):this.nodes.forEach(iw),this.clearAllSnapshots();const l=ks.now();us.delta=Vi(0,1e3/60,l-us.timestamp),us.timestamp=l,us.isProcessing=!0,wp.update.process(us),wp.preRender.process(us),wp.render.process(us),us.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Px.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(QB),this.sharedNodes.forEach(rV)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,kn.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){kn.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!js(this.snapshot.measuredBox.x)&&!js(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=Xn()),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:l}=this.options;l&&l.notify("LayoutMeasure",this.layout.layoutBox,a?a.layoutBox:void 0)}updateScroll(a="measure"){let l=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===a&&(l=!1),l&&this.instance){const c=s(this.instance);this.scroll={animationId:this.root.animationId,phase:a,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!o)return;const a=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,l=this.projectionDelta&&!NN(this.projectionDelta),c=this.getTransformTemplate(),d=c?c(this.latestValues,""):void 0,u=d!==this.prevTransformTemplateValue;a&&this.instance&&(l||ar(this.latestValues)||u)&&(o(this.instance,d),this.shouldResetTransform=!1,this.scheduleRender())}measure(a=!0){const l=this.measurePageBox();let c=this.removeElementScroll(l);return a&&(c=this.removeTransform(c)),dV(c),{animationId:this.root.animationId,measuredBox:l,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:a}=this.options;if(!a)return Xn();const l=a.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(uV))){const{scroll:d}=this.root;d&&(Ei(l.x,d.offset.x),Ei(l.y,d.offset.y))}return l}removeElementScroll(a){const l=Xn();if(ri(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&&ri(l,a),Ei(l.x,u.offset.x),Ei(l.y,u.offset.y))}return l}applyTransform(a,l=!1,c){const d=c||Xn();ri(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&&(Ei(d.x,-h.scroll.offset.x),Ei(d.y,-h.scroll.offset.y)),ar(h.latestValues)&&Hd(d,h.latestValues,h.layout?.layoutBox)}return ar(this.latestValues)&&Hd(d,this.latestValues,this.layout?.layoutBox),d}removeTransform(a){const l=Xn();ri(l,a);for(let c=0;c<this.path.length;c++){const d=this.path[c];if(!ar(d.latestValues))continue;let u;d.instance&&(wm(d.latestValues)&&d.updateSnapshot(),u=Xn(),ri(u,d.measurePageBox())),qb(l,d.latestValues,d.snapshot?.layoutBox,u)}return ar(this.latestValues)&&qb(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!==us.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=us.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=Xn(),this.targetWithTransforms=Xn()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),PB(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):ri(this.target,this.layout.layoutBox),fN(this.target,this.targetDelta)):ri(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||wm(this.parent.latestValues)||pN(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=Xn(),this.relativeTargetOrigin=Xn(),ju(this.relativeTargetOrigin,l,c,this.options.layoutAnchor||void 0),ri(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===us.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;ri(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,p=this.treeScale.y;lB(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=Xn());const{target:f}=a;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Bb(this.prevProjectionDelta.x,this.projectionDelta.x),Bb(this.prevProjectionDelta.y,this.projectionDelta.y)),xl(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==p||!Qb(this.projectionDelta.x,this.prevProjectionDelta.x)||!Qb(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",f))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(a=!0){if(this.options.visualElement?.scheduleRender(),a){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Xr(),this.projectionDelta=Xr(),this.projectionDeltaWithTransform=Xr()}setAnimationOrigin(a,l=!1,c){const d=this.snapshot,u=d?d.latestValues:{},h={...this.latestValues},p=Xr();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const f=Xn(),g=d?d.source:void 0,x=this.layout?this.layout.source:void 0,v=g!==x,y=this.getStack(),b=!y||y.members.length<=1,w=!!(v&&!b&&this.options.crossfade===!0&&!this.path.some(lV));this.animationProgress=0;let C;const _=c?.interpolateProjection(a);this.mixTargetDelta=N=>{const k=N/1e3,S=_?.(k);S?(p.x.translate=S.x,p.x.scale=Cn(a.x.scale,1,k),p.x.origin=a.x.origin,p.x.originPoint=a.x.originPoint,p.y.translate=S.y,p.y.scale=Cn(a.y.scale,1,k),p.y.origin=a.y.origin,p.y.originPoint=a.y.originPoint):(rw(p.x,a.x,k),rw(p.y,a.y,k)),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ju(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),aV(this.relativeTarget,this.relativeTargetOrigin,f,k),C&&LB(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=Xn()),ri(C,this.relativeTarget)),v&&(this.animationValues=h,GB(h,u,this.latestValues,k,w,b)),S&&S.rotate!==void 0&&(this.animationValues||(this.animationValues=h),this.animationValues.pathRotation=S.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=k},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(a){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(Fo(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=kn.update(()=>{Vd.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ga(0)),this.motionValue.jump(0,!1),this.currentAnimation=BB(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(KB),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&&PN(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Xn();const h=js(this.layout.layoutBox.x);c.x.min=a.target.x.min,c.x.max=c.x.min+h;const p=js(this.layout.layoutBox.y);c.y.min=a.target.y.min,c.y.max=c.y.min+p}ri(l,c),Hd(l,u),xl(this.projectionDeltaWithTransform,this.layoutCorrected,l,u)}}registerSharedNode(a,l){this.sharedNodes.has(a)||this.sharedNodes.set(a,new UB),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&&Ip("z",a,d,this.animationValues);for(let u=0;u<Tp.length;u++)Ip(`rotate${Tp[u]}`,a,d,this.animationValues),Ip(`skew${Tp[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=Bd(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=Bd(l?.pointerEvents)||""),this.hasProjected&&!ar(this.latestValues)&&(a.transform=c?c({},""):"none",this.hasProjected=!1);return}a.visibility="";const u=d.animationValues||d.latestValues;this.applyTransformsToTarget();let h=OB(this.projectionDeltaWithTransform,this.treeScale,u);c&&(h=c(u,h)),a.transform=h;const{x:p,y:f}=this.projectionDelta;a.transformOrigin=`${p.origin*100}% ${f.origin*100}% 0`,d.animationValues?a.opacity=d===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:a.opacity=d===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const g in Sm){if(u[g]===void 0)continue;const{correct:x,applyTo:v,isCSSVariable:y}=Sm[g],b=h==="none"?u[g]:x(u[g],d);if(v){const w=v.length;for(let C=0;C<w;C++)a[v[C]]=b}else y?this.options.visualElement.renderState.vars[g]=b:a[g]=b}this.options.layoutId&&(a.pointerEvents=d===this?Bd(l?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(a=>a.currentAnimation?.stop()),this.root.nodes.forEach(sw),this.root.sharedNodes.clear()}}}function YB(e){e.updateLayout()}function XB(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:o}=e.options,r=t.source!==e.layout.source;if(o==="size")Di(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=js(h);h.min=n[u].min,h.max=h.min+p});else if(o==="x"||o==="y"){const u=o==="x"?"y":"x";Cm(r?t.measuredBox[u]:t.layoutBox[u],n[u])}else PN(o,t.layoutBox,n)&&Di(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=js(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=Xr();xl(a,n,t.layoutBox);const l=Xr();r?xl(l,e.applyTransform(s,!0),t.measuredBox):xl(l,n,t.layoutBox);const c=!NN(a);let d=!1;if(!e.resumeFrom){const u=e.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:p}=u;if(h&&p){const f=e.options.layoutAnchor||void 0,g=Xn();ju(g,t.layoutBox,h.layoutBox,f);const x=Xn();ju(x,n,p.layoutBox,f),TN(g,x)||(d=!0),u.options.layoutRoot&&(e.relativeTarget=x,e.relativeTargetOrigin=g,e.relativeParent=u)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:d})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function JB(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 ZB(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function QB(e){e.clearSnapshot()}function sw(e){e.clearMeasurements()}function eV(e){e.isLayoutDirty=!0,e.updateLayout()}function iw(e){e.isLayoutDirty=!1}function tV(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function nV(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function ow(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function sV(e){e.resolveTargetDelta()}function iV(e){e.calcProjection()}function oV(e){e.resetSkewAndRotation()}function rV(e){e.removeLeadSnapshot()}function rw(e,t,n){e.translate=Cn(t.translate,0,n),e.scale=Cn(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function aw(e,t,n,s){e.min=Cn(t.min,n.min,s),e.max=Cn(t.max,n.max,s)}function aV(e,t,n,s){aw(e.x,t.x,n.x,s),aw(e.y,t.y,n.y,s)}function lV(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const cV={duration:.45,ease:[.4,0,.1,1]},lw=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),cw=lw("applewebkit/")&&!lw("chrome/")?Math.round:Qs;function dw(e){e.min=cw(e.min),e.max=cw(e.max)}function dV(e){dw(e.x),dw(e.y)}function PN(e,t,n){return e==="position"||e==="preserve-aspect"&&!EB(Zb(t),Zb(n),.2)}function uV(e){return e!==e.root&&e.scroll?.wasRoot}const hV=EN({attachResizeListener:(e,t)=>Ul(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Dp={current:void 0},AN=EN({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Dp.current){const e=new hV({});e.mount(window),e.setOptions({layoutScroll:!0}),Dp.current=e}return Dp.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),Fx=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function uw(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function pV(...e){return t=>{let n=!1;const s=e.map(o=>{const r=uw(o,t);return!n&&typeof r=="function"&&(n=!0),r});if(n)return()=>{for(let o=0;o<s.length;o++){const r=s[o];typeof r=="function"?r():uw(e[o],null)}}}}function fV(...e){return m.useCallback(pV(...e),e)}class mV extends m.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(Ld(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,o=Ld(s)&&s.offsetWidth||0,r=Ld(s)&&s.offsetHeight||0,a=getComputedStyle(n),l=this.props.sizeRef.current;l.height=parseFloat(a.height),l.width=parseFloat(a.width),l.top=n.offsetTop,l.left=n.offsetLeft,l.right=o-l.width-l.left,l.bottom=r-l.height-l.top,l.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function gV({children:e,isPresent:t,anchorX:n,anchorY:s,root:o,pop:r}){const a=m.useId(),l=m.useRef(null),c=m.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:d}=m.useContext(Fx),u=r!==!1?e.props?.ref??e?.ref:void 0,h=fV(l,u);return m.useInsertionEffect(()=>{const{width:p,height:f,top:g,left:x,right:v,bottom:y,direction:b}=c.current;if(t||r===!1||!l.current||!p||!f)return;const w=b==="rtl",C=n==="left"?w?`right: ${v}`:`left: ${x}`:w?`left: ${x}`:`right: ${v}`,_=s==="bottom"?`bottom: ${y}`:`top: ${g}`;l.current.dataset.motionPopId=a;const N=document.createElement("style");d&&(N.nonce=d);const k=o??document.head;return k.appendChild(N),N.sheet&&N.sheet.insertRule(`
6
- [data-motion-pop-id="${a}"] {
7
- position: absolute !important;
8
- width: ${p}px !important;
9
- height: ${f}px !important;
10
- ${C}px !important;
11
- ${_}px !important;
12
- }
13
- `),()=>{l.current?.removeAttribute("data-motion-pop-id"),k.contains(N)&&k.removeChild(N)}},[t]),i.jsx(mV,{isPresent:t,childRef:l,sizeRef:c,pop:r,children:r===!1?e:m.cloneElement(e,{ref:h})})}const xV=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:o,presenceAffectsLayout:r,mode:a,anchorX:l,anchorY:c,root:d})=>{const u=mx(vV),h=m.useId(),p=m.useRef(n),f=m.useRef(s);mu(()=>{p.current=n,f.current=s});let g=!0,x=m.useMemo(()=>(g=!1,{id:h,initial:t,isPresent:n,custom:o,onExitComplete:v=>{u.set(v,!0);for(const y of u.values())if(!y)return;s&&s()},register:v=>(u.set(v,!1),()=>{u.delete(v),!p.current&&!u.size&&f.current?.()})}),[n,u,s]);return r&&g&&(x={...x}),m.useMemo(()=>{u.forEach((v,y)=>u.set(y,!1))},[n]),m.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),e=i.jsx(gV,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:d,children:e}),i.jsx(kh.Provider,{value:x,children:e})};function vV(){return new Map}function MN(e=!0){const t=m.useContext(kh);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:o}=t,r=m.useId();m.useEffect(()=>{if(e)return o(r)},[e]);const a=m.useCallback(()=>e&&s&&s(r),[r,s,e]);return!n&&s?[!1,a]:[!0]}const Hc=e=>e.key||"";function hw(e){const t=[];return m.Children.forEach(e,n=>{m.isValidElement(n)&&t.push(n)}),t}const vl=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:o=!0,mode:r="sync",propagate:a=!1,anchorX:l="left",anchorY:c="top",root:d})=>{const[u,h]=MN(a),p=m.useMemo(()=>hw(e),[e]),f=a&&!u?[]:p.map(Hc),g=m.useRef(!0),x=m.useRef(p),v=mx(()=>new Map),y=m.useRef(new Set),[b,w]=m.useState(p),[C,_]=m.useState(p);mu(()=>{a&&!u&&!C.length&&h?.()},[u,a,C.length,h]),mu(()=>{g.current=!1,x.current=p;for(let S=0;S<C.length;S++){const A=Hc(C[S]);f.includes(A)?(v.delete(A),y.current.delete(A)):v.get(A)!==!0&&v.set(A,!1)}},[C,f.length,f.join("-")]);const N=[];if(p!==b){let S=[...p],A=0;for(const T of C){const I=f.indexOf(Hc(T));I===-1?(S.splice(A++,0,T),N.push(T)):A=I+N.length+1}return r==="wait"&&N.length&&(S=N),_(hw(S)),w(p),null}const{forceRender:k}=m.useContext(fx);return i.jsx(i.Fragment,{children:C.map(S=>{const A=Hc(S),T=a&&!u?!1:p===C||f.includes(A),I=()=>{if(y.current.has(A))return;if(v.has(A))y.current.add(A),v.set(A,!0);else return;let P=!0;v.forEach(D=>{D||(P=!1)}),P&&(k?.(),_(x.current),a&&h?.(),s&&s())};return i.jsx(xV,{isPresent:T,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:o,mode:r,root:d,onExitComplete:T?void 0:I,anchorX:l,anchorY:c,children:S},A)})})},RN=m.createContext({strict:!1}),pw={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 fw=!1;function bV(){if(fw)return;const e={};for(const t in pw)e[t]={isEnabled:n=>pw[t].some(s=>!!n[s])};dN(e),fw=!0}function LN(){return bV(),iB()}function wV(e){const t=LN();for(const n in e)t[n]={...t[n],...e[n]};dN(t)}const Ih=m.createContext({});function yV(e,t){if(Th(e)){const{initial:n,animate:s}=e;return{initial:n===!1||Wl(n)?n:void 0,animate:Wl(s)?s:void 0}}return e.inherit!==!1?t:{}}function SV(e){const{initial:t,animate:n}=yV(e,m.useContext(Ih));return m.useMemo(()=>({initial:t,animate:n}),[mw(t),mw(n)])}function mw(e){return Array.isArray(e)?e.join(" "):e}const Hx=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ON(e,t,n){for(const s in t)!hs(t[s])&&!xN(s,n)&&(e[s]=t[s])}function CV({transformTemplate:e},t){return m.useMemo(()=>{const n=Hx();return zx(n,t,e),Object.assign({},n.vars,n.style)},[t])}function kV(e,t){const n=e.style||{},s={};return ON(s,n,e),Object.assign(s,CV(e,t)),s}function jV(e,t){const n={},s=kV(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 zN=()=>({...Hx(),attrs:{}});function _V(e,t,n,s){const o=m.useMemo(()=>{const r=zN();return bN(r,t,yN(s),e.transformTemplate,e.style),{...r.attrs,style:{...r.style}}},[t]);if(e.style){const r={};ON(r,e.style,e),o.style={...r,...o.style}}return o}const NV=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 _u(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||NV.has(e)}function TV(e,t){return e.startsWith("on")?!_u(e):t?.(e)??!_u(e)}function IV(e,t,n,s){const o={};for(const r in e)r==="values"&&typeof e.values=="object"||hs(e[r])||(TV(r,s)||n===!0&&_u(r)||!t&&!_u(r)||e.draggable&&r.startsWith("onDrag"))&&(o[r]=e[r]);return o}const DV=["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 Bx(e){return typeof e!="string"||e.includes("-")?!1:!!(DV.indexOf(e)>-1||/[A-Z]/u.test(e))}function EV(e,t,n,{latestValues:s},o,r=!1,a,l){const d=(a??Bx(e)?_V:jV)(t,s,o,e),u=IV(t,typeof e=="string",r,l),h=e!==m.Fragment?{...u,...d,ref:n}:{},{children:p}=t,f=m.useMemo(()=>hs(p)?p.get():p,[p]);return m.createElement(e,{...h,children:f})}function PV({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,o){return{latestValues:AV(n,s,o,e),renderState:t()}}function AV(e,t,n,s){const o={},r=s(e,{});for(const p in r)o[p]=Bd(r[p]);let{initial:a,animate:l}=e;const c=Th(e),d=lN(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"&&!Nh(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f<p.length;f++){const g=Ix(e,p[f]);if(g){const{transitionEnd:x,transition:v,...y}=g;for(const b in y){let w=y[b];if(Array.isArray(w)){const C=u?w.length-1:0;w=w[C]}w!==null&&(o[b]=w)}for(const b in x)o[b]=x[b]}}}return o}const GN=e=>(t,n)=>{const s=m.useContext(Ih),o=m.useContext(kh),r=()=>PV(e,t,s,o);return n?r():mx(r)},MV=GN({scrapeMotionValuesFromProps:Gx,createRenderState:Hx}),RV=GN({scrapeMotionValuesFromProps:SN,createRenderState:zN}),LV=Symbol.for("motionComponentSymbol");function OV(e,t,n){const s=m.useRef(n);m.useInsertionEffect(()=>{s.current=n});const o=m.useRef(null);return m.useCallback(r=>{r&&e.onMount?.(r),t&&(r?t.mount(r):t.unmount());const a=s.current;if(typeof a=="function")if(r){const l=a(r);typeof l=="function"&&(o.current=l)}else o.current?(o.current(),o.current=null):a(r);else a&&(a.current=r)},[t])}const FN=m.createContext({});function $r(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function zV(e,t,n,s,o,r){const{visualElement:a}=m.useContext(Ih),l=m.useContext(RN),c=m.useContext(kh),d=m.useContext(Fx),u=d.reducedMotion,h=d.skipAnimations,p=m.useRef(null),f=m.useRef(!1);s=s||l.renderer,!p.current&&s&&(p.current=s(e,{visualState:t,parent:a,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:r}),f.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const g=p.current,x=m.useContext(FN);g&&!g.projection&&o&&(g.type==="html"||g.type==="svg")&&GV(p.current,n,o,x);const v=m.useRef(!1);m.useInsertionEffect(()=>{g&&v.current&&g.update(n,c)});const y=n[X1],b=m.useRef(!!y&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(y)&&window.MotionHasOptimisedAnimation?.(y));return mu(()=>{f.current=!0,g&&(v.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),b.current&&g.animationState&&g.animationState.animateChanges())}),m.useEffect(()=>{g&&(!b.current&&g.animationState&&g.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(y)}),b.current=!1),g.enteringChildren=void 0)}),g}function GV(e,t,n,s){const{layoutId:o,layout:r,drag:a,dragConstraints:l,layoutScroll:c,layoutRoot:d,layoutAnchor:u,layoutCrossfade:h}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:HN(e.parent)),e.projection.setOptions({layoutId:o,layout:r,alwaysMeasureLayout:!!a||l&&$r(l),visualElement:e,animationType:typeof r=="string"?r:"both",initialPromotionConfig:s,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function HN(e){if(e)return e.options.allowProjection!==!1?e.projection:HN(e.parent)}function Ep(e,{forwardMotionProps:t=!1,type:n}={},s,o){s&&wV(s);const r=n?n==="svg":Bx(e),a=r?RV:MV;function l(d,u){let h;const p={...m.useContext(Fx),...d,layoutId:FV(d)},{isStatic:f,isValidProp:g}=p,x=SV(d),v=a(d,f);if(!f&&typeof window<"u"){HV();const y=BV(p);h=y.MeasureLayout,x.visualElement=zV(e,v,p,o,y.ProjectionNode,r)}return i.jsxs(Ih.Provider,{value:x,children:[h&&x.visualElement?i.jsx(h,{visualElement:x.visualElement,...p}):null,EV(e,d,OV(v,x.visualElement,u),v,f,t,r,g)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=m.forwardRef(l);return c[LV]=e,c}function FV({layoutId:e}){const t=m.useContext(fx).id;return t&&e!==void 0?t+"-"+e:e}function HV(e,t){m.useContext(RN).strict}function BV(e){const t=LN(),{drag:n,layout:s}=t;if(!n&&!s)return{};const o={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function VV(e,t){if(typeof Proxy>"u")return Ep;const n=new Map,s=(r,a)=>Ep(r,a,e,t),o=(r,a)=>s(r,a);return new Proxy(o,{get:(r,a)=>a==="create"?s:(n.has(a)||n.set(a,Ep(a,void 0,e,t)),n.get(a))})}const $V=(e,t)=>t.isSVG??Bx(e)?new wB(t):new mB(t,{allowProjection:e!==m.Fragment});class WV extends qo{constructor(t){super(t),t.animationState||(t.animationState=jB(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Nh(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 UV=0;class KV extends qo{constructor(){super(...arguments),this.id=UV++,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=wr(this.node,r,a);if(l){const{transition:c,transitionEnd:d,...u}=l;for(const h in u)this.node.getValue(h)?.jump(u[h])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const o=this.node.animationState.setActive("exit",!t);n&&!t&&o.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const qV={animation:{Feature:WV},exit:{Feature:KV}};function _c(e){return{point:{x:e.pageX,y:e.pageY}}}const YV=e=>t=>Ax(t)&&e(t,_c(t));function bl(e,t,n,s){return Ul(e,t,YV(n),s)}const BN=({current:e})=>e?e.ownerDocument.defaultView:null,gw=(e,t)=>Math.abs(e-t);function XV(e,t){const n=gw(e.x,t.x),s=gw(e.y,t.y);return Math.sqrt(n**2+s**2)}const xw=new Set(["auto","scroll"]);class VN{constructor(t,n,{transformPagePoint:s,contextWindow:o=window,dragSnapToOrigin:r=!1,distanceThreshold:a=3,element:l}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=g=>{this.handleScroll(g.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Bc(this.lastRawMoveEventInfo,this.transformPagePoint));const g=Pp(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,v=XV(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!v)return;const{point:y}=g,{timestamp:b}=us;this.history.push({...y,timestamp:b});const{onStart:w,onMove:C}=this.handlers;x||(w&&w(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,g)},this.handlePointerMove=(g,x)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Bc(x,this.transformPagePoint),kn.update(this.updatePoint,!0)},this.handlePointerUp=(g,x)=>{this.end();const{onEnd:v,onSessionEnd:y,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=Pp(g.type==="pointercancel"?this.lastMoveEventInfo:Bc(x,this.transformPagePoint),this.history);this.startEvent&&v&&v(g,w),y&&y(g,w)},!Ax(t))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=o||window;const c=_c(t),d=Bc(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=us;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,Pp(d,this.history));const f={passive:!0,capture:!0};this.removeListeners=Cc(bl(this.contextWindow,"pointermove",this.handlePointerMove,f),bl(this.contextWindow,"pointerup",this.handlePointerUp,f),bl(this.contextWindow,"pointercancel",this.handlePointerUp,f)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(xw.has(s.overflowX)||xw.has(s.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const s=t===window,o=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},r={x:o.x-n.x,y:o.y-n.y};r.x===0&&r.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=r.x,this.lastMoveEventInfo.point.y+=r.y):this.history.length>0&&(this.history[0].x-=r.x,this.history[0].y-=r.y),this.scrollPositions.set(t,o),kn.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Fo(this.updatePoint)}}function Bc(e,t){return t?{point:t(e.point)}:e}function vw(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Pp({point:e},t){return{point:e,delta:vw(e,$N(t)),offset:vw(e,JV(t)),velocity:ZV(t,.1)}}function JV(e){return e[0]}function $N(e){return e[e.length-1]}function ZV(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const o=$N(e);for(;n>=0&&(s=e[n],!(o.timestamp-s.timestamp>Hs(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&o.timestamp-s.timestamp>Hs(t)*2&&(s=e[1]);const r=Ys(o.timestamp-s.timestamp);if(r===0)return{x:0,y:0};const a={x:(o.x-s.x)/r,y:(o.y-s.y)/r};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function QV(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?Cn(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?Cn(n,e,s.max):Math.min(e,n)),e}function bw(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function e$(e,{top:t,left:n,bottom:s,right:o}){return{x:bw(e.x,n,o),y:bw(e.y,t,s)}}function ww(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 t$(e,t){return{x:ww(e.x,t.x),y:ww(e.y,t.y)}}function n$(e,t){let n=.5;const s=js(e),o=js(t);return o>s?n=Vl(t.min,t.max-s,e.min):s>o&&(n=Vl(e.min,e.max-o,t.min)),Vi(0,1,n)}function s$(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 km=.35;function i$(e=km){return e===!1?e=0:e===!0&&(e=km),{x:yw(e,"left","right"),y:yw(e,"top","bottom")}}function yw(e,t,n){return{min:Sw(e,t),max:Sw(e,n)}}function Sw(e,t){return typeof e=="number"?e:e[t]||0}const o$=new WeakMap;class r${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=Xn(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const r=h=>{n&&this.snapToCursor(_c(h).point),this.stopAnimation()},a=(h,p)=>{const{drag:f,dragPropagation:g,onDragStart:x}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=RH(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),Di(y=>{let b=this.getAxisMotionValue(y).get()||0;if(Hi.test(b)){const{projection:w}=this.visualElement;if(w&&w.layout){const C=w.layout.layoutBox[y];C&&(b=js(C)*(parseFloat(b)/100))}}this.originPoint[y]=b}),x&&kn.update(()=>x(h,p),!1,!0),mm(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},l=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:x,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:y}=p;if(g&&this.currentDirection===null){this.currentDirection=l$(y),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",p.point,y),this.updateAxis("y",p.point,y),this.visualElement.render(),v&&kn.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 VN(t,{onSessionStart:r,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:s,contextWindow:BN(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,o=n||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!o||!s)return;const{velocity:a}=o;this.startAnimation(a);const{onDragEnd:l}=this.getProps();l&&kn.postRender(()=>l(s,o))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,s){const{drag:o}=this.getProps();if(!s||!Vc(t,o,this.currentDirection))return;const r=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=QV(a,this.constraints[t],this.elastic[t])),r.set(a)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;t&&$r(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=e$(s.layoutBox,t):this.constraints=!1,this.elastic=i$(n),o!==this.constraints&&!$r(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&Di(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=s$(s.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!$r(t))return!1;const s=t.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;o.root&&(o.root.scroll=void 0,o.root.updateScroll());const r=cB(s,o.root,this.visualElement.getTransformPagePoint());let a=t$(o.layout.layoutBox,r);if(n){const l=n(rB(a));this.hasMutatedConstraints=!!l,l&&(a=hN(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:o,dragTransition:r,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},d=Di(u=>{if(!Vc(u,n,this.currentDirection))return;let h=c&&c[u]||{};(a===!0||a===u)&&(h={min:0,max:0});const p=o?200:1e6,f=o?40:1e7,g={type:"inertia",velocity:s?t[u]:0,bounceStiffness:p,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...r,...h};return this.startAxisValueAnimation(u,g)});return Promise.all(d).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return mm(this.visualElement,t),s.start(Tx(t,s,0,n,this.visualElement,!1))}stopAnimation(){Di(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,o=this.visualElement.getProps()[n];return o||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){Di(n=>{const{drag:s}=this.getProps();if(!Vc(n,s,this.currentDirection))return;const{projection:o}=this.visualElement,r=this.getAxisMotionValue(n);if(o&&o.layout){const{min:a,max:l}=o.layout.layoutBox[n],c=r.get()||0;r.set(t[n]-Cn(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!$r(n)||!s||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};Di(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const c=l.get();o[a]=n$({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(),Di(a=>{if(!Vc(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:d}=this.constraints[a];l.set(Cn(c,d,o[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;o$.set(this.visualElement,this);const t=this.visualElement.current,n=bl(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=d.target,f=p!==t&&HH(p);u&&h&&!f&&this.start(d)});let s;const o=()=>{const{dragConstraints:d}=this.getProps();$r(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),s||(s=a$(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:r}=this.visualElement,a=r.addEventListener("measure",o);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),kn.read(o);const l=Ul(window,"resize",()=>this.scalePositionWithinConstraints()),c=r.addEventListener("didUpdate",(({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(Di(h=>{const p=this.getAxisMotionValue(h);p&&(this.originPoint[h]+=d[h].translate,p.set(p.get()+d[h].translate))}),this.visualElement.render())}));return()=>{l(),n(),a(),c&&c(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:o=!1,dragConstraints:r=!1,dragElastic:a=km,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:o,dragConstraints:r,dragElastic:a,dragMomentum:l}}}function Cw(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function a$(e,t,n){const s=Db(e,Cw(n)),o=Db(t,Cw(n));return()=>{s(),o()}}function Vc(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function l$(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class c$ extends qo{constructor(t){super(t),this.removeGroupControls=Qs,this.removeListeners=Qs,this.controls=new r$(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Qs}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 Ap=e=>(t,n)=>{e&&kn.update(()=>e(t,n),!1,!0)};class d$ extends qo{constructor(){super(...arguments),this.removePointerDownListener=Qs}onPointerDown(t){this.session=new VN(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:BN(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:o}=this.node.getProps();return{onSessionStart:Ap(t),onStart:Ap(n),onMove:Ap(s),onEnd:(r,a)=>{delete this.session,o&&kn.postRender(()=>o(r,a))}}}mount(){this.removePointerDownListener=bl(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 Mp=!1;class u$ extends m.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:o}=this.props,{projection:r}=t;r&&(n.group&&n.group.add(r),s&&s.register&&o&&s.register(r),Mp&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Vd.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:o,isPresent:r}=this.props,{projection:a}=s;return a&&(a.isPresent=r,t.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),Mp=!0,o||t.layoutDependency!==n||n===void 0||t.isPresent!==r?a.willUpdate():this.safeToRemove(),t.isPresent!==r&&(r?a.promote():a.relegate()||kn.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(),Px.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:o}=t;Mp=!0,o&&(o.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(o),s&&s.deregister&&s.deregister(o))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function WN(e){const[t,n]=MN(),s=m.useContext(fx);return i.jsx(u$,{...e,layoutGroup:s,switchLayoutGroup:m.useContext(FN),isPresent:t,safeToRemove:n})}const h$={pan:{Feature:d$},drag:{Feature:c$,ProjectionNode:AN,MeasureLayout:WN}};function kw(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const o="onHover"+n,r=s[o];r&&kn.postRender(()=>r(t,_c(t)))}class p$ extends qo{mount(){const{current:t}=this.node;t&&(this.unmount=OH(t,(n,s)=>(kw(this.node,s,"Start"),o=>kw(this.node,o,"End"))))}unmount(){}}class f$ extends qo{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=Cc(Ul(this.node.current,"focus",()=>this.onFocus()),Ul(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function jw(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const o="onTap"+(n==="End"?"":n),r=s[o];r&&kn.postRender(()=>r(t,_c(t)))}class m$ extends qo{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=VH(t,(o,r)=>(jw(this.node,r,"Start"),(a,{success:l})=>jw(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const jm=new WeakMap,Rp=new WeakMap,g$=e=>{const t=jm.get(e.target);t&&t(e)},x$=e=>{e.forEach(g$)};function v$({root:e,...t}){const n=e||document;Rp.has(n)||Rp.set(n,{});const s=Rp.get(n),o=JSON.stringify(t);return s[o]||(s[o]=new IntersectionObserver(x$,{root:e,...t})),s[o]}function b$(e,t,n){const s=v$(t);return jm.set(e,n),s.observe(e),()=>{jm.delete(e),s.unobserve(e)}}const w$={some:0,all:1};class y$ extends qo{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:o="some",once:r}=t,a={root:n?n.current:void 0,rootMargin:s,threshold:typeof o=="number"?o:w$[o]},l=c=>{const{isIntersecting:d}=c;if(this.isInView===d||(this.isInView=d,r&&!d&&this.hasEnteredView))return;d&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",d);const{onViewportEnter:u,onViewportLeave:h}=this.node.getProps(),p=d?u:h;p&&p(c)};this.stopObserver=b$(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(S$(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function S$({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const C$={inView:{Feature:y$},tap:{Feature:m$},focus:{Feature:f$},hover:{Feature:p$}},k$={layout:{ProjectionNode:AN,MeasureLayout:WN}},j$={...qV,...C$,...h$,...k$},Os=VV(j$,$V);function _$(){!Ox.current&&cN();const[e]=m.useState(Su.current);return e}const N$=[["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"}]],T$=rt("alarm-clock",N$);const I$=[["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"}]],Kl=rt("archive-restore",I$);const D$=[["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"}]],Oi=rt("archive",D$);const E$=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],P$=rt("arrow-down-to-line",E$);const A$=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],M$=rt("arrow-up-right",A$);const R$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]],L$=rt("ban",R$);const O$=[["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"}]],_w=rt("bell-off",O$);const z$=[["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"}]],G$=rt("bookmark-plus",z$);const F$=[["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"}]],UN=rt("bug",F$);const H$=[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]],B$=rt("chevrons-down-up",H$);const V$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],$$=rt("circle-dot",V$);const W$=[["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"}]],U$=rt("circle-play",W$);const K$=[["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"}]],q$=rt("circle-question-mark",K$);const Y$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],X$=rt("circle-stop",Y$);const J$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Vx=rt("circle",J$);const Z$=[["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"}]],KN=rt("clipboard-check",Z$);const Q$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],qN=rt("clock",Q$);const e6=[["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"}]],_m=rt("code-xml",e6);const t6=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],n6=rt("code",t6);const s6=[["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"}]],i6=rt("coins",s6);const o6=[["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"}]],r6=rt("compass",o6);const a6=[["path",{d:"m15 10 5 5-5 5",key:"qqa56n"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]],l6=rt("corner-down-right",a6);const c6=[["path",{d:"M14 9 9 4 4 9",key:"1af5af"}],["path",{d:"M20 20h-7a4 4 0 0 1-4-4V4",key:"1blwi3"}]],d6=rt("corner-left-up",c6);const u6=[["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"}]],h6=rt("cpu",u6);const p6=[["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"}]],f6=rt("database",p6);const m6=[["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"}]],Dh=rt("ellipsis",m6);const g6=[["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"}]],x6=rt("file-diff",g6);const v6=[["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"}]],b6=rt("file-pen",v6);const w6=[["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"}]],y6=rt("file-plus",w6);const S6=[["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"}]],C6=rt("file",S6);const k6=[["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"}]],j6=rt("fold-horizontal",k6);const _6=[["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"}]],N6=rt("folder-git-2",_6);const T6=[["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"}]],Nu=rt("folder-plus",T6);const I6=[["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"}]],Nc=rt("folder",I6);const D6=[["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"}]],E6=rt("folders",D6);const P6=[["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"}]],A6=rt("git-branch-plus",P6);const M6=[["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"}]],zi=rt("git-branch",M6);const R6=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],L6=rt("git-commit-horizontal",R6);const O6=[["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"}]],$x=rt("git-compare",O6);const z6=[["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"}]],Nw=rt("hand",z6);const G6=[["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"}]],F6=rt("hourglass",G6);const H6=[["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"}]],Tw=rt("house",H6);const B6=[["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"}]],YN=rt("image-off",B6);const V6=[["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"}]],Eh=rt("image-plus",V6);const $6=[["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"}]],W6=rt("images",$6);const U6=[["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"}]],Wx=rt("inbox",U6);const K6=[["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"}]],q6=rt("list-tree",K6);const Y6=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],Ux=rt("list",Y6);const X6=[["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"}]],J6=rt("mail",X6);const Z6=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Q6=rt("menu",Z6);const e4=[["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"}]],Cr=rt("message-circle",e4);const t4=[["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"}]],Ho=rt("message-square-plus",t4);const n4=[["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"}]],s4=rt("message-square",n4);const i4=[["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"}]],xa=rt("messages-square",i4);const o4=[["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"}]],r4=rt("package-minus",o4);const a4=[["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"}]],Kx=rt("panel-left-close",a4);const l4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],XN=rt("panel-left",l4);const c4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],JN=rt("panel-right",c4);const d4=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],u4=rt("paperclip",d4);const h4=[["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"}]],p4=rt("pause",h4);const f4=[["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"}]],Tu=rt("pin-off",f4);const m4=[["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"}]],hi=rt("pin",m4);const g4=[["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"}]],x4=rt("repeat",g4);const v4=[["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"}]],Yo=rt("rotate-ccw-clock",v4);const b4=[["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"}]],qx=rt("send",b4);const w4=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],y4=rt("sliders-horizontal",w4);const S4=[["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"}]],C4=rt("square-dashed",S4);const k4=[["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"}]],ZN=rt("square-pen",k4);const j4=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]],QN=rt("square-slash",j4);const _4=[["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"}]],N4=rt("square-x",_4);const T4=[["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"}]],I4=rt("tag",T4);const D4=[["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"}]],Ma=rt("target",D4);const E4=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M10 12H3",key:"1ulcyk"}],["path",{d:"M10 19H3",key:"108z41"}],["circle",{cx:"17",cy:"15",r:"3",key:"1upz2a"}],["path",{d:"m21 19-1.9-1.9",key:"dwi7p8"}]],eT=rt("text-search",E4);const P4=[["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"}]],va=rt("undo-2",P4);const A4=[["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"}]],M4=rt("unfold-horizontal",A4);const R4=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],L4=rt("user-minus",R4);const O4=[["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"}]],ql=rt("user-plus",O4);const z4=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],G4=rt("user-round",z4);const F4=[["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"}]],H4=rt("wallet",F4),Lp=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e;function B4(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,{status:n,originalCommand:s,rewrittenCommand:o,inputTokens:r,outputTokens:a,reason:l}=t;if(n!=="compressed"&&n!=="unchanged"&&n!=="pending"&&n!=="bypassed"&&n!=="unavailable"||typeof s!="string"||o!==void 0&&typeof o!="string"||l!==void 0&&typeof l!="string")return;const c={status:n,originalCommand:Lp(s,16e3)};if(o!==void 0&&(c.rewrittenCommand=Lp(o,16e3)),l!==void 0&&(c.reason=Lp(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 V4=15e3;function $4(e){const t=[];for(const n of e){const s=t.at(-1);if(s&&s.batch===n.batch&&s.phase===n.phase){s.members.push(n);continue}t.push({batch:n.batch,members:[n],...n.phase?{phase:n.phase}:{}})}return t}function tT(e){if(e.length===0)return;const t="0 0, 100% 0, 100% 100%, 0 100%, 0 0",n=e.map(s=>`${W4(s).map(([o,r])=>`${Dw(o)}px ${Dw(r)}px`).join(", ")}, 0 0`);return`polygon(evenodd, ${[t,...n].join(", ")})`}const Iw=6,Dw=e=>Math.round(e*100)/100;function W4({x:e,y:t,width:n,height:s,radius:o=0}){const r=e+n,a=t+s,l=Math.min(o,n/2,s/2);if(l<=0)return[[e,t],[r,t],[r,a],[e,a],[e,t]];const d=[[r-l,t+l,-90],[r-l,a-l,0],[e+l,a-l,90],[e+l,t+l,180]].flatMap(([u,h,p])=>Array.from({length:Iw+1},(f,g)=>{const x=(p+90*g/Iw)*Math.PI/180;return[u+l*Math.cos(x),h+l*Math.sin(x)]}));return[...d,d[0]]}function Ew(e,t){for(let n=t-1;n>=0;n--){const s=e[n];if(s==="@"){const o=n>0?e[n-1]:" ";return o===" "||o===`
14
- `?e.slice(n+1,t):null}if(s===" "||s===`
15
- `)return null}return null}function U4(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 K4(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 q4(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 Y4=/^\[Referenced past chat "(.+)" — transcript file: (.+) \(pi session jsonl; read it if relevant\)\]$/,X4=/^@(\S.*)$/;function J4(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"?q4(t.label,t.sessionFile):NA(t)).join("")}function Pw(e,t){u0.lastIndex=t,h0.lastIndex=t;const n=u0.exec(e),s=h0.exec(e),o=n?{index:n.index,length:n[0].length,segment:{type:"chat",label:n[1],sessionFile:n[2]}}:null,r=s?_A(s[0]):null,a=s&&r?{index:s.index,length:s[0].length,segment:{type:"ui-element",id:"",...r,imageId:""}}:null;return o&&a?o.index<=a.index?o:a:o??a}function Z4(e){const t=[];let n=0,s=Pw(e,0);for(;s;){const r=e.slice(n,s.index);for(const a of Aw(r))a.type==="text"&&a.text===""||t.push(a);t.push(s.segment),n=s.index+s.length,s=Pw(e,n)}const o=e.slice(n);if(o||t.length===0)for(const r of Aw(o))r.type==="text"&&r.text===""&&t.length>0||t.push(r);return t}const Q4=/^(?:[A-Za-z]:[\\/])?(?:[\p{L}\p{N}_./\\-]*\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\p{L}\p{N}_./\\-]+[\\/])$/u,eW=/^"([^"\n]*(?:\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\\/]))"/,tW=/#L\d+(?:-L\d+)?$/;function nW(e){return e.replace(tW,"")}function Ph(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).at(-1)||e}function Aw(e){return Zk(e).flatMap(t=>t.type==="file"?[t]:sW(t.text))}function sW(e){const t=[];let n="",s=0;for(;s<e.length;){const o=e.indexOf("@",s);if(o===-1){n+=e.slice(s);break}const r=o>0?e[o-1]:" ",a=r===" "||r===`
16
- `?eW.exec(e.slice(o+1)):null;if(a){n+=e.slice(s,o),n&&(t.push({type:"text",text:n}),n=""),t.push({type:"file",path:a[1]}),s=o+1+a[0].length;continue}const c=(/^\S*/.exec(e.slice(o+1))?.[0]??"").replace(/[),.;!?]+$/,"");(r===" "||r===`
17
- `)&&c&&Q4.test(c)?(n+=e.slice(s,o),n&&(t.push({type:"text",text:n}),n=""),t.push({type:"file",path:c}),s=o+1+c.length):(n+=e.slice(s,o+1),s=o+1)}return n&&t.push({type:"text",text:n}),t.length>0?t:[{type:"text",text:e}]}function iW(e){const t={body:e,files:[],chats:[]},n=e.split(`
18
- `),s=[],o=[];let r=n.length-1;for(;r>=0;r--){const a=n[r],l=Y4.exec(a);if(l){o.unshift({label:l[1],sessionFile:l[2]});continue}if(X4.test(a)){s.unshift(a.slice(1));continue}break}return s.length+o.length===0||r<0||n[r].trim()!==""?t:{body:n.slice(0,r).join(`
19
- `).trimEnd(),files:s,chats:o}}function Mw(e){const t=J4(e.segments).trim(),n=e.segments.filter(o=>o.type!=="text").map(o=>o.type==="file"?{kind:"file",id:o.path,label:Ph(o.path),relativePath:nW(o.path)}:o.type==="chat"?{kind:"chat",id:o.sessionFile,label:o.label,sessionFile:o.sessionFile}:{kind:"ui-element",id:o.id,label:o.label,path:o.path,text:o.text,imageId:o.imageId});e.recipient&&n.push(e.recipient);const s=e.slashes.join(" ");return{text:s?t?`${s} ${t}`:s:t,images:e.images.map(({data:o,mimeType:r})=>({data:o,mimeType:r})),mentions:n,...e.recipient?{recipient:e.recipient}:{}}}const oW={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 rW(){const e=Qk(),t=we(x=>x.backgroundImageEnabled),n=we(x=>x.backgroundSourceType),s=we(x=>x.backgroundImagePath),o=we(x=>x.backgroundFolderPath),r=we(x=>x.backgroundUrlPath),a=we(x=>x.backgroundRandomEnabled),l=we(x=>x.backgroundRandomInterval),c=we(x=>x.backgroundRefreshNonce),[d,u]=m.useState(0);m.useEffect(()=>{c>0&&u(x=>x+1)},[c]),m.useEffect(()=>{if(!t||!a||n==="file")return;const x=Math.max(5,l)*1e3,v=window.setInterval(()=>u(y=>y+1),x);return()=>window.clearInterval(v)},[t,a,l,n]);const[h,p]=m.useState([]);m.useEffect(()=>{if(!t||n!=="folder"||!o){p([]);return}let x=!1;return window.electronAPI.files.listMedia(o).then(v=>{x||p(v)}),()=>{x=!0}},[t,n,o,d]);const[f,g]=m.useState("");return m.useEffect(()=>{if(h.length===0){g("");return}g(x=>{if(h.length===1)return h[0];const v=h.filter(y=>y!==x);return v[Math.floor(Math.random()*v.length)]})},[h]),i.jsxs(aW,{children:[e?.source==="user"&&i.jsx(lW,{state:{sourceType:n,imagePath:s,folderPick:f,urlPath:r,tick:d},look:e}),e?.source==="theme"&&i.jsxs(iT,{look:e,children:[i.jsx(oT,{image:"var(--enso-asset-background)",look:e}),i.jsx(rT,{mask:e.mask})]})]})}function aW({children:e}){const t=fn(s=>s.browserHoles),n=tT(Object.values(t));return m.useLayoutEffect(()=>{const s=document.documentElement;return n?s.style.setProperty("--enso-browser-holes-clip",n):s.style.removeProperty("--enso-browser-holes-clip"),()=>{s.style.removeProperty("--enso-browser-holes-clip")}},[n]),i.jsx("div",{"aria-hidden":!0,"data-slot":"background-layer",className:"pointer-events-none absolute inset-0 -z-10 overflow-hidden",style:{clipPath:n,backgroundColor:"var(--canvas)"},children:e})}const nT=({blur:e,brightness:t,saturation:n})=>`blur(${e}px) brightness(${t}) saturate(${n})`,sT=({blur:e})=>e>0?`-${e*2}px`:"0";function lW({state:e,look:t}){const{sourceType:n,imagePath:s,folderPick:o,urlPath:r,tick:a}=e,l=m.useMemo(()=>{if(n==="file"&&s)return{src:Mf(s),video:op(s)};if(n==="folder"&&o)return{src:Mf(o),video:op(o)};if(n==="url"){const p=r.trim();if(/^https?:\/\//i.test(p))return{src:TA(p,a),video:op(p)}}return null},[n,s,o,r,a]),[c,d]=m.useState(null);if(m.useEffect(()=>{if(!l){d(null);return}if(l.video){d(l);return}let p=!1;const f=new Image;return f.onload=()=>{p||d(l)},f.src=l.src,()=>{p=!0}},[l]),!c)return null;const{src:u,video:h}=c;return i.jsxs(iT,{look:t,children:[h?i.jsx("video",{src:u,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"absolute",style:{inset:sT(t),width:"auto",height:"auto",minWidth:"100%",minHeight:"100%",objectFit:t.size==="contain"?"contain":"cover",filter:nT(t),transition:"filter 0.3s ease"}},u):i.jsx(oT,{image:`url("${u}")`,look:t},u),i.jsx(rT,{mask:t.mask})]})}function iT({look:e,children:t}){return i.jsx("div",{"data-slot":"background-media",className:"absolute inset-0",style:{opacity:IA(e.opacity).wallpaperOpacity},children:t})}function oT({image:e,look:t}){return i.jsx("div",{className:"absolute",style:{inset:sT(t),backgroundImage:e,...oW[t.size],filter:nT(t),transition:"filter 0.3s ease"}})}function rT({mask:e}){return e<=0?null:i.jsx("div",{"aria-hidden":!0,className:"absolute inset-0",style:{backgroundColor:`color-mix(in oklab, var(--canvas, var(--background)) ${Math.round(Math.min(1,Math.max(0,e))*100)}%, transparent)`}})}const cW={sm:"size-2",md:"size-2.5"},dW={sm:"h-3 w-3",md:"h-3.5 w-3.5"};function Tc({tone:e,size:t="sm",title:n,className:s,"data-enso":o,"data-status":r}){const{t:a}=ne();if(e==="waiting"){const l=a("Waiting for your answer");return i.jsx("span",{role:"img","aria-label":l,title:l,"data-slot":"conversation-status","data-tone":e,"data-enso":o,"data-status":r,className:W("flex shrink-0 items-center text-amber-500",s),children:i.jsx(q$,{className:W(dW[t],"stroke-[2.5]"),"aria-hidden":!0})})}return i.jsx("span",{"data-slot":"conversation-status","data-tone":e,"data-enso":o,"data-status":r,title:n,className:W("shrink-0 rounded-full",cW[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)})}const Ai=Qu(()=>({modHeld:!1,headerMounted:!1,activeIds:[],slots:[]})),Rw=(e,t)=>e.length===t.length&&e.every((n,s)=>n===t[s]);function uW(e,t){const n=Ai.getState();Rw(n.activeIds,e)&&Rw(n.slots,t)||Ai.setState({activeIds:e,slots:t})}function hW(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt}function pW(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:hW(e),messages:[],forkedFromConversationId:e.forkedFromConversationId,unread:e.unread,activeRenewedAt:e.activeRenewedAt,pendingAsks:e.pendingAsks,pendingApprovals:e.pendingApprovals,coworkerIds:e.coworkerIds,coworkerName:e.coworkerName,child:e.child,subagents:e.subagents,backgroundTasks:e.backgroundTasks?.map(({status:n})=>({status:n})),parentId:e.parentId,sessionFile:e.sessionFile,worktree:e.worktree}}function fW(e){return JSON.stringify(e)}let Ji=null;function Ah(e){if(Ji?.source===e)return Ji.value;const t={},n=[];for(const[s,o]of Object.entries(e)){if(!o||o.btwParentId)continue;const r=pW(o,Lg({status:o.status??"idle",spawning:o.spawning,subagents:o.subagents,coworkerIds:o.coworkerIds,backgroundTasks:o.backgroundTasks},e));t[s]=r,n.push(`${s}:${fW(r)}`)}return Ji&&Ji.prints.length===n.length&&Ji.prints.every((s,o)=>s===n[o])?(Ji={source:e,prints:n,value:Ji.value},Ji.value):(Ji={source:e,prints:n,value:t},t)}let Fa=null;function mW(e){if(Fa?.source===e)return Fa.value;const t=[];for(const[o,r]of Object.entries(e))!r||r.parentId||r.btwParentId||!r.sessionFile||t.push({id:r.id??o,title:r.title,projectId:r.projectId,sessionFile:r.sessionFile,createdAt:r.createdAt});const n=JSON.stringify(t),s=Fa?.print===n?Fa.value:t;return Fa={source:e,print:n,value:s},s}const gW=[],Lw=new WeakMap;function xW(e,t){const n=e[t];if(!n)return gW;const s=Lw.get(n);if(s?.source===e)return s.value;const o=(n.coworkerIds??[]).flatMap(l=>{const c=e[l];return c?[{id:c.id??l,title:c.title,status:c.status??"idle",spawning:c.spawning===!0,pendingApprovalCount:c.pendingApprovals?.length??0,pendingAskCount:c.pendingAsks?.length??0,coworkerName:c.coworkerName,child:c.child?.agentInstanceName?{agentInstanceName:c.child.agentInstanceName}:void 0,mode:c.child?.mode==="task"?"task":"coworker",reloading:c.reloading===!0}]:[]}),r=JSON.stringify(o),a=s?.print===r?s.value:o;return Lw.set(n,{source:e,print:r,value:a}),a}function vW({onNew:e}){const{t}=ne(),n=Ai(p=>p.activeIds),s=Ai(p=>p.slots),o=Ai(p=>p.modHeld),r=ie(p=>Ah(p.conversations)),a=ie(p=>p.activeId),l=ie(p=>p.selectConversation),c=m.useRef(null),[d,u]=m.useState({left:0,right:0});m.useEffect(()=>(Ai.setState({headerMounted:!0}),()=>Ai.setState({headerMounted:!1})),[]),m.useLayoutEffect(()=>{const p=c.current,f=document.querySelector('[data-enso="main"]');if(!p||!f)return;const g=()=>{const v=p.getBoundingClientRect(),y=f.getBoundingClientRect(),b=Math.max(0,Math.round(y.left-v.left)),w=Math.max(0,Math.round(v.right-y.right));u(C=>C.left===b&&C.right===w?C:{left:b,right:w})};g();const x=new ResizeObserver(g);return x.observe(f),x.observe(p),()=>x.disconnect()},[]),m.useEffect(()=>{a&&c.current?.querySelector(`[data-session-tab="${CSS.escape(a)}"]`)?.scrollIntoView({block:"nearest",inline:"nearest"})},[a]);const h=n.filter(p=>r[p]);return i.jsx("div",{ref:c,"data-enso":"header-session-tabs",className:"flex h-full min-w-0 flex-1 items-center gap-1",style:{paddingLeft:d.left,paddingRight:d.right},children:h.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"flex min-w-0 items-center gap-1 overflow-x-auto [scrollbar-width:none]",children:h.map(p=>{const f=s.indexOf(p);return i.jsx(bW,{id:p,conversation:r[p],active:p===a,hint:o&&f>=0&&f<9?ti(`mod+${f+1}`):void 0,untitled:t("New conversation"),onSelect:l},p)})}),i.jsx("button",{type:"button",className:"no-drag flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-foreground/[0.06] hover:text-foreground",onClick:e,title:t("New conversation"),"aria-label":t("New conversation"),children:i.jsx(as,{className:"size-3.5"})})]})})}function bW({id:e,conversation:t,active:n,hint:s,untitled:o,onSelect:r}){const a=(t.pendingApprovals?.length??0)>0?"attention":eh({status:t.status,spawning:t.spawning,unread:t.unread,pendingAskCount:t.pendingAsks?.length??0,hasRunningChild:t.hasRunningChild}),l=t.title||o;return i.jsxs("button",{type:"button","data-session-tab":e,"data-active":n||void 0,className:W("no-drag box-border flex h-7 w-[202.5px] min-w-[80px] shrink items-center gap-1.5 rounded-md border-[0.5px] border-foreground/10 px-2.5 py-0 text-[0.8125rem] transition-colors",n?"bg-background text-foreground":"bg-foreground/[0.04] text-muted-foreground hover:bg-foreground/[0.07] hover:text-foreground"),onClick:()=>r(e),title:l,children:[i.jsx("span",{className:"flex size-3.5 shrink-0 items-center justify-center",children:a==="idle"?i.jsx(s4,{className:"size-3"}):i.jsx(Tc,{tone:a,size:"sm"})}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:l}),s&&i.jsx("span",{className:"shrink-0 text-[10px] leading-none text-subtle-foreground tabular-nums",children:s})]})}let wl=null,yl=null,Sl=null,Cl=null,kl=null,na=null,jl=null;function wW(e){return wl=e,()=>{wl===e&&(wl=null)}}function yW(e){return Sl=e,()=>{Sl===e&&(Sl=null)}}function SW(e){return yl=e,()=>{yl===e&&(yl=null)}}function _o(){return Sl?(Sl(),!0):!1}function CW(e){return jl=e,()=>{jl===e&&(jl=null)}}function kW(e){return jl?jl(e):!1}function Yl(e){return wl?(wl(e),!0):!1}function Mh(e){return yl?(yl(e),!0):!1}function jW(e){return Cl=e,()=>{Cl===e&&(Cl=null)}}function Yx(e,t){return Cl?(Cl(e,t),!0):!1}function _W(e){return kl=e,()=>{kl===e&&(kl=null)}}function NW(e){return kl?(kl(e),!0):!1}function TW(e){return na=e,()=>{na===e&&(na=null)}}function IW(){return na!==null}function DW(e){return na?(na(e),!0):!1}function Iu(e,t,n,s){return{left:e,top:t,right:n,bottom:s,x:e,y:t,width:n-e,height:s-t}}function EW(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function aT(e){const t=[];let n,s=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const l of Array.from(e).sort((c,d)=>c.top-d.top)){if(s=Math.min(s,l.left),o=Math.min(o,l.top),r=Math.max(r,l.right),a=Math.max(a,l.bottom),!n||l.top-n.top>n.height/2)t.push(EW(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:Iu(s,o,r,a)}}function lT(e,t,n){return e.findIndex(s=>t>s.left-2&&t<s.right+2&&n>s.top-2&&n<s.bottom+2)}function Ow(e){return Iu(e.left,e.top,e.right,e.bottom)}function PW(e,t,n){const{lines:s}=aT(e.getClientRects());if(s.length<2)return;const o=lT(s,t,n);return{x:t,y:n,lineIndex:o===-1?void 0:o,element:e}}function AW(e,t,n){const{lines:s,fallback:o}=aT(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 Ow(s[n.lineIndex]);if(r!=null&&a!=null){const g=lT(s,r,a);if(g!==-1)return Ow(s[g])}if(s.length===2&&s[0].left>s[1].right&&r!=null&&a!=null)return o;if(l==="t"||l==="b"){const g=s[0],x=s[s.length-1],v=l==="t"?g:x;return Iu(v.left,g.top,v.right,x.bottom)}const c=l==="l";let d=s[0].left,u=s[0].right,h=c?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,p=s[0],f=s[0];for(const g of s){d=Math.min(d,g.left),u=Math.max(u,g.right);const x=c?g.left:g.right;c&&x<h||!c&&x>h?(h=x,p=g,f=g):x===h&&(f=g)}return Iu(d,p.top,u,f.bottom)}function MW(e){return"contextElement"in e&&e.contextElement?e.contextElement:DA(e)?e:void 0}function RW(e,t){function n(o){cT(e,o.currentTarget,o.clientX,o.clientY)}function s(o){t||n(o)}return{onFocus(){e.current=void 0},onMouseEnter:s,onMouseMove:s}}function cT(e,t,n,s){const o=PW(t,n,s);return e.current=o,o}function LW(e){return{name:"inline",async fn(t){const n=t.elements.reference;if(typeof n?.getClientRects!="function")return{};const s=MW(n),o=e.current,r=o?.element===n||o?.element===s?o:void 0,a=AW(n,t.placement,r);if(!a||typeof t.platform.getElementRects!="function")return{};const l=await t.platform.getElementRects({reference:{contextElement:s,getBoundingClientRect(){return a}},floating:t.elements.floating,strategy:t.strategy});return t.rects.reference.x===l.reference.x&&t.rects.reference.y===l.reference.y&&t.rects.reference.width===l.reference.width&&t.rects.reference.height===l.reference.height?{}:{reset:{rects:l}}}}}const Nm=10;function OW(e){const t=new Set,n=[];let s=0,o=0;for(const r of e){const a=r.path.trim();if(a){if(!r.isDirectory){s+=1;continue}t.has(a)||(t.add(a),o+=1,n.length<Nm&&n.push(a))}}return{directories:n,skippedFiles:s,truncated:o>Nm}}function zW(e){if(!e.types.includes("Files"))return{project:!1,attach:!1};const t=e.items.filter(n=>n.kind==="file");return{project:t.length===0||t.some(n=>n.type===""),attach:e.composerReady}}const GW=150;function FW(e,t=GW){let n=0,s=!1,o;const r=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},a=()=>{r(),n=0,s&&(s=!1,e(!1))},l=()=>{s||(s=!0,e(!0)),r(),o=setTimeout(a,t)};return{enter(c){c&&(n+=1,l())},over(c){c&&(n=Math.max(n,1),l())},leave(){s&&(n=Math.max(0,n-1),n===0&&a())},cancel:a,dispose:r}}function HW(e){const t=e.archivedIds.filter(o=>o!==e.projectId),n={...e.collapsed},s=e.knownIds.has(e.projectId);return s&&n[e.projectId]===!0&&(n[e.projectId]=!1),s&&e.latestConversationId?{archivedIds:t,collapsed:n,focus:{kind:"select",conversationId:e.latestConversationId}}:{archivedIds:t,collapsed:n,focus:{kind:"new"}}}const $d="enso-project-order",Tm="enso-pinned-order",co="enso-archived-projects",zw="enso-pinned-projects",Im=new Set;function Mi(e){try{const t=JSON.parse(localStorage.getItem(e)??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Ao(e,t){localStorage.setItem(e,JSON.stringify(t));for(const n of Im)n()}function dT(e){return Im.add(e),()=>Im.delete(e)}const uT="enso-collapsed-projects",Dm="enso-collapsed-projects-changed";function Em(){try{const e=JSON.parse(localStorage.getItem(uT)??"{}");return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function BW(e){return window.addEventListener(Dm,e),()=>window.removeEventListener(Dm,e)}function VW(e){localStorage.setItem(uT,JSON.stringify(e)),window.dispatchEvent(new Event(Dm))}function $W(){try{const e=localStorage.getItem("enso-selected-project-group");return e?we.getState().projectGroups.find(t=>t.id===e)?.id:void 0}catch{return}}function WW(e,t){return e.length===t.length&&e.every((n,s)=>n===t[s])}function UW(e){const t=e instanceof Error?e.message:String(e);return/not a directory/i.test(t)||/ENOENT|no such file/i.test(t)}function KW(e){const t=e instanceof Error?e.message:String(e);return/not a directory/i.test(t)}let Op=Promise.resolve();function hT(e){return Op=Op.then(e).catch(()=>{}),Op}async function pT(e,t){const n=we.getState(),s=new Set(n.projects.map(l=>l.id)),o=await n.addProject(e,void 0,t??$W());if(!o)return;const r=ie.getState(),a=HW({projectId:o.id,knownIds:s,archivedIds:Mi(co),collapsed:Em(),latestConversationId:Qr(r.order,r.conversations,o.id)[0]});return WW(Mi(co),a.archivedIds)||Ao(co,a.archivedIds),JSON.stringify(Em())!==JSON.stringify(a.collapsed)&&VW(a.collapsed),{project:o,focus:a.focus}}async function fT(e,t){const n=ie.getState();if(e.focus.kind==="select"){await(t??n.selectConversation)(e.focus.conversationId);return}if(!await n.newConversation(e.project.id))throw new Error("Failed to create a conversation for the project.")}async function mT(e,t={}){const n=await pT(e,t.groupId);if(n)return await fT(n,t.onSelect),n.project}const Gw="enso-mode",fo=Qu()(e=>({mode:localStorage.getItem(Gw)==="bot"?"bot":"code",setMode:t=>{localStorage.setItem(Gw,t),e({mode:t})}}));function $c(){return we.getState().botModeEnabled&&os.getState().activeNodeId==="local"&&fo.getState().mode==="bot"}function qW(){const e=we(s=>s.botModeEnabled),t=os(s=>s.activeNodeId==="local"),n=fo(s=>s.mode);return e&&t&&n==="bot"}async function YW(e){if(!we.getState().botModeEnabled)return;const t=typeof e.chatId=="string"?e.chatId:void 0,n=typeof e.conversationId=="string"?e.conversationId:void 0,s=ue.getState();t||await s.refreshDelegations(),os.getState().activeNodeId!=="local"&&os.getState().switchNode("local"),fo.getState().setMode("bot");const o=EA({chatId:t,conversationId:n},ue.getState().delegations);if(o.kind==="chat"){const r=s.chats.find(a=>a.id===o.chatId);r?.kind==="group"&&s.openThread(r.parentId??r.id,r.id)}s.setView(o)}function Xx(){os.getState().activeNodeId!=="local"&&os.getState().switchNode("local"),fo.getState().setMode("code")}const XW={project:!1,attach:!1};function Fw(e){const n=(e instanceof Element?e.closest("[data-drop-zone]"):null)?.getAttribute("data-drop-zone");return n==="project"||n==="attach"?n:null}function Hw(e){try{return window.electronAPI.files.pathForFile(e)}catch{return""}}function JW(e){const t=e.dataTransfer?.items;if(t&&t.length>0){const n=[];for(let s=0;s<t.length;s+=1){const o=t[s];if(o.kind!=="file")continue;const r=o.getAsFile();if(!r)continue;const a=Hw(r),l=o.webkitGetAsEntry?.();n.push({path:a,isDirectory:l?l.isDirectory:r.size===0&&r.type===""})}return n}return Array.from(e.dataTransfer?.files??[]).map(n=>({path:Hw(n),isDirectory:n.size===0&&n.type===""}))}async function ZW(e,t){const n=OW(e);let s=n.skippedFiles,o;for(const r of n.directories)try{o=await pT(r)??o}catch(a){if(KW(a)){s+=1;continue}if(UW(a))continue;ze({type:"error",title:t("Failed to add project"),description:a instanceof Error?a.message:String(a)})}if(o)try{await fT(o),Xx()}catch(r){ze({type:"error",title:t("Failed to add project"),description:r instanceof Error?r.message:String(r)})}n.directories.length===0&&s===0&&ze({type:"error",title:t("Could not read the path of the dropped folder")}),s>0&&ze({type:"info",title:t("Only folders can be added as projects")}),n.truncated&&ze({type:"info",title:t("Only the first {{count}} folders were added",{count:Nm})})}function QW(){const{t:e}=ne(),[t,n]=m.useState(!1),[s,o]=m.useState(XW),[r,a]=m.useState(null);if(Og(t),m.useEffect(()=>{if(window.electronAPI.remote)return;const c=FW(b=>{n(b),b||a(null)}),d=b=>Array.from(b.dataTransfer?.types??[]),u=b=>d(b).includes("Files"),h=b=>{const w=zW({types:d(b),items:Array.from(b.dataTransfer?.items??[],C=>({kind:C.kind,type:C.type})),composerReady:IW()});return o(C=>C.project===w.project&&C.attach===w.attach?C:w),w.project||w.attach},p=b=>{u(b)&&(b.preventDefault(),c.enter(h(b)))},f=b=>{if(!u(b))return;b.preventDefault(),c.over(h(b));const w=Fw(b.target);a(C=>C===w?C:w)},g=()=>c.leave(),x=()=>c.cancel(),v=b=>{b.key==="Escape"&&c.cancel()},y=b=>{if(c.cancel(),!u(b))return;b.preventDefault();const w=Fw(b.target);if(!w)return;if(b.stopPropagation(),w==="attach"){DW(Array.from(b.dataTransfer?.files??[]));return}const C=JW(b);hT(()=>ZW(C,e))};return window.addEventListener("dragenter",p,!0),window.addEventListener("dragover",f,!0),window.addEventListener("dragleave",g,!0),window.addEventListener("drop",y,!0),window.addEventListener("dragend",x,!0),window.addEventListener("blur",x),window.addEventListener("keydown",v,!0),()=>{window.removeEventListener("dragenter",p,!0),window.removeEventListener("dragover",f,!0),window.removeEventListener("dragleave",g,!0),window.removeEventListener("drop",y,!0),window.removeEventListener("dragend",x,!0),window.removeEventListener("blur",x),window.removeEventListener("keydown",v,!0),c.dispose()}},[e]),!t)return null;const l=[s.project&&{id:"project",Icon:Nu,label:e("New project")},s.attach&&{id:"attach",Icon:u4,label:e("Reference in chat")}].filter(c=>c!==!1);return i.jsx("div",{className:"pointer-events-none fixed inset-0 flex items-center justify-center gap-4 bg-background/70 backdrop-blur-[2px]",style:{zIndex:yn.MODAL_BACKDROP},children:l.map(({id:c,Icon:d,label:u})=>i.jsxs("div",{"data-drop-zone":c,className:W("pointer-events-auto flex h-40 w-56 flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed bg-card text-card-foreground shadow-lg transition-colors duration-150",r===c?"border-brand bg-brand/5":"border-border"),children:[i.jsx(d,{className:W("h-8 w-8",r===c?"text-brand":"text-muted-foreground")}),i.jsx("p",{className:"text-sm font-medium",children:u})]},c))})}function Bw(){const{t:e}=ne(),[t,n]=m.useState(null),[s,o]=m.useState(!1),[r,a]=m.useState(!1),[l,c]=m.useState(!1);if(m.useEffect(()=>{let f=!0;window.electronAPI.updater.getState().then(x=>f&&a(x.host==="desktop")).catch(()=>{});const g=window.electronAPI.updater.onStatus(x=>{n(x),x.status!=="checking"&&x.status!=="not-available"&&o(!1)});return()=>{f=!1,g()}},[]),s||!t)return null;const d=t.status==="available"&&r;if(t.status!=="downloaded"&&t.status!=="downloading"&&!d)return null;const u=t.info?.version,h=t.status==="downloaded",p=h&&t.restartPending===!0;return i.jsxs("div",{className:"border-b border-blue-500/20 bg-background",children:[i.jsxs("div",{className:"flex items-center gap-2 bg-blue-500/8 px-4 py-1.5 text-xs",children:[h?i.jsx(ej,{className:"h-3.5 w-3.5 shrink-0 text-blue-500"}):i.jsx(cc,{className:"h-3.5 w-3.5 shrink-0 animate-pulse text-blue-500"}),i.jsx("span",{className:"min-w-0 flex-1",children:p?e("Will restart to update {{version}} when the running turns finish.",{version:u??""}):h?e("New version {{version}} is ready — restart to update.",{version:u??""}):d?e("New version {{version}} found",{version:u??""}):e("Downloading update… {{percent}}%",{percent:Math.round(t.progress?.percent??0)})}),(h||d)&&i.jsx("button",{type:"button",onClick:()=>c(!0),className:"shrink-0 rounded-md px-2 py-1 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:e("Release notes")}),d&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.updater.downloadUpdate()},className:"shrink-0 rounded-md bg-primary px-2.5 py-1 text-primary-foreground transition-colors hover:bg-primary/90",children:e("Download update")}),p&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.updater.cancelRestart()},className:"shrink-0 rounded-md px-2 py-1 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:e("Cancel")}),h&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.updater.quitAndInstall({now:p})},className:"shrink-0 rounded-md bg-primary px-2.5 py-1 text-primary-foreground transition-colors hover:bg-primary/90",children:e(p?"Restart now":"Restart to update")}),i.jsx("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",title:e("Close"),children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]}),i.jsx(PA,{open:l,onOpenChange:c,status:t})]})}const zp="enso.zoomBanner.dismissedPercent";function e8(e,t){return e!==100&&e!==t}function t8(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function Gp(){return window.electronAPI.window.getZoomPercent()}function Vw(){const{t:e}=ne(),[t,n]=m.useState(Gp),[s,o]=m.useState(()=>t8(localStorage.getItem(zp)));return m.useEffect(()=>{const r=()=>n(Gp());return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e8(t,s)?i.jsx("div",{className:"border-b border-blue-500/20 bg-background",children:i.jsxs("div",{className:"flex items-center gap-2 bg-blue-500/8 px-4 py-1.5 text-xs",children:[i.jsx("span",{className:"min-w-0 flex-1",children:e("Interface is zoomed to {{percent}}% · {{shortcut}}",{percent:t,shortcut:ti("mod+0")})}),i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.window.resetZoom(),localStorage.removeItem(zp),o(null),n(Gp())},className:"shrink-0 rounded-md bg-primary px-2.5 py-1 text-primary-foreground transition-colors hover:bg-primary/90",children:e("Restore 100%")}),i.jsx("button",{type:"button",onClick:()=>{localStorage.setItem(zp,String(t)),o(t)},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",title:e("Close"),"aria-label":e("Close"),children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]})}):null}function n8(e,t){return[t,...e.filter(n=>n.parentId===t.id).sort((n,s)=>n.createdAt-s.createdAt)]}function s8(e,t){return(t.activeThreadId?e.find(s=>s.id===t.activeThreadId&&s.parentId===t.id):void 0)??t}const i8=10,gT=e=>[...e].sort((t,n)=>n.activityAt-t.activityAt);function xT(e,t,n=i8){const s=gT(e),o=a=>a.id===t.currentId||a.id===t.rootId?0:a.unread||a.running?1:2,r=new Set([...s].sort((a,l)=>o(a)-o(l)).slice(0,n).map(a=>a.id));return s.filter(a=>r.has(a.id)).sort((a,l)=>+(l.id===t.rootId)-+(a.id===t.rootId))}function $w(e,t,n){const s=t.trim().toLowerCase();return gT(e).filter(o=>(n==="all"||(n==="unread"?o.unread:o.running))&&(!s||`${o.title}
20
- ${o.preview??""}`.toLowerCase().includes(s)))}function Du({onResize:e,onResizingChange:t,gap:n=!1,edge:s=!1}){const[o,r]=m.useState(!1),a=m.useRef(0),l=m.useCallback(c=>{c.preventDefault(),r(!0),t?.(!0),a.current=c.clientX;const d=h=>{e(h.clientX-a.current),a.current=h.clientX},u=()=>{r(!1),t?.(!1),document.removeEventListener("mousemove",d),document.removeEventListener("mouseup",u)};document.addEventListener("mousemove",d),document.addEventListener("mouseup",u)},[e,t]);return i.jsxs("div",{className:W("relative z-20 shrink-0",s?"w-0":n?"w-[8px]":"w-px bg-border"),children:[i.jsx("div",{onMouseDown:l,className:W("absolute inset-y-0 z-10 cursor-col-resize","after:absolute after:inset-y-0 after:w-px after:transition-colors hover:after:bg-ring",s?"left-0 w-3 after:left-0":n?"inset-x-0 after:left-1/2":"-left-1 -right-1 after:left-1",o&&"after:bg-ring")}),o&&i.jsx("div",{className:"fixed inset-0 z-50 cursor-col-resize"})]})}const o8={"external-send":"Protected: external send",delete:"Protected: delete",payment:"Protected: payment",deploy:"Protected: deploy / production",secret:"Protected: secrets",destructive:"Protected: destructive command"};function vT(e,t){return t(o8[e])}const bT={exec:"Isolated sandbox",codemode:"Isolated sandbox",tool_search:"Tool search",apply_patch:"Apply patch",explore_mark:"Explore mark",explore_fold:"Explore fold",turn_discard:"Turn discard",turn_recall:"Turn recall",subagent:"Subagent",workflow:"Workflow",ask_user:"Ask user",task_output:"Task output",task_stop:"Task stop",message_coworker:"Message coworker",message_main_agent:"Message main agent",recall:"Recall memory",memory_search:"Memory search",memory_capture:"Memory capture",memory_crystallize:"Memory crystallize",memory_delete:"Memory delete",browser_navigate:"Browser navigate",browser_snapshot:"Browser snapshot",browser_click:"Browser click",browser_type:"Browser type",browser_tabs:"Browser tabs",browser_lock:"Browser lock",browser_fill:"Browser fill",browser_press_key:"Browser press key",browser_scroll:"Browser scroll",browser_select_option:"Browser select option",browser_mouse_click_xy:"Browser click xy",browser_drag:"Browser drag",browser_highlight:"Browser highlight",browser_get_bounding_box:"Browser bounding box",browser_screenshot:"Browser screenshot",browser_cdp:"Browser CDP",web_search:"Web search",web_fetch:"Web fetch",todo:"Todos"};function Bo(e,t){const n=bT[e];return n?t(n):e}const r8={report:"Read report",wait:"Wait",stop:"Stop",dismiss:"Dismiss agent",list:"List agents"};function Jx(e,t=0){const[n,s]=m.useState(()=>Date.now());return m.useEffect(()=>{if(e===void 0)return;s(Date.now());const o=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(o)},[e]),e===void 0?void 0:e+t-n}function Zx({remainingMs:e,expiredLabel:t}){const{t:n}=ne();if(e===void 0)return null;if(e<=0)return i.jsx("span",{className:"shrink-0 text-[10px] text-warning",children:n(t)});const s=Math.ceil(e/1e3),o=`${Math.floor(s/60)}:${String(s%60).padStart(2,"0")}`;return i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:n("{{time}} left",{time:o})})}const a8={command:Uo,"file-edit":b6,"file-write":y6,mcp:tj};function l8({kind:e,summary:t}){const[n,s]=m.useState(null);m.useEffect(()=>{if(e!=="command")return;let a=!0;return MA(t,"shellscript").then(l=>{a&&s({summary:t,html:l})}),()=>{a=!1}},[e,t]);const o=n?.summary===t?n.html:null,r=i.jsx(nj,{text:t,className:"absolute top-1 right-1 z-10 rounded-md bg-background/80 p-1 text-muted-foreground backdrop-blur"});return e==="command"&&o!=null?i.jsxs("div",{className:"relative mt-1.5",children:[i.jsx("div",{className:"max-h-24 overflow-auto rounded-md text-xs leading-relaxed [&_pre]:m-0 [&_pre]:py-1.5 [&_pre]:pr-7 [&_pre]:pl-2 [&_pre]:font-mono [&_pre]:whitespace-pre-wrap",dangerouslySetInnerHTML:{__html:o}}),r]}):i.jsxs("div",{className:"relative mt-1.5",children:[i.jsx("pre",{className:"max-h-24 overflow-auto rounded-md bg-muted/50 py-1.5 pr-7 pl-2 font-mono text-xs whitespace-pre-wrap",children:t}),r]})}const c8={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."},d8=400;function Rh({approvals:e,onRespond:t,allowSession:n=!0,handoff:s=!0,clockOffset:o}){const{t:r}=ne(),[a,l]=m.useState(null),[c,d]=m.useState(null),u=e[0],h=u?.requestId,p=Jx(u?.phase==="reviewing"?void 0:u?.expiresAt,o);if(m.useEffect(()=>{if(!h)return;const y=setTimeout(()=>d(h),d8);return()=>clearTimeout(y)},[h]),!u)return null;const f=a8[u.kind]??ca,g=u.phase==="reviewing",x=c!==u.requestId||a===u.requestId||p!==void 0&&p<=0,v=y=>{y!=="review"&&l(u.requestId),t(u.requestId,y)};return i.jsxs("div",{"data-enso":"approval",className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx(ca,{className:"h-3.5 w-3.5 shrink-0 text-amber-500"}),i.jsx("span",{className:"shrink-0 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:r(g?"Assistant reviewing…":"Approval required")}),i.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-muted-foreground",children:[i.jsx(f,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate font-mono",children:u.toolCallId&&AA(u.toolCallId)?`${r("Isolated sandbox")} › ${Bo(u.tool,r)}`:Bo(u.tool,r)})]}),u.protected&&i.jsx("span",{className:"shrink-0 rounded bg-destructive/15 px-1.5 text-[10px] text-destructive",children:vT(u.protected,r)}),i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[i.jsx(Zx,{remainingMs:p,expiredLabel:"Timed out · denied"}),e.length>1&&i.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["1/",e.length]})]})]}),u.reviewFallback&&i.jsx("p",{className:"mt-1 text-[11px] text-amber-600 dark:text-amber-400",children:r(c8[u.reviewFallback])}),u.guard&&i.jsx("p",{className:"mt-1 text-[11px] text-destructive",title:u.guard.ruleId,children:r("dcg: {{reason}}",{reason:u.guard.reason})}),u.summary&&i.jsx(l8,{kind:u.kind,summary:u.summary}),!g&&i.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[s&&u.kind==="command"&&i.jsx("button",{type:"button",disabled:x,title:r("Send back for a safer command"),onClick:()=>v("revise"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Adjust")}),s&&i.jsx("button",{type:"button",disabled:x,title:r("Let the assistant decide"),onClick:()=>v("review"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Assistant review")}),i.jsx("button",{type:"button",disabled:x,onClick:()=>v("deny"),className:"rounded-md px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50",children:r("Deny")}),n&&!u.protected&&i.jsx("button",{type:"button",disabled:x,onClick:()=>v("allowSession"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Always allow this session")}),i.jsx("button",{type:"button",disabled:x,onClick:()=>v("allow"),className:"rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:r("Allow")})]})]})}function Ww(e){return e>=0&&e<9?String(e+1):null}function u8(e,t){const n=t===void 0?-1:e?.indexOf(t)??-1;return n>=0?n:0}function h8(e,t,n){return n==="ArrowDown"?Math.min(e+1,t-1):n==="ArrowUp"?Math.max(e-1,0):null}function Lh({asks:e,onAnswer:t,clockOffset:n,autoFocus:s=!0}){const{t:o}=ne(),r=m.useRef(null),a=m.useRef([]),[l,c]=m.useState(""),[d,u]=m.useState(null),[h,p]=m.useState(()=>new Set),f=e[0],g=f?.requestId,x=Jx(f?.expiresAt,n),v=g!==void 0&&h.has(g),y=f?.options,b=f?.recommended,w=k=>{const S=a.current[k];y&&k<y.length&&S?S.focus():r.current?.focus()};if(m.useEffect(()=>{if(!s||!g||v)return;const k=u8(y,b),S=a.current[k];y&&k<y.length&&S?S.focus():r.current?.focus()},[s,g,v]),!f)return null;const C=d===f.requestId||x!==void 0&&x<=0,_=k=>{k.trim()&&(u(f.requestId),c(""),t(f.requestId,k.trim()))},N=()=>p(k=>k.has(f.requestId)?k:new Set(k).add(f.requestId));return v?i.jsxs("button",{type:"button","data-enso":"ask-later",onClick:()=>p(k=>{const S=new Set(k);return S.delete(f.requestId),S}),className:"mb-1 flex w-full items-center gap-2 rounded-lg border border-dashed border-border/60 px-2.5 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground",children:[i.jsx(p0,{className:"h-3.5 w-3.5 shrink-0 text-blue-500"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:f.question}),e.length>1&&i.jsxs("span",{className:"shrink-0 text-[10px] tabular-nums",children:["1/",e.length]}),i.jsx(un,{className:"h-3 w-3 shrink-0"})]}):i.jsxs("div",{"data-enso":"ask",className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",onKeyDown:k=>{if(k.nativeEvent.isComposing||C)return;if(k.key==="Escape"){k.preventDefault(),N();return}const S=k.target,A=(y?.length??0)+1,T=S===r.current?A-1:a.current.indexOf(S),I=T>=0?h8(T,A,k.key):null;if(I!==null){k.preventDefault(),w(I);return}if(S instanceof HTMLInputElement&&(S.value.length>0||k.key==="Enter"))return;const P=Number(k.key)-1,D=y?.[P];if(Ww(P)&&D){k.preventDefault(),_(D);return}S instanceof HTMLButtonElement&&T>=0&&(k.key==="Process"?r.current?.focus():k.key.length===1&&k.key!==" "&&!k.metaKey&&!k.ctrlKey&&!k.altKey&&(k.preventDefault(),c(O=>O+k.key),r.current?.focus()))},children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(p0,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-blue-500"}),i.jsx("span",{className:"min-w-0 flex-1 text-xs leading-relaxed whitespace-pre-wrap",children:f.question}),i.jsx("button",{type:"button",onClick:N,className:"shrink-0 rounded-md px-1.5 py-0.5 text-[10px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:o("Later")}),i.jsx(Zx,{remainingMs:x,expiredLabel:"Timed out · no answer"}),e.length>1&&i.jsxs("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:["1/",e.length]})]}),y&&y.length>0&&i.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:y.map((k,S)=>{const A=Ww(S);return i.jsxs("button",{ref:T=>{a.current[S]=T},type:"button",disabled:C,onClick:()=>_(k),className:"flex items-center gap-2 rounded-md border border-border/60 px-2 py-1 text-left text-xs text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus:border-ring focus:bg-muted focus:text-foreground disabled:opacity-50",children:[A&&i.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded bg-muted font-mono text-[10px] text-muted-foreground",children:A}),i.jsx("span",{className:"min-w-0 flex-1",children:k}),k===b&&i.jsx("span",{className:"shrink-0 rounded bg-success/15 px-1.5 text-[10px] text-success",children:o("Recommended")})]},k)})}),i.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[i.jsx("input",{ref:r,value:l,onChange:k=>c(k.target.value),onKeyDown:k=>{k.nativeEvent.isComposing||k.key==="Enter"&&_(l)},disabled:C,placeholder:o("Type an answer…"),className:"h-7 min-w-0 flex-1 rounded-md border bg-transparent px-2 text-xs outline-none focus:ring-1 focus:ring-ring disabled:opacity-50"}),i.jsx("button",{type:"button",disabled:C||!l.trim(),onClick:()=>_(l),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",children:i.jsx(qx,{className:"h-3.5 w-3.5"})})]})]})}const Oh=0,Xo=1,Ra=2,wT=4;function Uw(e){return()=>e}function p8(e){e()}function yT(e,t){return n=>e(t(n))}function Kw(e,t){return()=>e(t)}function f8(e,t){return n=>e(t,n)}function Qx(e){return e!==void 0}function m8(...e){return()=>{e.map(p8)}}function La(){}function zh(e,t){return t(e),e}function g8(e,t){return t(e)}function Mn(...e){return e}function gn(e,t){return e(Xo,t)}function Wt(e,t){e(Oh,t)}function ev(e){e(Ra)}function Ln(e){return e(wT)}function St(e,t){return gn(e,f8(t,Oh))}function xi(e,t){const n=e(Xo,s=>{n(),t(s)});return n}function qw(e){let t,n;return s=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{s(t)},e)}}function ST(e,t){return e===t}function Pn(e=ST){let t;return n=>s=>{e(t,s)||(t=s,n(s))}}function Mt(e){return t=>n=>{e(n)&&t(n)}}function ft(e){return t=>yT(t,e)}function Pi(e){return t=>()=>{t(e)}}function $e(e,...t){const n=x8(...t);return((s,o)=>{switch(s){case Ra:ev(e);return;case Xo:return gn(e,n(o))}})}function Gi(e,t){return n=>s=>{n(t=e(t,s))}}function kr(e){return t=>n=>{e>0?e--:t(n)}}function ho(e){let t=null,n;return s=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,s(t)},e))}}function en(...e){const t=Array.from({length:e.length});let n=0,s=null;const o=2**e.length-1;return e.forEach((r,a)=>{const l=2**a;gn(r,c=>{const d=n;n|=l,t[a]=c,d!==o&&n===o&&s&&(s(),s=null)})}),r=>a=>{const l=()=>{r([a].concat(t))};n===o?l():s=l}}function x8(...e){return t=>e.reduceRight(g8,t)}function v8(e){let t,n;const s=()=>t?.();return function(o,r){switch(o){case Xo:return r?n===r?void 0:(s(),n=r,t=gn(e,r),t):(s(),La);case Ra:s(),n=null;return}}}function Je(e){let t=e;const n=ln();return((s,o)=>{switch(s){case Oh:t=o;break;case Xo:{o(t);break}case wT:return t}return n(s,o)})}function ms(e,t){return zh(Je(t),n=>St(e,n))}function ln(){const e=[];return((t,n)=>{switch(t){case Oh:e.slice().forEach(s=>{s(n)});return;case Ra:e.splice(0);return;case Xo:return e.push(n),()=>{const s=e.indexOf(n);s>-1&&e.splice(s,1)}}})}function Bs(e){return zh(ln(),t=>St(e,t))}const b8={singleton:!0};function hn(e,t=[],n=b8){const{singleton:s}=n;return{constructor:e,dependencies:t,id:w8(),singleton:s}}const w8=()=>Symbol("id");function y8(e){const t=new Map,n=({constructor:s,dependencies:o,id:r,singleton:a})=>{if(a&&t.has(r))return t.get(r);const l=s(o.map(c=>n(c)));return a&&t.set(r,l),l};return n(e)}function Vn(...e){const t=ln(),n=Array.from({length:e.length});let s=0;const o=2**e.length-1;return e.forEach((r,a)=>{const l=2**a;gn(r,c=>{n[a]=c,s|=l,s===o&&Wt(t,n)})}),function(r,a){switch(r){case Ra:{ev(t);return}case Xo:return s===o&&a(n),gn(t,a)}}}function At(e,t=ST){return $e(e,Pn(t))}function Pm(...e){return function(t,n){switch(t){case Ra:return;case Xo:return m8(...e.map(s=>gn(s,n)))}}}const ts={DEBUG:0,INFO:1,WARN:2,ERROR:3},S8={[ts.DEBUG]:"debug",[ts.ERROR]:"error",[ts.INFO]:"log",[ts.WARN]:"warn"},C8=()=>typeof globalThis>"u"?window:globalThis,Jo=hn(()=>{const e=Je(ts.ERROR);return{log:Je((t,n,s=ts.INFO)=>{const o=C8().VIRTUOSO_LOG_LEVEL??Ln(e);s>=o&&console[S8[s]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function k8(e){return"self"in e?e.document.documentElement:e}function CT(e){const t=k8(e);return t.ownerDocument.defaultView.getComputedStyle(t).direction==="rtl"}function mr(e,t){return CT(e)?-t:t}function Yw(e,t){return CT(e)?-t:t}function Nr(e,t,n){return tv(e,t,n).callbackRef}function tv(e,t,n){const s=_e.useRef(null);let o=a=>{};const r=_e.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(a=>{const l=()=>{const c=a[0].target;c.offsetParent!==null&&e(c)};n?l():requestAnimationFrame(l)}):null,[e,n]);return o=a=>{a&&t?(r?.observe(a),s.current=a):(s.current&&r?.unobserve(s.current),s.current=null)},{callbackRef:o,ref:s}}function j8(e,t,n,s,o,r,a,l,c){const d=_e.useCallback(u=>{const h=_8(u.children,t,l?"offsetWidth":"offsetHeight",o);let p=u.parentElement;for(;p.dataset.virtuosoScroller===void 0;)p=p.parentElement;const f=p.lastElementChild?.dataset.viewportType==="window";let g;f&&(g=p.ownerDocument.defaultView);const x=a?l?a.scrollWidth:a.scrollHeight:f?l?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight:l?p.scrollWidth:p.scrollHeight,v=a?l?a.offsetWidth:a.offsetHeight:f?l?g.innerWidth:g.innerHeight:l?p.offsetWidth:p.offsetHeight,y=a?l?mr(a,a.scrollLeft):a.scrollTop:f?l?mr(g,g.scrollX||g.document.documentElement.scrollLeft):g.scrollY||g.document.documentElement.scrollTop:l?mr(p,p.scrollLeft):p.scrollTop;s({scrollHeight:x,scrollTop:Math.max(y,0),viewportHeight:v}),r?.(l?Xw("column-gap",getComputedStyle(u).columnGap,o):Xw("row-gap",getComputedStyle(u).rowGap,o)),h!==null&&e(h)},[e,t,o,r,a,s,l]);return tv(d,n,c)}function _8(e,t,n,s){const o=e.length;if(o===0)return null;const r=[];for(let a=0;a<o;a++){const l=e.item(a);if(l.dataset.index===void 0)continue;const c=parseInt(l.dataset.index,10),d=parseFloat(l.dataset.knownSize),u=t(l,n);if(u===0&&s("Zero-sized element, this should not happen",{child:l},ts.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 Xw(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,ts.WARN),t==="normal"?0:parseInt(t??"0",10)}function kT(e,t,n){const s=_e.useRef(null),o=_e.useCallback(c=>{if(!c?.offsetParent)return;const d=c.getBoundingClientRect(),u=d.width;let h,p;if(t){const f=t.getBoundingClientRect(),g=d.top-f.top;p=f.height-Math.max(0,g),h=g+t.scrollTop}else{const f=a.current.ownerDocument.defaultView;p=f.innerHeight-Math.max(0,d.top),h=d.top+f.scrollY}s.current={listHeight:d.height,offsetTop:h,visibleHeight:p,visibleWidth:u},e(s.current)},[e,t]),{callbackRef:r,ref:a}=tv(o,!0,n),l=_e.useCallback(()=>{o(a.current)},[o,a]);return _e.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 Es=hn(()=>{const e=ln(),t=ln(),n=Je(0),s=ln(),o=Je(0),r=ln(),a=ln(),l=Je(0),c=Je(0),d=Je(0),u=Je(0),h=ln(),p=ln(),f=Je(!1),g=Je(!1),x=Je(!1);return St($e(e,ft(({scrollTop:v})=>v)),t),St($e(e,ft(({scrollHeight:v})=>v)),a),St(t,o),{deviation:n,fixedFooterHeight:d,fixedHeaderHeight:c,footerHeight:u,headerHeight:l,horizontalDirection:g,scrollBy:p,scrollContainerState:e,scrollHeight:a,scrollingInProgress:f,scrollTo:h,scrollTop:t,skipAnimationFrameInResizeObserver:x,smoothScrollTargetReached:s,statefulScrollTop:o,viewportHeight:r}},[],{singleton:!0}),Xl={lvl:0};function jT(e,t){const n=e.length;if(n===0)return[];let{index:s,value:o}=t(e[0]);const r=[];for(let a=1;a<n;a++){const{index:l,value:c}=t(e[a]);r.push({end:l-1,start:s,value:o}),s=l,o=c}return r.push({end:1/0,start:s,value:o}),r}function Sn(e){return e===Xl}function Jl(e,t){if(!Sn(e))return t===e.k?e.v:t<e.k?Jl(e.l,t):Jl(e.r,t)}function Ci(e,t,n="k"){if(Sn(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const s=Ci(e.r,t,n);return s[0]===-1/0?[e.k,e.v]:s}return Ci(e.l,t,n)}function zs(e,t,n){return Sn(e)?TT(t,n,1):t===e.k?Zn(e,{k:t,v:n}):t<e.k?Jw(Zn(e,{l:zs(e.l,t,n)})):Jw(Zn(e,{r:zs(e.r,t,n)}))}function sa(){return Xl}function ia(e,t,n){if(Sn(e))return[];const s=Ci(e,t)[0];return N8(Mm(e,s,n))}function Am(e,t){if(Sn(e))return Xl;const{k:n,l:s,r:o}=e;if(t===n){if(Sn(s))return o;if(Sn(o))return s;const[r,a]=NT(s);return Wd(Zn(e,{k:r,l:_T(s),v:a}))}return t<n?Wd(Zn(e,{l:Am(s,t)})):Wd(Zn(e,{r:Am(o,t)}))}function gr(e){return Sn(e)?[]:[...gr(e.l),{k:e.k,v:e.v},...gr(e.r)]}function Mm(e,t,n){if(Sn(e))return[];const{k:s,l:o,r,v:a}=e;let l=[];return s>t&&(l=l.concat(Mm(o,t,n))),s>=t&&s<=n&&l.push({k:s,v:a}),s<=n&&(l=l.concat(Mm(r,t,n))),l}function Wd(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(Fp(t))return IT(Zn(e,{lvl:n-1}));if(!Sn(t)&&!Sn(t.r))return Zn(t.r,{l:Zn(t,{r:t.r.l}),lvl:n,r:Zn(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}if(Fp(e))return Rm(Zn(e,{lvl:n-1}));if(!Sn(s)&&!Sn(s.l)){const o=s.l,r=Fp(o)?s.lvl-1:s.lvl;return Zn(o,{l:Zn(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:Rm(Zn(s,{l:o.r,lvl:r}))})}throw new Error("Unexpected empty nodes")}function Zn(e,t){return TT(t.k===void 0?e.k:t.k,t.v===void 0?e.v:t.v,t.lvl===void 0?e.lvl:t.lvl,t.l===void 0?e.l:t.l,t.r===void 0?e.r:t.r)}function _T(e){return Sn(e.r)?e.l:Wd(Zn(e,{r:_T(e.r)}))}function Fp(e){return Sn(e)||e.lvl>e.r.lvl}function NT(e){return Sn(e.r)?[e.k,e.v]:NT(e.r)}function TT(e,t,n,s=Xl,o=Xl){return{k:e,l:s,lvl:n,r:o,v:t}}function Jw(e){return Rm(IT(e))}function IT(e){const{l:t}=e;return!Sn(t)&&t.lvl===e.lvl?Zn(t,{r:Zn(e,{l:t.r})}):e}function Rm(e){const{lvl:t,r:n}=e;return!Sn(n)&&!Sn(n.r)&&n.lvl===t&&n.r.lvl===t?Zn(n,{l:Zn(e,{r:n.l}),lvl:t+1}):e}function N8(e){return jT(e,({k:t,v:n})=>({index:t,value:n}))}function DT(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 nv=hn(()=>({recalcInProgress:Je(!1)}),[],{singleton:!0});function ET(e,t,n){return e[Eu(e,t,n)]}function Eu(e,t,n,s=0){let o=e.length-1;for(;s<=o;){const r=Math.floor((s+o)/2),a=e[r],l=n(a,t);if(l===0)return r;if(l===-1){if(o-s<2)return r-1;o=r-1}else{if(o===s)return r;s=r+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function T8(e,t,n,s){const o=Eu(e,t,s),r=Eu(e,n,s,o);return e.slice(o,r+1)}function Vo(e,t){return Math.round(e.getBoundingClientRect()[t])}function Gh(e){return!Sn(e.groupOffsetTree)}function sv({index:e},t){return t===e?0:t<e?-1:1}function I8(){return{groupIndices:[],groupOffsetTree:sa(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:sa()}}function D8(e,t){let n=Sn(e)?0:1/0;for(const s of t){const{endIndex:o,size:r,startIndex:a}=s;if(n=Math.min(n,a),Sn(e)){e=zs(e,0,r);continue}const l=ia(e,a-1,o+1);if(l.some(O8(s)))continue;let c=!1,d=!1;for(const{end:u,start:h,value:p}of l)c?(o>=h||r===p)&&(e=Am(e,h)):(d=p!==r,c=!0),u>o&&o>=h&&p!==r&&(e=zs(e,o+1,p));d&&(e=zs(e,a,r))}return[e,n]}function E8(e){return e.groupIndex!==void 0}function P8({offset:e},t){return t===e?0:t<e?-1:1}function Ql(e,t,n){if(t.length===0)return 0;const{index:s,offset:o,size:r}=ET(t,e,sv),a=e-s,l=r*a+(a-1)*n+o;return l>0?l+n:l}function PT(e,t){if(!Gh(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function AT(e,t,n){if(E8(e))return t.groupIndices[e.groupIndex]+1;const s=e.index==="LAST"?n:e.index;let o=PT(s,t);return o=Math.max(0,Math.min(n,o)),o}function A8(e,t,n,s=0){return s>0&&(t=Math.max(t,ET(e,s,sv).offset)),jT(T8(e,t,n,P8),L8)}function M8(e,[t,n,s,o]){t.length>0&&s("received item sizes",t,ts.DEBUG);const r=e.sizeTree;let a=r,l=0;if(n.length>0&&Sn(r)&&t.length===2){const p=t[0].size,f=t[1].size;a=n.reduce((g,x)=>zs(zs(g,x,p),x+1,f),a)}else[a,l]=D8(a,t);if(a===r)return e;const{lastIndex:c,lastOffset:d,lastSize:u,offsetTree:h}=Lm(e.offsetTree,l,a,o);return{groupIndices:n,groupOffsetTree:n.reduce((p,f)=>zs(p,f,Ql(f,h,o)),sa()),lastIndex:c,lastOffset:d,lastSize:u,offsetTree:h,sizeTree:a}}function R8(e){return gr(e).map(({k:t,v:n},s,o)=>{const r=o[s+1];return{endIndex:r===void 0?1/0:r.k-1,size:n,startIndex:t}})}function Zw(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 Lm(e,t,n,s){let o=e,r=0,a=0,l=0,c=0;if(t===0)o=[];else{c=Eu(o,t-1,sv),l=o[c].offset;const d=Ci(n,t-1);r=d[0],a=d[1],o.length&&o[c].size===Ci(n,t)[1]&&(c-=1),o=o.slice(0,c+1)}for(const{start:d,value:u}of ia(n,t,1/0)){const h=d-r,p=h*a+l+h*s;o.push({index:d,offset:p,size:u}),r=d,l=p,a=u}return{lastIndex:r,lastOffset:l,lastSize:a,offsetTree:o}}function L8(e){return{index:e.index,value:e}}function O8(e){const{endIndex:t,size:n,startIndex:s}=e;return o=>o.start===s&&(o.end===t||o.end===1/0)&&o.value===n}const z8={offsetHeight:"height",offsetWidth:"width"},Ki=hn(([{log:e},{recalcInProgress:t}])=>{const n=ln(),s=ln(),o=ms(s,0),r=ln(),a=ln(),l=Je(0),c=Je([]),d=Je(void 0),u=Je(void 0),h=Je(void 0),p=Je(void 0),f=Je((k,S)=>Vo(k,z8[S])),g=Je(void 0),x=Je(0),v=I8(),y=ms($e(n,en(c,e,x),Gi(M8,v),Pn()),v),b=ms($e(c,Pn(),Gi((k,S)=>({current:S,prev:k.current}),{current:[],prev:[]}),ft(({prev:k})=>k)),[]);St($e(c,Mt(k=>k.length>0),en(y,x),ft(([k,S,A])=>{const T=k.reduce((I,P,D)=>zs(I,P,Ql(P,S.offsetTree,A)||D),sa());return{...S,groupIndices:k,groupOffsetTree:T}})),y),St($e(s,en(y),Mt(([k,{lastIndex:S}])=>k<S),ft(([k,{lastIndex:S,lastSize:A}])=>[{endIndex:S,size:A,startIndex:k}])),n),St(d,u);const w=ms($e(d,ft(k=>k===void 0)),!0);St($e(u,Mt(k=>k!==void 0&&Sn(Ln(y).sizeTree)),ft(k=>{const S=Ln(h),A=Ln(c).length>0;return S!==void 0&&S!==0?A?[{endIndex:0,size:S,startIndex:0},{endIndex:1,size:k,startIndex:1}]:[]:[{endIndex:0,size:k,startIndex:0}]})),n),St($e(p,Mt(k=>k!==void 0&&k.length>0&&Sn(Ln(y).sizeTree)),ft(k=>{const S=[];let A=k[0],T=0;for(let I=1;I<k.length;I++){const P=k[I];P!==A&&(S.push({endIndex:I-1,size:A,startIndex:T}),A=P,T=I)}return S.push({endIndex:k.length-1,size:A,startIndex:T}),S})),n),St($e(c,en(h,u),Mt(([,k,S])=>k!==void 0&&S!==void 0),ft(([k,S,A])=>{const T=[];for(let I=0;I<k.length;I++){const P=k[I],D=k[I+1];T.push({startIndex:P,endIndex:P,size:S}),D!==void 0&&T.push({startIndex:P+1,endIndex:D-1,size:A})}return T})),n);const C=Bs($e(n,en(y),Gi(({sizes:k},[S,A])=>({changed:A!==k,sizes:A}),{changed:!1,sizes:v}),ft(k=>k.changed)));gn($e(l,Gi((k,S)=>({diff:k.prev-S,prev:S}),{diff:0,prev:0}),ft(k=>k.diff)),k=>{const{groupIndices:S}=Ln(y);if(k>0)Wt(t,!0),Wt(r,k+Zw(k,S));else if(k<0){const A=Ln(b);A.length>0&&(k-=Zw(-k,A)),Wt(a,k)}}),gn($e(l,en(e)),([k,S])=>{k<0&&S("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:l},ts.ERROR)});const _=Bs(r);St($e(r,en(y),ft(([k,S])=>{const A=S.groupIndices.length>0,T=[],I=S.lastSize;if(A){const P=Jl(S.sizeTree,0);let D=0,O=0;for(;D<k;){const R=S.groupIndices[O],$=S.groupIndices.length===O+1?1/0:S.groupIndices[O+1]-R-1;T.push({endIndex:R,size:P,startIndex:R}),T.push({endIndex:R+1+$-1,size:I,startIndex:R+1}),O++,D+=$+1}const z=gr(S.sizeTree);return D!==k&&z.shift(),z.reduce((R,{k:$,v:X})=>{let H=R.ranges;return R.prevSize!==0&&(H=[...R.ranges,{endIndex:$+k-1,size:R.prevSize,startIndex:R.prevIndex}]),{prevIndex:$+k,prevSize:X,ranges:H}},{prevIndex:k,prevSize:0,ranges:T}).ranges}return gr(S.sizeTree).reduce((P,{k:D,v:O})=>({prevIndex:D+k,prevSize:O,ranges:[...P.ranges,{endIndex:D+k-1,size:P.prevSize,startIndex:P.prevIndex}]}),{prevIndex:0,prevSize:I,ranges:[]}).ranges})),n);const N=Bs($e(a,en(y,x),ft(([k,{offsetTree:S},A])=>{const T=-k;return Ql(T,S,A)})));return St($e(a,en(y,x),ft(([k,S,A])=>{if(S.groupIndices.length>0){if(Sn(S.sizeTree))return S;let I=sa();const P=Ln(b);let D=0,O=0,z=0;for(;D<-k;){z=P[O];const R=P[O+1]-z-1;O++,D+=R+1}if(I=gr(S.sizeTree).reduce((R,{k:$,v:X})=>zs(R,Math.max(0,$+k),X),I),D!==-k){const R=Jl(S.sizeTree,z);I=zs(I,0,R);const $=Ci(S.sizeTree,-k+1)[1];I=zs(I,1,$)}return{...S,sizeTree:I,...Lm(S.offsetTree,0,I,A)}}const T=gr(S.sizeTree).reduce((I,{k:P,v:D})=>zs(I,Math.max(0,P+k),D),sa());return{...S,sizeTree:T,...Lm(S.offsetTree,0,T,A)}})),y),{beforeUnshiftWith:_,data:g,defaultItemSize:u,firstItemIndex:l,fixedItemSize:d,fixedGroupSize:h,gap:x,groupIndices:c,heightEstimates:p,itemSize:f,listRefresh:C,shiftWith:a,shiftWithOffset:N,sizeRanges:n,sizes:y,statefulTotalCount:o,totalCount:s,trackItemSizes:w,unshiftWith:r}},Mn(Jo,nv),{singleton:!0});function G8(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const MT=hn(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:s,scrollTop:o}])=>{const r=ln(),a=ln(),l=Bs($e(r,ft(G8)));return St($e(l,ft(c=>c.totalCount)),n),St($e(l,ft(c=>c.groupIndices)),e),St($e(Vn(o,t,s),Mt(([c,d])=>Gh(d)),ft(([c,d,u])=>Ci(d.groupOffsetTree,Math.max(c-u,0),"v")[0]),Pn(),ft(c=>[c])),a),{groupCounts:r,topItemsIndexes:a}},Mn(Ki,Es)),Zo=hn(([{log:e}])=>{const t=Je(!1),n=Bs($e(t,Mt(s=>s),Pn()));return gn(t,s=>{s&&Ln(e)("props updated",{},ts.DEBUG)}),{didMount:n,propsReady:t}},Mn(Jo),{singleton:!0}),F8=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function RT(e){const t=typeof e=="number"?{index:e}:{...e};return t.align||(t.align="start"),(!t.behavior||!F8)&&(t.behavior="auto"),t.offset===void 0&&(t.offset=0),t}const Ic=hn(([{gap:e,listRefresh:t,sizes:n,totalCount:s},{fixedFooterHeight:o,fixedHeaderHeight:r,footerHeight:a,headerHeight:l,scrollingInProgress:c,scrollTo:d,smoothScrollTargetReached:u,viewportHeight:h},{log:p}])=>{const f=ln(),g=ln(),x=Je(0);let v=null,y=null,b=null;function w(){v!==null&&(v(),v=null),b!==null&&(b(),b=null),y&&(clearTimeout(y),y=null),Wt(c,!1)}return St($e(f,en(n,h,s,x,l,a,p),en(e,r,o),ft(([[C,_,N,k,S,A,T,I],P,D,O])=>{const z=RT(C),{align:R,behavior:$,offset:X}=z,H=k-1,te=AT(z,_,H);let V=Ql(te,_.offsetTree,P)+A;R==="end"?(V+=D+Ci(_.sizeTree,te)[1]-N+O,te===H&&(V+=T)):R==="center"?V+=(D+Ci(_.sizeTree,te)[1]-N+O)/2:V-=S,X!==void 0&&X!==0&&(V+=X);const Y=q=>{w(),q?(I("retrying to scroll to",{location:C},ts.DEBUG),Wt(f,C)):(Wt(g,!0),I("list did not change, scroll successful",{},ts.DEBUG))};if(w(),$==="smooth"){let q=!1;b=gn(t,ee=>{q=q||ee}),v=xi(u,()=>{Y(q)})}else v=xi($e(t,H8(150)),Y);return y=setTimeout(()=>{w()},1200),Wt(c,!0),I("scrolling from index to",{behavior:$,index:te,top:V},ts.DEBUG),{behavior:$,top:V}})),d),{scrollTargetReached:g,scrollToIndex:f,topListHeight:x}},Mn(Ki,Es,Jo),{singleton:!0});function H8(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return s=>{s&&(t(!0),clearTimeout(n))}}}function iv(e,t){e===0?t():requestAnimationFrame(()=>{iv(e-1,t)})}function ov(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 Om(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 Dc=hn(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:s},{scrollTargetReached:o,scrollToIndex:r},{didMount:a}])=>{const l=Je(!0),c=Je(0),d=Je(!0);return St($e(a,en(c),Mt(([u,h])=>!Om(h)),Pi(!1)),l),St($e(a,en(c),Mt(([u,h])=>!Om(h)),Pi(!1)),d),gn($e(Vn(t,a),en(l,n,e,d),Mt(([[,u],h,{sizeTree:p},f,g])=>u&&(!Sn(p)||Qx(f))&&!h&&!g),en(c)),([,u])=>{if(u===void 0){Wt(l,!0),Wt(d,!0);return}xi(o,()=>{Wt(d,!0)}),iv(4,()=>{xi(s,()=>{Wt(l,!0)}),Wt(r,u)})}),{initialItemFinalLocationReached:d,initialTopMostItemIndex:c,scrolledToInitialItem:l}},Mn(Ki,Es,Ic,Zo),{singleton:!0});function LT(e,t){return Math.abs(e-t)<1.01}const ec="up",_l="down",B8="none",V8={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},$8=0,Ec=hn(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:s,scrollTop:o,viewportHeight:r}])=>{const a=Je(!1),l=Je(!0),c=ln(),d=ln(),u=Je(4),h=Je($8),p=ms($e(Pm($e(At(o),kr(1),Pi(!0)),$e(At(o),kr(1),Pi(!1),qw(100))),Pn()),!1),f=ms($e(Pm($e(n,Pi(!0)),$e(n,Pi(!1),qw(200))),Pn()),!1);St($e(Vn(At(o),At(h)),ft(([b,w])=>b<=w),Pn()),l),St($e(l,ho(50)),d);const g=Bs($e(Vn(s,At(r),At(t),At(e),At(u)),Gi((b,[{scrollHeight:w,scrollTop:C},_,N,k,S])=>{const A=C+_-w>-S,T={scrollHeight:w,scrollTop:C,viewportHeight:_};if(A){let P,D;return C>b.state.scrollTop?(P="SCROLLED_DOWN",D=b.state.scrollTop-C):(P="SIZE_DECREASED",D=b.state.scrollTop-C||b.scrollTopDelta),{atBottom:!0,atBottomBecause:P,scrollTopDelta:D,state:T}}let I;return T.scrollHeight>b.state.scrollHeight?I="SIZE_INCREASED":_<b.state.viewportHeight?I="VIEWPORT_HEIGHT_DECREASING":C<b.state.scrollTop?I="SCROLLING_UPWARDS":I="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:I,state:T}},V8),Pn((b,w)=>b!==void 0&&b.atBottom===w.atBottom))),x=ms($e(s,Gi((b,{scrollHeight:w,scrollTop:C,viewportHeight:_})=>{if(!LT(b.scrollHeight,w)){const N=w-(C+_)<1;return b.scrollTop!==C&&N?{changed:!0,jump:b.scrollTop-C,scrollHeight:w,scrollTop:C}:{changed:!0,jump:0,scrollHeight:w,scrollTop:C}}return{changed:!1,jump:0,scrollHeight:w,scrollTop:C}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Mt(b=>b.changed),ft(b=>b.jump)),0);St($e(g,ft(b=>b.atBottom)),a),St($e(a,ho(50)),c);const v=Je(_l);St($e(s,ft(({scrollTop:b})=>b),Pn(),Gi((b,w)=>Ln(f)?{direction:b.direction,prevScrollTop:w}:{direction:w<b.prevScrollTop?ec:_l,prevScrollTop:w},{direction:_l,prevScrollTop:0}),ft(b=>b.direction)),v),St($e(s,ho(50),Pi(B8)),v);const y=Je(0);return St($e(p,Mt(b=>!b),Pi(0)),y),St($e(o,ho(100),en(p),Mt(([b,w])=>w),Gi(([b,w],[C])=>[w,C],[0,0]),ft(([b,w])=>w-b)),y),{atBottomState:g,atBottomStateChange:c,atBottomThreshold:u,atTopStateChange:d,atTopThreshold:h,isAtBottom:a,isAtTop:l,isScrolling:p,lastJumpDueToItemResize:x,scrollDirection:v,scrollVelocity:y}},Mn(Es)),tc="top",nc="bottom",Qw="none";function ey(e,t,n){return typeof e=="number"?n===ec&&t===tc||n===_l&&t===nc?e:0:n===ec?t===tc?e.main:e.reverse:t===nc?e.main:e.reverse}function ty(e,t){return typeof e=="number"?e:e[t]??0}const rv=hn(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:s,viewportHeight:o}])=>{const r=ln(),a=Je(0),l=Je(0),c=Je(0),d=ms($e(Vn(At(s),At(o),At(n),At(r,Zl),At(c),At(a),At(t),At(e),At(l)),ft(([u,h,p,[f,g],x,v,y,b,w])=>{const C=u-b,_=v+y,N=Math.max(p-C,0);let k=Qw;const S=ty(w,tc),A=ty(w,nc);return f-=b,f+=p+y,g+=p+y,g-=b,f>u+_-S&&(k=ec),g<u-N+h+A&&(k=_l),k!==Qw?[Math.max(C-p-ey(x,tc,k)-S,0),C-N-y+h+ey(x,nc,k)+A]:null}),Mt(u=>u!==null),Pn(Zl)),[0,0]);return{increaseViewportBy:l,listBoundary:r,overscan:c,topListHeight:a,visibleRange:d}},Mn(Es),{singleton:!0});function W8(e,t,n){if(Gh(t)){const s=PT(e,t);return[{index:Ci(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 Hp={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Ud(e,t,n,s,o,r){const{lastIndex:a,lastOffset:l,lastSize:c}=o;let d=0,u=0;if(e.length>0){d=e[0].offset;const x=e[e.length-1];u=x.offset+x.size}const h=n-a,p=l+h*c+(h-1)*s,f=d,g=p-u;return{bottom:u,firstItemIndex:r,items:ny(e,o,r),offsetBottom:g,offsetTop:d,top:f,topItems:ny(t,o,r),topListHeight:t.reduce((x,v)=>v.size+x,0),totalCount:n}}function OT(e,t,n,s,o,r){let a=0;if(n.groupIndices.length>0)for(const u of n.groupIndices){if(u-a>=e)break;a++}const l=e+a,c=ov(t,l),d=Array.from({length:l}).map((u,h)=>({data:r[h+c],index:h+c,offset:0,size:0}));return Ud(d,[],l,o,n,s)}function ny(e,t,n){if(e.length===0)return[];if(!Gh(t))return e.map(d=>({...d,index:d.index+n,originalIndex:d.index}));const s=e[0].index,o=e[e.length-1].index,r=[],a=ia(t.groupOffsetTree,s,o);let l,c=0;for(const d of e){(!l||l.end<d.index)&&(l=a.shift(),c=t.groupIndices.indexOf(l.start));let u;d.index===l.start?u={index:c,type:"group"}:u={groupIndex:c,index:d.index-(c+1)+n},r.push({...u,data:d.data,offset:d.offset,originalIndex:d.index,size:d.size})}return r}function sy(e,t){return e===void 0?0:typeof e=="number"?e:e[t]??0}const Tr=hn(([{data:e,firstItemIndex:t,gap:n,sizes:s,totalCount:o},r,{listBoundary:a,topListHeight:l,visibleRange:c},{initialTopMostItemIndex:d,scrolledToInitialItem:u},{topListHeight:h},p,{didMount:f},{recalcInProgress:g}])=>{const x=Je([]),v=Je(0),y=ln(),b=Je(0);St(r.topItemsIndexes,x);const w=ms($e(Vn(f,g,At(c,Zl),At(o),At(s),At(d),u,At(x),At(t),At(n),At(b),e),Mt(([k,S,,A,,,,,,,,T])=>{const I=T!==void 0&&T.length!==A;return k&&!S&&!I}),ft(([,,[k,S],A,T,I,P,D,O,z,R,$])=>{const X=T,{offsetTree:H,sizeTree:te}=X,V=Ln(v);if(A===0)return{...Hp,totalCount:A};if(k===0&&S===0)return V===0?{...Hp,totalCount:A}:OT(V,I,T,O,z,$||[]);if(Sn(te))return V>0?null:Ud(W8(ov(I,A),X,$),[],A,z,X,O);const Y=[];if(D.length>0){const U=D[0],oe=D[D.length-1];let Se=0;for(const G of ia(te,U,oe)){const Q=G.value,ae=Math.max(G.start,U),Z=Math.min(G.end,oe);for(let ce=ae;ce<=Z;ce++)Y.push({data:$?.[ce],index:ce,offset:Se,size:Q}),Se+=Q}}if(!P)return Ud([],Y,A,z,X,O);const q=D.length>0?D[D.length-1]+1:0,ee=A8(H,k,S,q);if(ee.length===0)return null;const ge=A-1,Ce=zh([],U=>{for(const oe of ee){const Se=oe.value;let G=Se.offset,Q=oe.start;const ae=Se.size;if(Se.offset<k){Q+=Math.floor((k-Se.offset+z)/(ae+z));const ce=Q-oe.start;G+=ce*ae+ce*z}Q<q&&(G+=(q-Q)*ae,Q=q);const Z=Math.min(oe.end,ge);for(let ce=Q;ce<=Z&&!(G>=S);ce++)U.push({data:$?.[ce],index:ce,offset:G,size:ae}),G+=ae+z}}),Re=sy(R,tc),fe=sy(R,nc);if(Ce.length>0&&(Re>0||fe>0)){const U=Ce[0],oe=Ce[Ce.length-1];if(Re>0&&U.index>q){const Se=Math.min(Re,U.index-q),G=[];let Q=U.offset;for(let ae=U.index-1;ae>=U.index-Se;ae--){const Z=ia(te,ae,ae)[0]?.value??U.size;Q-=Z+z,G.unshift({data:$?.[ae],index:ae,offset:Q,size:Z})}Ce.unshift(...G)}if(fe>0&&oe.index<ge){const Se=Math.min(fe,ge-oe.index);let G=oe.offset+oe.size+z;for(let Q=oe.index+1;Q<=oe.index+Se;Q++){const ae=ia(te,Q,Q)[0]?.value??oe.size;Ce.push({data:$?.[Q],index:Q,offset:G,size:ae}),G+=ae+z}}}return Ud(Ce,Y,A,z,X,O)}),Mt(k=>k!==null),Pn()),Hp);St($e(e,Mt(Qx),ft(k=>k?.length)),o),St($e(w,ft(k=>k.topListHeight)),h),St(h,l),St($e(w,ft(k=>[k.top,k.bottom])),a),St($e(w,ft(k=>k.items)),y);const C=Bs($e(w,Mt(({items:k})=>k.length>0),en(o,e),Mt(([{items:k},S])=>k[k.length-1].originalIndex===S-1),ft(([,k,S])=>[k-1,S]),Pn(Zl),ft(([k])=>k))),_=Bs($e(w,ho(200),Mt(({items:k,topItems:S})=>k.length>0&&k[0].originalIndex===S.length),ft(({items:k})=>k[0].index),Pn())),N=Bs($e(w,Mt(({items:k})=>k.length>0),ft(({items:k})=>{let S=0,A=k.length-1;for(;k[S].type==="group"&&S<A;)S++;for(;k[A].type==="group"&&A>S;)A--;return{endIndex:k[A].index,startIndex:k[S].index}}),Pn(DT)));return{endReached:C,initialItemCount:v,itemsRendered:y,listState:w,minOverscanItemCount:b,rangeChanged:N,startReached:_,topItemsIndexes:x,...p}},Mn(Ki,MT,rv,Dc,Ic,Ec,Zo,nv),{singleton:!0}),zT=hn(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:s},{listState:o}])=>{const r=ln(),a=ms($e(Vn(n,e,s,t,o),ft(([l,c,d,u,h])=>l+c+d+u+h.offsetBottom+h.bottom)),0);return St(At(a),r),{totalListHeight:a,totalListHeightChanged:r}},Mn(Es,Tr),{singleton:!0}),U8=hn(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Je(!1),s=ms($e(Vn(n,e,t),Mt(([o])=>o),ft(([,o,r])=>Math.max(0,o-r)),ho(0),Pn()),0);return{alignToBottom:n,paddingTopAddition:s}},Mn(Es,zT),{singleton:!0}),GT=hn(()=>({context:Je(null)})),K8=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:s,...o},viewportBottom:r,viewportTop:a})=>t<a?{...o,align:n??"start",...s===void 0?{}:{behavior:s}}:e>r?{...o,align:n??"end",...s===void 0?{}:{behavior:s}}:null,FT=hn(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:s,fixedHeaderHeight:o,headerHeight:r,scrollingInProgress:a,scrollTop:l,viewportHeight:c},{scrollToIndex:d}])=>{const u=ln();return St($e(u,en(t,c,n,r,o,s,l),en(e),ft(([[h,p,f,g,x,v,y,b],w])=>{const{calculateViewLocation:C=K8,done:_,...N}=h,k=AT(h,p,g-1),S=Ql(k,p.offsetTree,w)+x+v,A=S+Ci(p.sizeTree,k)[1],T=b+v,I=b+f-y,P=C({itemBottom:A,itemTop:S,locationParams:N,viewportBottom:I,viewportTop:T});return P===null?_?.():_&&xi($e(a,Mt(D=>!D),kr(Ln(a)?1:2)),_),P}),Mt(h=>h!==null)),d),{scrollIntoView:u}},Mn(Ki,Es,Ic,Tr,Jo),{singleton:!0});function iy(e){return e===!1?!1:e==="smooth"?"smooth":"auto"}const q8=(e,t)=>typeof e=="function"?iy(e(t)):t&&iy(e),Y8=hn(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:s},{atBottomState:o,isAtBottom:r},{scrollToIndex:a},{scrolledToInitialItem:l},{didMount:c,propsReady:d},{log:u},{scrollingInProgress:h},{context:p},{scrollIntoView:f}])=>{const g=Je(!1),x=ln();let v=null;function y(_){Wt(a,{align:"end",behavior:_,index:"LAST"})}gn($e(Vn($e(At(t),kr(1)),c),en(At(g),r,l,h),ft(([[_,N],k,S,A,T])=>{let I=N&&A,P="auto";return I&&(P=q8(k,S||T),I=I&&P!==!1),{followOutputBehavior:P,shouldFollow:I,totalCount:_}}),Mt(({shouldFollow:_})=>_)),({followOutputBehavior:_,totalCount:N})=>{v!==null&&(v(),v=null),Ln(n)===void 0?v=xi(e,()=>{Ln(u)("following output to ",{totalCount:N},ts.DEBUG),y(_),v=null}):requestAnimationFrame(()=>{Ln(u)("following output to ",{totalCount:N},ts.DEBUG),y(_)})});function b(_){const N=xi(o,k=>{_&&!k.atBottom&&k.notAtBottomBecause==="SIZE_INCREASED"&&v===null&&(Ln(u)("scrolling to bottom due to increased size",{},ts.DEBUG),y("auto"))});setTimeout(N,100)}gn($e(Vn(At(g),t,d),Mt(([_,,N])=>_!==!1&&N),Gi(({value:_},[,N])=>({refreshed:_===N,value:N}),{refreshed:!1,value:0}),Mt(({refreshed:_})=>_),en(g,t)),([,_])=>{Ln(l)&&b(_!==!1)}),gn(x,()=>{b(Ln(g)!==!1)}),gn(Vn(At(g),o),([_,N])=>{_!==!1&&!N.atBottom&&N.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&y("auto")});const w=Je(null),C=ln();return St(Pm($e(At(s),ft(_=>_?.length??0)),$e(At(t))),C),gn($e(Vn($e(C,kr(1)),c),en(At(w),l,h,p),ft(([[_,N],k,S,A,T])=>N&&S&&k?.({context:T,totalCount:_,scrollingInProgress:A})),Mt(_=>!!_),ho(0)),_=>{v!==null&&(v(),v=null),Ln(n)===void 0?v=xi(e,()=>{Ln(u)("scrolling into view",{}),Wt(f,_),v=null}):requestAnimationFrame(()=>{Ln(u)("scrolling into view",{}),Wt(f,_)})}),{autoscrollToBottom:x,followOutput:g,scrollIntoViewOnChange:w}},Mn(Ki,Ec,Ic,Dc,Zo,Jo,Es,GT,FT)),X8=hn(([{data:e,firstItemIndex:t,gap:n,sizes:s},{initialTopMostItemIndex:o},{initialItemCount:r,listState:a},{didMount:l}])=>(St($e(l,en(r),Mt(([,c])=>c!==0),en(o,s,t,n,e),ft(([[,c],d,u,h,p,f=[]])=>OT(c,d,u,h,p,f))),a),{}),Mn(Ki,Dc,Tr,Zo),{singleton:!0}),J8=hn(([{didMount:e},{scrollTo:t},{listState:n}])=>{const s=Je(0);return gn($e(e,en(s),Mt(([,o])=>o!==0),ft(([,o])=>({top:o}))),o=>{xi($e(n,kr(1),Mt(r=>r.items.length>1)),()=>{requestAnimationFrame(()=>{Wt(t,o)})})}),{initialScrollTop:s}},Mn(Zo,Es,Tr),{singleton:!0}),HT=hn(([{scrollVelocity:e}])=>{const t=Je(!1),n=ln(),s=Je(!1);return St($e(e,en(s,t,n),Mt(([o,r])=>r!==!1&&r!==void 0),ft(([o,r,a,l])=>{const{enter:c,exit:d}=r;if(a){if(d(o,l))return!1}else if(c(o,l))return!0;return a}),Pn()),t),gn($e(Vn(t,e,n),en(s)),([[o,r,a],l])=>{o&&l!==!1&&l!==void 0&&l.change&&l.change(r,a)}),{isSeeking:t,scrollSeekConfiguration:s,scrollSeekRangeChanged:n,scrollVelocity:e}},Mn(Ec),{singleton:!0}),av=hn(([{scrollContainerState:e,scrollTo:t}])=>{const n=ln(),s=ln(),o=ln(),r=Je(!1),a=Je(void 0);return St($e(Vn(n,s),ft(([{scrollTop:l,viewportHeight:c},{offsetTop:d,listHeight:u}])=>({scrollHeight:u,scrollTop:Math.max(0,l-d),viewportHeight:c}))),e),St($e(t,en(s),ft(([l,{offsetTop:c}])=>({...l,top:l.top+c}))),o),{customScrollParent:a,useWindowScroll:r,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:s}},Mn(Es)),Z8=hn(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:s},{initialTopMostItemIndex:o},{didMount:r},{useWindowScroll:a,windowScrollContainerState:l,windowViewportRect:c}])=>{const d=ln(),u=Je(void 0),h=Je(null),p=Je(null);return St(l,h),St(c,p),gn($e(d,en(t,s,a,h,p,n)),([f,g,x,v,y,b,w])=>{const C=R8(g.sizeTree);v&&y!==null&&b!==null&&(x=y.scrollTop-b.offsetTop),x-=w,f({ranges:C,scrollTop:x})}),St($e(u,Mt(Qx),ft(Q8)),o),St($e(r,en(u),Mt(([,f])=>f!==void 0),Pn(),ft(([,f])=>f.ranges)),e),{getState:d,restoreStateFrom:u}},Mn(Ki,Es,Dc,Zo,av));function Q8(e){return{align:"start",index:0,offset:e.scrollTop}}const eU=hn(([{topItemsIndexes:e}])=>{const t=Je(0);return St($e(t,Mt(n=>n>=0),ft(n=>Array.from({length:n}).map((s,o)=>o))),e),{topItemCount:t}},Mn(Tr));function BT(e){let t=!1,n;return(()=>(t||(t=!0,n=e()),n))}const tU=BT(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),nU=hn(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:s},{isAtBottom:o,isScrolling:r,lastJumpDueToItemResize:a,scrollDirection:l},{listState:c},{beforeUnshiftWith:d,gap:u,shiftWithOffset:h,sizes:p},{log:f},{recalcInProgress:g}])=>{const x=Bs($e(c,en(a),Gi(([,y,b,w],[{bottom:C,items:_,offsetBottom:N,totalCount:k},S])=>{const A=C+N;let T=0;return b===k&&y.length>0&&_.length>0&&(_[0].originalIndex===0&&y[0].originalIndex===0||(T=A-w,T!==0&&(T+=S))),[T,_,k,A]},[0,[],0,0]),Mt(([y])=>y!==0),en(s,l,n,o,f,g),Mt(([,y,b,w,,,C])=>!C&&!w&&y!==0&&b===ec),ft(([[y],,,,,b])=>(b("Upward scrolling compensation",{amount:y},ts.DEBUG),y))));function v(y){y>0?(Wt(t,{behavior:"auto",top:-y}),Wt(e,0)):(Wt(e,0),Wt(t,{behavior:"auto",top:-y}))}return gn($e(x,en(e,r)),([y,b,w])=>{w&&tU()?Wt(e,b-y):v(-y)}),gn($e(Vn(ms(r,!1),e,g),Mt(([y,b,w])=>!y&&!w&&b!==0),ft(([y,b])=>b),ho(1)),v),St($e(h,ft(y=>({top:-y}))),t),gn($e(d,en(p,u),ft(([y,{groupIndices:b,lastSize:w,sizeTree:C},_])=>{function N(I){return I*(w+_)}if(b.length===0)return N(y);let k=0;const S=Jl(C,0);let A=0,T=0;for(;A<y;){A++,k+=S;let I=b.length===T+1?1/0:b[T+1]-b[T]-1;A+I>y&&(k-=S,I=y-A+1),A+=I,k+=N(I),T++}return k})),y=>{Wt(e,y),requestAnimationFrame(()=>{Wt(t,{top:y}),requestAnimationFrame(()=>{Wt(e,0),Wt(g,!1)})})}),{deviation:e}},Mn(Es,Ec,Tr,Ki,Jo,nv)),sU=hn(([e,t,n,s,o,r,a,l,c,d,u])=>({...e,...t,...n,...s,...o,...r,...a,...l,...c,...d,...u}),Mn(rv,X8,Zo,HT,zT,J8,U8,av,FT,Jo,GT)),VT=hn(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:s,fixedGroupSize:o,gap:r,groupIndices:a,heightEstimates:l,itemSize:c,sizeRanges:d,sizes:u,statefulTotalCount:h,totalCount:p,trackItemSizes:f},{initialItemFinalLocationReached:g,initialTopMostItemIndex:x,scrolledToInitialItem:v},y,b,w,C,{scrollToIndex:_},N,{topItemCount:k},{groupCounts:S},A])=>{const{listState:T,minOverscanItemCount:I,topItemsIndexes:P,rangeChanged:D,...O}=C;return St(D,A.scrollSeekRangeChanged),St($e(Vn(A.windowViewportRect,y.headerHeight,y.fixedHeaderHeight),ft(([z,R,$])=>Math.max(R+$+1,z.visibleHeight))),y.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:s,fixedGroupHeight:o,gap:r,groupCounts:S,heightEstimates:l,initialItemFinalLocationReached:g,initialTopMostItemIndex:x,scrolledToInitialItem:v,sizeRanges:d,topItemCount:k,topItemsIndexes:P,totalCount:p,...w,groupIndices:a,itemSize:c,listState:T,minOverscanItemCount:I,scrollToIndex:_,statefulTotalCount:h,trackItemSizes:f,rangeChanged:D,...O,...A,...y,sizes:u,...b}},Mn(Ki,Dc,Es,Z8,Y8,Tr,Ic,nU,eU,MT,sU));function iU(e,t){const n={},s={};let o=0;const r=e.length;for(;o<r;)s[e[o]]=1,o+=1;for(const a in t)Object.hasOwn(s,a)||(n[a]=t[a]);return n}const Wc=typeof document>"u"?_e.useEffect:_e.useLayoutEffect;function $T(e,t,n){const s=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),r=Object.keys(t.methods||{}),a=Object.keys(t.events||{}),l=_e.createContext({});function c(v,y){v.propsReady!==void 0&&Wt(v.propsReady,!1);for(const b of s){const w=v[t.required[b]];Wt(w,y[b])}for(const b of o)if(b in y){const w=v[t.optional[b]];Wt(w,y[b])}v.propsReady!==void 0&&Wt(v.propsReady,!0)}function d(v){return r.reduce((y,b)=>(y[b]=w=>{const C=v[t.methods[b]];Wt(C,w)},y),{})}function u(v){return a.reduce((y,b)=>(y[b]=v8(v[t.events[b]]),y),{})}const h=_e.forwardRef(function(v,y){const{children:b,...w}=v,[C]=_e.useState(()=>zh(y8(e),k=>{c(k,w)})),[_]=_e.useState(Kw(u,C));Wc(()=>{for(const k of a)k in w&&gn(_[k],w[k]);return()=>{Object.values(_).map(ev)}},[w,_,C]),Wc(()=>{c(C,w)}),_e.useImperativeHandle(y,Uw(d(C)));const N=n;return i.jsx(l.Provider,{value:C,children:n===void 0?b:i.jsx(N,{...iU([...s,...o,...a],w),children:b})})}),p=v=>{const y=_e.useContext(l);return _e.useCallback(b=>{Wt(y[v],b)},[y,v])},f=v=>{const y=_e.useContext(l)[v],b=_e.useCallback(w=>gn(y,w),[y]);return _e.useSyncExternalStore(b,()=>Ln(y),()=>Ln(y))},g=v=>{const y=_e.useContext(l)[v],[b,w]=_e.useState(Kw(Ln,y));return Wc(()=>gn(y,C=>{C!==b&&w(Uw(C))}),[y,b]),b},x=parseInt(_e.version,10)>=18?f:g;return{Component:h,useEmitter:(v,y)=>{const b=_e.useContext(l)[v];Wc(()=>gn(b,y),[y,b])},useEmitterValue:x,usePublisher:p}}const WT=_e.createContext(void 0),UT=_e.createContext(void 0),Bp="-webkit-sticky",oy="sticky",lv=BT(()=>{if(typeof document>"u")return oy;const e=document.createElement("div");return e.style.position=Bp,e.style.position===Bp?Bp:oy}),KT=typeof document>"u"?_e.useEffect:_e.useLayoutEffect;function Vp(e){return"self"in e}function oU(e){return"body"in e}function qT(e,t,n,s=La,o,r){const a=_e.useRef(null),l=_e.useRef(null),c=_e.useRef(null),d=_e.useCallback(p=>{let f,g,x;const v=p.target;if(oU(v)||Vp(v)){const b=Vp(v)?v:v.defaultView;x=r===!0?mr(b,b.scrollX):b.scrollY,f=r===!0?b.document.documentElement.scrollWidth:b.document.documentElement.scrollHeight,g=r===!0?b.innerWidth:b.innerHeight}else x=r===!0?mr(v,v.scrollLeft):v.scrollTop,f=r===!0?v.scrollWidth:v.scrollHeight,g=r===!0?v.offsetWidth:v.offsetHeight;const y=()=>{e({scrollHeight:f,scrollTop:Math.max(x,0),viewportHeight:g})};p.suppressFlushSync===!0?y():sj.flushSync(y),l.current!==null&&(x===l.current||x<=0||x===f-g)&&(l.current=null,t(!0),c.current&&(clearTimeout(c.current),c.current=null))},[e,t,r]);_e.useEffect(()=>{const p=o??a.current;return s(o??a.current),d({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",d,{passive:!0}),()=>{s(null),p.removeEventListener("scroll",d)}},[a,d,n,s,o]);function u(p){const f=a.current;if(!f||(r===!0?"offsetWidth"in f&&f.offsetWidth===0:"offsetHeight"in f&&f.offsetHeight===0))return;const g=p.behavior==="smooth";let x,v,y;Vp(f)?(v=Math.max(Vo(f.document.documentElement,r===!0?"width":"height"),r===!0?f.document.documentElement.scrollWidth:f.document.documentElement.scrollHeight),x=r===!0?f.innerWidth:f.innerHeight,y=r===!0?mr(f,f.scrollX):f.scrollY):(v=f[r===!0?"scrollWidth":"scrollHeight"],x=Vo(f,r===!0?"width":"height"),y=r===!0?mr(f,f.scrollLeft):f.scrollTop);const b=v-x;if(p.top===void 0){f.scrollTo(p);return}const w=Math.ceil(Math.max(Math.min(b,p.top),0));if(p.top=w,LT(x,v)||w===y){e({scrollHeight:v,scrollTop:y,viewportHeight:x}),g&&t(!0);return}g?(l.current=w,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,l.current=null,t(!0)},1e3)):l.current=null,r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},left:Yw(f,w)}),f.scrollTo(p)}function h(p){r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},...p.top===void 0?{}:{left:Yw(a.current,p.top)}}),a.current.scrollBy(p)}return{scrollByCallback:h,scrollerRef:a,scrollToCallback:u}}function cv(e){return e}const rU=hn(()=>{const e=Je(l=>`Item ${l}`),t=Je(l=>`Group ${l}`),n=Je({}),s=Je(cv),o=Je("div"),r=Je(La),a=(l,c=null)=>ms($e(n,ft(d=>d[l]),Pn()),c);return{components:n,computeItemKey:s,EmptyPlaceholder:a("EmptyPlaceholder"),FooterComponent:a("Footer"),GroupComponent:a("Group","div"),groupContent:t,HeaderComponent:a("Header"),HeaderFooterTag:o,ItemComponent:a("Item","div"),itemContent:e,ListComponent:a("List","div"),ScrollerComponent:a("Scroller","div"),scrollerRef:r,ScrollSeekPlaceholder:a("ScrollSeekPlaceholder"),TopItemListComponent:a("TopItemList")}}),aU=hn(([e,t])=>({...e,...t}),Mn(VT,rU)),lU=({height:e})=>i.jsx("div",{style:{height:e}}),cU={overflowAnchor:"none",position:lv(),zIndex:1},YT={overflowAnchor:"none"},dU={...YT,display:"inline-block",height:"100%"},ry=_e.memo(function({showTopList:e=!1}){const t=zt("listState"),n=Xs("sizeRanges"),s=zt("useWindowScroll"),o=zt("customScrollParent"),r=Xs("windowScrollContainerState"),a=Xs("scrollContainerState"),l=o||s?r:a,c=zt("itemContent"),d=zt("context"),u=zt("groupContent"),h=zt("trackItemSizes"),p=zt("itemSize"),f=zt("log"),g=Xs("gap"),x=zt("horizontalDirection"),{callbackRef:v}=j8(n,p,h,e?La:l,f,g,o,x,zt("skipAnimationFrameInResizeObserver")),[y,b]=_e.useState(0);uv("deviation",O=>{y!==O&&b(O)});const w=zt("EmptyPlaceholder"),C=zt("ScrollSeekPlaceholder")??lU,_=zt("ListComponent"),N=zt("ItemComponent"),k=zt("GroupComponent"),S=zt("computeItemKey"),A=zt("isSeeking"),T=zt("groupIndices").length>0,I=zt("alignToBottom"),P=zt("initialItemFinalLocationReached"),D=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginInlineStart:y===0?I?"auto":0:y,paddingInlineEnd:t.offsetBottom,paddingInlineStart:t.offsetTop,whiteSpace:"nowrap"}:{marginTop:y===0?I?"auto":0:y,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...P?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&w!==null&&w!==void 0?i.jsx(w,{...fs(w,d)}):i.jsx(_,{...fs(_,d),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:D,children:(e?t.topItems:t.items).map(O=>{const z=O.originalIndex,R=S(z+t.firstItemIndex,O.data,d);return A?m.createElement(C,{...fs(C,d),height:O.size,index:O.index,key:R,type:O.type||"item",...O.type==="group"?{}:{groupIndex:O.groupIndex}}):O.type==="group"?m.createElement(k,{...fs(k,d),"data-index":z,"data-item-index":O.index,"data-known-size":O.size,key:R,style:cU},u(O.index,d)):m.createElement(N,{...fs(N,d),...fU(N,O.data),"data-index":z,"data-item-group-index":O.groupIndex,"data-item-index":O.index,"data-known-size":O.size,key:R,style:x?dU:YT},T?c(O.index,O.groupIndex,O.data,d):c(O.index,O.data,d))})})}),uU={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},hU={outline:"none",overflowX:"auto",position:"relative"},dv=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:void 0}),XT=(e,t,n=0)=>({...dv(e),position:t?"relative":"absolute",top:t?-n:0}),pU={position:lv(),top:0,width:"100%",zIndex:1};function fs(e,t){if(typeof e!="string")return{context:t}}function fU(e,t){return{item:typeof e=="string"?void 0:t}}const mU=_e.memo(function(){const e=zt("HeaderComponent"),t=Xs("headerHeight"),n=zt("HeaderFooterTag"),s=Nr(_e.useMemo(()=>r=>{t(Vo(r,"height"))},[t]),!0,zt("skipAnimationFrameInResizeObserver")),o=zt("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...fs(e,o)})}):null}),gU=_e.memo(function(){const e=zt("FooterComponent"),t=Xs("footerHeight"),n=zt("HeaderFooterTag"),s=Nr(_e.useMemo(()=>r=>{t(Vo(r,"height"))},[t]),!0,zt("skipAnimationFrameInResizeObserver")),o=zt("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...fs(e,o)})}):null});function JT({useEmitter:e,useEmitterValue:t,usePublisher:n}){return _e.memo(function({children:s,style:o,context:r,...a}){const l=n("scrollContainerState"),c=t("ScrollerComponent"),d=n("smoothScrollTargetReached"),u=t("scrollerRef"),h=t("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:f,scrollToCallback:g}=qT(l,d,c,u,void 0,h);return e("scrollTo",g),e("scrollBy",p),i.jsx(c,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:f,style:{...h?hU:uU,...o},tabIndex:0,...a,...fs(c,r),children:s})})}function ZT({useEmitter:e,useEmitterValue:t,usePublisher:n}){return _e.memo(function({children:s,style:o,context:r,...a}){const l=n("windowScrollContainerState"),c=t("ScrollerComponent"),d=n("smoothScrollTargetReached"),u=t("totalListHeight"),h=t("deviation"),p=t("customScrollParent"),f=_e.useRef(null),g=t("scrollerRef"),{scrollByCallback:x,scrollerRef:v,scrollToCallback:y}=qT(l,d,c,g,p);return KT(()=>(v.current=p??f.current?.ownerDocument.defaultView,()=>{v.current=null}),[v,p]),e("windowScrollTo",y),e("scrollBy",x),i.jsx(c,{ref:f,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...u===0?void 0:{height:u+h}},...a,...fs(c,r),children:s})})}const xU=({children:e})=>{const t=_e.useContext(WT),n=Xs("viewportHeight"),s=Xs("fixedItemHeight"),o=zt("alignToBottom"),r=zt("horizontalDirection"),a=_e.useMemo(()=>yT(n,c=>Vo(c,r?"width":"height")),[n,r]),l=Nr(a,!0,zt("skipAnimationFrameInResizeObserver"));return _e.useEffect(()=>{t&&(n(t.viewportHeight),s(t.itemHeight))},[t,n,s]),i.jsx("div",{"data-viewport-type":"element",ref:l,style:dv(o),children:e})},vU=({children:e})=>{const t=_e.useContext(WT),n=Xs("windowViewportRect"),s=Xs("fixedItemHeight"),o=zt("customScrollParent"),r=zt("useWindowScroll"),a=zt("topListHeight"),l=kT(n,o,zt("skipAnimationFrameInResizeObserver")),c=zt("alignToBottom");return _e.useEffect(()=>{t&&(s(t.itemHeight),n({listHeight:0,offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,s]),i.jsx("div",{"data-viewport-type":"window",ref:l,style:XT(c,r,a),children:e})},bU=({children:e})=>{const t=zt("TopItemListComponent")??"div",n=zt("headerHeight"),s={...pU,marginTop:`${n}px`},o=zt("context");return i.jsx(t,{style:s,...fs(t,o),children:e})},wU=_e.memo(function(e){const t=zt("useWindowScroll"),n=zt("topItemsIndexes").length>0,s=zt("customScrollParent"),o=zt("context");return i.jsxs(s||t?CU:SU,{...e,context:o,children:[n&&i.jsx(bU,{children:i.jsx(ry,{showTopList:!0})}),i.jsxs(s||t?vU:xU,{children:[i.jsx(mU,{}),i.jsx(ry,{}),i.jsx(gU,{})]})]})}),{Component:yU,useEmitter:uv,useEmitterValue:zt,usePublisher:Xs}=$T(aU,{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"}},wU),SU=JT({useEmitter:uv,useEmitterValue:zt,usePublisher:Xs}),CU=ZT({useEmitter:uv,useEmitterValue:zt,usePublisher:Xs}),kU=yU,jU=hn(()=>{const e=Je(d=>i.jsxs("td",{children:["Item $",d]})),t=Je(null),n=Je(d=>i.jsxs("td",{colSpan:1e3,children:["Group ",d]})),s=Je(null),o=Je(null),r=Je({}),a=Je(cv),l=Je(La),c=(d,u=null)=>ms($e(r,ft(h=>h[d]),Pn()),u);return{components:r,computeItemKey:a,context:t,EmptyPlaceholder:c("EmptyPlaceholder"),FillerRow:c("FillerRow"),fixedFooterContent:o,fixedHeaderContent:s,itemContent:e,groupContent:n,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder"),TableBodyComponent:c("TableBody","tbody"),TableComponent:c("Table","table"),TableFooterComponent:c("TableFoot","tfoot"),TableHeadComponent:c("TableHead","thead"),TableRowComponent:c("TableRow","tr"),GroupComponent:c("Group","tr")}});Mn(VT,jU);lv();const ay={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},_U={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:ly,floor:Pu,max:Nl,min:$p,round:cy}=Math;function dy(e,t,n){return Array.from({length:t-e+1}).map((s,o)=>({data:n===null?null:n[o+e],index:o+e}))}function NU(e){return{..._U,items:e}}function Uc(e,t){return e!==void 0&&e.width===t.width&&e.height===t.height}function TU(e,t){return e!==void 0&&e.column===t.column&&e.row===t.row}const IU=hn(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:s},{footerHeight:o,headerHeight:r,scrollBy:a,scrollContainerState:l,scrollTo:c,scrollTop:d,smoothScrollTargetReached:u,viewportHeight:h},p,f,{didMount:g,propsReady:x},{customScrollParent:v,useWindowScroll:y,windowScrollContainerState:b,windowScrollTo:w,windowViewportRect:C},_])=>{const N=Je(0),k=Je(0),S=Je(ay),A=Je({height:0,width:0}),T=Je({height:0,width:0}),I=ln(),P=ln(),D=Je(0),O=Je(null),z=Je({column:0,row:0}),R=ln(),$=ln(),X=Je(!1),H=Je(0),te=Je(!0),V=Je(!1),Y=Je(!1);gn($e(g,en(H),Mt(([fe,U])=>!Om(U))),()=>{Wt(te,!1)}),gn($e(Vn(g,te,T,A,H,V),Mt(([fe,U,oe,Se,,G])=>fe&&!U&&oe.height!==0&&Se.height!==0&&!G)),([,,,,fe])=>{if(fe===void 0){Wt(te,!0);return}Wt(V,!0),iv(1,()=>{Wt(I,fe)}),xi($e(d),()=>{Wt(t,[0,0]),Wt(te,!0)})}),St($e($,Mt(fe=>fe!=null&&fe.scrollTop>0),Pi(0)),k),gn($e(g,en($),Mt(([,fe])=>fe!=null)),([,fe])=>{fe&&(Wt(A,fe.viewport),Wt(T,fe.item),Wt(z,fe.gap),fe.scrollTop>0&&(Wt(X,!0),xi($e(d,kr(1)),U=>{Wt(X,!1)}),Wt(c,{top:fe.scrollTop})))}),St($e(A,ft(({height:fe})=>fe)),h),St($e(Vn(At(A,Uc),At(T,Uc),At(z,(fe,U)=>fe!==void 0&&fe.column===U.column&&fe.row===U.row),At(d)),ft(([fe,U,oe,Se])=>({gap:oe,item:U,scrollTop:Se,viewport:fe}))),R),St($e(Vn(At(N),s,At(z,TU),At(T,Uc),At(A,Uc),At(O),At(k),At(X),At(te),At(H)),Mt(([,,,,,,,fe])=>!fe),ft(([fe,[U,oe],Se,G,Q,ae,Z,,ce,De])=>{const{column:Oe,row:Ne}=Se,{height:Ze,width:bt}=G,{width:Ut}=Q;if(Z===0&&(fe===0||Ut===0))return ay;if(bt===0){const mt=ov(De,fe),Lt=mt+Math.max(Z-1,0);return NU(dy(mt,Lt,ae))}const Et=QT(Ut,bt,Oe);let _t,B;ce?U===0&&oe===0&&Z>0?(_t=0,B=Z-1):(_t=Et*Pu((U+Ne)/(Ze+Ne)),B=Et*ly((oe+Ne)/(Ze+Ne))-1,B=$p(fe-1,Nl(B,Et-1)),_t=$p(B,Nl(0,_t))):(_t=0,B=-1);const Te=dy(_t,B,ae),{bottom:We,top:kt}=uy(Q,Se,G,Te),Gt=ly(fe/Et),de=Gt*Ze+(Gt-1)*Ne-We;return{bottom:We,itemHeight:Ze,items:Te,itemWidth:bt,offsetBottom:de,offsetTop:kt,top:kt}})),S),St($e(O,Mt(fe=>fe!==null),ft(fe=>fe.length)),N),St($e(Vn(A,T,S,z),Mt(([fe,U,{items:oe}])=>oe.length>0&&U.height!==0&&fe.height!==0),ft(([fe,U,{items:oe},Se])=>{const{bottom:G,top:Q}=uy(fe,Se,U,oe);return[Q,G]}),Pn(Zl)),t);const q=Je(!1);St($e(d,en(q),ft(([fe,U])=>U||fe!==0)),q);const ee=Bs($e(Vn(S,N),Mt(([{items:fe}])=>fe.length>0),en(q),Mt(([[fe,U],oe])=>{const Se=fe.items[fe.items.length-1].index===U-1;return(oe||fe.bottom>0&&fe.itemHeight>0&&fe.offsetBottom===0&&fe.items.length===U)&&Se}),ft(([[,fe]])=>fe-1),Pn())),ge=Bs($e(At(S),Mt(({items:fe})=>fe.length>0&&fe[0].index===0),Pi(0),Pn())),Ce=Bs($e(At(S),en(X),Mt(([{items:fe},U])=>fe.length>0&&!U),ft(([{items:fe}])=>({endIndex:fe[fe.length-1].index,startIndex:fe[0].index})),Pn(DT),ho(0)));St(Ce,f.scrollSeekRangeChanged),St($e(I,en(A,T,N,z),ft(([fe,U,oe,Se,G])=>{const Q=RT(fe),{align:ae,behavior:Z,offset:ce}=Q;let De=Q.index;De==="LAST"&&(De=Se-1),De=Nl(0,De,$p(Se-1,De));let Oe=zm(U,G,oe,De);return ae==="end"?Oe=cy(Oe-U.height+oe.height):ae==="center"&&(Oe=cy(Oe-U.height/2+oe.height/2)),ce!==void 0&&ce!==0&&(Oe+=ce),{behavior:Z,top:Oe}})),c);const Re=ms($e(S,ft(fe=>fe.offsetBottom+fe.bottom)),0);return St($e(C,ft(fe=>({height:fe.visibleHeight,width:fe.visibleWidth}))),A),{customScrollParent:v,data:O,deviation:D,footerHeight:o,gap:z,headerHeight:r,increaseViewportBy:e,initialItemCount:k,itemDimensions:T,overscan:n,restoreStateFrom:$,scrollBy:a,scrollContainerState:l,scrollHeight:P,scrollTo:c,scrollToIndex:I,scrollTop:d,smoothScrollTargetReached:u,totalCount:N,useWindowScroll:y,viewportDimensions:A,windowScrollContainerState:b,windowScrollTo:w,windowViewportRect:C,...f,gridState:S,horizontalDirection:Y,initialTopMostItemIndex:H,totalListHeight:Re,...p,endReached:ee,propsReady:x,rangeChanged:Ce,startReached:ge,stateChanged:R,stateRestoreInProgress:X,..._}},Mn(rv,Es,Ec,HT,Zo,av,Jo));function QT(e,t,n){return Nl(1,Pu((e+n)/(Pu(t)+n)))}function uy(e,t,n,s){const{height:o}=n;if(o===void 0||s.length===0)return{bottom:0,top:0};const r=zm(e,t,n,s[0].index);return{bottom:zm(e,t,n,s[s.length-1].index)+o,top:r}}function zm(e,t,n,s){const o=QT(e.width,n.width,t.column),r=Pu(s/o),a=r*n.height+Nl(0,r-1)*t.row;return a>0?a+t.row:a}const DU=hn(()=>{const e=Je(h=>`Item ${h}`),t=Je({}),n=Je(null),s=Je("virtuoso-grid-item"),o=Je("virtuoso-grid-list"),r=Je(cv),a=Je("div"),l=Je(La),c=(h,p=null)=>ms($e(t,ft(f=>f[h]),Pn()),p),d=Je(!1),u=Je(!1);return St(At(u),d),{components:t,computeItemKey:r,context:n,FooterComponent:c("Footer"),HeaderComponent:c("Header"),headerFooterTag:a,itemClassName:s,ItemComponent:c("Item","div"),itemContent:e,listClassName:o,ListComponent:c("List","div"),readyStateChanged:d,reportReadyState:u,ScrollerComponent:c("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:c("ScrollSeekPlaceholder","div")}}),EU=hn(([e,t])=>({...e,...t}),Mn(IU,DU)),PU=_e.memo(function(){const e=Dn("gridState"),t=Dn("listClassName"),n=Dn("itemClassName"),s=Dn("itemContent"),o=Dn("computeItemKey"),r=Dn("isSeeking"),a=Js("scrollHeight"),l=Dn("ItemComponent"),c=Dn("ListComponent"),d=Dn("ScrollSeekPlaceholder"),u=Dn("context"),h=Js("itemDimensions"),p=Js("gap"),f=Dn("log"),g=Dn("stateRestoreInProgress"),x=Js("reportReadyState"),v=Nr(_e.useMemo(()=>y=>{const b=y.parentElement.parentElement.scrollHeight;a(b);const w=y.firstChild;if(w!==null){const{height:C,width:_}=w.getBoundingClientRect();h({height:C,width:_})}p({column:hy("column-gap",getComputedStyle(y).columnGap,f),row:hy("row-gap",getComputedStyle(y).rowGap,f)})},[a,h,p,f]),!0,!1);return KT(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),g?null:i.jsx(c,{className:t,ref:v,...fs(c,u),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(y=>{const b=o(y.index,y.data,u);return r?i.jsx(d,{...fs(d,u),height:e.itemHeight,index:y.index,width:e.itemWidth},b):m.createElement(l,{...fs(l,u),className:n,"data-index":y.index,key:b},s(y.index,y.data,u))})})}),AU=_e.memo(function(){const e=Dn("HeaderComponent"),t=Js("headerHeight"),n=Dn("headerFooterTag"),s=Nr(_e.useMemo(()=>r=>{t(Vo(r,"height"))},[t]),!0,!1),o=Dn("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...fs(e,o)})}):null}),MU=_e.memo(function(){const e=Dn("FooterComponent"),t=Js("footerHeight"),n=Dn("headerFooterTag"),s=Nr(_e.useMemo(()=>r=>{t(Vo(r,"height"))},[t]),!0,!1),o=Dn("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...fs(e,o)})}):null}),RU=({children:e})=>{const t=_e.useContext(UT),n=Js("itemDimensions"),s=Js("viewportDimensions"),o=Nr(_e.useMemo(()=>r=>{s(r.getBoundingClientRect())},[s]),!0,!1);return _e.useEffect(()=>{t&&(s({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,s,n]),i.jsx("div",{ref:o,style:dv(!1),children:e})},LU=({children:e})=>{const t=_e.useContext(UT),n=Js("windowViewportRect"),s=Js("itemDimensions"),o=Dn("customScrollParent"),r=Dn("useWindowScroll"),a=kT(n,o,!1);return _e.useEffect(()=>{t&&(s({height:t.itemHeight,width:t.itemWidth}),n({listHeight:0,offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,s]),i.jsx("div",{ref:a,style:XT(!1,r),children:e})},OU=_e.memo(function({...e}){const t=Dn("useWindowScroll"),n=Dn("customScrollParent"),s=n||t?GU:zU,o=n||t?LU:RU,r=Dn("context");return i.jsx(s,{...e,...fs(s,r),children:i.jsxs(o,{children:[i.jsx(AU,{}),i.jsx(PU,{}),i.jsx(MU,{})]})})}),{useEmitter:eI,useEmitterValue:Dn,usePublisher:Js}=$T(EU,{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"}},OU),zU=JT({useEmitter:eI,useEmitterValue:Dn,usePublisher:Js}),GU=ZT({useEmitter:eI,useEmitterValue:Dn,usePublisher:Js});function hy(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,ts.WARN),t==="normal"?0:parseInt(t??"0",10)}function FU({className:e}){return i.jsx("svg",{viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",className:W("size-4",e),children:i.jsx("path",{d:"M 38.96 48.86 A 18.24 18.24 0 1 1 48.19 40.4",stroke:"currentColor",strokeWidth:"8.32",strokeLinecap:"round"})})}const HU={rows:new Set,expanded:new Set};function BU(e,t,n){const s=[],o=[],r=new Map,a=new Set;for(const l of t){if(l.kind!=="tool-group"||!l.explore)continue;const c=e.rows.has(l.key);if(l.explore.steps){a.add(l.key),c&&!e.expanded.has(l.key)&&o.push(l.key),l.children.forEach((f,g)=>{r.set(f.key,{group:l.key,index:g})});continue}const d=l.children[0]?.key??"",u=l.children.at(-1)?.key??"",h=!c&&e.rows.has(d)&&e.rows.has(u);if(!h&&!e.expanded.has(l.key))continue;const p=n(h?d:l.key,u);p>0&&s.push({key:l.key,height:p,pair:h})}return{collapses:s,expands:o,children:r,next:{rows:new Set(t.map(l=>l.key)),expanded:a}}}function VU({loading:e=!1,runStartedAt:t}){if(!e)return t}function $U(e){return e==="right"||e==="off"?e:"left"}function WU(e,t,n){return e!=="off"&&!t&&n>=2}const Kc=40;function UU({items:e,activeKey:t,onJump:n}){const s=we(g=>g.chatWide),o=$U(we(g=>g.navRailSide)),[r,a]=m.useState(null);if(!WU(o,s,e.length))return null;const l=o==="right",c=Math.max(0,e.findIndex(g=>g.key===t)),d=Math.min(Math.max(0,c-Math.floor(Kc/2)),Math.max(0,e.length-Kc)),u=e.slice(d,d+Kc),h=d>0,p=d+Kc<e.length,f=(g,x)=>{const v=x?24:12;if(r===null)return v;const y=Math.abs(g-r),b=Math.max(0,16-y*6);return v+b};return i.jsx("div",{className:W("group/rail absolute top-0 z-10 hidden h-full w-14 @min-[52rem]:block",l?"right-0":"left-0"),children:i.jsx("div",{className:W("absolute top-1/2 -translate-y-1/2 opacity-0 transition-opacity duration-200 group-hover/rail:opacity-100",l?"right-2":"left-2"),onMouseLeave:()=>a(null),children:i.jsxs("div",{className:"relative flex flex-col justify-center gap-[5px]",style:{maskImage:h||p?`linear-gradient(to bottom, ${h?"transparent, black 24px":"black"}, ${p?"black calc(100% - 24px), transparent":"black"})`:void 0},children:[u.map((g,x)=>{const v=g.key===t,y=x===r;return i.jsx("button",{type:"button",onClick:()=>n(g.key),onMouseEnter:()=>a(x),className:W("flex h-[7px] w-10 items-center",l&&"justify-end"),children:i.jsx("span",{className:W("rounded-full transition-all duration-150",v||y?"h-[3px] bg-foreground":"h-[2px] bg-muted-foreground/40"),style:{width:f(x,v)}})},g.key)}),r!==null&&u[r]&&i.jsxs("div",{className:W("pointer-events-none absolute w-72 -translate-y-1/2 rounded-xl border bg-popover p-3 shadow-lg",l?"right-10":"left-10"),style:{top:`${(r+.5)/u.length*100}%`},children:[i.jsx("p",{className:"line-clamp-2 text-xs font-semibold",children:u[r].question}),u[r].answer&&i.jsx("p",{className:"mt-1 line-clamp-3 text-xs text-muted-foreground",children:u[r].answer})]})]})})})}const Kd="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 tI(e){return e.content.filter(t=>t.type==="text").map(t=>t.text??"").join("").trim()}function KU(e){const t=[];for(const n of e){if(n.role!=="user"&&n.role!=="assistant")continue;const s=tI(n);s&&t.push(`${n.role==="user"?"User":"Assistant"}: ${s}`)}return t.slice(-40).join(`
21
- `)}function qU(e){for(const t of[...e].reverse()){if(t.role!=="assistant")continue;const n=tI(t);if(n)return n}return""}function py(e,t){if(e!=="contextual")return Kd;const n=t.trim();return n?`${Kd}
22
-
23
- # Main conversation (background only)
24
- ${n}`:Kd}function YU(e){return e.startsWith(Kd)}function XU(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 JU({message:e}){const{t}=ne(),n={queued:t("Queued"),running:t("In progress"),completed:t("Completed"),failed:t("Failed"),canceled:t("Canceled")},s=e.kind==="routine"?qN:e.kind==="group"?xa:e.kind==="delegation-task"?Sa:e.kind==="delegation-retry"||e.kind==="delegation-check-failed"?da:l6,o=e.kind==="routine"?`${e.dryRun?t("Routine dry run"):t("Routine task")} · ${e.title}`:e.kind==="group"?t("Group messages"):e.kind==="delegation-task"?t("Task from {{name}}",{name:e.from}):e.kind==="delegation-results"?t("Delegation results"):e.kind==="delegation-retry"?t("Continue delegated task"):e.kind==="delegation-check-failed"?t("Acceptance check not passed"):t("Result from {{name}}",{name:e.from});return i.jsxs("div",{"data-bot-injection":e.kind,className:"w-full rounded-lg border border-border/60 bg-muted/20 px-3 py-2 text-sm",children:[i.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx(s,{className:"size-3.5 shrink-0"}),i.jsx("span",{children:o}),e.kind==="delegation-result"&&e.status&&i.jsxs("span",{children:["· ",n[e.status]??e.status]})]}),i.jsx("div",{className:"whitespace-pre-wrap break-words",children:e.kind==="routine"?e.prompt:e.kind==="delegation-task"?e.task:e.kind==="delegation-result"||e.kind==="delegation-retry"||e.kind==="delegation-check-failed"?e.text:e.kind==="delegation-results"?e.results.map((r,a)=>i.jsxs("p",{children:[i.jsxs("span",{className:"font-medium",children:[r.from,r.status&&` · ${n[r.status]??r.status}`,":"]}),r.text]},`${a}:${r.from}`)):e.messages.map((r,a)=>i.jsxs("p",{children:[i.jsxs("span",{className:"font-medium",children:[r.from,":"]}),r.text]},`${a}:${r.from}`))}),e.kind==="delegation-task"&&e.context&&i.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[i.jsx("summary",{className:"cursor-pointer",children:t("Context")}),i.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words",children:e.context})]}),e.kind==="group"&&e.instruction&&i.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[i.jsx("summary",{className:"cursor-pointer",children:t("Instructions")}),i.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words",children:e.instruction})]}),e.kind==="group"&&!!e.refs?.length&&i.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:e.refs.map(r=>i.jsxs("span",{title:t("Referenced chat"),className:"inline-flex h-6 max-w-56 items-center gap-1 rounded-md bg-muted px-1.5 text-xs",children:[i.jsx(xa,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:r.title})]},r.id))}),e.kind==="group"&&e.note&&i.jsx("p",{className:"mt-1.5 text-xs text-muted-foreground",children:t("Dispatch hint: {{note}}",{note:e.note})}),e.kind!=="group"&&!!e.group?.length&&i.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[i.jsxs("summary",{className:"cursor-pointer",children:[t("Group messages")," · ",e.group.length]}),i.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words",children:e.group.map((r,a)=>i.jsxs("p",{children:[i.jsxs("span",{className:"font-medium",children:[r.from,":"]}),r.text]},`${a}:${r.from}`))})]})]})}const nI=new Map;let Jr;function ZU(e){if(Jr?.revision===e)return Jr.request;const t=window.electronAPI.providers.listOauth().then(s=>{const o=new Map;for(const r of s)for(const a of r.accounts){if(typeof a.email!="string")continue;let l="";for(const c of a.email){const d=c.codePointAt(0)??0;d>=32&&d!==127&&(l+=c)}l=l.trim(),l&&o.set(a.key,l)}return{revision:e,emails:o}}).catch(s=>(console.error("Failed to load OAuth account metadata",s),{revision:e,emails:nI})),n={revision:e,request:t,data:void 0};return Jr=n,t.then(s=>{Jr===n&&(n.data=s)}),t}function QU(){const e=ko(s=>s.snapshot.revision),[t,n]=m.useState(()=>Jr?.revision===e?Jr.data:void 0);return m.useEffect(()=>{let s=!1;return ZU(e).then(o=>{s||n(o)}),()=>{s=!0}},[e]),t?.revision===e?t.emails:nI}function fy(e,t=0){let n=3735928559^t,s=1103547991^t;for(let o=0;o<e.length;o++){const r=e.charCodeAt(o);n=Math.imul(n^r,2654435761),s=Math.imul(s^r,1597334677)}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),(4294967296*(2097151&s)+(n>>>0)).toString(36)}function hv(e,t,n){return`${e}:${fy(t)}:${fy(n,1)}`}const e7=/(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c|$)/g,t7=/(?:\x1b\[|\x9b)[0-?]*[ -/]*(?:[@-~]|$)/g;function ki(e){return e.replace(e7,"").replace(t7,"")}function n7(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 s7(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 i7(e){let t=0,n=0,s=0,o=0,r=0,a=0,l=0,c=0,d=0,u=0,h=0,p=0,f=null;for(const x of e){if(x.role==="user"&&(t+=1,f=null),x.role!=="assistant")continue;n+=1,x.usage&&(s+=x.usage.input,o+=x.usage.output,r+=x.usage.cacheRead,a+=x.usage.cacheWrite);const v=x.timing,y=s7(x);y!==void 0&&(l+=y);const b=n7(x);b!==void 0&&(d+=b,u+=1);const w=x.usage?.output??0;y!==void 0&&y>0&&w>0&&(h+=y,p+=w),v&&(f!==null&&(c+=Math.max(0,v.stepStartMs-f)),f=v.completedMs??null)}const g=s+r+a;return{turns:t,steps:n,llmMs:l,toolMs:c,inputTokens:g,outputTokens:o,cacheHitPercent:g===0?null:Math.round(r/g*100),ttftAvgMs:u>0?d/u:null,tokensPerSecond:h>0&&p>0?Math.round(p/(h/1e3)*10)/10:null}}function o7(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 my=Qu(e=>({byConversation:{},replace:(t,n)=>e(s=>{const o={...s.byConversation};if(n.length>0)o[t]=n;else if(o[t])delete o[t];else return s;return{byConversation:o}})})),r7={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 a7({value:e}){const t=RA(e),{t:n}=ne();if(!t)return null;const s=`allow ${t.allow.toFixed(2)} · ask ${t.ask.toFixed(2)} · block ${t.block.toFixed(2)}`;return i.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 border-border/60 border-t px-3 py-1 text-[10px] text-muted-foreground","data-approval-review":t.verdict,children:[i.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:t.verdict==="allow"?n("Auto-managed · allowed"):n("Auto-managed · denied")}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{className:"font-mono",children:t.model}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{className:"font-mono",children:s}),t.reason&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsxs("span",{children:[n("Reason"),": ",n(r7[t.reason])]})]})]})}function l7({ask:e,waiting:t}){const{t:n}=ne(),s=e.answer!==null&&!e.options.includes(e.answer)?e.answer:null;return i.jsxs("div",{className:"space-y-1.5 px-3 py-2 text-xs",children:[i.jsx("p",{className:"whitespace-pre-wrap break-words leading-relaxed text-foreground",children:e.question}),(e.options.length>0||s!==null)&&i.jsxs("ul",{className:"space-y-0.5",children:[e.options.map(o=>i.jsx(gy,{selected:o===e.answer,text:o},o)),s!==null&&i.jsx(gy,{selected:!0,text:s,label:e.options.length>0&&!e.autoSelected?n("Custom answer"):void 0})]}),e.autoSelected&&i.jsx("p",{className:"text-muted-foreground",children:n("No answer in time; the default was selected")}),t&&e.answer===null&&i.jsx("p",{className:"text-muted-foreground",children:n("Waiting for your answer")})]})}function gy({selected:e,text:t,label:n}){const{t:s}=ne(),o=e?zg:Vx;return i.jsxs("li",{"data-selected":e||void 0,className:W("flex items-start gap-1.5 rounded-md px-2 py-1 leading-relaxed",e?"bg-primary/10 text-foreground":"text-muted-foreground"),children:[i.jsx(o,{className:W("mt-0.5 h-3.5 w-3.5 shrink-0",e?"text-primary":"opacity-40")}),i.jsxs("span",{className:"min-w-0 whitespace-pre-wrap break-words",children:[n&&i.jsx("span",{className:"mr-1.5 text-muted-foreground",children:n}),t]}),e&&i.jsx("span",{className:"sr-only",children:s("Selected")})]})}const c7=/^Subagent ".*" \(agentId [^,\s]+, runId [^)\s]+\) \S+ after .+\.$/gm,d7=/^The following is the subagent's report: .*$\n?/m,u7=/<usage>([\s\S]*?)<\/usage>/,Wp=(e,t)=>{const n=new RegExp(`^${t}: (\\d+)$`,"m").exec(e);return n?Number(n[1]):null};function h7(e){const t=e.indexOf(`
27
- `),n=t<0?e:e.slice(0,t);let s=t<0?"":e.slice(t+1),o=null;const r=u7.exec(s);if(r){s=s.slice(0,r.index);const a=Wp(r[1],"subagent_tokens"),l=Wp(r[1],"tool_uses"),c=Wp(r[1],"duration_ms");a!==null&&l!==null&&c!==null&&(o={tokens:a,toolUses:l,durationMs:c})}return{header:n,report:s.replace(d7,"").trim(),usage:o}}function p7(e){const t=e.trim(),n=[...t.matchAll(c7)].map(s=>s.index);return n[0]!==0?null:n.map((s,o)=>h7(t.slice(s,n[o+1]).replace(/\n+---\s*$/,"").trim()))}const Fh=m.createContext(null);function qi(){return m.useContext(Fh)}const f7=["system","memory","tools","skills","files","results","chat"];function sI(e){const t=e.contextWindow&&e.contextWindow>0?e.contextWindow:e.used;if(!(t>0))return[];const n=new Map;if(e.parts&&e.parts.length>0)for(const s of e.parts)n.set(s.kind,s.tokens);else{const{buckets:s}=e;n.set("system",s.system),n.set("memory",s.instructions+s.reminders),n.set("tools",s.tools),n.set("skills",s.skills),n.set("chat",s.conversation+s.compaction)}return f7.flatMap(s=>{const o=n.get(s)??0;return o<=0?[]:[{kind:s,tokens:o,width:Math.round(o/t*1e3)/10}]})}const qc=8,xy=(e,t)=>e.reduce((n,s)=>n+(s.tag===t?s.n??1:1),0),vy=e=>e.reduce((t,n)=>t+n.tokens,0);function by(e,t){const n=e?.find(o=>o.kind===t)?.items??[];if(n.length<=qc)return n;if(t==="chat"){const o=n.filter(c=>c.tag==="compacted"),r=n.filter(c=>c.tag!=="compacted"),a=qc-o.length-1,l=r.slice(0,r.length-a);return[...o,{name:"earlier",tag:"turns",n:xy(l,"turns"),tokens:vy(l)},...r.slice(r.length-a)]}const s=n.slice(qc-1);return[...n.slice(0,qc-1),{name:"other",tag:"more",n:xy(s,"more"),tokens:vy(s)}]}function m7(e){switch(e.tag){case"more":return{key:"{{count}} more",vars:{count:e.n??0}};case"turns":return{key:"Earlier {{count}} turns",vars:{count:e.n??0}};case"turn":return{key:"Turn {{count}}",vars:{count:e.name}};case"compacted":return{key:"Compacted summary"};case"reminder":return{key:"System reminders"};default:return{raw:e.name}}}function g7(e,t){return!e||e<=0||t===void 0||t>=e?null:Math.round((1-t/e)*100)}const Up=e=>({type:"settings",link:{category:e,rowId:`${e}.root`}});function x7(e,t,n){const s=()=>{const o=Gg(t.name,n);return o?{type:"file",rel:o}:null};switch(e){case"files":return t.tag==="read"||t.tag==="shell"?s():null;case"memory":return t.tag==="project"?s()??Up("instructions"):null;case"tools":return t.tag==="more"?null:Up(t.tag==="mcp"?"mcp":"tools");case"skills":return t.tag==="more"?null:Up("skills");default:return null}}const v7=new TextEncoder,b7=new TextDecoder("utf-8",{ignoreBOM:!0}),w7=/[\uD800-\uDFFF]/,Gm=1024;let Zr=new Uint8Array(Gm);function y7(){Zr.length!==Gm&&(Zr=new Uint8Array(Gm))}function cs(e){if(e.length===0)return e;if(w7.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;Zr.length<t&&(Zr=new Uint8Array(t));const{written:n}=v7.encodeInto(e,Zr);return b7.decode(Zr.subarray(0,n))}const S7=4096,C7=.5;function k7(e){for(const t of e.hunks){for(let n=0;n<t.hunkContent.length;n++){const s=t.hunkContent[n];if(s.type!=="change")continue;const o=_7(e,s);o!=null&&(t.hunkContent.splice(n,1,...o),n+=o.length-1)}j7(t,e)}}function j7(e,t){const{hunkContent:n}=e;for(let s=1;s<n.length;s++){const o=n[s],r=n[s-1];if(o.type!=="change"||o.additions>0&&o.deletions>0||r.type!=="context")continue;const a=o.additions>0,l=a?t.additionLines:t.deletionLines,c=a?o.additionLineIndex:o.deletionLineIndex,d=a?o.additions:o.deletions,u=l[c]??"";if(u.trim()!=="")continue;let h=!0;for(let v=1;v<d;v++)if(l[c+v]!==u){h=!1;break}if(!h)continue;let p=0;for(;p<r.lines&&t.additionLines[r.additionLineIndex+r.lines-1-p]===u;)p++;if(p===0||s===1&&p===r.lines)continue;o.additionLineIndex-=p,o.deletionLineIndex-=p;const f=o.additionLineIndex+o.additions,g=o.deletionLineIndex+o.deletions,x=n[s+1];x?.type==="context"?(x.lines+=p,x.additionLineIndex=f,x.deletionLineIndex=g):n.splice(s+1,0,{type:"context",lines:p,additionLineIndex:f,deletionLineIndex:g}),r.lines-=p,r.lines===0&&(n.splice(s-1,1),s--)}}function _7(e,t){const{deletions:n,additions:s,deletionLineIndex:o,additionLineIndex:r}=t,a=Math.min(n,s),l=Math.abs(s-n);if(a===0||l===0||a*(l+1)>S7)return null;const c=[];for(let x=0;x<n;x++)c.push(wy(e.deletionLines[o+x]??""));const d=[];for(let x=0;x<s;x++)d.push(wy(e.additionLines[r+x]??""));const u=s>n;let h=0,p=-1;for(let x=0;x<=l;x++){let v=0;for(let y=0;y<a;y++)v+=T7(c[y+(u?0:x)],d[y+(u?x:0)]);x===0?p=v+a*C7:v>p&&(p=v,h=x)}if(h===0)return null;const f=[],g=(x,v,y,b)=>{(x>0||v>0)&&f.push({type:"change",deletions:x,additions:v,deletionLineIndex:y,additionLineIndex:b})};return u?(g(0,h,o,r),g(a,a,o,r+h),g(0,s-a-h,o+a,r+h+a)):(g(h,0,o,r),g(a,a,o+h,r),g(n-a-h,0,o+h+a,r+a)),f}const N7=/\s+/g;function wy(e){return e.replace(N7,"")}function T7(e,t){if(e===t)return 1;const n=Math.max(e.length,t.length),s=Math.min(e.length,t.length);if(s===0)return 0;let o=0;for(;o<s&&e[o]===t[o];)o++;let r=0;for(;r<s-o&&e[e.length-1-r]===t[t.length-1-r];)r++;return(o+r)/n}function I7(e,t){try{return D7(e,t)}finally{y7()}}function D7(e,{cacheKey:t,isGitDiff:n=FA.test(e),oldFile:s,newFile:o,throwOnError:r=!1}={}){let a=0;const l=R7(e,"@@ ");let c;const d=s==null||o==null;let u=0,h=0;for(const p of l){const f=iI(p),g=f[0];if(g==null){if(r)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",p);continue}const x=A7(g);let v=0,y=0;if(x==null||c==null){if(c!=null){if(r)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",p);continue}c={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:d,additionLines:!d&&s!=null&&o!=null?yy(o.contents):[],deletionLines:!d&&s!=null&&o!=null?yy(s.contents):[],cacheKey:Cy(t)},c.additionLines.length===1&&o?.contents===""&&(c.additionLines.length=0),c.deletionLines.length===1&&s?.contents===""&&(c.deletionLines.length=0);for(const A of f){if(A.startsWith("diff --git")){const I=A.trim().match(LA),P=I?.[1]??I?.[2],D=I?.[3]??I?.[4];if(P==null||D==null){if(r)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",A);continue}c.name=cs(D.trim()),P!==D&&(c.prevName=cs(P.trim()));continue}const T=A.startsWith("---")||A.startsWith("+++")?A.match(n?OA:zA):null;if(T!=null){const[,I,P]=T;if(I==="---"&&P!=="/dev/null"){const D=cs(P.trim());c.prevName=D,c.name=D}else I==="+++"&&P!=="/dev/null"&&(c.name=cs(P.trim()))}else if(n){if(A.startsWith("new mode ")&&(c.mode=cs(A.slice(8).trim())),A.startsWith("old mode ")&&(c.prevMode=cs(A.slice(8).trim())),A.startsWith("new file mode")&&(c.type="new",c.mode=cs(A.slice(13).trim())),A.startsWith("deleted file mode")&&(c.type="deleted",c.mode=cs(A.slice(17).trim())),A.startsWith("similarity index")&&(A.startsWith("similarity index 100%")?c.type="rename-pure":c.type="rename-changed"),A.startsWith("index ")){const[,I,P,D]=A.trim().match(GA)??[];I!=null&&(c.prevObjectId=cs(I)),P!=null&&(c.newObjectId=cs(P)),D!=null&&(c.mode=cs(D))}A.startsWith("rename from ")&&(c.prevName=cs(A.slice(12).trim())),A.startsWith("rename to ")&&(c.name=cs(A.slice(10).trim()))}}continue}let b,w;for(;f.length>0&&(f[f.length-1]===`
28
- `||f[f.length-1]==="\r"||f[f.length-1]===`\r
29
- `||f[f.length-1]==="");)f.pop();const{additionStart:C,deletionStart:_}=x;u=d?u:_-1,h=d?h:C-1;const N={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:x.additionCount,additionStart:C,additionLines:v,deletionCount:x.deletionCount,deletionStart:_,deletionLines:y,deletionLineIndex:u,additionLineIndex:h,hunkContent:[],hunkContext:Cy(x.hunkContext),hunkSpecs:cs(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let k=0,S=0;for(let A=1;A<f.length;A++){const T=f[A];if(k>=N.additionCount&&S>=N.deletionCount&&!T.startsWith("\\")){if(r&&E7(T)&&!P7(T))throw Error("parsePatchContent: hunk has more lines than expected");break}const I=T[0];if(I!=="+"&&I!=="-"&&I!==" "&&I!=="\\"){if(r)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${I}", full line: "${T}"`),console.error("processFile: invalid rawLine:",T);continue}const P=L7(I);if(P==="addition"){if(r&&k>=N.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const D=Kp(T);(b==null||b.type!=="change")&&(b=qp("change",u,h),N.hunkContent.push(b)),h++,k++,d&&c.additionLines.push(D),b.additions++,v++,w="addition"}else if(P==="deletion"){if(r&&S>=N.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const D=Kp(T);(b==null||b.type!=="change")&&(b=qp("change",u,h),N.hunkContent.push(b)),u++,S++,d&&c.deletionLines.push(D),b.deletions++,y++,w="deletion"}else if(P==="context"){if(r&&(S>=N.deletionCount||k>=N.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const D=Kp(T);(b==null||b.type!=="context")&&(b=qp("context",u,h),N.hunkContent.push(b)),h++,u++,k++,S++,d&&(c.deletionLines.push(D),c.additionLines.push(D)),b.lines++,w="context"}else if(P==="metadata"&&b!=null){if(b.type==="context"?(N.noEOFCRAdditions=!0,N.noEOFCRDeletions=!0):w==="deletion"?N.noEOFCRDeletions=!0:w==="addition"&&(N.noEOFCRAdditions=!0),d&&(w==="addition"||w==="context")){const D=c.additionLines.length-1;D>=0&&(c.additionLines[D]=Ml(c.additionLines[D]))}if(d&&(w==="deletion"||w==="context")){const D=c.deletionLines.length-1;D>=0&&(c.deletionLines[D]=Ml(c.deletionLines[D]))}}}if(r&&(k!==N.additionCount||S!==N.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");N.additionLines=v,N.deletionLines=y,N.collapsedBefore=Math.max(Ca(N.additionStart,N.additionCount)-a,0),c.hunks.push(N),a=mo(N.additionStart,N.additionCount);for(const A of N.hunkContent)A.type==="context"?(N.splitLineCount+=A.lines,N.unifiedLineCount+=A.lines):(N.splitLineCount+=Math.max(A.additions,A.deletions),N.unifiedLineCount+=A.deletions+A.additions);N.splitLineStart=c.splitLineCount+N.collapsedBefore,N.unifiedLineStart=c.unifiedLineCount+N.collapsedBefore,c.splitLineCount+=N.collapsedBefore+N.splitLineCount,c.unifiedLineCount+=N.collapsedBefore+N.unifiedLineCount}if(c!=null){if(r&&d&&!n&&c.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(c.hunks.length>0&&!d&&c.additionLines.length>0&&c.deletionLines.length>0){const p=c.hunks[c.hunks.length-1],f=mo(p.additionStart,p.additionCount),g=c.additionLines.length,x=Math.max(g-f,0);c.splitLineCount+=x,c.unifiedLineCount+=x}return n||(c.prevName!=null&&c.name!==c.prevName?c.hunks.length>0?c.type="rename-changed":c.type="rename-pure":(s==null||s.contents==="")&&o!=null&&o.contents!==""?c.type="new":s!=null&&s.contents!==""&&(o==null||o.contents==="")&&(c.type="deleted")),c.type!=="rename-pure"&&c.type!=="rename-changed"&&(c.prevName=void 0),k7(c),c}}function yy(e){const t=iI(e);for(let n=0;n<t.length;n++)t[n]=cs(t[n]);return t}function iI(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const s=e.indexOf(`
30
- `,n);if(s===-1)break;t.push(e.slice(n,s+1)),n=s+1}return n<e.length&&t.push(e.slice(n)),t}function E7(e){const t=e[0];return t==="+"||t==="-"||t===" "}function P7(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
31
- `&&n!=="\r")return!1}return!0}function A7(e){if(!e.startsWith("@@ -"))return;let t=4;const n=Yc(e,t);if(n==null)return;const s=n.value;t=n.endIndex;let o=1;if(e[t]===","){const u=Yc(e,t+1);if(u==null)return;o=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const r=Yc(e,t);if(r==null)return;const a=r.value;t=r.endIndex;let l=1;if(e[t]===","){const u=Yc(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=M7(e.slice(d+1))),{additionCount:l,additionStart:a,deletionCount:o,deletionStart:s,hunkContext:c}}function Yc(e,t){let n=t,s=0;for(;n<e.length;n++){const o=e.charCodeAt(n)-48;if(o<0||o>9)break;s=s*10+o}if(n!==t)return{value:s,endIndex:n}}function M7(e){return e.endsWith(`\r
32
- `)?e.slice(0,-2):e.endsWith(`
33
- `)?e.slice(0,-1):e}function R7(e,t){if(e.length===0)return[""];const n=`
34
- ${t}`,s=e.startsWith(t)?0:Sy(e,n,0);if(s===-1)return[e];const o=[];s>0&&o.push(e.slice(0,s));let r=s;for(;;){const a=Sy(e,n,r+1);if(a===-1)break;o.push(e.slice(r,a)),r=a}return o.push(e.slice(r)),o}function Sy(e,t,n){const s=e.indexOf(t,n);return s===-1?-1:s+1}function Cy(e){return e==null?e:cs(e)}function L7(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Kp(e){const t=e.slice(1);return cs(t===""?`
35
- `:t)}function qp(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 O7 extends HA{constructor(){super(...arguments),this.tokenize=G7}equals(t,n,s){return s.ignoreWhitespace?((!s.newlineIsToken||!t.includes(`
36
- `))&&(t=t.trim()),(!s.newlineIsToken||!n.includes(`
37
- `))&&(n=n.trim())):s.ignoreNewlineAtEof&&!s.newlineIsToken&&(t.endsWith(`
38
- `)&&(t=t.slice(0,-1)),n.endsWith(`
39
- `)&&(n=n.slice(0,-1))),super.equals(t,n,s)}}const z7=new O7;function ky(e,t,n){return z7.diff(e,t,n)}function G7(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
40
- `));const n=[],s=e.split(/(\n|\r\n)/);s[s.length-1]||s.pop();for(let o=0;o<s.length;o++){const r=s[o];o%2&&!t.newlineIsToken?n[n.length-1]+=r:n.push(r)}return n}function F7(e){for(let t=0;t<e.length;t++)if(e[t]<" "||e[t]>"~"||e[t]==='"'||e[t]==="\\")return!0;return!1}function Io(e){if(!F7(e))return e;let t='"';const n=new TextEncoder().encode(e);let s=0;for(;s<n.length;){const o=n[s];o===7?t+="\\a":o===8?t+="\\b":o===9?t+="\\t":o===10?t+="\\n":o===11?t+="\\v":o===12?t+="\\f":o===13?t+="\\r":o===34?t+='\\"':o===92?t+="\\\\":o>=32&&o<=126?t+=String.fromCharCode(o):t+="\\"+o.toString(8).padStart(3,"0"),s++}return t+='"',t}const jy={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function _y(e,t,n,s,o,r,a){let l;a?typeof a=="function"?l={callback:a}:l=a:l={},typeof l.context>"u"&&(l.context=4);const c=l.context;if(l.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(l.callback){const{callback:u}=l;ky(n,s,Object.assign(Object.assign({},l),{callback:h=>{const p=d(h);u(p)}}))}else return d(ky(n,s,l));function d(u){if(!u)return;u.push({value:"",lines:[]});function h(b){return b.map(function(w){return" "+w})}const p=[];let f=0,g=0,x=[],v=1,y=1;for(let b=0;b<u.length;b++){const w=u[b],C=w.lines||B7(w.value);if(w.lines=C,w.added||w.removed){if(!f){const _=u[b-1];f=v,g=y,_&&(x=c>0?h(_.lines.slice(-c)):[],f-=x.length,g-=x.length)}for(const _ of C)x.push((w.added?"+":"-")+_);w.added?y+=C.length:v+=C.length}else{if(f)if(C.length<=c*2&&b<u.length-2)for(const _ of h(C))x.push(_);else{const _=Math.min(C.length,c);for(const k of h(C.slice(0,_)))x.push(k);const N={oldStart:f,oldLines:v-f+_,newStart:g,newLines:y-g+_,lines:x};p.push(N),f=0,g=0,x=[]}v+=C.length,y+=C.length}}for(const b of p)for(let w=0;w<b.lines.length;w++)b.lines[w].endsWith(`
41
- `)?b.lines[w]=b.lines[w].slice(0,-1):(b.lines.splice(w+1,0,"\"),w++);return{oldFileName:e,newFileName:t,oldHeader:o,newHeader:r,hunks:p}}}function Fm(e,t){var n,s,o,r,a,l;if(t||(t=jy),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=>Fm(u,t)).join(`
42
- `)}const c=[];if(e.isGit){if(t=jy,!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 "+Io(u)+" "+Io(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 "+Io(((o=e.oldFileName)!==null&&o!==void 0?o:"").replace(/^a\//,""))),c.push("rename to "+Io(((r=e.newFileName)!==null&&r!==void 0?r:"").replace(/^b\//,"")))),e.isCopy&&(c.push("copy from "+Io(((a=e.oldFileName)!==null&&a!==void 0?a:"").replace(/^a\//,""))),c.push("copy to "+Io(((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("--- "+Io(e.oldFileName)+(e.oldHeader?" "+e.oldHeader:"")),c.push("+++ "+Io(e.newFileName)+(e.newHeader?" "+e.newHeader:"")));for(let u=0;u<e.hunks.length;u++){const h=e.hunks[u],p=h.oldLines===0?h.oldStart-1:h.oldStart,f=h.newLines===0?h.newStart-1:h.newStart;c.push("@@ -"+p+","+h.oldLines+" +"+f+","+h.newLines+" @@");for(const g of h.lines)c.push(g)}return c.join(`
43
- `)+`
44
- `}function H7(e,t,n,s,o,r,a){if(typeof a=="function"&&(a={callback:a}),a?.callback){const{callback:l}=a;_y(e,t,n,s,o,r,Object.assign(Object.assign({},a),{callback:c=>{l(c?Fm(c,a.headerOptions):void 0)}}))}else{const l=_y(e,t,n,s,o,r,a);return l?Fm(l,a?.headerOptions):void 0}}function B7(e){const t=e.endsWith(`
45
- `),n=e.split(`
46
- `).map(s=>s+`
47
- `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const V7="/dev/null";function yo(e,t,n,s=!1){if(e===null&&t===null)throw new Error("parseDiffFromFile: You must pass oldFile, newFile, or both");const o=e??Ny(),r=t??Ny(),a=I7(H7(o.name,r.name,o.contents,r.contents,o.header,r.header,n),{cacheKey:(()=>{const c=e?.cacheKey??e?.name,d=t?.cacheKey??t?.name;return c!=null&&d!=null?c+":"+d:c??d})(),oldFile:o,newFile:r,throwOnError:s});if(a==null)throw new Error("parseDiffFrom: FileInvalid diff -- probably need to fix something -- if the files are the same maybe?");e===null?(a.type="new",a.prevName=void 0):t===null&&(a.type="deleted",a.prevName=void 0);const l=t?.lang??(t===null?e?.lang:void 0);return l!=null&&(a.lang=l),a}function Ny(){return{name:V7,contents:""}}function $7(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function W7(e){return{...e,hunks:e.hunks.map(t=>({...t,hunkContent:t.hunkContent.map(n=>({...n}))})),deletionLines:[...e.deletionLines],additionLines:[...e.additionLines]}}function Hm(e){return e!==""?e.split(BA):[]}function Bm(e,t,n){const s=e==="clone"?W7(t):t;if(!s.isPartial)throw new Error("hydratePartialDiff: fileDiff must be partial");switch(s.type){case"change":case"rename-changed":return U7(s,q7(s,n),Ty(s,n));case"rename-pure":{const o=Ty(s,n);Y7(s,n);const r=Hm(o.contents);return s.isPartial=!1,s.deletionLines=r,s.additionLines=r,oI(s,null,o),s}}throw new Error(`hydratePartialDiff: ${s.type} diffs cannot be hydrated from loaded files`)}function U7(e,t,n){const s=Hm(t.contents),o=Hm(n.contents),{hunks:r,splitLineCount:a,unifiedLineCount:l}=K7(e.hunks,o.length);return e.hunks=r,e.splitLineCount=a,e.unifiedLineCount=l,e.isPartial=!1,e.deletionLines=s,e.additionLines=o,oI(e,t,n),e}function K7(e,t){let n=0,s=0,o=0;const r=[];for(const a of e){const l=Math.max(a.additionStart-1,0),c=Math.max(a.deletionStart-1,0);let d=l,u=c,h=0,p=0,f=0,g=0;const x=[];for(const y of a.hunkContent){if(y.type==="context"){x.push({...y,additionLineIndex:d,deletionLineIndex:u}),d+=y.lines,u+=y.lines,f+=y.lines,g+=y.lines;continue}x.push({...y,additionLineIndex:d,deletionLineIndex:u}),d+=y.additions,u+=y.deletions,h+=y.additions,p+=y.deletions,f+=Math.max(y.additions,y.deletions),g+=y.additions+y.deletions}const v=Math.max(Ca(a.additionStart,a.additionCount)-o,0);r.push({...a,collapsedBefore:v,additionLineIndex:l,deletionLineIndex:c,additionLines:h,deletionLines:p,hunkContent:x,splitLineStart:n+v,unifiedLineStart:s+v,splitLineCount:f,unifiedLineCount:g}),n+=v+f,s+=v+g,o=mo(a.additionStart,a.additionCount)}if(r.length>0){const a=r[r.length-1],l=mo(a.additionStart,a.additionCount),c=Math.max(t-l,0);n+=c,s+=c}return{hunks:r,splitLineCount:n,unifiedLineCount:s}}function q7(e,t){if(t.oldFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile`);return t.oldFile}function Ty(e,t){if(t.newFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires newFile`);return t.newFile}function Y7(e,t){if(t.oldFile!==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile to be null`)}function X7(e,t,n){return e.cacheKey!=null?`${e.cacheKey}:hydrated`:J7(t,n)}function oI(e,t,n){const s=X7(e,t,n);if(s==null){delete e.cacheKey;return}e.cacheKey=s}function J7(e,t){return e!=null&&t!=null?e.cacheKey!=null&&t.cacheKey!=null?`${e.cacheKey}:${t.cacheKey}`:void 0:e?.cacheKey??t?.cacheKey}var Z7=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 Xc(e){return vs({tagName:"div",properties:{"data-content-buffer":"","data-buffer-size":e,style:`grid-row: span ${e};min-height:calc(${e} * 1lh)`}})}function Jc(e){return vs({tagName:"div",children:[vs({tagName:"span",children:[Ed("No newline at end of file")]})],properties:{"data-no-newline":"","data-line-type":e,"data-column-content":""}})}function Yp(e){return vs({tagName:"div",children:[VA({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 Mr({type:e,content:t,expandIndex:n,chunked:s=!1,slotName:o,isFirstHunk:r,isLastHunk:a}){let l=0;const c=[];if(e==="metadata"&&t!=null&&c.push(vs({tagName:"div",children:[Ed(t)],properties:{"data-separator-wrapper":""}})),(e==="line-info"||e==="line-info-basic")&&t!=null){const d=[];n!=null&&(s?(r||(d.push(Yp("up")),l++),a||(d.push(Yp("down")),l++)):(d.push(Yp(!r&&!a?"both":r?"down":"up")),l++)),d.push(vs({tagName:"div",children:[vs({tagName:"span",children:[Ed(t)],properties:{"data-unmodified-lines":""}})],properties:{"data-separator-content":""}})),s&&n!=null&&d.push(vs({tagName:"div",children:[Ed("Expand all")],properties:{role:"button","data-expand-button":"","data-expand-all-button":""}})),c.push(vs({tagName:"div",children:d,properties:{"data-separator-wrapper":"","data-separator-multi-button":l>1?"":void 0}}))}return e==="custom"&&o!=null&&c.push(vs({tagName:"slot",properties:{name:o}})),vs({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 Q7(e,t){return`hunk-separator-${e}-${t}`}function e9(e){const t=e.at(-1);return t==null?0:Math.max(mo(t.additionStart,t.additionCount),mo(t.deletionStart,t.deletionCount))}function Vm(e){return e.startingLine===0&&e.totalLines===1/0&&e.bufferBefore===0&&e.bufferAfter===0}function oo(e,t){const n=yo({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 t9(e,t){const n=Math.max(e,1);let s=Array.from({length:n},(o,r)=>`${" ".repeat(r+1)}
48
- `).join("");return s===t&&(s=Array.from({length:n},(o,r)=>`\0${" ".repeat(r)}
49
- `).join("")),s}function n9(e){for(const t of e)if(t.trim().length>0)return!1;return!0}function $m(e,t){return t.length>0&&t.length<e.deletionLines.length&&n9(t)}function Au(e,t,n){const s=e.deletionLines.join(""),o=t9(t.length,s),r=yo({name:e.prevName??e.name,contents:s},{name:e.name,contents:o,lang:e.lang},n);return{hunks:r.hunks,splitLineCount:r.splitLineCount,unifiedLineCount:r.unifiedLineCount,additionLines:t,deletionLines:r.deletionLines,type:r.type}}function qd(e,t){return Au(e,[""],t)}function rI(e,t){if(e.additionLines.length===0)return qd(e,t);if($m(e,e.additionLines))return Au(e,e.additionLines,t);const n=e.additionLines,s=oo(e,t);return aI(s,n),s}function s9(e){return e.length>1&&e.at(-1)===""}function aI(e,t){if(!s9(t))return;const n=t.length-e.additionLines.length;if(n<=0)return;const s=e.additionLines.length,o=e.hunks.at(-1);if(o!=null&&mo(o.additionStart,o.additionCount)===s){for(const r of o.hunkContent)if(r.type==="change"&&r.additions<r.deletions&&r.additionLineIndex+r.additions===s){e.additionLines=t,r.additions+=n,o.additionCount+=n,o.additionLines+=n,fv(e);return}}}function i9(e,t,n){if(e.isPartial||e.deletionLines.length!==e.additionLines.length)return Zi(e,oo(e,n));const s=Array.from(t);if(s.length===0)return Zi(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||Ml(a)===Ml(l))return Zi(e,oo(e,n))}const o=o9(e,s);if(o.size===0)return Zi(e,oo(e,n));for(const r of o)if(!a9(e,r,n))return Zi(e,oo(e,n));return fv(e),$A(e)?Zi(e,oo(e,n)):Zi(e,{hunks:e.hunks,splitLineCount:e.splitLineCount,unifiedLineCount:e.unifiedLineCount,type:e.type})}function Zi(e,t){return Object.assign(e,t),t}function o9(e,t){const n=new Set;for(const s of t){const o=r9(e,s);if(o==null)return new Set;n.add(o)}return n}function r9(e,t){for(const[n,s]of e.hunks.entries()){const o=s.additionLineIndex+s.additionCount;if(t>=s.additionLineIndex&&t<o)return n}}function a9(e,t,n){const s=e.hunks[t];if(s==null)return!1;const o=e.deletionLines.slice(s.deletionLineIndex,s.deletionLineIndex+s.deletionCount),r=e.additionLines.slice(s.additionLineIndex,s.additionLineIndex+s.additionCount),a=yo({name:e.prevName??e.name,contents:o.join("")},{name:e.name,contents:r.join(""),lang:e.lang},{...n,context:0}),l=a.hunks[0];return l==null||a.hunks.length!==1?!1:(l9(s,l),lI(e,t),!0)}function lI(e,t){const n=e.hunks[t];if(n==null)return;if(t!==e.hunks.length-1){n.noEOFCRAdditions=!1,n.noEOFCRDeletions=!1;return}const s=e.additionLines.at(-1),o=e.deletionLines.at(-1);n.noEOFCRAdditions=s!=null&&s!==""&&!s.endsWith(`
50
- `),n.noEOFCRDeletions=o!=null&&o!==""&&!o.endsWith(`
51
- `)}function l9(e,t){const n=e.additionLineIndex,s=e.deletionLineIndex;e.hunkContent=t.hunkContent.map(o=>cI(o,n,s)),e.additionLineIndex=n+t.additionLineIndex,e.additionStart=e.additionStart+t.additionLineIndex,e.additionCount=t.additionCount,e.additionLines=t.additionLines,t.deletionLineIndex>=0&&(e.deletionLineIndex=s+t.deletionLineIndex,e.deletionStart=e.deletionStart+t.deletionLineIndex),e.deletionCount=t.deletionCount,e.deletionLines=t.deletionLines,e.noEOFCRAdditions=t.noEOFCRAdditions,e.noEOFCRDeletions=t.noEOFCRDeletions,pv(e)}function cI(e,t,n){return{...e,additionLineIndex:e.additionLineIndex+t,deletionLineIndex:e.deletionLineIndex+n}}function pv(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 fv(e){let t=0,n=0,s=0;for(const o of e.hunks)o.collapsedBefore=Math.max(Ca(o.additionStart,o.additionCount)-s,0),o.splitLineStart=t+o.collapsedBefore,o.unifiedLineStart=n+o.collapsedBefore,pv(o),t+=o.collapsedBefore+o.splitLineCount,n+=o.collapsedBefore+o.unifiedLineCount,s=mo(o.additionStart,o.additionCount);if(e.hunks.length>0){const o=e.hunks[e.hunks.length-1],r=Math.max(e.additionLines.length-mo(o.additionStart,o.additionCount),0);t+=r,n+=r}e.splitLineCount=t,e.unifiedLineCount=n}const Iy=new WeakMap;function c9(e){return e.length>1&&e[e.length-1]===""?e.slice(0,-1):e}function d9(e,t){const n=Math.min(e.length,t.length);let s=0;for(;s<n&&e[s]===t[s];)s++;let o=e.length,r=t.length;for(;o>s&&r>s&&e[o-1]===t[r-1];)o--,r--;if(!(s===o&&s===r))return{start:s,deletionEnd:o,additionEnd:r}}function Wm(e,t){const n=e.hunks,s=e.additionLines,o=c9(s),r=o===s?e:{...e,additionLines:o},a=b9(n,v9(r,t),e.deletionLines.length),l=S9(r,a);if(e.additionLines=o,e.hunks=l,e.editSessionDirty=!0,_9(e),aI(e,s),!!k9(n,e.hunks))return{regions:a.map(c=>c.previousSpan)}}function u9(e,t,n,s){const o=Array.from(new Set(t)).filter(c=>c>=0&&c<e.additionLines.length).sort((c,d)=>c-d);if(o.length===0)return;const{hunks:r}=e;let a,l=0;for(const c of o){for(;l<r.length;){const h=r[l];if(c<Mu(h)+h.additionCount)break;l++}const d=r[l],u=d==null?void 0:Mu(d);if(u==null||c<u||a!=null&&a!==l)return Wm(e,n);a=l}if(a!=null){if(h9(e,o,a,s,n)){e.editSessionDirty=!0;return}return Wm(e,n)}}function h9(e,t,n,s,o){if(s==null||o?.ignoreWhitespace===!0||o?.stripTrailingCr===!0)return!1;const r=p9(e),a=e.hunks[n];if(a.hunkContent.some(f9))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 p9(e){const t=Iy.get(e);if(t?.lines===e.deletionLines)return t.set;const n=new Set(e.deletionLines);return Iy.set(e,{lines:e.deletionLines,set:n}),n}function f9(e){return e?.type==="change"&&(e.additions===0||e.deletions===0)}function m9(e,t){const n=new Map,{regions:s}=t;for(let o=0;o<=s.length;o++){const r=s[o-1],a=s[o],l=o===0?e.get(0):r==null?void 0:e.get(r.lastIndex+1),c=a==null?void 0:e.get(a.firstIndex),d=l?.fromStart??0,u=c?.fromEnd??0;(d>0||u>0)&&n.set(o,{fromStart:d,fromEnd:u})}return n}function g9(e,t,n){const s=[];if(e.isPartial)return s;for(const[r,a]of e.hunks.entries()){const l=Rl({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:t,hunkIndex:r,collapsedContextThreshold:n});if(l.rangeSize<=n)continue;const c=jr(a),d=c-l.rangeSize;l.fromStart>0&&s.push([d,d+l.fromStart]),l.fromEnd>0&&s.push([c-l.fromEnd,c])}const o=Ll({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:t,collapsedContextThreshold:n,errorPrefix:"captureExpansionAnchors"});if(o!=null&&o.fromStart>0&&o.rangeSize>n){const r=e.hunks[e.hunks.length-1],a=jr(r)+r.deletionCount;s.push([a,a+o.fromStart])}return s}function x9(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=jr(a);s(r,l-Math.max(a.collapsedBefore,0),l)}const o=e.hunks[e.hunks.length-1];return o!=null&&!e.isPartial&&e.deletionLines.length>0&&s(e.hunks.length,jr(o)+o.deletionCount,e.deletionLines.length),n}function Um(e,t){return e.editSessionDirty!==!0?!1:(e.editSessionDirty=void 0,Object.assign(e,e.additionLines.length<=1&&e.additionLines.join("")===""?oo(e,t):rI(e,t)),!0)}function v9(e,t){if(d9(e.deletionLines,e.additionLines)==null)return[];const n=yo({name:e.prevName??e.name,contents:e.deletionLines.join("")},{name:e.name,contents:e.additionLines.join(""),lang:e.lang},t),s=[];let o=0,r=0;for(const a of n.hunks){const l=a.additionCount>0?a.additionLineIndex-o:a.deletionLineIndex-r;o+=l,r+=l;for(const c of a.hunkContent){if(c.type==="context"){o+=c.lines,r+=c.lines;continue}const d=cI(c,0,0);d.additions===0&&(d.additionLineIndex=o),d.deletions===0&&(d.deletionLineIndex=r),s.push(d),o+=d.additions,r+=d.deletions}}return s}function b9(e,t,n){const s=e.map((a,l)=>{const c=jr(a);return{deletionStart:c,deletionEnd:c+a.deletionCount,blocks:[],previousSpan:{firstIndex:l,lastIndex:l}}}),o=[];let r=0;for(const a of t){const l=a.deletionLineIndex,c=l+a.deletions;for(;r<s.length&&s[r].deletionEnd<l;)o.push(s[r]),r++;let d=o.length>0&&w9(l,c,o[o.length-1])?o.pop():void 0;for(;r<s.length&&s[r].deletionStart<=c;)d=y9(d,s[r]),r++;if(d==null){let u=l,h=c;if((a.deletions===0||a.additions===0)&&n>a.deletions){const p=o[o.length-1]?.deletionEnd??0,f=s[r]?.deletionStart??n;l>p?u--:c<f&&h++}d={deletionStart:u,deletionEnd:h,blocks:[],previousSpan:void 0}}d.deletionStart=Math.min(d.deletionStart,l),d.deletionEnd=Math.max(d.deletionEnd,c),d.blocks.push(a),o.push(d)}for(;r<s.length;)o.push(s[r]),r++;return o}function w9(e,t,n){return e<=n.deletionEnd&&t>=n.deletionStart}function y9(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 S9(e,t){const n=[];let s=0,o=0;for(const r of t){const a=r.deletionStart-s;if(a<0)throw new Error("buildRegionHunks: overlapping old-side regions");s+=a,o+=a;const l=o,c=[];for(const u of r.blocks){const h=u.deletionLineIndex-s,p=u.additionLineIndex-o;if(h<0||h!==p)throw new Error("buildRegionHunks: canonical block context mismatch");Dy(c,h,o,s),s+=h,o+=p,c.push({...u}),s+=u.deletions,o+=u.additions}const d=r.deletionEnd-s;if(d<0)throw new Error("buildRegionHunks: block exceeds its old-side region");Dy(c,d,o,s),s+=d,o+=d,n.push(C9(e,{additionStart:l,additionEnd:o,deletionStart:r.deletionStart,deletionEnd:r.deletionEnd},c))}if(e.deletionLines.length-s!==e.additionLines.length-o)throw new Error("buildRegionHunks: trailing context mismatch");return n}function C9(e,t,n){const s=t.additionEnd-t.additionStart,o=t.deletionEnd-t.deletionStart;let r=0,a=0;for(const c of n)c.type==="change"&&(r+=c.additions,a+=c.deletions);const l={collapsedBefore:0,additionStart:Zc(t.additionStart,s),additionCount:s,additionLines:r,additionLineIndex:Py(t.additionStart,s),deletionStart:Zc(t.deletionStart,o),deletionCount:o,deletionLines:a,deletionLineIndex:Py(t.deletionStart,o),hunkContent:n,hunkSpecs:`@@ -${Zc(t.deletionStart,o)},${o} +${Zc(t.additionStart,s)},${s} @@`,splitLineStart:0,splitLineCount:0,unifiedLineStart:0,unifiedLineCount:0,noEOFCRAdditions:!1,noEOFCRDeletions:!1};return pv(l),l}function Dy(e,t,n,s){t>0&&e.push({type:"context",lines:t,additionLineIndex:n,deletionLineIndex:s})}function k9(e,t){if(e.length!==t.length)return!0;for(let n=0;n<e.length;n++){const s=e[n],o=t[n];if(jr(s)!==jr(o)||s.deletionCount!==o.deletionCount||Mu(s)!==Mu(o)||s.additionCount!==o.additionCount||s.splitLineCount!==o.splitLineCount||!j9(s,o))return!0}return!1}function j9(e,t){const n=Ey(e),s=Ey(t);for(;;){const o=n.next(),r=s.next();if(o.done===!0||r.done===!0)return o.done===r.done;if(o.value[0]!==r.value[0]||o.value[1]!==r.value[1])return!1}}function*Ey(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 Mu(e){return Ca(e.additionStart,e.additionCount)}function jr(e){return Ca(e.deletionStart,e.deletionCount)}function Zc(e,t){return t===0?e:e+1}function Py(e,t){return t===0?e-1:e}function _9(e){fv(e);for(let t=0;t<e.hunks.length;t++)lI(e,t)}let N9=-1;var T9=class{options;onRenderUpdate;workerManager;__id=`diff-hunks-renderer:${++N9}`;highlighter;diff;expandedHunks=new Map;deletionAnnotations={};additionAnnotations={};computedLang="text";renderCache;editSessionActive=!1;constructor(e={theme:Li},t,n){this.options=e,this.onRenderUpdate=t,this.workerManager=n,n?.isWorkingPool()!==!0&&(this.highlighter=rp(e.theme??Li)?WA():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,qd(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)||td(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);Pr(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)??UA}getExpandedHunksMap(){return this.expandedHunks}setExpandedHunksMap(e){this.expandedHunks=e}setLineAnnotations(e){this.additionAnnotations={},this.deletionAnnotations={};for(const t of e){const n=(()=>{switch(t.side){case"deletions":return this.deletionAnnotations;case"additions":return this.additionAnnotations}})(),s=n[t.lineNumber]??[];n[t.lineNumber]=s,s.push(t)}}updateRenderCache(e,t,n=!1){if(this.renderCache==null)return!1;const{result:s,diff:o}=this.renderCache;if(s==null)return!1;if(o.isPartial)throw new Error("Could not update render cache for partial diff");const r=s.code.additionLines,a=[],l=new Map;for(const[d,u]of e){const h=r[d]?.properties??{},p=u.map(v=>v[2]).join(""),f=d<o.additionLines.length,g=f?o.additionLines[d]??"":"",x=Ml(g);f&&(o.additionLines[d]=KA(g,p),x!==p&&(a.push(d),l.set(d,g))),r[d]={type:"element",tagName:"div",properties:{"data-line":h["data-line"]??d+1,"data-line-index":h["data-line-index"]??d,"data-line-type":h["data-line-type"]??"context"},children:u.map(([v,y,b])=>v===0&&y===""?b===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:b}:{type:"element",tagName:"span",properties:{"data-char":v,style:`color:${y};`},children:[{type:"text",value:b}]})}}let c=!1;if(a.length>0)if(this.editSessionActive&&!o.isPartial){if(!n)if(o.additionLines.length<=1&&o.additionLines.join("")==="")Object.assign(o,qd(o,this.options.parseDiffOptions)),this.markEditSessionPass(o),c=!0;else if($m(o,o.additionLines))Object.assign(o,Au(o,o.additionLines,this.options.parseDiffOptions)),this.markEditSessionPass(o),c=!0;else{const d=u9(o,a,this.options.parseDiffOptions,l);this.applyExpansionRemap(d),c=d!=null}}else Object.assign(o,i9(o,a,this.options.parseDiffOptions));return s.baseThemeType=t,this.renderCache.isDirty=!0,c}applyExpansionRemap(e){e!=null&&(this.expandedHunks=m9(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=P9(e,s),n.code.additionLines=E9(s,t.additionLines,n.code.additionLines,e),t.additionLines.length<=1&&t.additionLines.join("")===""?(Object.assign(t,qd(t,this.options.parseDiffOptions)),n.code.additionLines[0]=Km(0,e.getLineText(0)),this.markEditSessionPass(t)):this.editSessionActive?this.applySessionDocumentChange(t):Object.assign(t,rI(t,this.options.parseDiffOptions)),this.renderCache.isDirty=!0}applySessionDocumentChange(e){const{parseDiffOptions:t}=this.options,n=e.additionLines;if($m(e,n)){Object.assign(e,Au(e,n,t)),this.markEditSessionPass(e);return}this.applyExpansionRemap(Wm(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=>qA(e);getOptionsWithDefaults(){const{diffIndicators:e="bars",diffStyle:t="split",disableBackground:n=!1,disableFileHeader:s=!1,disableLineNumbers:o=!1,disableVirtualizationBuffers:r=!1,collapsed:a=!1,expandUnchanged:l=!1,collapsedContextThreshold:c=1,expansionLineCount:d=100,hunkSeparators:u="line-info",lineDiffType:h="word-alt",maxLineDiffLength:p=1e3,overflow:f="scroll",stickyHeader:g=!1,theme:x=Li,headerRenderMode:v="default",tokenizeMaxLineLength:y=1e3,tokenizeMaxLength:b=YA,useTokenTransformer:w=!1,useCSSClasses:C=!1}=this.options;return{diffIndicators:e,diffStyle:t,disableBackground:n,disableFileHeader:s,disableLineNumbers:o,disableVirtualizationBuffers:r,collapsed:a,expandUnchanged:l,collapsedContextThreshold:c,expansionLineCount:d,hunkSeparators:u,lineDiffType:h,maxLineDiffLength:p,overflow:f,stickyHeader:g,theme:this.workerManager?.getDiffRenderOptions().theme??x,headerRenderMode:v,tokenizeMaxLineLength:y,tokenizeMaxLength:b,useTokenTransformer:w,useCSSClasses:C}}async initializeHighlighter(){return this.highlighter=await XA(JA(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=td(e,this.getTokenizeMaxLength());let s=this.workerManager?.getDiffResultCache(e);s!=null&&!Pr(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??ap(e.name),this.initializeHighlighter())}getLocalHighlightTheme(){return this.workerManager?.getDiffRenderOptions().theme??this.options.theme??Li}getEffectiveCodeOptions(){const e=this.workerManager?.isWorkingPool()===!0?this.workerManager.getDiffRenderOptions():void 0;return{theme:this.getLocalHighlightTheme(),tokenizeMaxLineLength:e?.tokenizeMaxLineLength??this.options.tokenizeMaxLineLength}}getRenderOptions(e){const t=(()=>{if(this.workerManager?.isWorkingPool()===!0){const l=this.workerManager.getDiffRenderOptions();return this.editSessionActive&&l.useTokenTransformer!==!0?{...l,useTokenTransformer:!0}:l}const{theme:s,tokenizeMaxLineLength:o,lineDiffType:r,maxLineDiffLength:a}=this.getOptionsWithDefaults();return{theme:s,useTokenTransformer:this.editSessionActive||this.options.useTokenTransformer===!0,tokenizeMaxLineLength:o,lineDiffType:r,maxLineDiffLength:a}})();this.getOptionsWithDefaults();const{renderCache:n}=this;return n?.result==null?{options:t,forceHighlight:!0}:!Ur(e,n.diff)||!Pr(t,n.options)?{options:t,forceHighlight:!0}:{options:t,forceHighlight:!1}}renderDiff(e=this.renderCache?.diff,t=f0){if(e==null)return;const{expandUnchanged:n,collapsedContextThreshold:s}=this.getOptionsWithDefaults();let{options:o,forceHighlight:r}=this.getRenderOptions(e);const a=this.getMatchingWorkerResultCache(e,o);a!=null&&!this.hasHighlightedRenderCache(e,o)&&(this.renderCache={diff:e,highlighted:!0,renderRange:void 0,...a},r=!1),this.renderCache??={diff:e,highlighted:!1,options:o,result:void 0,renderRange:void 0};const l=e.additionLines.length>0||e.deletionLines.length>0,c=!l||Pd(e)||td(e,this.getTokenizeMaxLength()),d=!Ur(e,this.renderCache.diff),u=!ij(this.renderCache.renderRange,t);if(!this.editSessionActive&&this.workerManager?.isWorkingPool()===!0){const h=this.renderCache.result==null&&this.renderCache.highlighted&&!c&&!d&&Vm(t);h&&(this.renderCache.highlightPending=!0),!h&&(c||this.renderCache.result==null||!this.renderCache.highlighted&&(d||u))&&(this.renderCache.diff=e,this.renderCache.options=o,this.renderCache.highlighted=!1,(this.renderCache.result==null||d||u||r)&&(this.renderCache.result=this.workerManager.getPlainDiffAST(e,t.startingLine,t.totalLines,Vm(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??ap(e.name);const h=this.highlighter!=null&&rp(o.theme),p=this.highlighter!=null&&m0(this.computedLang),f=!c&&p;if(this.highlighter!=null&&h&&(r||c||!this.renderCache.highlighted&&f||this.renderCache.result==null)){const{result:g,options:x}=this.renderDiffWithHighlighter(e,this.highlighter,c||!p);this.renderCache={diff:e,options:x,highlighted:f,result:g,renderRange:void 0}}(!h||!c&&!p)&&this.asyncHighlight(e).then(({result:g,options:x})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.applyHighlightResult(e,g,x,!c)})}return this.renderCache.result!=null?this.processDiffResult(this.renderCache.diff,t,this.renderCache.result):void 0}async asyncRender(e,t=f0){const{result:n}=await this.asyncHighlight(e);return this.processDiffResult(e,t,n)}createPreElement(e,t,n){const{diffIndicators:s,disableBackground:o,disableLineNumbers:r,overflow:a}=this.getOptionsWithDefaults();return ZA({type:"diff",diffIndicators:s,disableBackground:o,disableLineNumbers:r,overflow:a,split:e,totalLines:t,customProperties:n})}async asyncHighlight(e){const t=td(e,this.getTokenizeMaxLength());this.computedLang=t?"text":e.lang??ap(e.name);const n=this.highlighter!=null&&rp(this.getLocalHighlightTheme()),s=t||this.highlighter!=null&&m0(this.computedLang);return(this.highlighter==null||!n||!s)&&(this.highlighter=await this.initializeHighlighter()),this.renderDiffWithHighlighter(e,this.highlighter,t)}renderDiffWithHighlighter(e,t,n=!1){const{options:s}=this.getRenderOptions(e),{collapsedContextThreshold:o}=this.getOptionsWithDefaults(),r=QA(e,t,s,{forcePlainText:n,expandedHunks:n?!0:void 0,collapsedContextThreshold:o});if(this.editSessionActive&&e.additionLines.length===1&&e.additionLines[0]===""&&r.code.additionLines[0]==null){let a;if(ea({diff:e,diffStyle:"both",expandedHunks:n?!0:void 0,collapsedContextThreshold:o,callback:({additionLine:l})=>{if(l?.lineIndex===0)return a=l,!0}}),a==null)throw new Error("DiffHunksRenderer: missing empty addition line");r.code.additionLines[0]=Km(0,"",a.unifiedLineIndex,a.splitLineIndex)}return{result:r,options:s}}onHighlightSuccess(e,t,n,s=!0){this.editSessionActive||this.applyHighlightResult(e,t,n,s)}applyHighlightResult(e,t,n,s=!0){if(this.renderCache==null)return;const o=this.renderCache.highlightPending===!0||!this.renderCache.highlighted||!Pr(this.renderCache.options,n)||!Ur(this.renderCache.diff,e);this.renderCache={diff:e,options:n,highlighted:s,result:t,renderRange:void 0},o&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(e,t){if(this.editSessionActive)return;const n=this.workerManager?.getDiffResultCache(e);if(!(n==null||!Pr(t,n.options)))return n}hasHighlightedRenderCache(e,t){const{renderCache:n}=this;return n?.result!=null&&n.highlighted&&Ur(e,n.diff)&&Pr(t,n.options)}onHighlightError(e){console.error(e)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}processDiffResult(e,t,{code:n,themeStyles:s,baseThemeType:o}){const{diffStyle:r,disableFileHeader:a,expandUnchanged:l,expansionLineCount:c,collapsedContextThreshold:d,hunkSeparators:u}=this.getOptionsWithDefaults(),h=this.renderCache?.isDirty??!1;this.diff=e;const p=r==="unified",f=R9(e,this.options.loadDiffFiles!=null),g=!e.isPartial||f;let x=[],v=[],y=[];const b=[],{additionLines:w,deletionLines:C}=n,_={rowCount:0,hunkSeparators:u,additionsContentAST:x,deletionsContentAST:v,unifiedContentAST:y,unifiedGutterAST:Lc(),deletionsGutterAST:Lc(),additionsGutterAST:Lc(),expansionLineCount:c,hunkData:b,incrementRowCount(R=1){_.rowCount+=R},pushToGutter(R,$){switch(R){case"unified":_.unifiedGutterAST.children.push($);break;case"deletions":_.deletionsGutterAST.children.push($);break;case"additions":_.additionsGutterAST.children.push($);break}}},N=eM({fileDiff:e,errorPrefix:"DiffHunksRenderer.processDiffResult"}),k={size:0,side:void 0,increment(){this.size+=1},flush(){if(r!=="unified"){if(this.size<=0||this.side==null){this.side=void 0,this.size=0;return}this.side==="additions"?(_.pushToGutter("additions",ci(void 0,"buffer",this.size)),x?.push(Xc(this.size))):(_.pushToGutter("deletions",ci(void 0,"buffer",this.size)),v?.push(Xc(this.size))),this.size=0,this.side=void 0}}},S=(R,$,X,H,te)=>{_.pushToGutter(R,sM($,X,H,te))};function A(R){k.flush(),r==="unified"?Xp("unified",R,_):(Xp("deletions",R,_),Xp("additions",R,_))}this.pushFileLevelAnnotations(e,r,t,_),ea({diff:e,diffStyle:r,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:l?!0:this.expandedHunks,collapsedContextThreshold:d,callback:({hunkIndex:R,hunk:$,collapsedBefore:X,collapsedAfter:H,additionLine:te,deletionLine:V,type:Y})=>{const q=V!=null?V.splitLineIndex:te.splitLineIndex,ee=te!=null?te.unifiedLineIndex:V.unifiedLineIndex;r==="split"&&Y!=="change"&&k.flush(),X>0&&A({hunkIndex:R,collapsedLines:X,rangeSize:Math.max($?.collapsedBefore??0,0),hunkSpecs:$?.hunkSpecs,isFirstHunk:R===0,isLastHunk:!1,isExpandable:g});const ge=r==="unified"?ee:q,Ce={type:Y,hunkIndex:R,lineIndex:ge,unifiedLineIndex:ee,splitLineIndex:q,deletionLine:V,additionLine:te};if(r==="unified"){const Q=this.getUnifiedInjectedRowsForLine?.(Ce);Q?.before!=null&&My(Q.before,_);let ae=V!=null?C[V.lineIndex]:void 0,Z=te!=null?w[te.lineIndex]:void 0;if(ae==null&&Z==null){const Oe="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(Oe,{file:e.name}),new Error(Oe)}const ce=Y==="change"?te!=null?"change-addition":"change-deletion":Y,De=this.getUnifiedLineDecoration({type:Y,lineType:ce,additionLineIndex:te?.lineIndex,deletionLineIndex:V?.lineIndex});S("unified",De.gutterLineType,te!=null?te.lineNumber:V.lineNumber,`${ee},${q}`,De.gutterProperties),Z!=null?Z=ed(Z,De.contentProperties,h&&te!=null?{"data-line":te.lineNumber,"data-line-index":`${ee},${q}`}:void 0):ae!=null&&(ae=ed(ae,De.contentProperties,h&&V!=null?{"data-line":V.lineNumber,"data-line-index":`${ee},${q}`}:void 0)),Qc({diffStyle:"unified",type:Y,deletionLine:ae,additionLine:Z,unifiedSpan:this.getAnnotations("unified",V?.lineNumber,te?.lineNumber,R,ge),createAnnotationElement:Oe=>this.createAnnotationElement(Oe),context:_}),Q?.after!=null&&My(Q.after,_)}else{const Q=this.getSplitInjectedRowsForLine?.(Ce);Q?.before!=null&&Ry(Q.before,_,k);let ae=V!=null?C[V.lineIndex]:void 0,Z=te!=null?w[te.lineIndex]:void 0;const ce=this.getSplitLineDecoration({side:"deletions",type:Y,lineIndex:V?.lineIndex}),De=this.getSplitLineDecoration({side:"additions",type:Y,lineIndex:te?.lineIndex});if(ae==null&&Z==null){const Ze="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(Ze,{file:e.name}),new Error(Ze)}const Oe=(()=>{if(Y==="change"){if(Z==null)return"additions";if(ae==null)return"deletions"}})();Oe!=null?(k.side!=null&&k.side!==Oe&&k.flush(),k.side=Oe,k.increment()):Y==="change"&&k.flush();const Ne=this.getAnnotations("split",V?.lineNumber,te?.lineNumber,R,ge);if(Ne!=null&&k.size>0&&k.flush(),V!=null){const Ze=ed(ae,ce.contentProperties,h?{"data-line":V.lineNumber,"data-line-index":`${V.unifiedLineIndex},${q}`}:void 0);S("deletions",ce.gutterLineType,V.lineNumber,`${V.unifiedLineIndex},${q}`,ce.gutterProperties),Ze!=null&&(ae=Ze)}if(te!=null){const Ze=ed(Z,De.contentProperties,h?{"data-line":te.lineNumber,"data-line-index":`${te.unifiedLineIndex},${q}`}:void 0);S("additions",De.gutterLineType,te.lineNumber,`${te.unifiedLineIndex},${q}`,De.gutterProperties),Ze!=null&&(Z=Ze)}Qc({diffStyle:"split",type:Y,additionLine:Z,deletionLine:ae,...Ne,createAnnotationElement:Ze=>this.createAnnotationElement(Ze),context:_}),Q?.after!=null&&Ry(Q.after,_,k)}const Re=r==="split"&&$!=null&&q===$.splitLineStart+$.splitLineCount-1,fe=R===e.hunks.length-1&&$!=null&&(r==="split"?q===$.splitLineStart+$.splitLineCount-1:ee===$.unifiedLineStart+$.unifiedLineCount-1),U=Re?$.noEOFCRDeletions:!1,oe=Re?$.noEOFCRAdditions:!1,Se=(V?.noEOFCR??!1)||U,G=(te?.noEOFCR??!1)||oe;if(G||Se){if(r==="split"&&k.flush(),Se){const Q=Y==="context"||Y==="context-expanded"?Y:"change-deletion";r==="unified"?(_.unifiedContentAST.push(Jc(Q)),_.pushToGutter("unified",ci(Q,"metadata",1))):(_.deletionsContentAST.push(Jc(Q)),_.pushToGutter("deletions",ci(Q,"metadata",1)),G||(_.pushToGutter("additions",ci(void 0,"buffer",1)),_.additionsContentAST.push(Xc(1))))}if(G){const Q=Y==="context"||Y==="context-expanded"?Y:"change-addition";r==="unified"?(_.unifiedContentAST.push(Jc(Q)),_.pushToGutter("unified",ci(Q,"metadata",1))):(_.additionsContentAST.push(Jc(Q)),_.pushToGutter("additions",ci(Q,"metadata",1)),Se||(_.pushToGutter("deletions",ci(void 0,"buffer",1)),_.deletionsContentAST.push(Xc(1))))}_.incrementRowCount(1)}u!=="simple"&&u!=="metadata"&&(H>0||fe&&f)&&A({hunkIndex:Y==="context-expanded"?R:R+1,collapsedLines:fe&&f?"unknown":H,rangeSize:N,hunkSpecs:void 0,isFirstHunk:!1,isLastHunk:!0,isExpandable:g}),_.incrementRowCount(1)}}),r==="split"&&k.flush();const T=Math.max(e9(e.hunks),e.additionLines.length??0,e.deletionLines.length??0),I=t.bufferBefore>0||t.bufferAfter>0,P=!p&&e.type!=="deleted",D=!p&&e.type!=="new",O=_.rowCount>0||I;x=P&&O?x:void 0,v=D&&O?v:void 0,y=p&&O?y:void 0;const z=this.createPreElement(v!=null&&x!=null,T);return{unifiedGutterAST:p&&O?_.unifiedGutterAST.children:void 0,unifiedContentAST:y,deletionsGutterAST:D&&O?_.deletionsGutterAST.children:void 0,deletionsContentAST:v,additionsGutterAST:P&&O?_.additionsGutterAST.children:void 0,additionsContentAST:x,hunkData:b,preNode:z,themeStyles:s,baseThemeType:o,headerElement:a?void 0:this.renderHeader(this.diff),totalLines:T,rowCount:_.rowCount,bufferBefore:t.bufferBefore,bufferAfter:t.bufferAfter,css:""}}renderCodeAST(e,t){const n=e==="unified"?t.unifiedGutterAST:e==="deletions"?t.deletionsGutterAST:t.additionsGutterAST,s=e==="unified"?t.unifiedContentAST:e==="deletions"?t.deletionsContentAST:t.additionsContentAST;if(n==null||s==null)return;const o=Lc(n);return o.properties.style=`grid-row: span ${t.rowCount}`,[o,tM(s,t.rowCount)]}renderFullAST(e,t=[]){const n=this.getOptionsWithDefaults().hunkSeparators==="line-info",s=this.renderCodeAST("unified",e);if(s!=null)return t.push(vs({tagName:"code",children:s,properties:{"data-code":"","data-container-size":n?"":void 0,"data-unified":""}})),{...e.preNode,children:t};const o=this.renderCodeAST("deletions",e);o!=null&&t.push(vs({tagName:"code",children:o,properties:{"data-code":"","data-container-size":n?"":void 0,"data-deletions":""}}));const r=this.renderCodeAST("additions",e);return r!=null&&t.push(vs({tagName:"code",children:r,properties:{"data-code":"","data-container-size":n?"":void 0,"data-additions":""}})),{...e.preNode,children:t}}renderFullHTML(e,t=[]){return hr(this.renderFullAST(e,t))}renderPartialHTML(e,t){return t==null?hr(e):hr(vs({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(!oj(n))return;const o=e.type!=="new"?Ay(g0(this.deletionAnnotations)):[],r=e.type!=="deleted"?Ay(g0(this.additionAnnotations)):[];if(o.length===0&&r.length===0)return;const a=-1,l=-1,{createAnnotationElement:c}=this;if(t==="unified"){Qc({diffStyle:t,type:"context",unifiedSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:o.concat(r)},createAnnotationElement:c,context:s});return}Qc({diffStyle:t,type:"context",deletionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:o},additionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:r},createAnnotationElement:c,context:s})}getAnnotations(e,t,n,s,o){const r={type:"annotation",hunkIndex:s,lineIndex:o,annotations:[]};if(t!=null)for(const l of this.deletionAnnotations[t]??[])r.annotations.push(ua(l));const a={type:"annotation",hunkIndex:s,lineIndex:o,annotations:[]};if(n!=null)for(const l of this.additionAnnotations[n]??[])(e==="unified"?r:a).annotations.push(ua(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 nM({fileOrDiff:e,mode:t,stickyHeader:n})}};function Ay(e){return e?.map(t=>ua(t))??[]}const I9=new Intl.PluralRules("en-US");function D9(e){return`${e} unmodified line${I9.select(e)==="one"?"":"s"}`}function My(e,t){for(const n of e)t.unifiedContentAST.push(n.content),t.pushToGutter("unified",n.gutter),t.incrementRowCount(1)}function Ry(e,t,n){for(const{deletion:s,addition:o}of e){if(s==null&&o==null)continue;const r=s!=null&&o!=null?void 0:s==null?"deletions":"additions";(r==null||n.side!==r)&&n.flush(),s!=null&&(t.deletionsContentAST.push(s.content),t.pushToGutter("deletions",s.gutter)),o!=null&&(t.additionsContentAST.push(o.content),t.pushToGutter("additions",o.gutter)),r!=null&&(n.side=r,n.increment()),t.incrementRowCount(1)}}function Qc({diffStyle:e,type:t,deletionLine:n,additionLine:s,unifiedSpan:o,deletionSpan:r,additionSpan:a,createAnnotationElement:l,context:c}){let d=!1;if(e==="unified"){if(s!=null?c.unifiedContentAST.push(s):n!=null&&c.unifiedContentAST.push(n),o!=null){const u=t==="change"?n!=null?"change-deletion":"change-addition":t;c.unifiedContentAST.push(l(o)),c.pushToGutter("unified",ci(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",ci(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",ci(u,"annotation",1)),d=!0}}d&&c.incrementRowCount(1)}function Xp(e,{hunkIndex:t,collapsedLines:n,rangeSize:s,hunkSpecs:o,isFirstHunk:r,isLastHunk:a,isExpandable:l},c){if(typeof n=="number"&&n<=0)return;const d=e==="unified"?c.unifiedContentAST:e==="deletions"?c.deletionsContentAST:c.additionsContentAST;if(c.hunkSeparators==="metadata"){o!=null&&(c.pushToGutter(e,Mr({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),d.push(Mr({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),e!=="additions"&&c.incrementRowCount(1));return}if(c.hunkSeparators==="simple"){t>0&&(c.pushToGutter(e,Mr({type:"simple",isFirstHunk:r,isLastHunk:!1})),d.push(Mr({type:"simple",isFirstHunk:r,isLastHunk:!1})),e!=="additions"&&c.incrementRowCount(1));return}const u=Q7(e,t),h=s>c.expansionLineCount,p=l?t:void 0,f=typeof n=="number"?D9(n):"More unchanged context may be available";c.pushToGutter(e,Mr({type:c.hunkSeparators,content:f,expandIndex:p,chunked:h,slotName:u,isFirstHunk:r,isLastHunk:a})),d.push(Mr({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 ed(e,t,n){return e==null||e.type!=="element"||t==null&&n==null?e:{...e,properties:{...e.properties,...t,...n}}}function Ly(e){return e.length>0&&e[e.length-1]===""?e.length-1:e.length}function E9(e,t,n,s){const o=Ly(e),r=Ly(t),a=Math.min(o,r);let l=0;for(;l<a&&e[l]===t[l];)l++;let c=0;for(;c<a-l&&e[o-1-c]===t[r-1-c];)c++;const d=new Array(t.length);for(let u=0;u<l;u++)d[u]=n[u];for(let u=0;u<c;u++)d[r-1-u]=n[o-1-u];o<e.length&&r<t.length&&(d[t.length-1]=n[e.length-1]);for(let u=e.length;u<t.length;u++)d[u]??=n[u];for(let u=l;u<t.length;u++)d[u]??=Km(u,s.getLineText(u));return d}function Km(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 P9(e,t){const n=[],s=M9(t);for(let o=0;o<e.lineCount;o++){const r=e.getLineText(o,!0);n.push(o<e.lineCount-1&&!A9(r)?r+s:r)}return n}function A9(e){return e.endsWith(`
52
- `)||e.endsWith("\r")}function M9(e){for(const t of e){if(t.endsWith(`\r
53
- `))return`\r
54
- `;if(t.endsWith(`
55
- `))return`
56
- `;if(t.endsWith("\r"))return"\r"}return`
57
- `}function td(e,t){return Math.max(e.additionLines.length,e.deletionLines.length)>t}function R9(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function L9(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side&&e.metadata===t.metadata}function O9(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 qm(e,t=300){let n;try{await Promise.race([e(),new Promise(s=>{n=setTimeout(s,t)})])}finally{n!=null&&clearTimeout(n)}}function Ym({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 z9(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:iM(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 G9(e){return e.isPartial&&(e.type==="change"||e.type==="rename-changed"||e.type==="rename-pure")}let F9=-1;var dI=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file-diff:${++F9}`;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:Li},n,s=!1){this.options=t,this.workerManager=n,this.isContainerManaged=s,this.hunksRenderer=this.createHunksRenderer(t),this.resizeManager=new oM,this.scrollSyncManager=new Z7,this.interactionManager=new rM("diff",x0(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 z9(t)}createHunksRenderer(t){return new T9(this.getHunksRendererOptions(t),this.handleHighlightRender,this.workerManager)}getLineIndex=(t,n="additions")=>{const s=this.fileDiffCache;if(s==null)return;const o=s.hunks.at(-1);let r,a;e:for(const l of s.hunks){const c=n==="deletions"?l.deletionStart:l.additionStart,d=n==="deletions"?l.deletionCount:l.additionCount;let u=Ca(c,d)+1,h=l.splitLineStart,p=l.unifiedLineStart;if(t<u){const f=u-t;r=Math.max(p-f,0),a=Math.max(h-f,0);break e}if(t>=u+d){if(l===o){const f=t-(u+d);r=p+l.unifiedLineCount+f,a=h+l.splitLineCount+f;break e}continue}for(const f of l.hunkContent)if(f.type==="context")if(t<u+f.lines){const g=t-u;a=h+g,r=p+g;break e}else u+=f.lines,h+=f.lines,p+=f.lines;else{const g=n==="deletions"?f.deletions:f.additions;if(t<u+g){const x=t-u;r=p+(n==="additions"?f.deletions:0)+x,a=h+x;break e}else u+=g,h+=Math.max(f.deletions,f.additions),p+=f.deletions+f.additions}break e}if(!(r==null||a==null))return[r,a]};setOptions(t){t!=null&&(this.options=t,this.cachedHeaderHTML=void 0,this.hunksRenderer.setOptions(this.getHunksRendererOptions(t)),this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(x0(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&&!rj(this.appliedThemeCSS.theme,this.options.theme??Li)}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){Rf(this.handleEditSessionRender),this.emitPostRender(!0),this.editor?.cleanUp(t),this.editor=void 0,this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.pendingFiles=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,t||(this.lineAnnotations=[]),this.clearAuxiliaryNodes(),this.annotationCache.clear(),this.pre=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.placeHolder?.remove(),this.placeHolder=void 0,this.lastRenderedHeaderHTML=void 0,t||(this.cachedHeaderHTML=void 0),this.errorWrapper?.remove(),this.errorWrapper=void 0,this.spriteSVG=void 0,this.lastRowCount=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,t?this.hunksRenderer.recycle():(this.hunksRenderer.cleanUp(),this.workerManager=void 0,this.fileDiff=void 0,this.deletionFile=void 0,this.additionFile=void 0),this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,this.enabled=!1}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate({fileContainer:t,prerenderedHTML:n,preventEmit:s=!1,lineAnnotations:o,fileDiff:r,...a}){if(!this.enabled)throw new Error("FileDiff.hydrate: attempting to call hydrate after cleaned up");if(this.fileContainer!=null)throw new Error("FileDiff.hydrate: hydrate can only be called before the instance has rendered or hydrated");const l=Ym(a,"FileDiff.hydrate"),c=l?.oldFile,d=l?.newFile;this.hydrateElements(t,n),V9(this.pre,H9({fileDiff:r,oldFile:c,newFile:d}),this.options.collapsed)||$9(this.headerElement,B9({fileDiff:r,oldFile:c,newFile:d}),this.options.disableFileHeader)?this.render({...a,fileContainer:t,lineAnnotations:o,fileDiff:r,preventEmit:!0}):this.hydrationSetup({fileDiff:r,lineAnnotations:o,...l}),s||this.emitPostRender()}hydrateElements(t,n){this.fileContainer!==t&&this.emitPostRender(!0),aM(t,n);for(const s of t.shadowRoot?.children??[]){if(s instanceof SVGElement){this.spriteSVG=s;continue}if(s instanceof HTMLElement){if(s instanceof HTMLPreElement){this.pre=s;for(const o of s.children)!(o instanceof HTMLElement)||o.tagName.toLowerCase()!=="code"||("deletions"in o.dataset&&(this.codeDeletions=o),"additions"in o.dataset&&(this.codeAdditions=o),"unified"in o.dataset&&(this.codeUnified=o));continue}if("diffsHeader"in s.dataset){this.headerElement=s;continue}if(s instanceof HTMLStyleElement&&s.hasAttribute("data-theme-css")){this.themeCSSStyle=s;continue}if(s instanceof HTMLStyleElement&&s.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=s,this.appliedUnsafeCSS=s.textContent;continue}}}this.pre!=null&&(this.syncCodeNodesFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=t,this.hydrateMeasuredScrollbar()}hydrationSetup({fileDiff:t,oldFile:n,newFile:s,lineAnnotations:o}){this.lineAnnotations=o??this.lineAnnotations,this.additionFile=s,this.deletionFile=n,this.fileDiff=t??(n!==void 0&&s!==void 0?yo(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||!G9(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||(Bm("merge",t,n),this.setHydratedState(n),await qm(()=>this.primeHighlightCache(t)),!(!this.enabled||this.fileDiff!==t)&&this.rerender())}setHydratedState(t){this.deletionFile=t.oldFile,this.additionFile=t.newFile,this.workerManager?.cleanUpTasks(this.hunksRenderer),this.hunksRenderer.clearRenderCache()}render({fileDiff:t,deferManagers:n=!1,forceRender:s=!1,preventEmit:o=!1,lineAnnotations:r,fileContainer:a,containerWrapper:l,renderRange:c,...d}){const u=Ym(d,"FileDiff.render"),h=u?.oldFile,p=u?.newFile;if(!this.enabled)throw new Error("FileDiff.render: attempting to call render after cleaned up");t!=null&&t.cacheKey===void 0&&(t.cacheKey=t.prevName!=null?t.prevName+":"+t.name:t.name),this.editor?.__postponeBgTokenizeToNextFrame();const{collapsed:f=!1,themeType:g="system",expandUnchanged:x=!1}=this.options,v=f?void 0:c,y=this.hasThemeChanged(),b=u!=null,w=b&&(!Oy(h,this.deletionFile)||!Oy(p,this.additionFile));let C=t!=null&&t!==this.fileDiff;const _=r!=null&&(r.length>0||this.lineAnnotations.length>0)?r!==this.lineAnnotations:!1;if(!f&&ij(v,this.renderRange)&&!s&&!_&&!y&&(t!=null&&t===this.fileDiff||t==null&&!w))return this.applyCachedThemeState(g);let N;t==null&&b&&(w||this.fileDiff==null)&&(N=yo(u.oldFile,u.newFile,this.options.parseDiffOptions));const{renderRange:k}=this;if(this.renderRange=v,b?(this.deletionFile=h,this.additionFile=p):t!=null&&(this.deletionFile=void 0,this.additionFile=void 0),t!=null?this.fileDiff=t:N!=null&&(C=!0,this.fileDiff=N),C&&(this.cachedHeaderHTML=void 0),r!=null&&this.setLineAnnotations(r),this.fileDiff==null)return!1;this.fileDiff.editSessionDirty===!0&&this.shouldSelfHealEditSession()&&(Um(this.fileDiff,this.options.parseDiffOptions),this.hunksRenderer.refreshHighlightedResult()),x&&this.loadFilesIfNecessary(),this.hunksRenderer.setOptions(this.getHunksRendererOptions(this.options)),this.syncInteractionOptions(),this.hunksRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:S=!1,disableFileHeader:A=!1}=this.options;if(A&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),a=this.getOrCreateFileContainer(a,l),this.applyCachedThemeState(g),f){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const T=this.hunksRenderer.renderDiff(this.fileDiff,lM);T!=null&&this.applyThemeState(a,T.themeStyles,g,T.baseThemeType),T?.headerElement!=null&&this.applyHeaderToDOM(T.headerElement,a),this.renderSeparators([]),this.injectUnsafeCSS()}catch(T){if(S)throw T;console.error(T),T instanceof Error&&this.applyErrorToDOM(T,a)}return o||this.emitPostRender(),!0}try{const T=this.getOrCreatePreNode(a);if(!(this.canPartiallyRender(s,_,w||C||y)&&this.applyPartialRender({previousRenderRange:k,renderRange:v}))){const I=this.hunksRenderer.renderDiff(this.fileDiff,v);if(I==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(a,I.themeStyles,g,I.baseThemeType),I.headerElement!=null&&this.applyHeaderToDOM(I.headerElement,a),I.additionsContentAST!=null||I.deletionsContentAST!=null||I.unifiedContentAST!=null?this.applyHunksToDOM(T,I):this.pre!=null&&(this.pre.remove(),this.pre=void 0),this.renderSeparators(I.hunkData)}this.applyBuffers(T,v),this.injectUnsafeCSS(),this.renderAnnotations(),this.renderGutterUtility(),this.managersDirty=!0,n||this.flushManagers(),this.editor!=null&&this.syncRenderViewToEditor()}catch(T){if(S)throw T;console.error(T),T instanceof Error&&this.applyErrorToDOM(T,a)}return o||this.emitPostRender(),!0}emitPostRender(t=!1){const{fileContainer:n,options:{onPostRender:s}}=this;if(t){if(!this.mounted||(this.mounted=!1,n==null))return;this.options.onPostRender?.(n,this,"unmount");return}if(n==null)return;const o=this.mounted?"update":"mount";this.mounted=!0,s?.(n,this,o)}get fileDiffCache(){return this.hunksRenderer.diffCache??this.fileDiff}syncRenderViewToEditor(){const t=this.editor,n=this.fileContainer,s=this.fileDiffCache,o=this.lineAnnotations,r=this.computeEditorRenderRange(this.renderRange);t!=null&&n!=null&&s!=null&&!s.isPartial&&this.hunksRenderer.initializeHighlighter().then(a=>{!this.enabled||this.editor!==t||this.fileContainer!==n||this.fileDiffCache!==s||t.__syncRenderView(a,n,s,o,r)})}computeEditorRenderRange(t){const n=this.fileDiffCache;if(t==null||n==null||Vm(t))return t;const{diffStyle:s="split",expandUnchanged:o=!1,collapsedContextThreshold:r=1}=this.options;let a,l;return ea({diff:n,diffStyle:s,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r,callback:({additionLine:c})=>{c!=null&&(a??=c.lineNumber,l=c.lineNumber)}}),a==null||l==null?{...t,startingLine:0,totalLines:0}:{...t,startingLine:a-1,totalLines:l-a+1}}attachEditor(t){if(this.type!=="file-diff")throw new Error(`FileDiff.attachEditor: cannot attach an editor to a "${this.type}" diff`);return this.editor?.cleanUp(),this.editor=t,this.hunksRenderer.beginEditSession(),this.fileDiff?.isPartial===!0&&this.loadFilesIfNecessary(),this.hunksRenderer.editorRenderReady()?this.syncRenderViewToEditor():this.rerender(),n=>{this.editor=void 0,n!==!0&&this.finishEditSession()}}finishEditSession(){this.hunksRenderer.endEditSession(),this.completeEditSession()}completeEditSession(){const t=this.fileDiffCache;if(t==null||t.editSessionDirty!==!0)return!1;const{collapsedContextThreshold:n=1}=this.options,s=g9(t,this.hunksRenderer.getExpandedHunksMap(),n);return Um(t,this.options.parseDiffOptions),this.hunksRenderer.setExpandedHunksMap(x9(t,s)),this.hunksRenderer.refreshHighlightedResult(),this.escalateEditSessionRender(),!0}applyDocumentChange(t,n){this.hunksRenderer.applyDocumentChange(t);const s=this.hunksRenderer.diffCache;if(s!=null){const o=this.fileDiff?.cacheKey;o!=null&&s.cacheKey==null&&(s.cacheKey=o),this.fileDiff=s}n!==void 0&&n!==this.lineAnnotations&&(this.setLineAnnotations(n),this.hunksRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations()),this.rerender(),this.interactionManager.setSelectionDirty()}updateRenderCache(t,n,s={}){const{shouldRefreshDiffsView:o,lineCountChangeInFlight:r}=s;if(this.hunksRenderer.updateRenderCache(t,n,r)){this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!0,this.escalateEditSessionRender();return}o===!0&&(this.refreshViewTimeout!=null&&clearTimeout(this.refreshViewTimeout),this.lineStateRefreshPending=!0,this.refreshViewTimeout=setTimeout(()=>{this.refreshViewTimeout=void 0,this.options.diffStyle==="split"?this.refreshSplitDiffView():this.refreshUnifiedDiffView(),this.flushDeferredLineState()},150))}isLineRenderable(t){const n=this.fileDiffCache;if(n==null)return!0;const{expandUnchanged:s=!1,collapsedContextThreshold:o=1}=this.options;return aj({fileDiff:n,lineNumber:t,expandedHunks:s?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:o})}getNearestRenderableLine(t,n){const s=this.fileDiffCache;if(s==null)return t;const{expandUnchanged:o=!1,collapsedContextThreshold:r=1}=this.options;return cM({fileDiff:s,lineNumber:t,direction:n,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r})}revealLine(t){const n=this.fileDiffCache,{expandUnchanged:s=!1,collapsedContextThreshold:o=1,expansionLineCount:r=100}=this.options;if(n==null||n.isPartial||s)return!1;const a=this.hunksRenderer.getExpandedHunksMap();for(const[u,h]of n.hunks.entries()){const[p,f]=v0(h);if(t<p){const g=Rl({isPartial:n.isPartial,rangeSize:h.collapsedBefore,expandedHunks:a,hunkIndex:u,collapsedContextThreshold:o}),x=p-g.rangeSize;if(g.renderAll||t<x+g.fromStart||t>=p-g.fromEnd)return!1;const v=t-(x+g.fromStart)+1,y=p-g.fromEnd-t;return v<=y?this.expandHunk(u,"up",v+r):this.expandHunk(u,"down",y+r),!0}if(t<f)return!1}const l=Ll({fileDiff:n,hunkIndex:n.hunks.length-1,expandedHunks:a,collapsedContextThreshold:o,errorPrefix:"FileDiff.revealLine"});if(l==null||l.renderAll)return!1;const c=n.hunks[n.hunks.length-1],[,d]=v0(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(){lj(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(o=>{console.error(o)})}cleanChildNodes(){this.resizeManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.interactionManager.cleanUp(),this.clearAuxiliaryNodes(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.codeAdditions?.remove(),this.codeDeletions?.remove(),this.codeUnified?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.codeAdditions=void 0,this.codeDeletions=void 0,this.codeUnified=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderSeparators(t){const{hunkSeparators:n}=this.options;if(this.isContainerManaged||this.fileContainer==null||typeof n!="function"){for(const{element:o}of this.separatorCache.values())o.remove();this.separatorCache.clear();return}const s=new Map(this.separatorCache);for(const o of t){const r=o.slotName;let a=this.separatorCache.get(r);if(a==null||!O9(o,a.hunkData)){a?.element.remove();const l=document.createElement("div");l.style.display="contents",l.slot=o.slotName;const c=n(o,this);c!=null&&l.appendChild(c),this.fileContainer.appendChild(l),a={element:l,hunkData:o},this.separatorCache.set(r,a)}s.delete(r)}for(const[o,{element:r}]of s.entries())this.separatorCache.delete(o),r.remove()}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:s}of this.annotationCache.values())s.remove();this.annotationCache.clear();return}const t=new Map(this.annotationCache),{renderAnnotation:n}=this.options;if(n!=null&&this.lineAnnotations.length>0)for(const[s,o]of this.lineAnnotations.entries()){const r=`${s}-${ua(o)}`;let a=this.annotationCache.get(r);if(a==null||!L9(o,a.annotation)){a?.element.remove();const l=n(o);if(l==null)continue;a={element:dM(ua(o)),annotation:o},a.element.appendChild(l),this.fileContainer.appendChild(a.element),this.annotationCache.set(r,a)}t.delete(r)}for(const[s,{element:o}]of t.entries())this.annotationCache.delete(s),o.remove()}renderGutterUtility(){const{renderGutterUtility:t}=this.options;if(this.fileContainer==null||t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=t(this.interactionManager.getHoveredLine);if(n!=null&&this.gutterUtilityContent!=null)return;if(n==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const s=uM();s.appendChild(n),this.fileContainer.appendChild(s),this.gutterUtilityContent=s}getOrCreateFileContainer(t,n){const{fileContainer:s}=this,o=t??s??document.createElement("diffs-container"),r=s!==o;return s!=null&&r&&this.editor?.__captureFocusForDOMReplacement(),r&&this.emitPostRender(!0),this.fileContainer=o,s!=null&&r&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),n!=null&&this.fileContainer.parentNode!==n&&n.appendChild(this.fileContainer),r&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(t){const{shadowRoot:n}=t;if(n!=null)for(const s of n.children)s instanceof SVGElement?this.spriteSVG??=s:Lf(s)&&s.hasAttribute("data-theme-css")?(this.themeCSSStyle??=s,this.hasAdoptedThemeCSS=!0):Lf(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=hM;const o=s.firstChild;o instanceof SVGElement&&(this.spriteSVG=o)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==n&&n.appendChild(this.spriteSVG)}getOrCreatePreNode(t){const n=t.shadowRoot??t.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,n.appendChild(this.pre)):this.pre.parentNode!==n&&(this.editor?.__captureFocusForDOMReplacement(),n.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodesFromPre(t){this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0;for(const n of Array.from(t.children))n instanceof HTMLElement&&(n.hasAttribute("data-unified")?this.codeUnified=n:n.hasAttribute("data-deletions")?this.codeDeletions=n:n.hasAttribute("data-additions")&&(this.codeAdditions=n))}applyHeaderToDOM(t,n){this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const{fileDiff:s}=this,o=this.cachedHeaderHTML??hr(t);if(this.cachedHeaderHTML=o,o!==this.lastRenderedHeaderHTML){const p=document.createElement("div");p.innerHTML=o;const f=p.firstElementChild;if(!(f instanceof HTMLElement))return;this.headerElement!=null?n.shadowRoot?.replaceChild(f,this.headerElement):n.shadowRoot?.prepend(f),this.headerElement=f,this.lastRenderedHeaderHTML=o}if(this.isContainerManaged||s==null)return;const{renderCustomHeader:r,renderHeaderPrefix:a,renderHeaderFilenameSuffix:l,renderHeaderMetadata:c}=this.options;if(r!=null){const p=r(s)??void 0;this.headerCustom=this.upsertHeaderSlotElement(n,this.headerCustom,cj,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,pM,d),this.headerFilenameSuffix=this.upsertHeaderSlotElement(n,this.headerFilenameSuffix,fM,u),this.headerMetadata=this.upsertHeaderSlotElement(n,this.headerMetadata,mM,h),this.headerCustom?.remove(),this.headerCustom=void 0}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(t,n,s,o){if(o==null){n?.remove();return}const r=n??this.createHeaderSlotElement(s);return n==null&&t.appendChild(r),this.replaceHeaderSlotContent(r,o),r}replaceHeaderSlotContent(t,n){t.replaceChildren(),n instanceof Element?t.appendChild(n):t.innerText=`${n}`}createHeaderSlotElement(t){const n=document.createElement("div");return n.slot=t,n}injectUnsafeCSS(){const{unsafeCSS:t}=this.options,n=this.fileContainer?.shadowRoot;if(n!=null){if(t==null||t===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===n&&this.appliedUnsafeCSS===t||(this.unsafeCSSStyle??=gM(),this.unsafeCSSStyle.parentNode!==n&&n.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=xM(t),this.appliedUnsafeCSS=t)}}applyThemeState(t,n,s,o){const r=t.shadowRoot??t.attachShadow({mode:"open"}),a=o??s,l=this.options.theme??Li,c=typeof l=="string"?l:{...l},d=b0(r);if(this.themeCSSStyle?.parentNode===r&&this.appliedThemeCSS?.themeStyles===n&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===d){this.appliedThemeCSS.theme=c;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===r){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:c,themeStyles:n,themeType:a,baseThemeType:o,scrollbarGutter:d};return}this.themeCSSStyle=vM({shadowRoot:r,currentNode:this.themeCSSStyle,themeCSS:CM(n,a,d)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:c,themeStyles:n,themeType:a,baseThemeType:o,scrollbarGutter:d}:void 0}hydrateMeasuredScrollbar(){const t=this.fileContainer?.shadowRoot;t==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=bM(this.themeCSSStyle.textContent??"",b0(t)))}shouldGuardRebuildScroll(){return this.editor!=null&&wM()}applyHunksToDOM(t,n){this.shouldGuardRebuildScroll()?w0(t,()=>this.replaceCodeColumns(t,n)):this.replaceCodeColumns(t,n)}applyCodeColumnsInPlace(t,n,s){const o=this.getColumnPair(t);if(o==null)return!1;const r=Do(n[0]),a=Do(n[1]);return r==null||a==null?!1:(o.gutter.innerHTML=hr(r),o.content.innerHTML=hr(a),s!==this.lastRowCount&&(o.gutter.style.setProperty("grid-row",`span ${s}`),o.content.style.setProperty("grid-row",`span ${s}`)),!0)}replaceCodeColumns(t,n){const{overflow:s="scroll"}=this.options,o=(this.options.hunkSeparators??"line-info")==="line-info",r=s==="wrap"?n.rowCount:void 0;this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,n);let a=!1;const l=[],c=this.hunksRenderer.renderCodeAST("unified",n),d=this.hunksRenderer.renderCodeAST("deletions",n),u=this.hunksRenderer.renderCodeAST("additions",n);this.editor?.__captureFocusForDOMReplacement(),c!=null?(a=this.codeUnified==null||this.codeAdditions!=null||this.codeDeletions!=null,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0,this.codeUnified=lp({code:this.codeUnified,columnType:"unified",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeUnified,c,n.rowCount)||(this.codeUnified.innerHTML=this.hunksRenderer.renderPartialHTML(c)),l.push(this.codeUnified)):d!=null||u!=null?(d!=null?(a=this.codeDeletions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions=lp({code:this.codeDeletions,columnType:"deletions",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeDeletions,d,n.rowCount)||(this.codeDeletions.innerHTML=this.hunksRenderer.renderPartialHTML(d)),l.push(this.codeDeletions)):(this.codeDeletions?.remove(),this.codeDeletions=void 0),u!=null?(a=a||this.codeAdditions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeAdditions=lp({code:this.codeAdditions,columnType:"additions",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeAdditions,u,n.rowCount)||(this.codeAdditions.innerHTML=this.hunksRenderer.renderPartialHTML(u)),l.push(this.codeAdditions)):(this.codeAdditions?.remove(),this.codeAdditions=void 0)):(this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0),l.length===0?t.textContent="":a&&t.replaceChildren(...l),this.lastRowCount=n.rowCount}applyPartialRender({previousRenderRange:t,renderRange:n}){const{pre:s,codeUnified:o,codeAdditions:r,codeDeletions:a,options:{diffStyle:l="split"}}=this;if(s==null||t==null||n==null||!Number.isFinite(t.totalLines)||!Number.isFinite(n.totalLines)||this.lastRowCount==null)return!1;const c=this.getCodeColumns(l,o,a,r);if(c==null)return!1;const d=t.startingLine,u=n.startingLine,h=d+t.totalLines,p=u+n.totalLines,f=Math.max(d,u),g=Math.min(h,p);if(g<=f)return!1;const x=Math.max(0,f-d),v=Math.max(0,h-g),y=this.trimColumns({columns:c,trimStart:x,trimEnd:v,previousStart:d,overlapStart:f,overlapEnd:g,diffStyle:l});if(y<0)throw new Error("FileDiff.applyPartialRender: failed to trim to overlap");if(this.lastRowCount<y)throw new Error("FileDiff.applyPartialRender: trimmed beyond DOM row count");let b=this.lastRowCount-y;const w=(k,S)=>{if(!(S<=0||this.fileDiff==null))return this.hunksRenderer.renderDiff(this.fileDiff,{startingLine:k,totalLines:S,bufferBefore:0,bufferAfter:0})},C=w(u,Math.max(f-u,0));if(C==null&&u<f)return!1;const _=w(g,Math.max(p-g,0));if(_==null&&p>g)return!1;const N=(k,S)=>{if(k!=null){if(l==="unified"&&!Array.isArray(c))this.insertPartialHTML(l,c,k,S);else if(l==="split"&&Array.isArray(c))this.insertPartialHTML(l,c,k,S);else throw new Error("FileDiff.applyPartialRender.applyChunk: invalid chunk application");b+=k.rowCount}};return this.cleanupErrorWrapper(),N(C,"afterbegin"),N(_,"beforeend"),this.lastRowCount!==b&&(this.applyRowSpan(l,c,b),this.lastRowCount=b),!0}insertPartialHTML(t,n,s,o){if(t==="unified"&&!Array.isArray(n)){const r=this.hunksRenderer.renderCodeAST("unified",s);this.renderPartialColumn(n,r,o)}else if(t==="split"&&Array.isArray(n)){const r=this.hunksRenderer.renderCodeAST("deletions",s),a=this.hunksRenderer.renderCodeAST("additions",s);this.renderPartialColumn(n[0],r,o),this.renderPartialColumn(n[1],a,o)}else throw new Error("FileDiff.insertPartialHTML: Invalid argument composition")}refreshSplitDiffView(){if(this.options.diffStyle!=="split")return;const t=this.hunksRenderer.renderDiff(this.fileDiff,this.renderRange);if(t==null)return;const n=this.getCodeColumns("split",this.codeUnified,this.codeDeletions,this.codeAdditions);if(!Array.isArray(n))return;const s=(o,r)=>{if(r==null)return;const a=this.hunksRenderer.renderCodeAST(o,t),l=Do(a?.[0]),c=Do(a?.[1]);for(const[d,u]of[[r.gutter,l],[r.content,c]])if(u!=null&&d.childElementCount===u.length)for(let h=0;h<u.length;h++){const p=d.children[h],f=u[h].properties["data-line-type"];f!=null&&p.dataset.lineType!==f&&(p.dataset.lineType=f)}};s("deletions",n[0]),s("additions",n[1])}refreshUnifiedDiffView(){if(this.options.diffStyle!=="unified")return;const t=this.hunksRenderer.renderDiff(this.fileDiff,this.renderRange);if(t==null)return;const n=this.getCodeColumns("unified",this.codeUnified,this.codeDeletions,this.codeAdditions);if(n==null||Array.isArray(n))return;const s=this.hunksRenderer.renderCodeAST("unified",t),o=Do(s?.[0]),r=Do(s?.[1]),a=()=>{for(const[l,c]of[[n.gutter,o],[n.content,r]])c!=null&&(l.innerHTML=hr(c));t.rowCount!==this.lastRowCount&&(this.applyRowSpan("unified",n,t.rowCount),this.lastRowCount=t.rowCount)};this.shouldGuardRebuildScroll()?w0(this.pre,a):a(),this.renderSeparators(t.hunkData),this.managersDirty=!0,this.flushManagers(),this.syncRenderViewToEditor()}renderPartialColumn(t,n,s){if(t==null||n==null)return;const o=Do(n[0]),r=Do(n[1]);if(o==null||r==null)throw new Error("FileDiff.insertPartialHTML: Unexpected AST structure");const a=r.at(0);s==="beforeend"&&a?.type==="element"&&typeof a.properties["data-buffer-size"]=="number"&&this.mergeBuffersIfNecessary(a.properties["data-buffer-size"],t.content.children[t.content.children.length-1],t.gutter.children[t.gutter.children.length-1],o,r,!0);const l=r.at(-1);s==="afterbegin"&&l?.type==="element"&&typeof l.properties["data-buffer-size"]=="number"&&this.mergeBuffersIfNecessary(l.properties["data-buffer-size"],t.content.children[0],t.gutter.children[0],o,r,!1),t.gutter.insertAdjacentHTML(s,this.hunksRenderer.renderPartialHTML(o)),t.content.insertAdjacentHTML(s,this.hunksRenderer.renderPartialHTML(r))}mergeBuffersIfNecessary(t,n,s,o,r,a){if(!(n instanceof HTMLElement)||!(s instanceof HTMLElement))return;const l=this.getBufferSize(n.dataset);l!=null&&(a?(o.shift(),r.shift()):(o.pop(),r.pop()),this.updateBufferSize(n,l+t),this.updateBufferSize(s,l+t))}applyRowSpan(t,n,s){const o=r=>{r!=null&&(r.gutter.style.setProperty("grid-row",`span ${s}`),r.content.style.setProperty("grid-row",`span ${s}`))};if(t==="unified"&&!Array.isArray(n))o(n);else if(t==="split"&&Array.isArray(n))o(n[0]),o(n[1]);else throw new Error("dun fuuuuked up")}trimColumnRows(t,n,s){let o=0,r=0,a=0,l=!1;const c=s>=0;if(t==null)return 0;const d=Array.from(t.content.children),u=Array.from(t.gutter.children);if(d.length!==u.length)throw new Error("FileDiff.trimColumnRows: columns do not match");for(;a<d.length&&!(n<=0&&!c&&!l);){const h=u[a],p=d[a];if(a++,!(h instanceof HTMLElement)||!(p instanceof HTMLElement))throw console.error({gutterElement:h,contentElement:p}),new Error("FileDiff.trimColumnRows: invalid row elements");if(l&&(l=!1,h.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in p.dataset||h.dataset.gutterBuffer==="metadata"&&"noNewline"in p.dataset)){h.remove(),p.remove(),r++;continue}if("lineIndex"in h.dataset&&"lineIndex"in p.dataset){(n>0||c&&o>=s)&&(h.remove(),p.remove(),n>0&&(n--,n===0&&(l=!0)),r++),o++;continue}if("separator"in h.dataset&&"separator"in p.dataset){(n>0||c&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in p.dataset){(n>0||c&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="metadata"&&"noNewline"in p.dataset){(n>0||c&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="buffer"&&"contentBuffer"in p.dataset){const f=this.getBufferSize(p.dataset);if(f==null)throw new Error("FileDiff.trimColumnRows: invalid element");if(n>0){const g=Math.min(n,f),x=f-g;x>0?(this.updateBufferSize(h,x),this.updateBufferSize(p,x),r+=g):(h.remove(),p.remove(),r+=f),n-=g,n===0&&x===0&&(l=!0)}else if(c){const g=o,x=o+f-1;if(s<=g)h.remove(),p.remove(),r+=f;else if(s<=x){const v=x-s+1,y=f-v;this.updateBufferSize(h,y),this.updateBufferSize(p,y),r+=v}}o+=f;continue}throw console.error({gutterElement:h,contentElement:p}),new Error("FileDiff.trimColumnRows: unknown row elements")}return r}trimColumns({columns:t,diffStyle:n,overlapEnd:s,overlapStart:o,previousStart:r,trimEnd:a,trimStart:l}){const c=Math.max(0,o-r),d=s-r;if(d<0)throw new Error("FileDiff.trimColumns: overlap ends before previous");const u=l>0,h=a>0;if(!u&&!h)return 0;const p=u?c:0,f=h?d:-1;if(n==="unified"&&!Array.isArray(t))return this.trimColumnRows(t,p,f);if(n==="split"&&Array.isArray(t)){const g=this.trimColumnRows(t[0],p,f),x=this.trimColumnRows(t[1],p,f);if(t[0]!=null&&t[1]!=null&&g!==x)throw new Error("FileDiff.trimColumns: split columns out of sync");return t[0]!=null?g:x}else throw console.error({diffStyle:n,columns:t}),new Error("FileDiff.trimColumns: Invalid columns for diffType")}getBufferSize(t){const n=Number.parseInt(t?.bufferSize??"",10);return Number.isNaN(n)?void 0:n}updateBufferSize(t,n){t.dataset.bufferSize=`${n}`,t.style.setProperty("grid-row",`span ${n}`),t.style.setProperty("min-height",`calc(${n} * 1lh)`)}getColumnPair(t){if(t==null)return;const n=t.children[0],s=t.children[1];if(!(!(n instanceof HTMLElement)||!(s instanceof HTMLElement)||n.dataset.gutter==null||s.dataset.content==null))return{gutter:n,content:s}}getCodeColumns(t,n,s,o){if(t==="unified")return this.getColumnPair(n);{const r=this.getColumnPair(s),a=this.getColumnPair(o);return r!=null||a!=null?[r,a]:void 0}}updateBuffers(t){this.pre!=null&&this.applyBuffers(this.pre,t)}applyBuffers(t,n){if(n==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}n.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",t.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${n.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),n.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",t.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${n.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyPreNodeAttributes(t,{additionsContentAST:n,deletionsContentAST:s,totalLines:o},r){const{diffIndicators:a="bars",disableBackground:l=!1,disableLineNumbers:c=!1,overflow:d="scroll",diffStyle:u="split"}=this.options,h={type:"diff",diffIndicators:a,disableBackground:l,disableLineNumbers:c,overflow:d,split:u==="unified"?!1:n!=null&&s!=null,totalLines:o,customProperties:r};yM(h,this.appliedPreAttributes)||(SM(t,h),this.appliedPreAttributes=h)}applyErrorToDOM(t,n){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const s=n.shadowRoot??n.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",s.appendChild(this.errorWrapper);const o=document.createElement("div");o.dataset.errorMessage="",o.innerText=t.message,this.errorWrapper.appendChild(o);const r=document.createElement("pre");r.dataset.errorStack="",r.innerText=t.stack??"No Error Stack",this.errorWrapper.appendChild(r)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Oy(e,t){return e==null||t==null?e==null&&t==null:dj(e,t)}function H9({fileDiff:e,oldFile:t,newFile:n}){return e!=null&&e.hunks.length>0||t!=null||n!=null}function B9({fileDiff:e,oldFile:t,newFile:n}){return e!=null||t!=null||n!=null}function V9(e,t,n=!1){return!n&&e==null&&t}function $9(e,t,n=!1){return e==null&&t&&!n}function Do(e){if(!(e==null||e.type!=="element"))return e.children??[]}function W9({fileDiff:e,metrics:t,disableFileHeader:n,hunkSeparators:s,expandUnchanged:o,expandedHunks:r,collapsedContextThreshold:a,canHydratePartialDiff:l}){let c=Br(t,n),d=c;const u=o?!0:r,h=e.hunks.length-1;for(let p=0;p<e.hunks.length;p++){const f=e.hunks[p];if(f==null)throw new Error("computeEstimatedDiffHeights: invalid hunk index");const g=Rl({isPartial:e.isPartial,rangeSize:f.collapsedBefore,expandedHunks:u,hunkIndex:p,collapsedContextThreshold:a}),x=(g.fromStart+g.fromEnd)*t.lineHeight;if(c+=x,d+=x,g.collapsedLines>0){const b=nl({type:s,metrics:t,hunkIndex:p,hunkSpecs:f.hunkSpecs})?.totalHeight??0;c+=b,d+=b}c+=f.splitLineCount*t.lineHeight,d+=f.unifiedLineCount*t.lineHeight;const v=U9(f);c+=v.split*t.lineHeight,d+=v.unified*t.lineHeight;const y=p===h?Ll({fileDiff:e,hunkIndex:p,expandedHunks:u,collapsedContextThreshold:a,errorPrefix:"computeEstimatedDiffHeights"}):void 0;if(y!=null){const b=(y.fromStart+y.fromEnd)*t.lineHeight;if(c+=b,d+=b,y.collapsedLines>0){const w=ur({type:s,metrics:t})?.totalHeight??0;c+=w,d+=w}}else if(p===h&&e.isPartial&&l){const b=ur({type:s,metrics:t})?.totalHeight??0;c+=b,d+=b}}if(e.hunks.length>0){const p=uj(t);c+=p,d+=p}return{splitHeight:c,unifiedHeight:d}}function U9(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 K9(e,t)}function K9(e,t){const n=(t.deletions>0&&e.noEOFCRDeletions?1:0)+(t.additions>0&&e.noEOFCRAdditions?1:0),s=t.deletions>0&&e.noEOFCRDeletions,o=t.additions>0&&e.noEOFCRAdditions;return{split:s||o?1:0,unified:n}}const Xm=3e3;let q9=-1;var uI=class extends dI{__id=`little-virtualized-file-diff:${++q9}`;top;height=0;metrics;cache={heightDeltas:new Map,measuredHeightDeltaTotal:0,estimatedSplitHeight:void 0,estimatedUnifiedHeight:void 0,checkpoints:[],totalLines:0,fileAnnotationHeight:0};isVisible=!1;isSetup=!1;virtualizer;layoutDirty=!0;forceRenderOverride;currentCollapsed;currentExpandUnchanged;pendingHydratedDiff;pendingExpansions;constructor(e,t,n,s,o=!1){super(e,s,o),this.virtualizer=t,this.metrics=cp(n)}setMetrics(e,t=!1){const n=cp(e);!t&&Of(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||!kM(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=!th(t,e),s=n&&eK(t,e);super.setOptions(e),s&&this.resetLayoutCache({forceSimpleRecompute:!0,includeEstimatedHeights:tK(t,e)}),n&&(this.forceRenderOverride=!0),n&&this.isSimpleMode()&&this.virtualizer.instanceChanged(this,s)}setThemeType(e){if(this.isAdvancedMode())throw new Error("VirtualizedFileDiff.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(e)}resetLayoutCache({forceSimpleRecompute:e=!1,includeEstimatedHeights:t=!1,resetRenderRange:n=!0}={}){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heightDeltas.size>0&&this.cache.heightDeltas.clear(),this.cache.measuredHeightDeltaTotal!==0&&(this.cache.measuredHeightDeltaTotal=0),this.invalidateDerivedLayoutCache(t,n),e&&this.isSimpleMode()&&this.computeApproximateSize()}invalidateDerivedLayoutCache(e,t=!0){this.layoutDirty=!0,this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.cache.totalLines!==0&&(this.cache.totalLines=0),e&&(this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0),this.renderRange!=null&&t&&(this.renderRange=void 0)}reconcileHeights(){let e=!1;const{overflow:t="scroll"}=this.options;if(this.fileContainer==null||this.fileDiff==null)return this.height!==0&&(e=!0),this.height=0,e;if(this.top=this.getVirtualizedTop(),t==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled())return e;const n=this.getDiffStyle(),s=n==="split"?[this.codeDeletions,this.codeAdditions]:[this.codeUnified],o=this.hasFileAnnotations(this.fileDiff);if(this.renderRange!=null&&o&&oj(this.renderRange)){const r=Y9(s)??0;this.setFileAnnotationHeight(r)&&(e=!0)}else!o&&this.setFileAnnotationHeight(0)&&(e=!0);for(const r of s){if(r==null)continue;const a=r.children[1];if(a instanceof HTMLElement)for(const l of a.children){if(!(l instanceof HTMLElement))continue;const c=l.dataset.lineIndex;if(c==null)continue;const d=sK(c,n);let u=l.getBoundingClientRect().height,h=!1;l.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in l.nextElementSibling.dataset||"noNewline"in l.nextElementSibling.dataset)&&("noNewline"in l.nextElementSibling.dataset&&(h=!0),u+=l.nextElementSibling.getBoundingClientRect().height);const p=this.getEstimatedLineHeight(h),f=this.cache.heightDeltas.get(d)??0,g=u-p;g!==f&&(e=!0,this.cache.measuredHeightDeltaTotal+=g-f,g===0?this.cache.heightDeltas.delete(d):this.cache.heightDeltas.set(d,g))}}return(e||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),e}onRender=e=>this.fileContainer==null?!1:(e&&(this.top=this.getVirtualizedTop()),this.render());flushManagers(){super.flushManagers(),this.lineStateRefreshPending&&this.flushDeferredLineState()}prepareCodeViewItem(e,t,n,s){const o=!Ur(this.fileDiff,e),r=this.syncLineAnnotations(s);let a=n?.resetDiffLayoutCache===!0||o||r,l=o||n?.resetDiffLayoutCache===!0&&n.includeEstimatedDiffHeights;n?.metrics!=null&&(this.metrics=cp(n.metrics),a=!0,l=!0);const{collapsed:c=!1,expandUnchanged:d=!1}=this.options;return this.currentCollapsed!==c&&(this.currentCollapsed=c,a=!0),this.currentExpandUnchanged!==d&&(this.currentExpandUnchanged=d,a=!0,l=!0),a&&this.resetLayoutCache({includeEstimatedHeights:l}),this.fileDiff=e,this.top=t,this.computeApproximateSize(),this.height}getLinePosition(e,t="additions"){if(this.fileDiff==null||e<1)return;const n=this.getLineIndex(e,t);if(n==null)return;const{disableFileHeader:s=!1,expandUnchanged:o=!1,collapsed:r=!1,collapsedContextThreshold:a=1}=this.options,l=this.getDiffStyle(),c=this.getHunkSeparatorType(),d=l==="split"?n[1]:n[0];this.approximateLayoutCheckpoints();const u=Br(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 ea({diff:this.fileDiff,diffStyle:l,startingLine:h?.renderedLineIndex??0,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:g,hunk:x,collapsedBefore:v,collapsedAfter:y,deletionLine:b,additionLine:w})=>{const C=l==="split"?w?.splitLineIndex??b?.splitLineIndex:w?.unifiedLineIndex??b?.unifiedLineIndex;if(C==null)throw new Error("VirtualizedFileDiff.getLinePosition: missing line index data");if(v>0){const N=nl({type:c,metrics:this.metrics,hunkIndex:g,hunkSpecs:x?.hunkSpecs});if(N!=null){if(p+=N.gapBefore,d>=C-v&&d<C)return f={top:p,height:N.height},!0;p+=N.height+N.gapAfter}}const _=this.getLineHeight(C,(w?.noEOFCR??!1)||(b?.noEOFCR??!1));if(C===d)return f={top:p,height:_},!0;if(p+=_,y>0){const N=ur({type:c,metrics:this.metrics});if(N!=null){if(d>C&&d<=C+y)return f={top:p+N.gapBefore,height:N.height},!0;p+=N.totalHeight}}return!1}}),f}getEditorViewport(){return this.virtualizer.type==="simple"?this.virtualizer.getRoot():this.virtualizer.getContainerElement()}getNumericScrollAnchor(e){if(this.fileDiff==null)return;const{disableFileHeader:t=!1,expandUnchanged:n=!1,collapsed:s=!1,collapsedContextThreshold:o=1}=this.options;if(s)return;const r=this.getDiffStyle(),a=this.getHunkSeparatorType();this.approximateLayoutCheckpoints();const l=this.getLayoutCheckpointBeforeTop(e);let c=l?.top??Br(this.metrics,t)+this.cache.fileAnnotationHeight,d;return ea({diff:this.fileDiff,diffStyle:r,startingLine:l?.renderedLineIndex??0,expandedHunks:n?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:o,callback:({hunkIndex:u,hunk:h,collapsedBefore:p,collapsedAfter:f,deletionLine:g,additionLine:x})=>{const v=r==="split"?x?.splitLineIndex??g?.splitLineIndex:x?.unifiedLineIndex??g?.unifiedLineIndex;if(v==null)throw new Error("VirtualizedFileDiff.getNumericScrollAnchor: missing line index data");if(p>0){const b=nl({type:a,metrics:this.metrics,hunkIndex:u,hunkSpecs:h?.hunkSpecs});b!=null&&(c+=b.totalHeight)}if(c>=e&&(g!=null?d={lineNumber:g.lineNumber,side:"deletions",top:c}:x!=null&&(d={lineNumber:x.lineNumber,side:"additions",top:c}),d!=null))return!0;const y=this.getLineHeight(v,(x?.noEOFCR??!1)||(g?.noEOFCR??!1));if(c+=y,f>0){const b=ur({type:a,metrics:this.metrics});b!=null&&(c+=b.totalHeight)}return!1}}),d}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(e){if(this.top==null||this.fileDiff==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const t=e!=null?this.computeRenderRangeFromWindow(this.fileDiff,this.top,e):this.renderRange;if(t==null)return;const{bufferBefore:n,bufferAfter:s,totalLines:o}=t;let r=0;if(o===0){const a=e??this.virtualizer.getWindowSpecs();this.top<a.top&&(r=s)}return{topOffset:this.top+n+r,height:this.height-(n+s)}}cleanUp(e=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),e||(this.resetLayoutCache({includeEstimatedHeights:!0}),this.pendingExpansions=void 0,this.pendingHydratedDiff=void 0),this.isSetup=!1,super.cleanUp(e)}expandHunk=(e,t,n)=>{this.fileDiff!=null&&(this.isAdvancedMode()?(this.pendingExpansions??=[],this.pendingExpansions.push({hunkIndex:e,direction:t,expansionLineCountOverride:n})):(this.hunksRenderer.expandHunk(e,t,n),this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()),this.loadFilesIfNecessary(),this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))};async handleFilesLoaded(e,t){if(!(this.fileDiff!==e||!e.isPartial)){if(this.isAdvancedMode()){const n=Bm("clone",e,t);if(await qm(()=>this.primeHighlightCache(n)),!this.enabled||this.fileDiff!==e)return;this.pendingHydratedDiff={expectedDiff:e,nextDiff:n,files:t}}else{if(Bm("merge",e,t),this.setHydratedState(t),await qm(()=>this.primeHighlightCache(e)),!this.enabled||this.fileDiff!==e)return;this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}}consumeCodeViewLayoutChanges(e){let t=!1,n;const{pendingExpansions:s,pendingHydratedDiff:o}=this;if(s!=null){this.pendingExpansions=void 0;for(const r of s)this.hunksRenderer.expandHunk(r.hunkIndex,r.direction,r.expansionLineCountOverride),t=!0}return o!=null&&(this.pendingHydratedDiff=void 0,o.expectedDiff===e&&(this.setHydratedState(o.files),n=o.nextDiff)),n!=null?(this.forceRenderOverride=!0,this.resetLayoutCache({includeEstimatedHeights:!0})):t&&(this.forceRenderOverride=!0,this.invalidateDerivedLayoutCache(!0)),n}loadFilesIfNecessary(){if(this.pendingHydratedDiff!=null){if(this.pendingHydratedDiff.expectedDiff===this.fileDiff)return;this.pendingHydratedDiff=void 0}super.loadFilesIfNecessary()}isLineRenderable(e){if(super.isLineRenderable(e))return!0;const{pendingExpansions:t}=this,n=this.fileDiffCache;if(t==null||t.length===0||n==null)return!1;const{expansionLineCount:s=100,collapsedContextThreshold:o=1}=this.options,r=new Map(this.hunksRenderer.getExpandedHunksMap());for(const a of t){const l={...r.get(a.hunkIndex)??{fromStart:0,fromEnd:0}},c=a.expansionLineCountOverride??s;(a.direction==="up"||a.direction==="both")&&(l.fromStart+=c),(a.direction==="down"||a.direction==="both")&&(l.fromEnd+=c),r.set(a.hunkIndex,l)}return aj({fileDiff:n,lineNumber:e,expandedHunks:r,collapsedContextThreshold:o})}invalidateEditSessionLayout(){this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1}),this.isSimpleMode()||this.computeApproximateSize(!0),this.getSimpleVirtualizer()?.requestHeightReconcile(this)}escalateEditSessionRender(){this.invalidateEditSessionLayout(),!(!this.enabled||this.fileDiff==null)&&(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))}shouldSelfHealEditSession(){return!this.isAdvancedMode()&&super.shouldSelfHealEditSession()}setVisibility(e){this.isAdvancedMode()||this.fileContainer==null||(this.renderRange=void 0,e&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!e&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.fileDiff==null&&this.additionFile==null&&this.deletionFile==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(e,t,n=!1){const{renderRange:s}=this;if(this.getAdvancedVirtualizer()?.capturePendingLayoutAnchor(),super.applyDocumentChange(e,t),this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1}),!this.isSimpleMode())this.computeApproximateSize(!0);else if(n&&s!==void 0&&this.fileDiff!==void 0){const o=this.virtualizer.getWindowSpecs(),r=this.computeRenderRangeFromWindow(this.fileDiff,this.top??0,o);r.bufferAfter!==s.bufferAfter&&this.updateBuffers(r)}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}computeApproximateSize(e=!1,t=this.fileDiff){const n=this.isResizeDebuggingEnabled();if(!e&&!this.layoutDirty&&!n)return;const s=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.cache.totalLines=0,t==null){this.layoutDirty=!1;return}const{disableFileHeader:o=!1,collapsed:r=!1}=this.options,a=Br(this.metrics,o);if(this.height+=a,r){this.layoutDirty=!1;return}this.height=this.getActiveEstimatedHeight(t)+this.cache.measuredHeightDeltaTotal,n&&!s&&this.validateComputedHeight(t),this.layoutDirty=!1}getActiveEstimatedHeight(e=this.fileDiff){this.ensureEstimatedDiffHeights(e);const t=this.getDiffStyle()==="split"?this.cache.estimatedSplitHeight:this.cache.estimatedUnifiedHeight;if(t==null)throw new Error("VirtualizedFileDiff.getActiveEstimatedHeight: missing estimated height");return t}ensureEstimatedDiffHeights(e=this.fileDiff){if(e==null){this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0;return}if(this.cache.estimatedSplitHeight!=null&&this.cache.estimatedUnifiedHeight!=null)return;const{disableFileHeader:t=!1,expandUnchanged:n=!1,collapsedContextThreshold:s=1}=this.options,{splitHeight:o,unifiedHeight:r}=W9({fileDiff:e,metrics:this.metrics,disableFileHeader:t,hunkSeparators:this.getHunkSeparatorType(),expandUnchanged:n,expandedHunks:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:s,canHydratePartialDiff:Jp(e,this.options.loadDiffFiles!=null)});this.cache.estimatedSplitHeight=o,this.cache.estimatedUnifiedHeight=r}validateComputedHeight(e=this.fileDiff){if(this.fileContainer==null||e==null)return;const t=this.fileContainer.getBoundingClientRect();t.height!==this.height?console.log("VirtualizedFileDiff.computeApproximateSize: computed height doesnt match",{name:e.name,elementHeight:t.height,computedHeight:this.height}):console.log("VirtualizedFileDiff.computeApproximateSize: computed height IS CORRECT")}render({fileContainer:e,fileDiff:t,forceRender:n=!1,lineAnnotations:s,...o}={}){const r=Ym(o,"VirtualizedFileDiff.render"),a=r!=null,l=r?.oldFile,c=r?.newFile,d=a&&(!Fy(l,this.deletionFile)||!Fy(c,this.additionFile));let u=t??this.fileDiff;t==null&&a&&(d||this.fileDiff==null)&&(u=yo(r.oldFile,r.newFile,this.options.parseDiffOptions));const{forceRenderOverride:h,isSetup:p}=this;this.forceRenderOverride=void 0;const f=this.syncLineAnnotations(s);f&&this.resetLayoutCache({includeEstimatedHeights:!1});const g=t!=null&&t!==this.fileDiff,x=u!=null&&!Ur(this.fileDiff,u),v=g||d;if(x&&this.resetLayoutCache({includeEstimatedHeights:!0}),e=this.getOrCreateFileContainer(e),u==null)return console.error("VirtualizedFileDiff.render: attempting to virtually render when we dont have the correct data"),!1;if(p)this.top??=this.getVirtualizedTop(),x&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.computeApproximateSize(!1,u));else{this.computeApproximateSize(!1,u);const _=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(_==null)throw new Error("VirtualizedFileDiff.render: simple virtualizer is not available");_.connect(e,this),this.isVisible=_.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode()&&(!v||!p))return this.fileDiff=u,r!=null&&(this.deletionFile=l,this.additionFile=c),x&&(this.cachedHeaderHTML=void 0),this.renderPlaceholder(this.height);const y=this.virtualizer.getWindowSpecs(),b=this.top??0,w=this.computeRenderRangeFromWindow(u,b,y),C=super.render({fileDiff:u,fileContainer:e,renderRange:w,lineAnnotations:s,forceRender:(h??n)||f||x,...r,...o});return this.isSimpleMode()&&C&&this.getSimpleVirtualizer()?.requestHeightReconcile(this),C}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}shouldGuardRebuildScroll(){return!1}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}getAdvancedVirtualizer(){return this.virtualizer.type==="advanced"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}getDiffStyle(){return this.options.diffStyle??"split"}getHunkSeparatorType(){return nK(this.options.hunkSeparators)}approximateLayoutCheckpoints(e=this.fileDiff){if(!this.layoutDirty&&this.cache.checkpoints.length>0||e==null||e.hunks.length===0||this.options.collapsed===!0)return;const{disableFileHeader:t=!1,expandUnchanged:n=!1,collapsedContextThreshold:s=1}=this.options,o=e.hunks.length-1,r=Jp(e,this.options.loadDiffFiles!=null),a=this.getDiffStyle(),l=this.getHunkSeparatorType(),c=n?!0:this.hunksRenderer.getExpandedHunksMap(),d=X9(this.cache.heightDeltas);let u=Br(this.metrics,t)+this.cache.fileAnnotationHeight,h=0;const p=({rowCount:f,startLineIndex:g,preSeparatorHeight:x=0,postSeparatorHeight:v=0,metadataOffsets:y=[]})=>{if(f<=0)return;const b=h,w=h+f;let C=J9(b);for(;C<w;){const _=C-b,N=u+(_>0?x:0)+_*this.metrics.lineHeight+Z9(y,_)*this.metrics.lineHeight+zy(d,g,g+_);this.cache.checkpoints.push({renderedLineIndex:C,lineIndex:g+_,top:N}),C+=Xm}u+=x+f*this.metrics.lineHeight+y.length*this.metrics.lineHeight+zy(d,g,g+f)+v,h=w};for(let f=0;f<e.hunks.length;f++){const g=e.hunks[f];if(g==null)throw new Error("VirtualizedFileDiff.approximateLayoutCheckpoints: invalid hunk index");const x=Rl({isPartial:e.isPartial,rangeSize:g.collapsedBefore,expandedHunks:c,hunkIndex:f,collapsedContextThreshold:s}),v=x.collapsedLines>0?nl({type:l,metrics:this.metrics,hunkIndex:f,hunkSpecs:g.hunkSpecs})?.totalHeight??0:0;p({rowCount:x.fromStart,startLineIndex:(a==="split"?g.splitLineStart:g.unifiedLineStart)-x.rangeSize});let y=v;p({rowCount:x.fromEnd,startLineIndex:(a==="split"?g.splitLineStart:g.unifiedLineStart)-x.fromEnd,preSeparatorHeight:y}),x.fromEnd>0&&(y=0);const b=f===o?Ll({fileDiff:e,hunkIndex:f,expandedHunks:c,collapsedContextThreshold:s,errorPrefix:"VirtualizedFileDiff"}):void 0,w=b!=null&&b.collapsedLines>0?ur({type:l,metrics:this.metrics})?.totalHeight??0:f===o&&r?ur({type:l,metrics:this.metrics})?.totalHeight??0:0,C=b!=null?b.fromStart+b.fromEnd:0,_=a==="split"?g.splitLineCount:g.unifiedLineCount,N=a==="split"?g.splitLineStart:g.unifiedLineStart;p({rowCount:_,startLineIndex:N,preSeparatorHeight:y,postSeparatorHeight:C===0?w:0,metadataOffsets:Q9({diffStyle:a,hunk:g,rowCount:_})}),b!=null&&C>0&&p({rowCount:C,startLineIndex:N+_,postSeparatorHeight:w})}this.cache.totalLines=h}getLayoutCheckpointBeforeLineIndex(e){if(e<=0||this.cache.checkpoints.length===0)return;let t=0,n=this.cache.checkpoints.length-1,s;for(;t<=n;){const o=t+n>>1,r=this.cache.checkpoints[o];if(r==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");r.lineIndex<=e?(s=r,t=o+1):n=o-1}return s}getLayoutCheckpointBeforeTop(e,t){let n=0,s=this.cache.checkpoints.length-1,o=-1;for(;n<=s;){const r=n+s>>1,a=this.cache.checkpoints[r];if(a==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");a.top<=e?(o=r,n=r+1):s=r-1}if(t==null)return o>=0?this.cache.checkpoints[o]:void 0;for(let r=o;r>=0;r--){const a=this.cache.checkpoints[r];if(a==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");if(a.renderedLineIndex%t===0)return a}}getExpandedLineCount(e,t){let n=0;if(e.isPartial){for(const l of e.hunks)n+=t==="split"?l.splitLineCount:l.unifiedLineCount;return n}const{expandUnchanged:s=!1,collapsedContextThreshold:o=1}=this.options,r=s?!0:this.hunksRenderer.getExpandedHunksMap();for(const[l,c]of e.hunks.entries()){const d=t==="split"?c.splitLineCount:c.unifiedLineCount;n+=d;const u=Math.max(c.collapsedBefore,0),{fromStart:h,fromEnd:p,renderAll:f}=Rl({isPartial:e.isPartial,rangeSize:u,expandedHunks:r,hunkIndex:l,collapsedContextThreshold:o});u>0&&(n+=f?u:h+p)}const a=Ll({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:r,collapsedContextThreshold:o,errorPrefix:"VirtualizedFileDiff"});return a!=null&&(n+=a.fromStart+a.fromEnd),n}getLayoutLineCount(e,t){const n=this.getExpandedLineCount(e,t),s=t==="split"?e.splitLineCount:e.unifiedLineCount;return Math.max(n,s,e.additionLines.length,e.deletionLines.length,this.cache.totalLines)}computeRenderRangeFromWindow(e,t,{top:n,bottom:s}){const{disableFileHeader:o=!1,expandUnchanged:r=!1,collapsedContextThreshold:a=1}=this.options,{hunkLineCount:l,lineHeight:c}=this.metrics,d=this.getDiffStyle(),u=this.getHunkSeparatorType(),h=Jp(e,this.options.loadDiffFiles!=null),p=this.height;let f=this.getLayoutLineCount(e,d);const g=Br(this.metrics,o),x=e.hunks.length>0?uj(this.metrics):0,{fileAnnotationHeight:v}=this.cache,y=g+v,b=Math.max(0,p-g-v-x),w=this.hasFileAnnotations(e),C=t+g,_=v>0&&w&&C<s&&C+v>n;if(t<n-p||t>s)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-g-x};if(f<=l||e.hunks.length===0)return{startingLine:0,totalLines:l,bufferBefore:0,bufferAfter:0};this.approximateLayoutCheckpoints(e),f=this.getLayoutLineCount(e,d);const N=Math.ceil(Math.max(s-n,0)/c),k=Math.ceil(N/l)*l+l,S=k/l,A=S,T=[],I=(n+s)/2,P=this.getLayoutCheckpointBeforeTop(Math.max(0,n-t-k*c*2),l);let D=t+(P?.top??y),O=P?.renderedLineIndex??0,z,R,$;if(ea({diff:e,diffStyle:d,startingLine:P?.renderedLineIndex??0,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:Re,hunk:fe,collapsedBefore:U,collapsedAfter:oe,deletionLine:Se,additionLine:G})=>{const Q=G!=null?G.splitLineIndex:Se.splitLineIndex,ae=G!=null?G.unifiedLineIndex:Se.unifiedLineIndex,Z=(G?.noEOFCR??!1)||(Se?.noEOFCR??!1),ce=Re===e.hunks.length-1&&fe!=null&&(d==="split"?Q===fe.splitLineStart+fe.splitLineCount-1:ae===fe.unifiedLineStart+fe.unifiedLineCount-1),De=(U>0?nl({type:u,metrics:this.metrics,hunkIndex:Re,hunkSpecs:fe?.hunkSpecs}):void 0)?.totalHeight??0;D+=De;const Oe=O%l===0,Ne=Math.floor(O/l);if(Oe&&(T[Ne]=D-(t+y+De),$!=null)){if($<=0)return!0;$--}const Ze=this.getLineHeight(d==="split"?Q:ae,Z);if(D>n-Ze&&D<s&&(z??=Ne),R==null&&D+Ze>I&&(R=Ne),$==null&&D>=s&&Oe&&($=A),O++,D+=Ze,oe>0||ce&&h){const bt=ur({type:u,metrics:this.metrics});bt!=null&&(D<s&&D+bt.totalHeight>n&&(z??=Ne),R==null&&D+bt.totalHeight>I&&(R=Ne),D+=bt.totalHeight)}return!1}}),z==null)if(_)z=0,R=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-g-x};R??=z;const X=Math.round(R-S/2),H=Math.max(0,Math.ceil(f/l)-S),te=Math.max(0,Math.min(X,H)),V=te*l,Y=X<0?k+X*l:k,q=T[te]??0,ee=V===0?0:v+q,ge=te+Y/l,Ce=ge<T.length?b-T[ge]:b-(D-t-y);return{startingLine:V,totalLines:Y,bufferBefore:ee,bufferAfter:Math.max(0,Ce)}}};function Y9(e){let t;for(const n of e){if(n==null)continue;const s=n.children[1];if(s instanceof HTMLElement)for(const o of s.children)o instanceof HTMLElement&&o.dataset.lineAnnotation===jM&&(t=Math.max(t??0,o.getBoundingClientRect().height))}return t}function X9(e){const t=Array.from(e).sort((r,a)=>r[0]-a[0]),n=[],s=[0];let o=0;for(const[r,a]of t)n.push(r),o+=a,s.push(o);return{lineIndexes:n,prefixTotals:s}}function zy({lineIndexes:e,prefixTotals:t},n,s){if(n>=s||e.length===0)return 0;const o=Gy(e,n);return(t[Gy(e,s)]??0)-(t[o]??0)}function Gy(e,t){let n=0,s=e.length;for(;n<s;){const o=n+s>>1,r=e[o];if(r==null)throw new Error("VirtualizedFileDiff: invalid prefix index");r<t?n=o+1:s=o}return n}function J9(e){return Math.ceil(e/Xm)*Xm}function Z9(e,t){let n=0;for(const s of e)s<t&&n++;return n}function Q9({diffStyle:e,hunk:t,rowCount:n}){if(n<=0||!t.noEOFCRAdditions&&!t.noEOFCRDeletions)return[];const s=t.hunkContent.at(-1);if(s==null)return[];if(s.type==="context")return[n-1];const o=Math.max(s.deletions,s.additions),r=s.deletions+s.additions;if(e==="split")return o>0&&(t.noEOFCRAdditions||t.noEOFCRDeletions)?[n-1]:[];const a=[],l=n-r;return s.deletions>0&&t.noEOFCRDeletions&&a.push(l+s.deletions-1),s.additions>0&&t.noEOFCRAdditions&&a.push(n-1),a}function eK(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 tK(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 Jp(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function nK(e){return typeof e=="function"?"custom":e??"line-info"}function Fy(e,t){return e==null||t==null?e==null&&t==null:dj(e,t)}function sK(e,t){const[n,s]=e.split(",").map(Number);return t==="split"?s:n}function hI(e,t){return e==null||t==null?e===t:e.header!==t.header||e.footer!==t.footer?!1:iK(e.items,t.items)}function iK(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const s=e[n],o=t[n];if(s==null||o==null||s.id!==o.id||s.type!==o.type||s.element!==o.element||s.instance!==o.instance||s.version!==o.version)return!1}return!0}function oK(e,t,n){const s=document.createElement("div");return s.style.display="flow-root",e==="header"?(s.setAttribute(_M,""),t.before(s)):(s.setAttribute(NM,""),t.after(s)),n?.observe(s),s}function Ti(e){const t=window.devicePixelRatio??1;return Math.round(e*t)/t}const rK=["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"],aK=["theme","disableLineNumbers","overflow","themeType","disableFileHeader","disableVirtualizationBuffers","preferredHighlighter","useCSSClasses","useTokenTransformer","tokenizeMaxLineLength","tokenizeMaxLength","unsafeCSS","lineHoverHighlight","enableTokenInteractionsOnWhitespace","enableGutterUtility","__debugPointerEvents","enableLineSelection","controlledSelection","disableErrorHandling"],Hy=["renderCustomHeader","renderHeaderPrefix","renderHeaderFilenameSuffix","renderHeaderMetadata","renderAnnotation","renderGutterUtility","onPostRender","onGutterUtilityClick","onLineClick","onLineNumberClick","onLineEnter","onLineLeave","onTokenClick","onTokenEnter","onTokenLeave"],By=["onLineSelected","onLineSelectionStart","onLineSelectionChange","onLineSelectionEnd"],pI=Symbol("CodeView.itemOptionsState");function Vy(e,t){Object.defineProperty(e,pI,{configurable:!1,enumerable:!1,value:t})}function Ha(e){return e[pI]}function Qi(e,t,n){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get(){return n(this)}})}const lK=120,$y=1,Wy="--diffs-overflow-override",mv=12e6,fI=1e6,mI=2e6,cK=mv-mI,Uy=mv-fI;function dK(e){if(e==null)throw new Error("CodeView: createEditor is required for items with edit: true")}const uK=(()=>{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 hK=class io{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=Oa;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:Li},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??TM}getItemTopOffset(){return this.getLayout().paddingTop+this.header.height}computeMetricsCache(t){return this.itemMetricsCache={hunkLineCount:t?.hunkLineCount??Oa.hunkLineCount,lineHeight:t?.lineHeight??Oa.lineHeight,diffHeaderHeight:t?.diffHeaderHeight??Oa.diffHeaderHeight,hunkSeparatorHeight:t?.hunkSeparatorHeight,spacing:t?.spacing??Oa.spacing,paddingTop:t?.paddingTop,paddingBottom:t?.paddingBottom},this.itemMetricsCache}getSmoothScrollSettings(){return this.options.smoothScrollSettings??IM}shouldDisablePointerEvents(){return this.options.pointerEventsOnScroll!==!0}shouldValidateItemHeights(){return DM&&this.options.__devOnlyValidateItemHeights===!0}validateRenderedItemHeight(t){if(!this.shouldValidateItemHeights()||t.element==null)return;const n=t.instance.getAdvancedStickySpecs();if(n==null)return;const s=n.height,o=t.element.getBoundingClientRect().height;s!==o&&console.error("CodeView: reconciled item height does not match DOM height",{id:t.item.id,type:t.type,index:t.index,version:t.version,expectedHeight:s,actualHeight:o,delta:o-s,stickyTopOffset:n.topOffset,virtualizedHeight:t.instance.getVirtualizedHeight(),top:t.top,scrollTop:this.getScrollTop(),windowSpecs:{...this.windowSpecs},element:t.element,instance:t.instance})}validateStickyContainerHeight(){if(!this.shouldValidateItemHeights())return;const{firstIndex:t,lastIndex:n,stickyHeight:s,stickyTop:o,stickyBottom:r}=this.renderState;if(t===-1||n===-1)return;const a=this.stickyContainer.getBoundingClientRect().height;Math.abs(a-s)<$y||console.error("CodeView: sticky container height does not match computed layout",{computedStickyHeight:s,actualStickyHeight:a,delta:a-s,stickyTop:o,stickyBottom:r,firstIndex:t,lastIndex:n,firstStickySpecs:this.items[t]?.instance.getAdvancedStickySpecs(),lastStickySpecs:this.items[n]?.instance.getAdvancedStickySpecs(),scrollTop:this.getScrollTop(),scrollPageOffset:this.scrollPageOffset,windowSpecs:{...this.windowSpecs},stickyContainer:this.stickyContainer})}clearScrollInteractionTimer(){this.scrollInteractionFixTimer!=null&&(clearTimeout(this.scrollInteractionFixTimer),this.scrollInteractionFixTimer=void 0)}suspendScrollInteractions(){this.clearScrollInteractionTimer(),this.shouldDisablePointerEvents()&&!this.pointerEventsDisabled&&(this.stickyContainer.style.pointerEvents="none",this.pointerEventsDisabled=!0),uK&&!this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Wy,"hidden"),this.codeOverflowFix=!0),this.scrollInteractionFixTimer=setTimeout(this.restoreScrollInteractions,lK)}restoreScrollInteractions=()=>{this.clearScrollInteractionTimer(),this.pointerEventsDisabled&&(this.stickyContainer.style.removeProperty("pointer-events"),this.pointerEventsDisabled=!1),this.codeOverflowFix&&(this.stickyContainer.style.setProperty(Wy,"auto"),this.codeOverflowFix=!1)};syncLayout(){const{gap:t,paddingBottom:n,paddingTop:s}=this.getLayout();this.stickyContainer.style.gap=`${t}px`,this.container?.style.setProperty("margin-top",`${s}px`),this.container?.style.setProperty("margin-bottom",`${n}px`)}reconcileHeaderFooterHosts(){const t=this.reconcileHost("header"),n=this.reconcileHost("footer");return t||n}reconcileHost(t){const{root:n,container:s}=this;if(n==null||s==null)return!1;const o=t==="header"?this.header:this.footer,r=t==="header"?this.options.renderCodeViewHeader:this.options.renderCodeViewFooter;if(r==null)return o.element==null||(this.resizeObserver?.unobserve(o.element),o.element.remove(),o.element=void 0,o.render=void 0,this.setHostHeight(o,0)),!1;if(o.element!=null&&r===o.render)return!1;const a=o.element??oK(t,s,this.resizeObserver);o.element=a;const l=r();return l!=null?a.replaceChildren(l):!this.isContainerManaged&&a.children.length>0&&(a.textContent=""),o.render=r,!0}setHostHeight(t,n){t.height!==n&&(t.height=n,this.scrollDirty=!0)}measureMountedHosts(){this.header.element!=null&&this.setHostHeight(this.header,this.header.element.getBoundingClientRect().height),this.footer.element!=null&&this.setHostHeight(this.footer,this.footer.element.getBoundingClientRect().height)}setup(t){if(this.root!=null)throw new Error("CodeView.setup: already setup");this.workerManager?.subscribeToThemeChanges(this),this.root=t,this.root.style.overflowAnchor="none",this.root.hasAttribute("tabindex")||(this.root.tabIndex=-1),this.container??=document.createElement("div"),this.container.style.contain="layout style",this.syncLayout(),this.container.appendChild(this.stickyOffset),this.container.appendChild(this.stickyContainer),this.root.appendChild(this.container),this.scrollDirty=!0,this.heightDirty=!0,this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(this.stickyContainer),this.root.addEventListener("scroll",this.handleScroll,{passive:!0}),this.root.addEventListener("wheel",this.clearPendingScroll,{passive:!0}),this.root.addEventListener("touchstart",this.clearPendingScroll,{passive:!0}),this.root.addEventListener("pointerdown",this.clearPendingScroll,{passive:!0}),this.root.addEventListener("keydown",this.clearPendingScroll,{passive:!0}),this.resizeObserver.observe(this.root),this.render(!0),window.__INSTANCE=this,window.__TOGGLE=()=>{io.__STOP?(io.__STOP=!1,this.scrollTo({type:"position",position:io.__lastScrollPosition,behavior:"instant"})):(io.__lastScrollPosition=this.getScrollTop(),io.__STOP=!0)}}reset(){Rf(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(hj),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))xK(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 $7()?"instant":t.behavior!=="smooth-auto"?t.behavior??"instant":Math.abs(n-this.getScrollTop())<=this.getHeight()*10?"smooth":"instant"}scrollTo(t){if(this.root==null)return;const n=this.normalizeScrollTarget(t);if(n==null)return;const s=this.resolveScrollTargetTop(n);s!=null&&(this.primeScrollTarget(n),this.resolveEffectiveScrollBehavior(n,s)==="smooth"?this.scrollAnimation??={position:this.getScrollTop(),velocity:0,lastTimestamp:performance.now()}:this.scrollAnimation=void 0,this.suspendScrollInteractions(),this.pendingLayoutAnchor=void 0,this.pendingScrollTarget=n,this.render())}setSelectedLines(t,n){this.applySelectedLines(t,n)}getSelectedLines(){return this.selectedLines}clearSelectedLines(t){this.applySelectedLines(null,t)}getItem(t){return this.idToItem.get(t)?.item}getEditor(t){return this.itemEditors.get(t)?.editor}updateItem(t){const n=this.idToItem.get(t.id);return n==null?(console.error(`CodeView.updateItem: unknown item id "${t.id}"`),!1):this.syncItemRecord(n,t)?(this.markItemLayoutDirty(n),this.scrollDirty=!0,this.render(),this.syncItemEditors(),this.syncSelection(),!0):!1}updateItemId(t,n){if(t===n)return!0;const s=this.idToItem.get(t);if(s==null)return console.error(`CodeView.updateItemId: unknown item id "${t}"`),!1;if(this.idToItem.has(n))return console.error(`CodeView.updateItemId: duplicate item id "${n}"`),!1;this.idToItem.delete(t),s.item.id=n,this.idToItem.set(n,s),this.updateItemOptionsId(s.instance.options,n),this.selectedLines?.id===t&&(this.selectedLines={...this.selectedLines,id:n},this.options.onSelectedLinesChange?.(this.selectedLines));const o=this.itemEditors.get(t);return o!=null&&(o.state.id=n,this.itemEditors.delete(t),this.itemEditors.set(n,o),this.attachedEditors.delete(t)&&this.attachedEditors.add(n)),this.renamePendingScrollTarget(t,n),this.renamePendingLayoutAnchor(t,n),this.render(),!0}addItem(t){this.addItems([t])}addItems(t){this.appendItemsInternal(t),this.syncItemEditors(),this.syncSelection()}removeItem(t){const n=this.idToItem.get(t);if(n==null)return console.error(`CodeView.removeItem: unknown item id "${t}"`),!1;const s=[];for(const o of this.items)o!==n&&s.push(o.item);return this.setItems(s),!0}setItems(t){let n;this.items.length===0?this.appendItemsInternal(t):this.tryAppendItems(t)||(n=this.reconcileItems(t)),this.syncItemEditors(n),this.syncSelection()}appendItemsInternal(t,n=!0){if(t.length===0)return;const s=this.getLayout();let o=this.items.length===0?0:this.scrollHeight+s.gap;const r=o;for(let a=0;a<t.length;a++){const l=t[a];if(l==null)throw new Error("CodeView.appendItemsInternal: missing input item");if(this.idToItem.has(l.id))throw new Error(`CodeView.addItem: duplicate id "${l.id}"`);const c=this.createItem(l,this.items.length,o);this.items.push(c),this.idToItem.set(c.item.id,c),this.instanceToItem.set(c.instance,c),c.height=pK(c),o+=c.height+s.gap}this.scrollHeight=o-s.gap,this.scrollDirty=!0,n&&(this.canSkipRenderForAppend(r)?this.syncContainerHeight():this.render())}canSkipRenderForAppend(t){return this.container!=null&&this.renderState.firstIndex!==-1&&this.pendingScrollTarget==null&&this.scrollAnimation==null&&this.layoutDirtyIndex==null&&t>this.windowSpecs.bottom}onThemeChange(){this.invalidateElementPool()}setOptions(t){if(t==null)return;this.capturePendingLayoutAnchor();const{options:n}=this,s=this.getLayout(),{itemMetricsCache:o}=this;fK(n,t)&&this.invalidateElementPool(),this.options=t;const r=this.computeMetricsCache(t.itemMetrics),a=!Of(o,r),l=!Of(s,this.getLayout());l&&this.syncLayout();const c=a||mK(n,t);if(c){const u=this.pendingLayoutReset;this.pendingLayoutReset={metrics:a?r:u?.metrics,resetFileLayoutCache:!0,resetDiffLayoutCache:!0,includeEstimatedDiffHeights:u?.includeEstimatedDiffHeights===!0||a||gK(n,t)}}(l||c)&&(this.markLayoutDirtyFromIndex(0),this.scrollDirty=!0),th(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){io.__STOP||(t?(Rf(this.computeRenderRangeAndEmit),this.computeRenderRangeAndEmit()):lj(this.computeRenderRangeAndEmit))}isReady(){const{workerManager:t}=this;return t==null||t.isInitialized()||t.getStats().workersFailed?(this.clearReadySubscription(),!0):(this.isReadySubscription??=t.subscribeToStatChanges(n=>{n.managerState!=="initialized"&&!n.workersFailed||(this.clearReadySubscription(),this.render(!0))}),t.getStats().managerState==="waiting"&&t.initialize().catch(()=>{}),!1)}clearReadySubscription(){this.isReadySubscription!=null&&(this.isReadySubscription(),this.isReadySubscription=void 0)}instanceChanged(t,n){const s=this.instanceToItem.get(t);if(s==null)throw new Error("CodeView.instanceChanged: An instance has changed that is not registered");n&&this.markItemLayoutDirty(s),this.render()}getWindowSpecs(){return this.windowSpecs}getContainerElement(){return this.root}getHeaderElement(){return this.header.element}getFooterElement(){return this.footer.element}getRenderedItems(){const{firstIndex:t,lastIndex:n}=this.renderState;if(t===-1||n===-1||n<t)return[];const s=[];for(let o=t;o<=n;o++){const r=this.items[o];r?.element!=null&&(r.type==="diff"?s.push({id:r.item.id,type:"diff",item:r.item,version:r.version,element:r.element,instance:r.instance}):s.push({id:r.item.id,type:"file",item:r.item,version:r.version,element:r.element,instance:r.instance}))}return s}setSlotCoordinator(t){return t===this.slotCoordinator?!1:(this.slotCoordinator=t,this.slotSnapshot=void 0,!0)}getSlotSnapshot(t){return this.buildSlotSnapshot(t)}buildSlotSnapshot(t){const n=bK(this.getRenderedItems(),t),{element:s}=this.header,{element:o}=this.footer;if(!(n==null&&s==null&&o==null))return{items:n,header:s,footer:o}}subscribeToScroll(t){return this.scrollListeners.add(t),()=>{this.scrollListeners.delete(t)}}getLocalTopForInstance(t){const n=this.instanceToItem.get(t);if(n==null)throw new Error("CodeView.getLocalTopForInstance: unknown virtualized instance");return n.top}getTopForItem(t){const n=this.idToItem.get(t);if(n!=null)return n.top+this.getItemTopOffset()}createItem(t,n,s){const{itemMetricsCache:o}=this;if(t.type==="diff"){const a=new uI(this.createDiffOptions(t.id),this,o,this.workerManager,this.isContainerManaged);return{type:"diff",item:t,version:t.version,index:n,top:s,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:a}}const r=new EM(this.createFileOptions(t.id),this,o,this.workerManager,this.isContainerManaged);return{type:"file",item:t,version:t.version,index:n,top:s,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:r}}applySelectedLines(t,n){const{selectedLines:s}=this;t==null&&s==null||t!=null&&s?.id===t.id&&PM(s.range,t.range)||(s!=null&&s.id!==t?.id&&this.idToItem.get(s.id)?.instance.setSelectedLines(null,{notify:!1}),this.selectedLines=t,this.idToItem.get(t?.id??"")?.instance.setSelectedLines(t?.range??null,n))}syncSelection(){if(this.selectedLines==null)return;const t=this.idToItem.get(this.selectedLines.id);if(t==null){this.selectedLines=null,this.options.onSelectedLinesChange?.(null);return}t.instance.setSelectedLines(this.selectedLines.range,{notify:!1})}isItemInEditMode(t){return t.item.edit===!0&&t.item.collapsed!==!0}attachItemEditor(t){const{id:n}=t.item,{createEditor:s}=this.options;if(t.element==null||this.attachedEditors.has(n)||!this.isItemInEditMode(t))return;let o=this.itemEditors.get(n),r=!1;try{if(o==null){dK(s);const a={id:n},l=s({onChange:(c,d)=>{const u=this.idToItem.get(a.id);u!=null&&(a.lastChange={item:u.item,file:c,lineAnnotations:d},this.options.onItemEditChange?.(u.item,c,d))}});if(l==null)return;o={editor:l,state:a},this.itemEditors.set(n,o),r=!0}o.editor.edit(t.instance),this.attachedEditors.add(n)}catch(a){throw r&&o!=null&&(this.itemEditors.delete(n),o.editor.cleanUp()),this.releaseRenderedItem(t),a}}syncItemEditors(t){if(this.itemEditors.size===0)return;const n=[];for(const[s,o]of this.itemEditors){const r=this.idToItem.get(s),a=t?.get(s);if(a==null&&r!=null&&this.isItemInEditMode(r))continue;o.editor.cleanUp(),this.itemEditors.delete(s),this.attachedEditors.delete(s);const{lastChange:l}=o.state,c=a==null?r?.item??l?.item:l?.item??a.item;c?.type==="diff"&&(a==null&&r!=null&&r.type==="diff"&&r.instance.completeEditSession()&&(this.markItemLayoutDirty(r),this.render()),Um(c.fileDiff)),l!=null&&n.push(a!=null||r==null?l:{...l,item:r.item})}for(const{item:s,file:o,lineAnnotations:r}of n)this.options.onItemEditComplete?.(s,o,r)}renamePendingScrollTarget(t,n){const{pendingScrollTarget:s}=this;s==null||s.type==="position"||s.id!==t||(this.pendingScrollTarget={...s,id:n})}renamePendingLayoutAnchor(t,n){this.pendingLayoutAnchor?.id===t&&(this.pendingLayoutAnchor.id=n)}createFileOptionsPrototype(){const t={};for(const n of aK)Qi(t,n,()=>this.options[n]);Qi(t,"stickyHeader",()=>this.options.stickyHeaders),Qi(t,"collapsed",n=>{const s=Ha(n);if(s!=null)return this.getItemOptions(s,"file")?.item.collapsed});for(const n of Hy)this.defineItemSharedCallback(t,"file",n);for(const n of By)this.defineItemSelectionCallback(t,"file",n);return t}createDiffOptionsPrototype(){const t={};for(const n of rK)Qi(t,n,()=>this.options[n]);Qi(t,"stickyHeader",()=>this.options.stickyHeaders),Qi(t,"hunkSeparators",()=>this.options.hunkSeparators),Qi(t,"collapsed",n=>{const s=Ha(n);if(s!=null)return this.getItemOptions(s,"diff")?.item.collapsed});for(const n of Hy)this.defineItemSharedCallback(t,"diff",n);for(const n of By)this.defineItemSelectionCallback(t,"diff",n);return t}createFileOptions(t){const n=Object.create(this.fileOptionsPrototype);return Vy(n,{id:t}),n}createDiffOptions(t){const n=Object.create(this.diffOptionsPrototype);return Vy(n,{id:t}),n}updateItemOptionsId(t,n){const s=Ha(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){Qi(t,s,o=>{if(this.options[s]==null)return;const r=Ha(o);if(r==null)return;const a=r.callbackCache??={};let l=a[s];return l==null&&(l=((...c)=>{const d=this.getItemOptions(r,n);if(d==null)return;const u=this.options[s];return u?.(...c,d)}),a[s]=l),l})}defineItemSelectionCallback(t,n,s){Qi(t,s,o=>{const r=Ha(o);if(r==null)return;const a=r.callbackCache??={};let l=a[s];return l==null&&(l=(c=>{const d=this.getItemOptions(r,n);if(d==null)return;const u=c==null?null:{id:d.item.id,range:c};this.options.controlledSelection!==!0&&(c!=null||this.selectedLines?.id===d.item.id)&&this.applySelectedLines(u,{notify:!1}),this.options.onSelectedLinesChange?.(u);const h=this.options[s];return h?.(c,d)}),a[s]=l),l})}markLayoutDirtyFromIndex(t){this.layoutDirtyIndex=Math.min(this.layoutDirtyIndex??t,t)}markItemLayoutDirty(t){if(this.items[t.index]!==t)throw new Error(`CodeView.markItemLayoutDirty: unknown item id "${t.item.id}"`);this.markLayoutDirtyFromIndex(t.index)}tryAppendItems(t){if(t.length<=this.items.length)return!1;for(let n=0;n<this.items.length;n++){const s=this.items[n];if(s==null)throw new Error("CodeView.tryAppendItems: missing existing item");const o=t[n];if(o==null||s.item.id!==o.id||s.type!==o.type)return!1}for(let n=0;n<this.items.length;n++){const s=this.items[n];if(s==null)throw new Error("CodeView.tryAppendItems: missing existing item");const o=t[n];if(o==null)throw new Error("CodeView.tryAppendItems: append candidate missing prefix item");this.syncItemRecord(s,o)&&this.markLayoutDirtyFromIndex(n)}return this.appendItemsInternal(t.slice(this.items.length),!1),this.scrollDirty=!0,this.render(),!0}reconcileItems(t){const{items:n,idToItem:s}=this,o=new Set(n),r=[],a=new Map,l=new Map,c=new Map;let d;for(let u=0;u<t.length;u++){const h=t[u];if(h==null)throw new Error("CodeView.reconcileItems: missing input item");if(a.has(h.id))throw new Error(`CodeView.setItems: duplicate id "${h.id}"`);const p=s.get(h.id),f=p!=null&&p.type===h.type?p:this.createItem(h,u,0);f.index=u,p!=null&&p.type===h.type?(o.delete(p),this.syncItemRecord(f,h)&&(d=Math.min(d??u,u))):d=Math.min(d??u,u),n[u]!==f&&(d=Math.min(d??u,u)),r.push(f),a.set(h.id,f),l.set(f.instance,f)}if(d==null){if(o.size===0)return;d=Math.max(r.length-1,0)}this.capturePendingLayoutAnchor(a);for(let u=0;u<n.length;u++){const h=n[u];if(h==null||!o.has(h))continue;c.set(h.item.id,h),this.releaseRenderedItem(h);const p=Math.max(r.length-1,0);d=Math.min(d??p,p)}return this.items=r,this.idToItem=a,this.instanceToItem=l,this.renderState.firstIndex>=r.length?this.resetRenderState():this.renderState.lastIndex>=r.length&&(this.renderState.lastIndex=r.length-1),this.markLayoutDirtyFromIndex(d),this.scrollDirty=!0,this.render(),c.size>0?c:void 0}syncItemRecord(t,n){if(t.type!==n.type)throw new Error(`CodeView.syncItemRecord: type mismatch for id "${n.id}"`);return t.version===n.version?!1:(t.item=n,t.version=n.version,t.renderedOptionsRevision=-1,!0)}getMaxScrollTopForHeight(t){const{paddingBottom:n,paddingTop:s}=this.getLayout();return Math.max(s+this.header.height+t+this.footer.height+n-this.getHeight(),0)}getMaxScrollTop(){return this.getMaxScrollTopForHeight(this.getScrollHeight())}shouldRebaseScroll(){return this.getMaxScrollTop()>Uy}getPagedScrollHeight(){return this.shouldRebaseScroll()?Math.min(this.getScrollHeight(),mv):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=Ti(this.clampPagedScrollTop(n)),o=this.clampScrollPageOffset(t-s);return s=Ti(this.clampPagedScrollTop(t-o)),o=this.clampScrollPageOffset(t-s),{pagedScrollTop:s,scrollPageOffset:o}}resolvePagedScrollPosition(t){if(!this.shouldRebaseScroll())return{pagedScrollTop:this.clampPagedScrollTop(t),scrollPageOffset:0};const n=this.clampScrollPageOffset(this.scrollPageOffset),s=t-n,o=this.getMaxPagedScrollTop(),r=this.getMaxScrollPageOffset(),a=s>Uy&&n<r,l=s<fI&&n>0;return s<0||s>o||a||l?this.resolveScrollPageWindow(t,l?Math.min(cK,o):mI):{pagedScrollTop:Ti(this.clampPagedScrollTop(s)),scrollPageOffset:n}}needsScrollPageUpdate(t){const n=Ti(this.clampScrollTop(t)),{scrollPageOffset:s}=this.resolvePagedScrollPosition(n);return s!==this.scrollPageOffset}getPagedLayoutTop(t){return this.shouldRebaseScroll()?Math.max(t-this.scrollPageOffset,0):t}getStickyHeaderOffset(){return this.options.stickyHeaders===!0&&this.options.disableFileHeader!==!0?this.itemMetricsCache.diffHeaderHeight:0}getScrollTargetRect(t){const n=this.idToItem.get(t.id);if(n==null){console.warn(`CodeView.scrollTo: unknown item id "${t.id}"`);return}if(t.type==="item")return{top:n.top,height:n.height};if(t.type==="range"){const o=this.getRangeScrollPosition(n,t);if(o==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Ky(t.range)} for item "${t.id}"`);return}return{top:n.top+o.top,height:o.height}}const s=this.getLineScrollPosition(n,t);if(s==null){console.warn(`CodeView.scrollTo: unable to resolve line ${t.lineNumber} for item "${t.id}"`);return}return{top:n.top+s.top,height:s.height}}normalizeScrollTarget(t){if(t.type==="position"||t.align!=="nearest")return t;const n=this.getScrollTargetRect(t);if(n==null)return;const s=t.offset??0,o=this.getItemTopOffset()+n.top,r=o+n.height,a=this.getScrollTop(),l=a+(t.type==="line"||t.type==="range"?this.getStickyHeaderOffset():0),c=a+this.getHeight();if(!(o-s<=l&&r+s>=c)){if(o-s<l)return{...t,align:"start"};if(r+s>c)return{...t,align:"end"}}}resolveScrollTargetTop(t){if(t.type==="position"){const o=this.clampScrollTop(t.position);return o!==t.position?o:this.clampScrollTop(t.position-this.getStickyHeaderOffset())}const n=this.idToItem.get(t.id);if(n==null){console.warn(`CodeView.scrollTo: unknown item id "${t.id}"`);return}if(t.type==="item")return this.clampScrollTop(this.resolveAlignedScrollPosition(n.top,n.height,t.align,t.offset));if(t.type==="range"){const o=this.getRangeScrollPosition(n,t);if(o==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Ky(t.range)} for item "${t.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(n.top+o.top,o.height,t.align,t.offset,this.getStickyHeaderOffset()))}const s=this.getLineScrollPosition(n,t);if(s==null){console.warn(`CodeView.scrollTo: unable to resolve line ${t.lineNumber} for item "${t.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(n.top+s.top,s.height,t.align,t.offset,this.getStickyHeaderOffset()))}resolveAlignedScrollPosition(t,n,s,o=0,r=0){t+=this.getItemTopOffset();const a=this.getHeight();return s==="center"&&n+o<a?t-(a-n)/2+o:s==="end"?t-(a-n)+o:t-r-o}getLineScrollPosition(t,n){return t.type==="diff"?t.instance.getLinePosition(n.lineNumber,n.side):t.instance.getLinePosition(n.lineNumber)}getRangeScrollPosition(t,n){const{range:s}=n,o=this.getLineScrollPosition(t,{type:"line",id:n.id,lineNumber:s.start,side:s.side}),r=this.getLineScrollPosition(t,{type:"line",id:n.id,lineNumber:s.end,side:s.endSide??s.side});if(o==null||r==null)return;const a=o.top,l=a+o.height,c=r.top,d=c+r.height,u=Math.min(a,c);return{top:u,height:Math.max(l,d)-u}}computeTargetScrollTopForFrame(t,n){if(this.pendingScrollTarget==null)return t;const s=this.resolveScrollTargetTop(this.pendingScrollTarget);if(s==null)return t;const{scrollAnimation:o}=this;return o==null?s:this.computeSpringStep(o,s,n).position}computeSpringStep(t,n,s){const o=Math.max(0,s-t.lastTimestamp),{omega:r}=this.getSmoothScrollSettings(),a=Math.exp(-r*o),l=t.position-n,c=t.velocity+r*l;return{position:n+(l+c*o)*a,velocity:(c*(1-r*o)-r*l)*a}}advanceScrollAnimation(t,n){if(this.pendingScrollTarget==null)return;const s=this.resolveScrollTargetTop(this.pendingScrollTarget);if(s==null){this.pendingScrollTarget=void 0,this.scrollAnimation=void 0;return}const o=this.scrollAnimation;if(o==null)return s;o.position+=n;const{position:r,velocity:a}=this.computeSpringStep(o,s,t);o.lastTimestamp=t,o.position=r,o.velocity=a;const{positionEpsilon:l,velocityEpsilon:c}=this.getSmoothScrollSettings();return Math.abs(s-r)<=l&&Math.abs(a)<=c?(o.position=s,o.velocity=0,this.scrollAnimation=void 0,s):o.position}computeRenderRangeAndEmit=(t=performance.now())=>{if(io.__STOP||this.container==null||!this.isReady())return;const n=this.getHeight(),s=this.getScrollTop();let o=s,r=this.pendingLayoutAnchor!=null,a=this.getScrollAnchor(o);if(this.layoutDirtyIndex!=null&&(this.recomputeLayout(this.layoutDirtyIndex,this.pendingLayoutReset),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,r=!0),r&&a!=null){const k=this.resolveAnchoredScrollTop(a);if(k!=null){const S=k-o;o=k,this.scrollAnimation!=null&&(this.scrollAnimation.position+=S)}}r&&(o=this.clampScrollTop(o),this.syncContainerHeight());const l=this.computeTargetScrollTopForFrame(o,t),c=!r&&(this.renderState.scrollTop===-1||Math.abs(l-this.renderState.scrollTop)>n+this.config.overscrollSize*2);c&&(a=void 0),this.windowSpecs=AM({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 k=p;k<=f;k++){const S=this.items[k];if(S==null)throw new Error(`CodeView.computeRenderRangeAndEmit: No item at index: ${k}`);S.top>u-S.height&&S.top<=h||this.releaseRenderedItem(S)}const g=this.reconcileHeaderFooterHosts();let x;const v=new Set,y=this.findFirstVisibleIndex(u),b=this.findLastVisibleIndex(h);for(let k=y;k<=b;k++){const S=this.items[k];if(S==null)throw new Error("CodeView.computeRenderRangeAndEmit: missing item");const{instance:A}=S;S.element==null?(S.element=this.acquireElement(),Xy(this.stickyContainer,S.element,x),A.virtualizedSetup(),Yy(S,S.element)&&(S.renderedOptionsRevision=this.renderOptionsRevision,v.add(S)),x=S.element):(Xy(this.stickyContainer,S.element,x),Yy(S,void 0,S.renderedOptionsRevision!==this.renderOptionsRevision)&&(S.renderedOptionsRevision=this.renderOptionsRevision,v.add(S)),x=S.element),S.item.edit===!0&&this.attachItemEditor(S)}this.renderState.firstIndex=y<=b?y:-1,this.renderState.lastIndex=b,this.flushSlotCoordinator(),this.flushManagers(v),g&&this.measureMountedHosts(),this.reconcileRenderedItems(v),this.syncContainerHeight(),this.updateStickyPositioning();const w=a!=null?this.resolveAnchoredScrollTop(a):void 0;a===this.pendingLayoutAnchor&&(this.pendingLayoutAnchor=void 0);const C=w!=null?w-o:0;let _=l,N=!1;if(this.pendingScrollTarget!=null){const k=this.advanceScrollAnimation(t,C);k!=null?(_=k,N=!0):_=o}else _=w??l;_!==d&&(this.applyScrollFix(_,d,this.windowSpecs),d=_),N&&this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),this.renderState.scrollTop=Ti(d),this.updateStickyPositioning(),this.validateStickyContainerHeight(),this.fixContainerFocus(),(c||this.scrollAnimation!=null)&&this.render()};flushManagers(t){for(const n of t)n.instance.flushManagers()}syncContainerHeight(){const t=this.getPagedScrollHeight();this.container==null||this.containerHeight===t||(this.container.style.height=`${t}px`,this.containerHeight=t)}getStickyBounds(t){const{firstIndex:n,lastIndex:s}=t!=null?{firstIndex:this.findFirstVisibleIndex(t.top),lastIndex:this.findLastVisibleIndex(t.bottom)}:this.renderState;if(n===-1||s===-1||n>s)return;const o=this.items[n]?.instance.getAdvancedStickySpecs(t),r=this.items[s]?.instance.getAdvancedStickySpecs(t);if(!(o==null||r==null))return{stickyTop:this.getPagedLayoutTop(Math.max(o.topOffset,0)),stickyBottom:this.getPagedLayoutTop(r.topOffset+r.height)}}applyStickyPositioning({stickyTop:t,stickyBottom:n}){const s=this.getHeight(),{itemMetricsCache:o}=this,r=n-t;this.renderState.stickyHeight=r,this.renderState.stickyTop=t,this.renderState.stickyBottom=n,this.stickyOffset.style.height=`${t}px`;const a=(Math.random()*o.lineHeight>>0)*-1,l=-Math.max(r+a,0)+s;this.stickyContainer.style.top=`${l}px`,this.stickyContainer.style.bottom=`${l+o.diffHeaderHeight}px`}syncPagedScrollScaffolding(t){this.syncContainerHeight();const n=this.getStickyBounds(t);n!=null&&this.applyStickyPositioning(n)}reconcileRenderedItems(t){const{firstIndex:n,lastIndex:s}=this.renderState;if(n===-1)return;let o=-1,r=!1;for(let a=n;a<this.items.length&&!(!r&&a>s);a++){const l=this.items[a];if(l==null)throw new Error("CodeView.reconcileRenderedItems: Invalid item");o===-1?o=l.top:l.top!==o&&(l.top=o,l.instance.syncVirtualizedTop(),r=!0),(t==null?a<=s:t.has(l))&&(l.instance.reconcileHeights()&&(r=!0,l.height=l.instance.getVirtualizedHeight()),this.validateRenderedItemHeight(l)),o+=l.instance.getVirtualizedHeight(),a<this.items.length-1&&(o+=this.getLayout().gap)}r&&o!=null&&(this.scrollDirty=!0,this.scrollHeight=o)}updateStickyPositioning(){const t=this.getStickyBounds();if(t==null){this.renderState.firstIndex===-1&&(this.stickyOffset.style.height="");return}const{stickyTop:n,stickyBottom:s}=t;s-n===this.renderState.stickyHeight&&n===this.renderState.stickyTop&&s===this.renderState.stickyBottom||this.applyStickyPositioning(t)}handleScroll=()=>{io.__STOP||(this.suspendScrollInteractions(),this.scrollDirty=!0,this.notifyScroll(),this.render())};clearPendingScroll=()=>{this.pendingScrollTarget=void 0,this.pendingLayoutAnchor=void 0,this.scrollAnimation=void 0};handleResize=t=>{let n=!1;for(const s of t)if(s.target===this.stickyContainer){const o=s.borderBoxSize[0].blockSize;if(Math.abs(o-this.renderState.stickyHeight)>=$y){const r=this.getScrollTop(),a=this.getScrollAnchor(r);this.reconcileRenderedItems(),this.updateStickyPositioning();const l=a!=null?this.resolveAnchoredScrollTop(a):void 0;if(l!=null){const c=l-r;this.applyScrollFix(l,r,this.windowSpecs),this.scrollAnimation!=null&&(this.scrollAnimation.position+=c)}this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),n=!0}}else if(s.target===this.header.element||s.target===this.footer.element){const o=s.target===this.header.element?this.header:this.footer,r=s.borderBoxSize[0].blockSize;if(r!==o.height){const a=this.getScrollTop(),l=this.getScrollAnchor(a);this.setHostHeight(o,r);const c=l!=null?this.resolveAnchoredScrollTop(l):void 0;if(c!=null){const d=c-a;this.applyScrollFix(c,a,this.windowSpecs),this.scrollAnimation!=null&&(this.scrollAnimation.position+=d)}this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),n=!0}}else this.scrollDirty=!0,this.heightDirty=!0,n=!0;n&&this.render(!0)};getScrollAnchorViewportTop(t,n){return t<n?n+this.getStickyHeaderOffset():n}getScrollAnchor(t,n=this.idToItem){let s;const{pendingLayoutAnchor:o}=this;if(o!=null){const u=this.idToItem.get(o.id);if(u!=null&&n.get(o.id)===u)return o;u!=null&&(s=u)}if(t<=0)return;const{firstIndex:r,lastIndex:a,stickyTop:l,stickyBottom:c}=this.renderState;if(r===-1||a===-1)return;const d=this.getHeight();if(!(l===-1||c===-1)){for(let u=r;u<=a;u++){const h=this.items[u];if(h==null)continue;const p=this.getItemTopOffset()+h.top;if(p+h.height<=t)continue;if(p>=t+d)break;if(n.get(h.item.id)!==h){s??=h;continue}if(p>=t)return{type:"item",id:h.item.id,viewportOffset:p-t};const f=this.getScrollAnchorViewportTop(p,t)-p,g=h.instance.getNumericScrollAnchor(f);if(g!=null){const x=p+g.top;return{type:"line",id:h.item.id,lineNumber:g.lineNumber,side:g.side,viewportOffset:x-t}}}if(s!=null)for(let u=s.index+1;u<this.items.length;u++){const h=this.items[u];if(h!=null&&n.get(h.item.id)===h)return{type:"item",id:h.item.id,viewportOffset:0}}}}resolveAnchoredScrollTop(t){const n=this.idToItem.get(t.id);if(n==null)return;const s=this.getItemTopOffset();if(t.type==="item"){const a=s+n.top;return this.clampScrollTop(a-t.viewportOffset)}const o=n.type==="diff"?n.instance.getLinePosition(t.lineNumber,t.side):n.instance.getLinePosition(t.lineNumber);if(o==null)return;const r=s+n.top+o.top;return this.clampScrollTop(r-t.viewportOffset)}applyScrollFix(t,n,s){if(this.root==null)return;const o=Ti(this.clampScrollTop(t)),r=Ti(n),{scrollPageOffset:a}=this,l=Ti(this.clampPagedScrollTop(r-a)),{pagedScrollTop:c,scrollPageOffset:d}=this.resolvePagedScrollPosition(o),u=c,h=a!==d;o===this.renderState.scrollTop&&o===r&&u===l&&!h||(this.suspendScrollInteractions(),(u!==l||h)&&(this.scrollPageOffset=d,this.syncPagedScrollScaffolding(s)),u!==l&&this.root.scrollTo({top:u,behavior:"instant"}),this.renderState.scrollTop=o,this.scrollTop=o,this.scrollDirty=!1)}isPendingTargetSettled(t){const n=this.resolveScrollTargetTop(t);return n==null?!0:Ti(this.getScrollTop())===Ti(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);hI(this.slotSnapshot,t)||(this.slotSnapshot=t,this.slotCoordinator.onSnapshotChange(t))}notifyScroll(){if(this.scrollListeners.size===0)return;const t=this.getScrollTop();for(const n of this.scrollListeners)n(t,this)}findFirstVisibleIndex(t){let n=0,s=this.items.length-1,o=this.items.length;for(;n<=s;){const r=n+s>>1,a=this.items[r];if(a==null)throw new Error("CodeView.findFirstVisibleIndex: invalid item index");a.top+a.height>t?(o=r,s=r-1):n=r+1}return o}findLastVisibleIndex(t){let n=0,s=this.items.length-1,o=-1;for(;n<=s;){const r=n+s>>1,a=this.items[r];if(a==null)throw new Error("CodeView.findLastVisibleIndex: invalid item index");a.top<=t?(o=r,n=r+1):s=r-1}return o}recomputeLayout(t=0,n){if(this.items.length===0){this.scrollHeight=0;return}const s=this.getLayout();let o=0;if(t>0){const r=this.items[t-1];if(r==null)throw new Error("CodeView.recomputeLayout: invalid dirty index");o=r.top+r.height+s.gap}for(let r=t;r<this.items.length;r++){const a=this.items[r];if(a==null)throw new Error("CodeView.recomputeLayout: invalid item index");if(a.top=o,a.type==="diff"){const l=a.instance.consumeCodeViewLayoutChanges(a.item.fileDiff);l!=null&&Object.assign(a.item.fileDiff,l),a.height=a.instance.prepareCodeViewItem(a.item.fileDiff,o,n,a.item.annotations??[])}else a.height=a.instance.prepareCodeViewItem(a.item.file,o,n,a.item.annotations??[]);o+=a.height,r<this.items.length-1&&(o+=s.gap)}o!==this.scrollHeight&&(this.scrollDirty=!0),this.scrollHeight=o}resetRenderState(){this.renderState.scrollTop=-1,this.renderState.firstIndex=-1,this.renderState.lastIndex=-1,this.renderState.stickyHeight=0,this.renderState.stickyTop=-1,this.renderState.stickyBottom=-1}getFitPerfectlyOverscroll(){return this.getLayout().gap+this.itemMetricsCache.diffHeaderHeight}};function pK(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 fK(e,t){return!rj(e.theme??Li,t.theme??Li)||(e.themeType??"system")!==(t.themeType??"system")||e.unsafeCSS!==t.unsafeCSS}function mK(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 gK(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 xK(e){return e instanceof SVGElement?!0:Lf(e)&&(e.hasAttribute("data-core-css")||e.hasAttribute("data-theme-css")||e.hasAttribute("data-unsafe-css"))}function Ky(e){const t=qy(e.start,e.side),n=qy(e.end,e.endSide??e.side);return t===n?t:`${t}-${n}`}function qy(e,t){return t==null?`${e}`:`${t==="deletions"?"D":"A"}${e}`}function Yy(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 Xy(e,t,n){if(n==null){e.firstChild!==t&&e.prepend(t);return}n.nextSibling!==t&&n.after(t)}function vK(e){return(e.annotations?.length??0)>0}function bK(e,{hasHeaderRenderers:t,hasAnnotationRenderer:n,hasGutterRenderer:s}){if(e.length===0)return;if(t||s)return e;if(!n)return;const o=[];for(const r of e)vK(r.item)&&o.push(r);return o.length>0?o:void 0}function wK({hunkIndex:e,lineIndex:t,conflictIndex:n}){return`merge-conflict-action-${e}-${t}-${n}`}function yK(e,t){const n=t.hunks[e.hunkIndex];if(n!=null)return{hunkIndex:e.hunkIndex,lineIndex:SK(n,e.startContentIndex)}}function SK(e,t){let n=e.unifiedLineStart;for(let s=0;s<t;s++){const o=e.hunkContent[s];n+=o.type==="context"?o.lines:o.deletions+o.additions}return n}function gI({fileDiff:e,actions:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderMergeConflictUtility:c,lineAnnotations:d,getHoveredLine:u,getInstance:h}){const p=n?.(e),f=s?.(e),g=o?.(e),x=r?.(e);return i.jsxs(i.Fragment,{children:[p!=null?i.jsx("div",{slot:cj,children:p}):i.jsxs(i.Fragment,{children:[f!=null&&i.jsx("div",{slot:"header-prefix",children:f}),g!=null&&i.jsx("div",{slot:"header-filename-suffix",children:g}),x!=null&&i.jsx("div",{slot:"header-metadata",children:x})]}),a!=null&&d?.map((v,y)=>i.jsx("div",{slot:ua(v),children:a(v)},y)),t!=null&&c!=null&&h!=null&&t.map(v=>{if(v==null)return;const y=CK(v,e);return i.jsx("div",{slot:y,style:MM,children:c(v,h)},y)}),l!=null&&i.jsx("div",{slot:"gutter-utility-slot",style:RM,children:l(u)})]})}function CK(e,t){const n=yK(e,t);return n!=null?wK({hunkIndex:n.hunkIndex,lineIndex:n.lineIndex,conflictIndex:e.conflictIndex}):void 0}const Jy=typeof window>"u"?m.useEffect:m.useLayoutEffect;function Zy(e){return{instance:void 0,items:void 0,controlled:e,managedOptions:void 0,disableFlushSync:!1,slotCoordinator:void 0}}function kK(e,t){const{className:n,containerRef:s,disableWorkerPool:o=!1,editorOptions:r,initialItems:a,items:l,onItemEditChange:c,onItemEditComplete:d,onScroll:u,onSelectedLinesChange:h,options:p,renderAnnotation:f,renderCodeViewFooter:g,renderCodeViewHeader:x,renderCustomHeader:v,renderGutterUtility:y,renderHeaderFilenameSuffix:b,renderHeaderMetadata:w,renderHeaderPrefix:C,selectedLines:_,style:N}=e,k=l!==void 0,S=pj(),A=m.useContext(fj),T=m.useRef(Zy(k)),I=v!=null,P=f!=null,D=y!=null,O=I||C!=null||b!=null||w!=null,z=O||P||D,R=x!=null,$=g!=null,X=ro(U=>{h?.(U)}),H=_!==void 0,te=ro(U=>{if(S==null)throw new Error("CodeView: EditContext is not attached");const oe=S({...r,...U});if(oe==null)throw new Error("CodeView: EditProvider.createEditor must return an editor instance");return oe}),V=ro((U,oe,Se)=>{c?.(U,oe,Se)}),Y=ro((U,oe,Se)=>{d?.(U,oe,Se)}),q=m.useMemo(()=>TK({options:p,hasCustomHeader:I,hasGutterRenderer:D,hasCodeViewHeader:R,hasCodeViewFooter:$,onSelectedLinesChange:h!=null?X:void 0,controlledSelection:H,createEditor:S!=null?te:void 0,onItemEditChange:c!=null?V:void 0,onItemEditComplete:d!=null?Y:void 0}),[S,H,te,V,Y,X,$,R,I,D,c,d,h,p]),[ee]=m.useState(()=>NK()),[,ge]=m.useState({}),Ce=ro(U=>{T.current.instance!=null&&(U==null||U!==T.current.instance.getContainerElement())&&(T.current.instance.cleanUp(),ee.publish(void 0),T.current=Zy(k)),U!=null&&U!==T.current.instance?.getContainerElement()&&(T.current.instance=new hK(q,o?void 0:A,!0),T.current.instance.setup(U)),typeof s=="function"?s(U):s!=null&&(s.current=U)}),Re=ro(U=>{T.current.disableFlushSync?ee.publish(U):qs.flushSync(()=>{ee.publish(U)})}),fe=m.useMemo(()=>{if(!(!O&&!P&&!D&&!R&&!$))return{hasHeaderRenderers:O,hasAnnotationRenderer:P,hasGutterRenderer:D,onSnapshotChange:Re}},[Re,P,D,O,R,$]);return Jy(()=>u!=null?T.current.instance?.subscribeToScroll(u):void 0),Jy(()=>{const{instance:U,controlled:oe,items:Se,managedOptions:G,slotCoordinator:Q}=T.current;if(U!=null)try{T.current.disableFlushSync=!0;let ae=!1;if(th(q,G)||(T.current.managedOptions=q,U.setOptions(q),ae=!0),oe!==k){console.error("CodeView: cannot switch between controlled and uncontrolled modes. Remount with a new key instead.");return}if(k)l!==Se&&(_K(Se,l)?T.current.items=l:jK(Se,l)?(T.current.items=l,U.addItems(l.slice(Se.length))):(T.current.items=l,U.setItems(l),ae=!0));else if(Se==null){const De=a??[];T.current.items=De,De.length>0&&(U.setItems(De),ae=!0)}_!==void 0&&U.setSelectedLines(_,{notify:!1});const Z=U.setSlotCoordinator(fe);let ce=!1;fe!==Q&&((fe==null||Q==null)&&(ce=!0),T.current.slotCoordinator=fe),(ae||Z)&&U.render(!0),Z&&fe==null&&ee.publish(void 0),ce&&ge({})}finally{T.current.disableFlushSync=!1}}),m.useImperativeHandle(t,()=>({addItems(U){const{controlled:oe,instance:Se}=T.current;nd(oe,"addItems"),Se==null?console.error("CodeView.addItems: no valid instance to append items with",U):Se.addItems(U)},getItem(U){const{instance:oe}=T.current;if(oe==null){console.error("CodeView.getItem: no valid instance exists",U);return}else return oe.getItem(U)},removeItem(U){const{controlled:oe,instance:Se}=T.current;return nd(oe,"removeItem"),Se==null?(console.error("CodeView.removeItem: no valid instance to remove item from",U),!1):Se.removeItem(U)},updateItem(U){const{controlled:oe,instance:Se}=T.current;return nd(oe,"updateItem"),Se==null?(console.error("CodeView.updateItem: no valid instance to update item with",U),!1):Se.updateItem(U)},updateItemId(U,oe){const{controlled:Se,instance:G}=T.current;return nd(Se,"updateItemId"),G==null?(console.error("CodeView.updateItemId: no valid instance to update item id with",U,oe),!1):G.updateItemId(U,oe)},scrollTo(U){const{instance:oe}=T.current;oe==null?console.error("CodeView.scrollTo: no valid instance to scroll with",U):oe.scrollTo(U)},setSelectedLines(U){const{instance:oe}=T.current;oe==null?console.error("CodeView.setSelectedLines: no valid instance to update selection with",U):(oe.setSelectedLines(U,{notify:!1}),X(U))},getSelectedLines(){const{instance:U}=T.current;return U==null?(console.error("CodeView.getSelectedLines: no valid instance exists"),null):U.getSelectedLines()},clearSelectedLines(){const{instance:U}=T.current;U==null?console.error("CodeView.clearSelectedLines: no valid instance to update selection with"):(U.clearSelectedLines({notify:!1}),X(null))},getEditor(U){const{instance:oe}=T.current;if(oe==null){console.error("CodeView.getEditor: no valid instance exists",U);return}return oe.getEditor(U)},getInstance(){return T.current.instance}}),[X]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:Ce,className:n,style:N}),(z||R||$)&&i.jsx(IK,{managedContentStore:ee,renderCustomHeader:v,renderHeaderPrefix:C,renderHeaderFilenameSuffix:b,renderHeaderMetadata:w,renderAnnotation:f,renderGutterUtility:y,renderCodeViewHeader:x,renderCodeViewFooter:g})]})}const xI=m.forwardRef(kK);function jK(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 _K(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 nd(e,t){if(e)throw new Error(`CodeView.${t} cannot be used when CodeView is controlled. Use initialItems for imperative item updates.`)}function NK(){let e;const t=new Set;return{getSnapshot(){return e},publish(n){if(!hI(e,n)){e=n;for(const s of t)s()}},subscribe(n){return t.add(n),()=>{t.delete(n)}}}}function TK({options:e,hasCustomHeader:t,hasGutterRenderer:n,hasCodeViewHeader:s,hasCodeViewFooter:o,onSelectedLinesChange:r,controlledSelection:a,createEditor:l,onItemEditChange:c,onItemEditComplete:d}){const u={...e,controlledSelection:a,onSelectedLinesChange:r,createEditor:l};return c!=null&&(u.onItemEditChange=c),d!=null&&(u.onItemEditComplete=d),t&&(u.renderCustomHeader=sd),n&&(u.renderGutterUtility=sd),s&&(u.renderCodeViewHeader=sd),o&&(u.renderCodeViewFooter=sd),u}const IK=m.memo(function({managedContentStore:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderCodeViewHeader:c,renderCodeViewFooter:d}){"use no memo";const u=ro(g=>t.subscribe(g)),h=ro(()=>t.getSnapshot()),p=m.useSyncExternalStore(u,h,h);let f="";for(const g of p?.items??[])f+=`${g.id}:${g.version}:${g.type}`;return i.jsxs(i.Fragment,{children:[m.useMemo(()=>p?.items?.map(g=>qs.createPortal(DK({renderedItem:g,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l}),g.element,g.id)),[n,s,o,r,a,l,f]),m.useMemo(()=>c!=null&&p?.header!=null?qs.createPortal(c(),p.header):null,[c,p?.header]),m.useMemo(()=>d!=null&&p?.footer!=null?qs.createPortal(d(),p.footer):null,[d,p?.footer])]})});function DK({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderFilenameSuffix:s,renderHeaderMetadata:o,renderAnnotation:r,renderGutterUtility:a}){if(e.type==="diff"){const{item:l,instance:c}=e;return gI({fileDiff:l.fileDiff,renderCustomHeader:t!=null?()=>t(l):void 0,renderHeaderPrefix:n!=null?()=>n(l):void 0,renderHeaderFilenameSuffix:s!=null?()=>s(l):void 0,renderHeaderMetadata:o!=null?()=>o(l):void 0,renderAnnotation:r!=null?d=>r(d,l):void 0,lineAnnotations:l.annotations,renderGutterUtility:a!=null?d=>a(d,l):void 0,getHoveredLine:c.getHoveredLine})}else{const{item:l,instance:c}=e;return LM({file:l.file,renderCustomHeader:t!=null?()=>t(l):void 0,renderHeaderPrefix:n!=null?()=>n(l):void 0,renderHeaderFilenameSuffix:s!=null?()=>s(l):void 0,renderHeaderMetadata:o!=null?()=>o(l):void 0,renderAnnotation:r!=null?d=>r(d,l):void 0,lineAnnotations:l.annotations,renderGutterUtility:a!=null?d=>a(d,l):void 0,getHoveredLine:c.getHoveredLine})}}function sd(){}const Qy=typeof window>"u"?m.useEffect:m.useLayoutEffect;function EK({fileDiff:e,options:t,editorOptions:n,lineAnnotations:s,selectedLines:o,prerenderedHTML:r,metrics:a,hasGutterRenderUtility:l,hasCustomHeader:c,disableWorkerPool:d,edit:u}){const h=OM(),p=o!==void 0,f=m.useContext(fj),g=pj(),x=m.useRef(null),v=ro(y=>{if(y!=null){if(x.current!=null)throw new Error("useFileDiffInstance: An instance should not already exist when a node is created");h!=null?x.current=new uI(Zp({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),h,a,d?void 0:f,!0):x.current=new dI(Zp({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),d?void 0:f,!0),x.current.hydrate({fileDiff:e,fileContainer:y,lineAnnotations:s,prerenderedHTML:r})}else{if(x.current==null)throw new Error("useFileDiffInstance: A FileDiff instance should exist when unmounting");x.current.cleanUp(),x.current=null}});return Qy(()=>{const{current:y}=x;if(y==null)return;const b=Zp({controlledSelection:p,hasCustomHeader:c,hasGutterRenderUtility:l,options:t}),w=b!==void 0&&!th(y.options,b);y.setOptions(b),y.render({forceRender:w,fileDiff:e,lineAnnotations:s}),o!==void 0&&y.setSelectedLines(o)}),Qy(()=>{if(u&&x.current!=null){if(g===void 0)throw new Error("FileDiff: EditContext is not attached");const y=g(n??{});if(y==null)throw new Error("FileDiff: EditProvider.createEditor must return an editor instance");try{return y.edit(x.current)}catch(b){throw y.cleanUp(),b}}},[u]),{ref:v,getHoveredLine:m.useCallback(()=>x.current?.getHoveredLine(),[])}}function Zp({options:e,controlledSelection:t,hasCustomHeader:n,hasGutterRenderUtility:s}){return t||s||n?{...e,controlledSelection:t,renderCustomHeader:n?y0:e?.renderCustomHeader,renderGutterUtility:s?y0:e?.renderGutterUtility}:e}function PK({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:o,selectedLines:r,className:a,style:l,prerenderedHTML:c,renderAnnotation:d,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderGutterUtility:g,disableWorkerPool:x=!1,edit:v=!1}){const{ref:y,getHoveredLine:b}=EK({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:o,selectedLines:r,prerenderedHTML:c,hasGutterRenderUtility:g!=null,hasCustomHeader:u!=null,disableWorkerPool:x,edit:v});return i.jsx(hj,{ref:y,className:a,style:l,children:zM(gI({fileDiff:e,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderAnnotation:d,renderGutterUtility:g,lineAnnotations:o,getHoveredLine:b}),c)})}function AK(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 MK(e,t){const n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(s=>e[s]===t[s])}function vI(e,t){let n=e;for(let s=t.length-1;s>=0;s--){const{oldText:o,newText:r}=t[s];if(r===""&&n!=="")return null;const a=n.indexOf(r);if(a===-1)return null;n=n.slice(0,a)+o+n.slice(a+r.length)}return n}function RK(e){const t=new Map;for(const r of e.tools){if(!r.path)continue;const a=t.get(r.path)??[];a.push(r),t.set(r.path,a)}const n=[],s=new Set(Object.entries(e.snapshots).flatMap(([r,a])=>a===null?[r]:[])),o={...e.snapshots};for(const[r,a]of t){const l=e.currentByPath[r],c=a.flatMap(b=>b.edits??[]),d=a.flatMap(b=>b.fileChange&&b.fileChange.truncated!==!0?[b.fileChange]:[]),u=[...a].reverse().find(b=>b.writeContent!=null)?.writeContent,h=a.find(b=>b.fileChange)?.fileChange,p=[...a].reverse().find(b=>b.fileChange||b.writeContent!=null||b.edits?.length),f=p?.fileChange?p.fileChange.truncated===!0?null:p.fileChange.newText:p?.writeContent??null,g=Object.hasOwn(o,r),x=o[r];if(!g&&h?.truncated===!0){o[r]=null,s.add(r);continue}if(g&&x===null){s.add(r);continue}let v=typeof x=="string"?x:d[0]?.oldText??null;const y=typeof l=="string"?l:f;v==null&&(c.length>0&&typeof l=="string"?v=vI(l,c):u!=null&&c.length===0&&(v="")),y==null&&p?.fileChange?.truncated===!0&&s.add(r),!(v==null||y==null)&&(v===y&&d.length===0||(o[r]=v,n.push({path:r,oldText:v,newText:y})))}return{files:n,snapshots:o,...s.size>0?{incompletePaths:[...s]}:{}}}const gv=m.createContext(null),LK={theme:ka,diffStyle:"split",lineDiffType:"word",disableFileHeader:!0,preferredHighlighter:"shiki-js",overflow:"wrap"};function eS({path:e,blocks:t,snapshot:n}){const{t:s}=ne(),o=e.split("/").pop()||"file",[r,a]=m.useState({kind:"loading"}),l=m.useContext(gv),c=m.useContext(nh),d=l??c,u=d?.conversationId,h=d?.projectId,p=d?Gg(e,d.cwd):null,f=d&&p===null&&mj(e)?e:null;return m.useEffect(()=>{let g=!0;if(n)return a({kind:"loading"}),ha().then(()=>{g&&a({kind:"full",oldText:n.oldText,newText:n.newText})}).catch(()=>{g&&a({kind:"blocks"})}),()=>{g=!1};const x=u&&h&&p?window.electronAPI.files.read({conversationId:u,projectId:h,rel:p}):u&&h&&f?window.electronAPI.files.read({conversationId:u,projectId:h,path:f}):Promise.resolve(null);return Promise.all([ha(),x]).then(([,v])=>{if(!g)return;const y=typeof v=="string"?vI(v,t):null;a(y!=null&&typeof v=="string"?{kind:"full",oldText:y,newText:v}:{kind:"blocks"})}).catch(()=>{g&&a({kind:"blocks"})}),()=>{g=!1}},[t,u,f,h,p,n]),r.kind==="loading"?i.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs text-muted-foreground",children:s("Loading diff…")}):i.jsx("div",{className:"border-t border-border/60 text-xs",children:r.kind==="full"?i.jsx(tS,{name:o,oldText:r.oldText,newText:r.newText}):t.map((g,x)=>i.jsx(tS,{name:o,oldText:g.oldText,newText:g.newText},x))})}function tS({name:e,oldText:t,newText:n}){const s=dc(LK),o=m.useMemo(()=>{const r=yo({name:e,contents:t},{name:e,contents:n});return r.cacheKey=hv(e,t,n),r},[e,t,n]);return i.jsx(PK,{fileDiff:o,options:s})}function Jm({hits:e,defaultOpen:t=!1}){const{t:n}=ne();return e.length===0?i.jsx("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("No results")}):i.jsx("ul",{className:"divide-y divide-border/60",children:e.map(s=>i.jsx(zK,{hit:s,defaultOpen:t},s.id))})}function OK({view:e}){const{t}=ne(),n=e.written?e.deduplicated&&t("Identical memory already exists, nothing new was written"):t("Similar memories already exist, nothing was written");return i.jsxs(i.Fragment,{children:[n&&i.jsx("p",{className:"px-3 pt-2 text-xs text-muted-foreground",children:n}),e.written?i.jsx(Jm,{hits:[e.memory],defaultOpen:!0}):i.jsx(Jm,{hits:e.candidates})]})}function zK({hit:e,defaultOpen:t}){const{t:n}=ne(),[s,o]=m.useState(t);return i.jsx("li",{children:i.jsxs("button",{type:"button","aria-expanded":s,onClick:r=>{const a=window.getSelection();a?.toString()&&r.currentTarget.contains(a.anchorNode)||o(l=>!l)},className:"block w-full cursor-pointer px-3 py-2 text-left transition-colors hover:bg-muted/40",children:[i.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:W("min-w-0 flex-1 font-medium text-foreground text-xs",s?"break-words":"truncate"),children:e.title}),e.unitType&&i.jsx(pa,{variant:"secondary",size:"sm",children:e.unitType}),e.space&&i.jsx(pa,{variant:"outline",size:"sm",children:n(e.space==="global"?"Global":"Project")}),e.relevance!==null&&i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",title:n("Semantic similarity"),children:e.relevance.toFixed(2)})]}),i.jsx("span",{className:W("mt-0.5 whitespace-pre-wrap break-words text-muted-foreground text-xs leading-relaxed",s?"block":"line-clamp-2"),children:e.content})]})})}const GK={"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 xv(e){return W("inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",GK[e])}function FK({label:e,onRemove:t}){return i.jsx("button",{type:"button",onClick:t,className:"rounded-sm opacity-70 transition-opacity hover:opacity-100","aria-label":e,children:i.jsx(dn,{className:"h-3 w-3"})})}function HK({recipient:e,onRemove:t}){const{t:n}=ne();return i.jsxs("span",{className:W(xv("agent-type"),"mt-0.5 shrink-0"),children:[i.jsx(Ws,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:e.label}),i.jsx(FK,{label:n("Remove Agent recipient"),onRemove:t}),i.jsx("span",{className:"sr-only",children:e.typeKey})]})}const vv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bI(e){if(!e)return null;try{const t=JSON.parse(e);return vv(t)?t:null}catch{return null}}function Zm(e,t){if(!Array.isArray(e))return null;const n=[];for(const s of e){if(!vv(s)||typeof s.id!="string"||!s.id||typeof s.title!="string"||typeof s.content!="string")return null;const{spaceId:o,[t]:r}=s;n.push({id:s.id,title:s.title,content:s.content,unitType:typeof s.unitType=="string"&&s.unitType?s.unitType:null,space:o==="global"?"global":typeof o=="string"&&o.startsWith("proj:")?"project":null,relevance:typeof r=="number"&&Number.isFinite(r)?r:null})}return n}function BK(e){const t=bI(e);return t?Zm(t.results,"relevance"):null}function VK(e,t){const n=bI(e);if(n?.status==="candidates_found"){const o=Zm(n.candidates,"similarity");return o?{written:!1,candidates:o}:null}if(n?.status!=="inserted"||!vv(n.memory)||!t)return null;const s=Zm([{...n.memory,content:t}],"relevance")?.[0];return s?{written:!0,deduplicated:n.deduplicated===!0,memory:s}:null}const wI=m.createContext(void 0);function Pc(e){const t=m.useContext(wI);if(t===void 0&&!e)throw new Error(uc(50));return t}const $K=600,yI=300,WK={...FM,instantType:e=>e.instantType,adaptiveOrigin:e=>e.adaptiveOrigin,closeDelay:e=>e.closeDelay};class UK extends GM{constructor(t,n,s){const o=new $M;super(KK(t,o,n,s),qK(o),WK)}setOpen=(t,n)=>{const{inlineRectCoordsRef:s}=this.context;HM(this,t,n,{onBeforeDispatch(){const o=n.event;t&&n.reason===WM&&n.trigger&&"clientX"in o&&"clientY"in o&&s.current?.element!==n.trigger&&cT(s,n.trigger,o.clientX,o.clientY)}})}}function KK(e,t,n,s=!1){const o={...BM(),instantType:void 0,adaptiveOrigin:void 0,closeDelay:yI,...e};return o.floatingRootContext=VM(t,n,s),o}function qK(e){return{popupRef:m.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e,inlineRectCoordsRef:{current:void 0}}}function nS(e){const{open:t,defaultOpen:n=!1,onOpenChange:s,onOpenChangeComplete:o,actionsRef:r,handle:a,triggerId:l,defaultTriggerId:c=null,children:d}=e,u=qM((y,b)=>new UK({open:n,openProp:t,activeTriggerId:c,triggerIdProp:l},y,b));u.useControlledProp("openProp",t),u.useControlledProp("triggerIdProp",l),u.useContextCallback("onOpenChange",s),u.useContextCallback("onOpenChangeComplete",o);const h=u.useState("open"),p=u.useState("activeTriggerId"),f=u.useState("mounted"),g=u.useState("payload");YM(u,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:x}=XM(h,u,()=>{u.context.inlineRectCoordsRef.current=void 0});Fg(()=>{h&&p==null&&u.set("payload",void 0)},[u,p,h]),m.useImperativeHandle(r,()=>({unmount:x,close:()=>u.setOpen(!1,JM(ZM))}),[x,u]);const v=h||f;return i.jsxs(wI.Provider,{value:u,children:[a&&i.jsx(QM,{handle:a,store:u}),v&&i.jsx(YK,{store:u}),typeof d=="function"?d({payload:g}):d]})}function YK({store:e}){const t=e.useState("floatingRootContext"),n=eR(t);return tR(e,{activeTriggerProps:n.reference,inactiveTriggerProps:n.trigger,popupProps:n.floating}),null}const XK=UM(function(t){return Pc(!0)?i.jsx(nS,{...t}):i.jsx(KM,{children:i.jsx(nS,{...t})})}),SI=m.createContext(void 0);function JK(){const e=m.useContext(SI);if(e===void 0)throw new Error(uc(48));return e}const ZK=m.forwardRef(function(t,n){const{keepMounted:s=!1,...o}=t;return Pc().useState("mounted")||s?i.jsx(SI.Provider,{value:s,children:i.jsx(nR,{ref:n,...o})}):null}),QK=sR(function(t,n){const{render:s,className:o,delay:r,closeDelay:a,id:l,payload:c,handle:d,style:u,...h}=t,p=Pc(!0),g=iR(d)??p;if(!g)throw new Error(uc(89));const x=gj(l),v=g.useState("isTriggerActive",x),y=g.useState("isOpenedByTrigger",x),b=g.useState("floatingRootContext"),w=g.context.inlineRectCoordsRef,C=m.useRef(null),_=r??$K,N=a??yI,{registerTrigger:k,isMountedByThisTrigger:S}=oR(x,C,g,{payload:c,closeDelay:N}),A=rR(b,{mouseOnly:!0,move:!1,handleClose:aR(),delay:()=>({open:_,close:N}),triggerElementRef:C,isActiveTrigger:v,isClosing:()=>g.select("transitionStatus")==="ending"}),T=lR(b,{delay:_}),I={open:y},P=g.useState("triggerProps",S),D=RW(w,y);return hc("a",t,{state:I,ref:[n,k,C],props:[A,T.reference,P,D,{id:x},h],stateAttributesMapping:cR})}),CI=m.createContext(void 0);function eq(){const e=m.useContext(CI);if(e===void 0)throw new Error(uc(49));return e}const tq=m.forwardRef(function(t,n){const{render:s,className:o,anchor:r,positionMethod:a="absolute",side:l="bottom",align:c="center",sideOffset:d=0,alignOffset:u=0,collisionBoundary:h="clipping-ancestors",collisionPadding:p=5,arrowPadding:f=5,sticky:g=!1,disableAnchorTracking:x=!1,collisionAvoidance:v=dR,style:y,...b}=t,w=Pc(),C=JK(),_=uR(),N=w.useState("open"),k=w.useState("mounted"),S=w.useState("floatingRootContext"),A=w.useState("instantType"),T=w.useState("transitionStatus"),I=w.useState("adaptiveOrigin"),P=w.context.inlineRectCoordsRef,D=hR({anchor:r,floatingRootContext:S,positionMethod:a,mounted:k,side:l,sideOffset:d,align:c,alignOffset:u,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:g,disableAnchorTracking:x,keepMounted:C,nodeId:_,collisionAvoidance:v,adaptiveOrigin:I,inline:LW(P)}),O=D.update;Fg(()=>{N&&k&&O()},[N,k,O]);const z={open:N,side:D.side,align:D.align,anchorHidden:D.anchorHidden,instant:A},R=pR(t,z,{styles:D.positionerStyles,transitionStatus:T,props:b,refs:[n,w.useStateSetter("positionerElement")],hidden:!k,inert:!N});return i.jsx(CI.Provider,{value:D,children:i.jsx(fR,{id:_,children:R})})}),nq=m.forwardRef(function(t,n){const{className:s,render:o,style:r,...a}=t,l=Pc(),{side:c,align:d}=eq(),u=l.useState("open"),h=l.useState("instantType"),p=l.useState("transitionStatus"),f=l.useState("popupProps"),g=l.useState("floatingRootContext"),x=l.useState("closeDelay");return mR({open:u,ref:l.context.popupRef,onComplete(){u&&l.context.onOpenChangeComplete?.(!0)}}),gR(g,{closeDelay:x}),hc("div",t,{state:{open:u,side:c,align:d,instant:h,transitionStatus:p},ref:[n,l.context.popupRef,l.useStateSetter("popupElement")],props:[xR,f,bR(p),a],stateAttributesMapping:vR})}),bv=XK;function wv({...e}){return i.jsx(QK,{"data-slot":"preview-card-trigger",...e})}function kI({className:e,children:t,align:n="center",sideOffset:s=4,...o}){return i.jsx(ZK,{children:i.jsx(tq,{align:n,className:"z-50","data-slot":"preview-card-positioner",sideOffset:s,children:i.jsx(nq,{className:W("relative flex w-64 origin-(--transform-origin) text-balance rounded-lg border bg-popover bg-clip-padding p-4 text-popover-foreground text-sm shadow-lg transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",e),"data-slot":"preview-card-content",...o,children:t})})})}const sS={mask:"text-sky-600 dark:text-sky-400",warn:"text-amber-600 dark:text-amber-400",block:"text-red-600 dark:text-red-400"},sq={mask:sh,warn:ca,block:xj},iq={mask:"Mask",warn:"Warn only",block:"Block"},oq={system:"System prompt",user:"Your message",tool_result:"Tool output",tool_args:"Tool arguments",assistant:"Earlier replies",tools:"Tool descriptions"};function rq({report:e}){const{t}=ne(),n=wR(e);if(!n)return null;const s=sq[n],o=new Set(e.hits.map(r=>r.token)).size;return i.jsxs(bv,{children:[i.jsxs(wv,{render:i.jsx("span",{className:W("inline-flex shrink-0 items-center gap-0.5 text-[11px]",sS[n]),"data-privacy-mask":n}),children:[i.jsx(s,{className:"size-3.5"}),i.jsx("span",{className:"tabular-nums",children:o})]}),i.jsxs(kI,{className:"max-h-(--available-height) w-72 flex-col overflow-y-auto overscroll-contain text-xs",children:[i.jsx("p",{className:"mb-1.5 font-medium",children:t("Privacy masking")}),i.jsx("ul",{className:"space-y-1",children:yR(e.hits).map(r=>i.jsxs("li",{className:"flex flex-wrap gap-x-2",children:[i.jsx("span",{className:sS[r.action],children:t(iq[r.action])}),i.jsx("span",{children:r.kind}),i.jsx("span",{className:"text-muted-foreground",children:t(oq[r.where]??r.where)}),i.jsx("span",{className:"text-muted-foreground",children:r.values>1?t("{{count}} values",{count:r.values}):r.preview}),r.count>1&&i.jsxs("span",{className:"text-muted-foreground",children:["×",r.count]})]},`${r.action}-${r.kind}-${r.where}`))}),e.restored>0&&i.jsx("p",{className:"mt-1.5 text-muted-foreground",children:t("Restored {{count}} in the reply",{count:e.restored})})]})]})}const aq=/^\[.+#[0-9A-Fa-f]{4}\]$/;function lq(e){const t=e.indexOf(`
58
- `),n=t===-1?e:e.slice(0,t);return aq.test(n)?t===-1?"":e.slice(t+1).split(`
59
- `).map(s=>s.replace(/^\d+:/,"")).join(`
60
- `):e}const cq={theme:ka,disableFileHeader:!0,overflow:"wrap",preferredHighlighter:"shiki-js"};function Yd({path:e,contents:t}){const{t:n}=ne(),[s,o]=m.useState(!1),r=dc(cq);m.useEffect(()=>{let l=!0;return ha().then(()=>{l&&o(!0)}),()=>{l=!1}},[]);const a=m.useMemo(()=>({name:e.split("/").pop()||"file",contents:lq(t)}),[e,t]);return s?i.jsx(vj,{file:a,disableWorkerPool:!0,options:r}):i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("Loading...")})}function dq(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 uq={compressed:"Compressed",unchanged:"Unchanged",pending:"Background task started",bypassed:"Bypassed",unavailable:"Unavailable"};function hq({value:e}){const t=B4(e),{t:n}=ne();if(!t)return null;const s=dq(t);return i.jsxs("div",{className:"border-border/60 border-t text-[10px] text-muted-foreground","data-rtk-status":t.status,children:[i.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 px-3 py-1",children:[i.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:"RTK"}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:n(uq[t.status])}),s&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:n("~{{count}} tokens saved",{count:Qn(s.tokens)})}),s.percent!==null&&i.jsxs("span",{children:["(",s.percent,"%)"]})]})]}),i.jsxs("div",{className:"space-y-2 px-3 pb-2",children:[t.status==="pending"&&i.jsx("p",{className:"rounded bg-muted/40 px-2 py-1 text-foreground/80",children:n("This is the startup receipt; see the task_output result for final statistics.")}),(t.inputTokens!==void 0||t.reason)&&i.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1",children:[t.inputTokens!==void 0&&t.outputTokens!==void 0&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{children:n("Input estimate")}),i.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:Qn(t.inputTokens)})}),i.jsx("dt",{children:n("Output estimate")}),i.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:Qn(t.outputTokens)})})]}),t.reason&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{children:n("Reason")}),i.jsx("dd",{className:"min-w-0 whitespace-pre-wrap text-foreground/80",children:t.reason})]})]})]})]})}function pq(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 fq(e,t,n=V4){const s=t-e;return s>=n?s:null}const mq={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"},gq={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."},jI=600;function xq(e){return e?.kind==="deadline"?["background","timeout"]:[]}function vq(e,t,n){const s=`\`\`\`
61
- ${t}
62
- \`\`\``;return e==="background"?n(`Rerun this command with background: true:
63
-
64
- {{command}}`,{command:s}):n(`Rerun this command with timeout: {{seconds}}:
65
-
66
- {{command}}`,{seconds:jI,command:s})}function bq(e,t,n){return t(e)?(n(),!0):!1}function wq(){const[e,t]=m.useState(()=>Date.now());return m.useEffect(()=>{const n=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(n)},[]),e}const Qm=5,iS=2*Math.PI*Qm;function yq({startedAt:e,deadlineAt:t,output:n}){const{t:s}=ne(),o=wq(),r=m.useRef({output:n,at:e??Date.now()});r.current.output!==n&&(r.current={output:n,at:Date.now()});const a=pq(e,t,o),l=fq(r.current.at,o);return!a&&l===null?null:i.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[10px] text-muted-foreground/70 tabular-nums",children:[l!==null&&i.jsx("span",{"data-shell-quiet":!0,className:"rounded bg-muted px-1",children:s("No output for {{seconds}}s",{seconds:Math.floor(l/1e3)})}),a&&a.remainingMs>0&&i.jsxs("span",{className:"flex items-center gap-0.5",title:s("Moves to background in {{seconds}}s",{seconds:Math.ceil(a.remainingMs/1e3)}),children:[i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",children:[i.jsx("circle",{cx:"6",cy:"6",r:Qm,fill:"none",stroke:"currentColor",opacity:"0.25"}),i.jsx("circle",{cx:"6",cy:"6",r:Qm,fill:"none",stroke:"currentColor",strokeDasharray:iS,strokeDashoffset:iS*(1-a.fraction),transform:"rotate(-90 6 6)"})]}),Math.ceil(a.remainingMs/1e3),"s"]})]})}function _I(e,t){return e.kind==="exit_nonzero"&&e.exitCode===void 0?t("Failed"):t(mq[e.kind],{code:e.exitCode??""})}function Sq({failure:e}){const{t}=ne();return i.jsx("span",{"data-shell-failure":e.kind,className:W("shrink-0 rounded px-1 text-[10px]",e.retryable?"bg-muted text-muted-foreground":"bg-destructive/10 text-destructive"),children:_I(e,t)})}function Cq({failure:e,command:t}){const{t:n}=ne(),[s,o]=m.useState(!1);if(!e)return null;const r=gq[e.kind],a=xq(e);return i.jsxs("div",{"data-shell-status":e.kind,className:"mt-2 flex items-center gap-2 border-t border-current/10 pt-1.5 text-[11px] opacity-80",children:[i.jsx("span",{className:"shrink-0 font-medium",children:_I(e,n)}),r&&i.jsx("span",{className:"min-w-0 flex-1",children:n(r)}),a.map(l=>i.jsx("button",{type:"button","data-shell-rerun":l,onClick:()=>{bq(vq(l,t,n),Mh,_o)},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:jI})},l)),i.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{o(!0),setTimeout(()=>o(!1),1e3)})},className:"ml-auto flex shrink-0 items-center gap-1 hover:opacity-100",title:n("Copy command"),children:[s?i.jsx(Yn,{className:"h-3 w-3"}):i.jsx(ih,{className:"h-3 w-3"}),n("Copy command")]})]})}function kq(e){return e.startsWith("/skill:")?"skill":e==="/goal"?"goal":"command"}function jq(e){return e.startsWith("/skill:")?e.slice(7):e.replace(/^\//,"")}function Ru(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 _q={skill:ii,goal:Ma,command:QN},Nq={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 NI(e,t=!1){return W("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",Nq[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 Lu({name:e,className:t,interactive:n=!1,trailing:s}){const o=kq(e),r=_q[o];return i.jsxs("span",{className:W(NI(o,n),t),children:[i.jsx(r,{className:"h-3 w-3"}),jq(e),s]})}function Tq({icon:e,state:t}){const n=t==="running"||t==="reviewing";return i.jsxs("span",{className:W("relative flex size-[22px] shrink-0 items-center justify-center rounded-full border text-muted-foreground",n&&"border-transparent text-brand",t==="error"&&"border-destructive/40 text-destructive"),children:[i.jsx(e,{className:"size-3"}),n&&i.jsx("span",{className:"absolute -inset-px animate-spin rounded-full border-[1.5px] border-brand/20 border-t-brand"})]})}function TI({state:e}){const t=e==="running"||e==="reviewing";return i.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:t?i.jsx("span",{className:"size-2.5 animate-spin rounded-full border-[1.5px] border-border border-t-brand"}):e==="error"?i.jsx("span",{className:"size-1.5 rounded-full bg-destructive"}):i.jsx("span",{className:"size-1 rounded-full bg-current opacity-60"})})}const Iq={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 Dq({view:e,titles:t}){const{t:n}=ne();return i.jsxs("div",{className:"space-y-2 px-3 py-2 text-sm",children:[e.kind==="report"&&e.text&&i.jsx(Ts,{text:e.text}),e.kind==="report"&&e.value&&i.jsx(Ts,{text:`\`\`\`json
67
- ${e.value}
68
- \`\`\``}),e.kind==="report"&&e.error&&i.jsx("p",{className:"whitespace-pre-wrap text-destructive",children:e.error}),e.runs.length>0&&i.jsx("ul",{className:"space-y-0.5 text-xs text-muted-foreground",children:e.runs.map(s=>i.jsx(Eq,{run:s,title:t?.[s.agentId]},s.runId||s.agentId))}),e.kind==="list"&&e.runs.length===0&&i.jsx("p",{className:"text-xs text-muted-foreground",children:n("No agents")}),e.kind==="wait"&&e.timedOut&&i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Timed out; unfinished agents keep running")}),e.kind==="wait"&&e.interrupted&&i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Wait was interrupted")}),i.jsxs("details",{className:"text-xs text-muted-foreground",children:[i.jsx("summary",{className:"cursor-pointer hover:text-foreground",children:n("Run info")}),i.jsx("pre",{className:"mt-1 whitespace-pre-wrap font-mono",children:e.info})]}),e.head&&i.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:e.head})]})}function Eq({run:e,title:t}){const{t:n}=ne(),[s,o]=Iq[e.status]??[null,"bg-muted-foreground"],r=e.durationMs===null?"":n("took {{duration}}",{duration:qn(e.durationMs)});return i.jsxs("li",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:W("h-1.5 w-1.5 shrink-0 rounded-full",o)}),t&&i.jsx("span",{className:"truncate text-foreground",children:t}),i.jsx("span",{className:"shrink-0",children:[s?n(s):e.status,r].filter(Boolean).join(" · ")})]})}const yv=e=>!!e&&typeof e=="object"&&!Array.isArray(e),oS=e=>typeof e=="string"&&e.trim()?e:null;function eg(e){if(!yv(e))return null;const{agentId:t,runId:n,status:s,createdAt:o,startedAt:r,finishedAt:a}=e;if(typeof t!="string"||typeof n!="string"||typeof s!="string")return null;const l=typeof r=="number"?r:o;return{agentId:t,runId:n,status:s,durationMs:typeof a=="number"&&typeof l=="number"?Math.max(0,a-l):null}}const Pq=new Set(["closed","parked","creating"]);function Aq(e){if(!yv(e))return null;const{agentId:t,status:n,latestRun:s}=e;return typeof t!="string"||typeof n!="string"?null:(Pq.has(n)?null:eg(s))??{agentId:t,runId:"",status:n,durationMs:null}}function Mq(e,t){const n=SR(t);if(!n)return null;const{head:s,value:o}=n;if(e==="report"){const l=eg(o.run);if(!l)return null;const{text:c,value:d,error:u,...h}=o;return{kind:"report",head:s,runs:[l],text:oS(c),value:d==null?null:JSON.stringify(d,null,2),error:oS(u),info:JSON.stringify(h,null,2)}}if(e==="list"){if(!Array.isArray(o.agents))return null;const l=o.agents.flatMap(c=>Aq(c)??[]);return l.length===o.agents.length?{kind:"list",head:s,runs:l,info:JSON.stringify(o,null,2)}:null}const r=e==="wait"?o:e===void 0?o.report:null;if(!yv(r)||!Array.isArray(r.runs))return e===void 0&&o.report===void 0&&typeof o.agentId=="string"&&typeof o.runId=="string"?{kind:"receipt",head:s,runs:[],info:JSON.stringify(o,null,2)}:null;const a=r.runs.flatMap(l=>eg(l)??[]);return a.length!==r.runs.length?null:{kind:"wait",head:s,runs:a,timedOut:r.timedOut===!0,interrupted:r.interrupted===!0,info:JSON.stringify(o,null,2)}}function Rq({command:e,output:t,failure:n}){const s=we(a=>a.terminalTheme),o=we(a=>a.terminalFontFamily),r=oh(s)??CR;return i.jsxs("div",{"data-slot":"terminal-output",className:"px-3 py-2 text-xs leading-relaxed",style:{backgroundColor:r.background,"--terminal-bg":r.background,color:r.foreground,fontFamily:o},children:[i.jsxs("div",{className:"whitespace-pre-wrap [overflow-wrap:anywhere]",children:[i.jsx("span",{style:{color:r.green},children:"$ "}),e]}),t&&i.jsx("pre",{className:"mt-1 whitespace-pre-wrap [overflow-wrap:anywhere]",style:{fontFamily:"inherit"},children:ki(t)}),i.jsx(Cq,{failure:n,command:e})]})}function Lq(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(!(n.role!=="toolResult"||n.toolName!=="todo"||!n.todos))return n.todos.some(s=>s.status!=="completed")?{id:n.toolCallId??String(t),todos:n.todos}:null}return null}function II({todos:e}){return i.jsx("ul",{className:"space-y-0.5 text-xs",children:e.map(t=>i.jsxs("li",{className:"flex items-start gap-1.5",children:[t.status==="completed"?i.jsx(Yn,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):t.status==="in_progress"?i.jsx($$,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):i.jsx(Vx,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/50"}),i.jsx("span",{className:W(t.status==="completed"?"text-muted-foreground line-through":t.status==="in_progress"?"font-medium":"text-muted-foreground"),children:t.content})]},t.content))})}function DI({done:e,total:t,className:n}){return i.jsx("div",{className:W("h-0.5 overflow-hidden rounded-full bg-border",n),children:i.jsx("div",{className:"h-full rounded-full bg-brand transition-[width]",style:{width:`${t?e/t*100:0}%`}})})}const rS=new Set;function Oq({conversationId:e}){const{t}=ne(),n=we(u=>u.pinUnfinishedTodos),s=ie(u=>u.conversations[e]?.messages),o=m.useMemo(()=>n&&s?Lq(s):null,[n,s]),[r,a]=m.useState(!1),[,l]=m.useState(0);if(!o||rS.has(o.id))return null;const c=o.todos.filter(u=>u.status==="completed").length,d=o.todos.find(u=>u.status==="in_progress")??o.todos.find(u=>u.status==="pending");return i.jsxs("div",{"data-enso":"todo",className:"mb-1.5 rounded-xl border bg-card px-3 py-1.5 text-xs shadow-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>a(u=>!u),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(bj,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-medium",children:t("Todos")}),i.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums",children:[c,"/",o.todos.length]}),!r&&d&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",title:d.content,children:d.content}),r?i.jsx($n,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx(un,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"})]}),i.jsx("button",{type:"button",title:t("Hide until the todo list updates"),onClick:()=>{rS.add(o.id),l(u=>u+1)},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]}),r&&i.jsxs("div",{className:"mt-1.5 max-h-48 overflow-y-auto pb-0.5",children:[i.jsx(DI,{done:c,total:o.todos.length,className:"mb-2"}),i.jsx(II,{todos:o.todos})]})]})}const zq=1e3,Gq=new Set(["ask_user"]);function EI(e,t){let n=t;for(;n>0&&e[n-1]?.role!=="user";)n--;const s=[];for(let c=n;c<=t&&c<e.length;c++){const d=e[c];if(d.role==="assistant"&&d.timing){const u=d.timing.stepStartMs,h=d.timing.completedMs??(typeof d.duration=="number"?u+d.duration:void 0);if(h!==void 0&&h>u){const p=x=>x!==void 0&&x>u&&x<h?x:void 0,f=p(d.timing.firstTokenMs),g=p(d.timing.thinkingEndMs);s.push({key:`m${c}`,kind:"model",label:"",start:u,end:h,...f!==void 0||g!==void 0?{phases:{...f!==void 0?{firstTokenMs:f}:{},...g!==void 0?{thinkingEndMs:g}:{}}}:{}})}}else if(d.role==="toolResult"&&typeof d.toolDurationMs=="number"&&typeof d.timestamp=="number"){const u=d.toolName??"tool";s.push({key:`t${c}`,kind:Gq.has(u)?"wait":"tool",label:u,start:d.timestamp-d.toolDurationMs,end:d.timestamp})}}if(s.length===0||s.length===1&&!s[0].phases)return null;s.sort((c,d)=>c.start-d.start);const o=[];let r=s[0].start;for(const c of s)c.start-r>zq&&o.push({key:`w${c.key}`,kind:"wait",label:"",start:r,end:c.start}),o.push(c),r=Math.max(r,c.end);let a;const l=o.filter(c=>c.kind!=="wait");for(const c of l.length>1?l:[])(!a||c.end-c.start>a.end-a.start)&&(a=c);return{start:o[0].start,end:r,bars:o,...a?{slowest:a.key}:{}}}function Fq(e,t){return ie(n=>{const s=e?n.conversations[e]:void 0;if(!s)return!1;const o=t-(s.historyBaseIndex??0);return s.messages[o]?.timing?EI(s.messages,o)!==null:!1})}const Qp={ttft:"bg-brand/30",thinking:"bg-brand/60",output:"bg-brand"};function Hq(e){const{firstTokenMs:t,thinkingEndMs:n}=e.phases??{},s=[];let o=e.start;t!==void 0&&(s.push({phase:"ttft",from:o,to:t}),o=t),n!==void 0&&n>o&&(s.push({phase:"thinking",from:o,to:n}),o=n),s.push({phase:"output",from:o,to:e.end});const r=Math.max(1,e.end-e.start);return s.map(a=>({...a,width:(a.to-a.from)/r*100}))}const aS=e=>e<1e3?`${Math.round(e)}ms`:qn(e),lS={ttft:"Waiting for first token",thinking:"Think time",output:"Output"},Bq={model:"bg-brand",tool:"bg-info",wait:"bg-muted-foreground/30"};function Vq({conversationId:e,messageIndex:t}){const{t:n}=ne(),s=ie(c=>c.conversations[e]?.messages),o=ie(c=>c.conversations[e]?.historyBaseIndex??0),r=m.useMemo(()=>s?EI(s,t-o):null,[s,t,o]);if(!r)return null;const a=Math.max(1,r.end-r.start),l=r.bars.some(c=>c.phases);return i.jsxs("div",{"data-enso":"turn-waterfall",className:"mt-1.5 max-h-64 overflow-auto rounded-lg border border-border/60 px-2.5 py-2 text-[11px]",children:[r.bars.map(c=>{const d=c.key===r.slowest,u=c.kind==="model"?n("Model"):c.label||n("Wait");return i.jsxs("div",{className:"grid grid-cols-[7rem_1fr_3.5rem] items-center gap-2 py-px",children:[i.jsx("span",{className:W("truncate text-muted-foreground",c.kind==="tool"&&"font-mono",d&&"font-medium text-warning"),title:u,children:u}),i.jsx("span",{className:"relative h-2.5",children:i.jsx("span",{className:W("absolute top-0.5 flex h-1.5 min-w-px overflow-hidden rounded-sm",c.phases?d&&"ring-1 ring-warning ring-offset-1 ring-offset-background":d?"bg-warning":Bq[c.kind]),style:{left:`${(c.start-r.start)/a*100}%`,width:`${(c.end-c.start)/a*100}%`},children:c.phases&&Hq(c).map(h=>i.jsx("span",{className:W("h-full",Qp[h.phase]),style:{width:`${h.width}%`},title:`${n(lS[h.phase])} ${aS(h.to-h.from)}`},h.phase))})}),i.jsx("span",{className:W("text-right tabular-nums text-muted-foreground",d&&"font-medium text-warning"),children:aS(c.end-c.start)})]},c.key)}),l&&i.jsx("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-muted-foreground",children:Object.keys(Qp).map(c=>i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx("span",{className:W("h-1.5 w-2.5 rounded-sm",Qp[c])}),n(lS[c])]},c))})]})}const $q={report:()=>{},scroller:{current:null}},PI=m.createContext($q),Wq=PI.Provider;function Uq(){return m.useContext(PI)}async function Kq(e){const t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(!t)return(await fetch(e)).blob();const n=atob(t[2]),s=new Uint8Array(n.length);for(let o=0;o<n.length;o++)s[o]=n.charCodeAt(o);return new Blob([s],{type:t[1]})}async function qq(e){const t=await Kq(e);let n=t;if(t.type!=="image/png"){const s=await createImageBitmap(t),o=new OffscreenCanvas(s.width,s.height);o.getContext("2d")?.drawImage(s,0,0),s.close(),n=await o.convertToBlob({type:"image/png"})}await navigator.clipboard.write([new ClipboardItem({"image/png":n})])}function AI({src:e,className:t,frameClassName:n,onError:s}){const{t:o}=ne(),[r,a]=m.useState(!1);Og(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=()=>{qq(e).then(()=>ze({type:"success",title:o("Image copied")}),c=>ze({type:"error",title:o("Could not copy image"),description:c instanceof Error?c.message:String(c)}))};return i.jsxs(i.Fragment,{children:[i.jsxs(go,{children:[i.jsx(xo,{render:i.jsx("button",{type:"button",onClick:()=>a(!0),className:W("cursor-zoom-in",n),children:i.jsx("img",{src:e,alt:"",className:t,onError:s})}),onContextMenu:c=>c.stopPropagation()}),i.jsx(vo,{className:"min-w-36",children:i.jsx($t,{closeOnClick:!0,onClick:l,children:o("Copy image")})})]}),r&&i.jsx("button",{type:"button",onClick:()=>a(!1),className:W("fixed inset-0 flex cursor-zoom-out items-center justify-center bg-black/75"),style:{zIndex:yn.NESTED_MODAL_BACKDROP},"data-enso-float":"",children:i.jsx("img",{src:e,alt:"",className:"max-h-[92vh] max-w-[92vw] rounded-lg object-contain"})})]})}const Yq=(e,t)=>e===t||!!e&&!!t&&e.runMs===t.runMs&&e.turnMs===t.turnMs&&e.ttftMs===t.ttftMs&&e.tps===t.tps;function Xq(e,t){const n=e.item,s=t.item;if(n===s)return!0;if(n.kind!==s.kind||n.key!==s.key)return!1;switch(n.kind){case"user":return s.kind!=="user"||n.text!==s.text||n.images.length!==s.images.length||n.timestamp!==s.timestamp||n.deliveryState!==s.deliveryState||n.turnDurationMs!==s.turnDurationMs||n.collapsed!==s.collapsed||n.canCollapse!==s.canCollapse?!1:n.images.every((o,r)=>o===s.images[r]);case"text":case"thinking":return s.kind===n.kind&&n.text===s.text&&n.streaming===s.streaming&&(n.kind!=="text"||s.kind==="text"&&Yq(n.perf,s.perf)&&n.timestamp===s.timestamp&&n.turnDurationMs===s.turnDurationMs)&&(n.kind!=="thinking"||s.kind==="thinking"&&n.durationMs===s.durationMs);case"tool":return s.kind==="tool"&&n.state===s.state&&n.name===s.name&&n.summary===s.summary&&n.output===s.output&&n.edits===s.edits&&n.writeContent===s.writeContent&&n.fileChanges===s.fileChanges&&n.imagePath===s.imagePath&&n.generatedImages===s.generatedImages&&n.todos===s.todos&&n.durationMs===s.durationMs&&n.startedAt===s.startedAt&&n.agentMeta===s.agentMeta&&n.source===s.source&&n.nestedPending===s.nestedPending&&JSON.stringify(n.sandbox)===JSON.stringify(s.sandbox)&&n.rtk===s.rtk&&n.approvalReview===s.approvalReview&&n.plan?.title===s.plan?.title&&n.plan?.text===s.plan?.text&&n.sentMessage===s.sentMessage&&n.memoryContent===s.memoryContent&&n.ask?.question===s.ask?.question&&n.ask?.options.join(`
69
- `)===s.ask?.options.join(`
70
- `)&&n.ask?.answer===s.ask?.answer&&n.ask?.autoSelected===s.ask?.autoSelected&&n.subagentOp===s.subagentOp&&JSON.stringify(n.subagentTitles)===JSON.stringify(s.subagentTitles)&&n.waiting===s.waiting&&n.pluginArtifacts===s.pluginArtifacts&&n.shellFailure===s.shellFailure;case"tool-group":return s.kind==="tool-group"&&n.expanded===s.expanded&&n.count===s.count&&n.stats.commands===s.stats.commands&&n.stats.reads===s.stats.reads&&n.stats.searches===s.stats.searches&&n.stats.others===s.stats.others&&n.exploring===s.exploring&&n.live===s.live&&n.activity?.thinking===s.activity?.thinking&&n.activity?.workedMs===s.activity?.workedMs&&n.explore?.goal===s.explore?.goal&&n.explore?.report===s.explore?.report&&n.explore?.steps===s.explore?.steps;case"error":return s.kind==="error"&&n.text===s.text;case"task-note":return s.kind==="task-note"&&n.detail===s.detail;case"compaction":case"compaction-notice":return(s.kind==="compaction"||s.kind==="compaction-notice")&&n.kind===s.kind&&n.summary===s.summary&&n.tokensBefore===s.tokensBefore&&n.tokensAfter===s.tokensAfter&&n.verified===s.verified;case"compaction-progress":return s.kind==="compaction-progress"&&n.state===s.state;case"session-custom":return s.kind==="session-custom"&&n.entry===s.entry;case"divider":return s.kind==="divider"&&n.text===s.text;case"plugin-message":return s.kind==="plugin-message"&&n.text===s.text&&n.pluginId===s.pluginId;case"discarded-turn":return s.kind==="discarded-turn"&&n.expanded===s.expanded&&n.reason===s.reason&&n.messages.length===s.messages.length&&n.messages.every((o,r)=>o===s.messages[r])&&n.tools.length===s.tools.length}}const Jq=/^<(agent-notification|goal-continuation|coworker-hired|coworker-dismissed|background-task-update)>\n?([\s\S]*?)\n?<\/\1>\s*$/,MI=/^<role>\n?([\s\S]*?)\n?<\/role>\s*/,Zq=/^<workspace-migrated>\n?([\s\S]*?)\n?<\/workspace-migrated>\s*/;function Qq({note:e}){const{t}=ne(),n=/(?:moved to|main working tree): (.+)$/m.exec(e)?.[1]?.trim(),s=e.includes("main working tree");return i.jsxs("aside",{title:e,className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(zi,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0",children:[t(s?"Workspace fell back to the main working tree":"Workspace moved to an isolated worktree"),n&&i.jsx("span",{className:"ml-1.5 break-all font-mono text-[11px] opacity-80",children:n})]})]})}function RI({note:e}){const{t}=ne();return i.jsxs("aside",{className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(Sa,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0",children:t(e==="on"?"Plan mode on: read-only research, then a plan for your approval":e==="off"?"Plan mode off":"Context compacted: the approved plan was attached again")})]})}function LI({note:e}){const{t}=ne(),n=e==="on";return i.jsxs("aside",{className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[n?i.jsx(UR,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):i.jsx(G4,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0",children:t(n?"Unattended mode on: no one is watching, so it decides and keeps going":"Unattended mode off: a person is available again")})]})}function eY({tag:e,body:t}){const n=e==="agent-notification"?p7(t):null;return n?i.jsx(tY,{notices:n}):i.jsx(nY,{tag:e,body:t})}function tY({notices:e}){const{t}=ne(),[n,s]=m.useState(!1);return i.jsxs("div",{className:"w-full overflow-hidden rounded-lg border border-dashed border-border/60 text-xs text-muted-foreground",children:[i.jsxs("button",{type:"button",onClick:()=>s(o=>!o),className:"flex w-full items-start gap-2 px-3 py-2 text-left hover:text-foreground",children:[i.jsx(Ws,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:e.map(o=>o.header).join(" · ")}),i.jsx(un,{className:W("mt-0.5 h-3 w-3 shrink-0 transition-transform",n&&"rotate-90")})]}),n&&e.map((o,r)=>i.jsxs("div",{className:"border-border/60 border-t",children:[e.length>1&&i.jsx("p",{className:"truncate px-3 pt-2",children:o.header}),o.report&&i.jsx("div",{className:"max-h-80 overflow-auto px-3 py-2 text-sm text-foreground",children:i.jsx(Ts,{text:o.report})}),o.usage&&i.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 border-border/60 border-t px-3 py-1 text-[10px]",children:[i.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:"Subagent"}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:t("{{count}} tokens",{count:Qn(o.usage.tokens)})}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:t("{{count}} tool calls",{count:o.usage.toolUses})}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:qn(o.usage.durationMs)})]})]},r))]})}function nY({tag:e,body:t}){const[n,s]=m.useState(!1),o=t.trim(),r=o.indexOf(`
71
- `),a=r>0,l=e.startsWith("coworker-")||e==="agent-notification"?Ws:Uo;return i.jsxs("div",{className:"w-full rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsxs("button",{type:"button",disabled:!a,onClick:()=>s(c=>!c),className:"flex w-full items-start gap-2 text-left enabled:hover:text-foreground",children:[i.jsx(l,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:W("min-w-0 flex-1",a?"truncate":"whitespace-pre-wrap"),children:a?o.slice(0,r):o}),a&&i.jsx(un,{className:W("mt-0.5 h-3 w-3 shrink-0 transition-transform",n&&"rotate-90")})]}),a&&n&&i.jsx("pre",{className:"mt-1.5 max-h-80 overflow-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-words",children:o.slice(r+1)})]})}const OI=/^<message-from-main-agent>\n?([\s\S]*?)\n?<\/message-from-main-agent>\s*$/;function sY(e){const t=MI.exec(e);return OI.test(t?e.slice(t[0].length):e)}function iY({name:e,content:t}){const{t:n}=ne();return i.jsxs(xn,{children:[i.jsxs(JR,{className:NI("skill",!0),children:[i.jsx(ii,{className:"h-3 w-3"}),e]}),i.jsxs(vn,{className:"max-w-lg",children:[i.jsx(bn,{children:i.jsxs(wn,{className:"text-base",children:[n("Skill")," · ",e]})}),i.jsx(An,{className:"max-h-[50vh] text-sm",children:i.jsx(Ts,{text:t})})]})]})}function tg({chip:e,extra:t}){return i.jsxs("div",{className:"max-w-[80%] rounded-2xl rounded-br-md bg-muted px-4 py-2.5 text-sm",children:[i.jsx("div",{className:"flex flex-wrap items-center gap-1",children:e}),t?i.jsx("div",{className:"mt-1.5 whitespace-pre-wrap break-words leading-relaxed",children:t}):null]})}function oY({blocks:e}){const t=YR(e.rest),n=i.jsx(tg,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:e.skills.map(s=>i.jsx(iY,{name:s.name,content:s.body},s.location))}),extra:t.rest.trim()});return!t.plan&&!t.unattended?n:i.jsxs(i.Fragment,{children:[t.plan&&i.jsx(RI,{note:t.plan}),t.unattended&&i.jsx(LI,{note:t.unattended}),n]})}function rY({text:e}){const t=jj(e);if(t.names.length>1)return i.jsx(tg,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:t.names.map(s=>i.jsx(Lu,{name:`/skill:${s}`},s))}),extra:t.rest});const n=Ru(e);return n.slash?i.jsx(tg,{chip:i.jsx(Lu,{name:n.slash}),extra:n.rest.trim()}):null}function aY({preset:e}){const{t}=ne();return i.jsxs("div",{className:"min-w-64 max-w-[80%] overflow-hidden rounded-2xl rounded-br-md bg-muted text-sm",children:[i.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2.5",children:[i.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-info/15 text-info",children:i.jsx(Hg,{className:"h-4 w-4"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("Workflow preset")}),i.jsx("p",{className:"truncate font-medium",title:e.id,children:e.name||e.id})]})]}),e.args.length>0&&i.jsx("dl",{className:"space-y-1 border-t border-border/60 px-3.5 py-2 text-xs",children:e.args.map(([n,s])=>i.jsxs("div",{className:"flex gap-2",children:[i.jsx("dt",{className:"shrink-0 font-mono text-muted-foreground",children:n}),i.jsx("dd",{className:"min-w-0 whitespace-pre-wrap break-words",children:s})]},n))})]})}function Tl({kind:e,label:t,title:n}){const s=e==="file"?jo:e==="chat"?Yo:C4;return i.jsxs("span",{className:W(xv(e),"mx-0.5 max-w-52 rounded-md px-1.5 align-middle leading-4"),title:n,children:[i.jsx(s,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:t})]})}function Ba({text:e,searchQuery:t="",activeNth:n=-1}){const s=Z4(KR(e)),o={n:0};return i.jsx("span",{className:"whitespace-pre-wrap",children:s.map((r,a)=>r.type==="file"?i.jsx(kj,{path:r.path,children:i.jsx(Tl,{kind:"file",label:Ph(r.path),title:r.path})},a):r.type==="chat"?i.jsx(Tl,{kind:"chat",label:r.label,title:r.sessionFile},a):r.type==="ui-element"?i.jsx(Tl,{kind:"ui-element",label:r.label,title:`${r.path}${r.text?` · ${r.text}`:""}`},a):i.jsx("span",{children:t.trim()?qR(r.text,t,n,o):r.text},a))})}function lY({files:e,chats:t}){return i.jsxs("span",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[e.map(n=>i.jsx(kj,{path:n,children:i.jsx(Tl,{kind:"file",label:Ph(n),title:n})},`f:${n}`)),t.map(n=>i.jsx(Tl,{kind:"chat",label:n.label,title:n.sessionFile},`c:${n.sessionFile}`))]})}const ol="max-w-[82%] rounded-[10px] bg-muted px-3.5 py-[9px] text-(length:--chat-body-size) leading-[1.6]";function rl({text:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=ne(),o=qi(),r=!!(o?.speaker||o?.botSession),a=r?MR(e):null;if(a)return i.jsx(JU,{message:a});const l=r?RR(e):e;if(l!==e)return i.jsx(rl,{text:l,searchQuery:t,activeNth:n});const c=r?LR(e):null;if(c?.refs.length)return i.jsxs("div",{className:"flex w-full flex-col items-end gap-1.5",children:[c.body&&i.jsx(rl,{text:c.body,searchQuery:t,activeNth:n}),i.jsx("div",{className:"flex flex-wrap justify-end gap-1.5",children:c.refs.map(N=>i.jsxs("span",{title:s("Referenced chat"),className:"inline-flex h-6 max-w-56 items-center gap-1 rounded-md bg-muted px-1.5 text-xs",children:[i.jsx(xa,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:N.title})]},N.id))})]});const d=OR(e);if(d.note){const N=d.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(RI,{note:d.note}),N&&i.jsx(rl,{text:N,searchQuery:t,activeNth:n})]})}const u=zR(e);if(u.note){const N=u.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(LI,{note:u.note}),N&&i.jsx(rl,{text:N,searchQuery:t,activeNth:n})]})}const h=GR(e);if(h?.kind==="approved")return i.jsxs("div",{className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(KN,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0",children:[s("Plan approved, executing"),i.jsx("span",{className:"ml-1.5 text-foreground",children:h.title})]})]});if(h?.kind==="feedback")return i.jsxs("div",{className:W(ol,"whitespace-pre-wrap"),children:[i.jsxs("p",{className:"mb-1 flex items-center gap-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:[i.jsx(Sa,{className:"h-3 w-3"}),s("Plan feedback")]}),i.jsx(Ba,{text:h.feedback,searchQuery:t,activeNth:n})]});const p=FR(e);if(p)return i.jsx(aY,{preset:p});const f=iW(e);if(f.files.length>0||f.chats.length>0){const N=Ru(f.body);return i.jsxs("div",{className:ol,children:[N.slash?i.jsxs(i.Fragment,{children:[i.jsx(Lu,{name:N.slash}),N.rest.trim()?i.jsx("span",{className:"ml-1.5 align-middle",children:i.jsx(Ba,{text:N.rest.trim(),searchQuery:t,activeNth:n})}):null]}):i.jsx(Ba,{text:f.body,searchQuery:t,activeNth:n}),i.jsx(lY,{files:f.files,chats:f.chats})]})}const x=HR(e);if(x)return i.jsx(oY,{blocks:x});if(Ru(e).slash)return i.jsx(rY,{text:e});const v=Zq.exec(e);if(v){const N=e.slice(v[0].length).trim();return i.jsxs(i.Fragment,{children:[i.jsx(Qq,{note:v[1]}),N&&i.jsx("div",{className:W(ol,"whitespace-pre-wrap"),children:i.jsx(Ba,{text:N,searchQuery:t,activeNth:n})})]})}const y=Jq.exec(e);if(y)return i.jsx(eY,{tag:y[1],body:y[2]});const b=MI.exec(e),w=b?e.slice(b[0].length):e,C=OI.exec(w),_=C?C[1]:w;return i.jsxs("div",{className:W(C?"max-w-[80%] rounded-2xl rounded-bl-md border border-blue-500/20 bg-blue-500/8 px-4 py-2.5 text-sm":W(ol,"whitespace-pre-wrap")),children:[C&&i.jsxs("p",{className:"mb-1 flex items-center gap-1 text-[10px] font-medium tracking-wide text-blue-600 uppercase dark:text-blue-400",children:[i.jsx(Ws,{className:"h-3 w-3"}),s("From main agent")]}),b?.[1]&&!YU(b[1])&&i.jsxs("div",{className:"mb-2 rounded-md bg-background/60 px-2.5 py-1.5 text-xs text-muted-foreground",children:[i.jsx("span",{className:"font-semibold",children:s("Role")})," · ",b[1]]}),C?i.jsx(Ts,{text:_,searchQuery:t,activeNth:n}):i.jsx(Ba,{text:_,searchQuery:t,activeNth:n})]})}function cS(e){return e.kind==="tool-group"||e.kind==="thinking"||e.kind==="tool"&&yj(e)}const ba="text-[color:var(--subtle-foreground,var(--muted-foreground))]",oa="animate-pulse motion-reduce:animate-none";function cY({model:e,at:t,privacyMask:n}){const s=qi()?.speaker,o=[e,typeof t=="number"?Hh(t):null].filter(Boolean).join(" · ");return!s&&!o&&!n?null:i.jsxs("div",{className:"mb-2 flex h-6 min-w-0 items-center gap-2 text-xs select-none",children:[s&&(s.image?i.jsx("img",{src:s.image,alt:"",draggable:!1,className:"size-[22px] shrink-0 rounded-full object-cover",style:{backgroundColor:s.color}}):i.jsx("span",{className:"flex size-[22px] shrink-0 items-center justify-center rounded-full font-semibold text-[11px] text-white",style:{backgroundColor:s.color},children:[...s.name.trim()][0]?.toUpperCase()??"?"})),s&&i.jsx("span",{className:"shrink-0 truncate text-[13px] font-semibold text-foreground",children:s.name}),o&&i.jsx("span",{className:W("min-w-0 truncate text-[11.5px]",ba),children:o}),n&&i.jsx(rq,{report:n})]})}const dY=m.memo(function({item:t,onToggleGroup:n,onToggleTurn:s}){const o=kR(),r=o.query,a=o.activeKey===t.key?o.activeNth:-1;switch(t.kind){case"user":{const l=t.text?sY(t.text):!1,c=t.collapsed===!0;return i.jsxs("div",{"data-enso":"message-user",className:W("group/user flex flex-col gap-1.5",l?"items-start":"items-end"),children:[t.images.map((d,u)=>i.jsx(AI,{src:`data:${d.mimeType};base64,${d.data}`,className:"max-h-48 max-w-full rounded-lg border object-contain"},u)),t.text&&i.jsx(rl,{text:t.text,searchQuery:r,activeNth:a}),c?i.jsx(bY,{turnKey:t.key,timestamp:t.timestamp,turnDurationMs:t.turnDurationMs,onToggle:s}):i.jsx(wY,{turnKey:t.key,messageIndex:Number(t.key),timestamp:t.timestamp,deliveryState:t.deliveryState,canCollapse:t.canCollapse,onToggleTurn:s})]})}case"text":return i.jsx(yY,{item:t,searchQuery:r,activeNth:a});case"thinking":return i.jsx(kY,{itemKey:t.key,text:t.text,streaming:t.streaming,durationMs:t.durationMs,startedAt:t.startedAt});case"tool":return i.jsxs(i.Fragment,{children:[i.jsx(jR,{name:t.name,output:t.output,state:t.state}),i.jsx(EY,{item:t}),t.pluginArtifacts?i.jsx(_R,{artifacts:t.pluginArtifacts}):null]});case"tool-group":return i.jsx(TY,{item:t,onToggle:n});case"error":return i.jsxs("div",{className:"flex items-start gap-2 text-sm text-destructive",children:[i.jsx(yr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("p",{className:"min-w-0 flex-1 whitespace-pre-wrap",children:t.text}),i.jsx(GI,{})]});case"task-note":return i.jsx(jY,{item:t});case"compaction":case"compaction-notice":return i.jsx(NY,{item:t});case"compaction-progress":return i.jsx(_Y,{state:t.state});case"session-custom":return i.jsx(fY,{entry:t.entry});case"plugin-message":return i.jsx(hY,{item:t});case"discarded-turn":return i.jsx(pY,{item:t,onToggle:n});case"divider":return i.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground",children:[i.jsx("span",{className:"h-px flex-1 bg-border"}),t.text,i.jsx("span",{className:"h-px flex-1 bg-border"})]})}},Xq),dS=e=>{if(typeof e=="string")return e;if(e===void 0)return"—";try{return JSON.stringify(e)}catch{return String(e)}};function uY({entry:e}){const{t}=ne(),n=QU(),s=n.get(e.accountKey),o=e.previousAccountKey?n.get(e.previousAccountKey):void 0,r=e.previousAccountKey?o&&s?t("ChatGPT account switched: {{previous}} → {{current}}",{previous:o,current:s}):t("ChatGPT account switched"):s?t("ChatGPT account selected: {{account}}",{account:s}):t("ChatGPT account selected");return i.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-xs",children:[i.jsx(Ko,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),i.jsx("p",{className:"min-w-0 break-words text-muted-foreground",children:r})]})}function hY({item:e}){const{t}=ne();return i.jsxs("div",{"data-plugin-message":e.pluginId,className:"rounded-md border border-dashed border-border bg-muted/20 px-3 py-2 text-xs",children:[i.jsxs("p",{className:"mb-1 flex items-center gap-1.5 text-muted-foreground",children:[i.jsx(rh,{pluginId:e.pluginId,className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:t("From plugin {{name}}",{name:e.pluginName})}),i.jsx("span",{className:"font-mono opacity-70",children:e.pluginId})]}),i.jsx("p",{className:"whitespace-pre-wrap break-words text-foreground",children:e.text})]})}function pY({item:e,onToggle:t}){const{t:n}=ne();return i.jsxs("div",{"data-discarded-turn":e.pluginId,children:[i.jsxs("button",{type:"button",onClick:()=>t?.(e.key),"data-enso":"tool-row",className:W("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",ba),children:[i.jsx(wj,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"shrink-0 text-muted-foreground group-hover/step:text-foreground",children:Bo("turn_discard",n)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:[e.pluginName,e.reason].filter(Boolean).join(" · ")}),i.jsx(un,{className:W("h-3 w-3 shrink-0 transition-transform",e.expanded&&"rotate-90")})]}),e.expanded&&i.jsxs("div",{className:"t-acc-reveal mt-1 mb-1.5 ml-5 space-y-2 rounded-md border border-dashed border-border bg-muted/20 px-3 py-2 text-xs",children:[i.jsxs("p",{className:"flex items-center gap-1.5 text-muted-foreground",children:[i.jsx(rh,{pluginId:e.pluginId,className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:n("From plugin {{name}}",{name:e.pluginName})})]}),e.messages.map((s,o)=>i.jsx("p",{className:"whitespace-pre-wrap break-words text-foreground",children:s},o)),e.tools.map((s,o)=>i.jsxs("p",{className:W("truncate",ba),children:[Bo(s.name,n)," ",s.summary]},o))]})]})}function fY({entry:e}){const{t}=ne();if(e.kind==="oauth-account-selected")return i.jsx(uY,{entry:e});if(e.kind==="agent-dispatch")return i.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-xs",children:[i.jsx(Ws,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),i.jsx("span",{className:"text-muted-foreground",children:t("Dispatched to")}),i.jsx("span",{className:"font-medium",children:e.child.instanceName})]});if(e.kind==="agent-completed")return i.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-emerald-500/20 bg-emerald-500/5 px-2.5 py-2 text-xs",children:[i.jsx(Yn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("p",{className:"font-medium",children:[e.child.instanceName," · ",t("Completed")]}),e.receiptSummary&&i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:e.receiptSummary})]})]});if(e.kind==="agent-failed")return i.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/20 bg-destructive/5 px-2.5 py-2 text-xs",children:[i.jsx(yr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive"}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("p",{className:"font-medium",children:[e.child.instanceName," · ",t("Failed")]}),i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:e.message})]})]});if(e.kind==="tool-batch-label")return null;const n=e.receipt,s=n.outcome==="succeeded";return i.jsx("div",{className:W("rounded-md border px-2.5 py-2 text-xs",s?"border-emerald-500/20 bg-emerald-500/5":n.outcome==="failed"?"border-destructive/20 bg-destructive/5":"border-amber-500/20 bg-amber-500/5"),children:i.jsxs("div",{className:"flex items-start gap-2",children:[s?i.jsx(Yn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"}):i.jsx(yr,{className:W("mt-0.5 h-3.5 w-3.5 shrink-0",n.outcome==="failed"?"text-destructive":"text-amber-500")}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("p",{className:"font-medium",children:[n.subject.label," · ",t(n.outcome)]}),i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:n.summary}),n.changes&&n.changes.length>0&&i.jsx("dl",{className:"mt-2 space-y-1 border-t border-border/50 pt-2",children:n.changes.map(o=>i.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[i.jsx("dt",{className:"truncate text-muted-foreground",children:o.field}),i.jsxs("dd",{className:"text-right font-mono",children:[dS(o.previous)," → ",dS(o.value)]})]},o.field))})]})]})})}function Ms(e){const t=e.activeId?e.conversations[e.activeId]:null;return t?t.activeTabId?e.conversations[t.activeTabId]??t:t:null}const zI=()=>()=>{};function GI(){const{t:e}=ne(),t=qi(),n=t?.botControls,s=ie(l=>{if(t&&(!t.canRetry||t.botControls))return!1;const c=Ms(l);return!!(c?.started&&!c.spawning&&c.status!=="running")}),o=()=>{if(!n||!t?.canRetry)return!1;const l=n.projection();return!!(l&&l.status!=="running")},r=m.useSyncExternalStore(n?.subscribe??zI,o,o);return(n?r:s)?i.jsxs("button",{type:"button",title:e("Retry"),onClick:()=>{if(n)return n.retry();const l=Ms(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:[i.jsx(Ko,{className:"h-3 w-3"}),e("Retry")]}):null}function mY(e,t){return XR(Ms(e),t)}const Sv="flex items-center gap-1 text-[11px] text-muted-foreground transition-opacity hover:text-foreground";function gY({messageIndex:e}){const{t}=ne(),n=qi();return ie(o=>$R(Ms(o),n))?i.jsxs("button",{type:"button",className:Sv,title:t("Keep this session and start a parallel one from here"),onClick:()=>{const o=ie.getState(),r=Ms(o);if(!r)return;const a=WR(r,e);a!==null&&o.forkFromMessage(r.id,a)},children:[i.jsx(zi,{className:"h-3 w-3"}),t("Conversation branch")]}):null}function xY({messageIndex:e}){const{t}=ne(),n=qi(),s=ie(r=>Ms(r)?.id),o=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 BR(l)||a.status==="running"&&VR(l)?l?.deliveryId:void 0});return!s||!o?null:i.jsxs("button",{type:"button",title:t("Withdraw message"),onClick:()=>ie.getState().withdrawMessage(s,{kind:"delivery",id:o}),className:"inline-flex items-center gap-1 hover:text-foreground",children:[i.jsx(va,{className:"h-3 w-3"}),t("Withdraw message")]})}function vY({messageIndex:e}){const{t}=ne(),[n,s]=m.useState(!1),[o,r]=m.useState(null),a=qi(),l=a?.botControls,c=ie(x=>{if(a?.botControls)return!1;const v=Ms(x);return mY(x,a)&&!!(v&&Oc(v.id,v.id,v,e))}),d=()=>{if(!l||!a?.canRewind||!a.sessionId)return null;const x=l.projection();return!x||x.status==="running"?null:Oc(a.sessionId,a.sessionId,x,e)?.entryId??null},u=m.useSyncExternalStore(l?.subscribe??zI,d,d);if(!(l?u!==null:c))return null;const p=x=>{if(l&&a?.sessionId&&u){r({restoreFiles:x,conversationId:a.sessionId,entryId:u});return}const v=Ms(ie.getState());if(!v)return;const y=Oc(v.id,v.id,v,e);y&&r({restoreFiles:x,conversationId:v.id,entryId:y.entryId})},f=(x,v,y)=>{if(l)return l.rewind(y,x);const b=ie.getState(),w=Ms(b),C=Oc(v,w?.id,b.conversations[v],e,y);C&&b.rewind(C.conversationId,C.entryId,x)},g=[{icon:va,label:t("Conversation only"),desc:t("Rewind to this message"),restoreFiles:!1,action:()=>p(!1)},{icon:Yo,label:t("Conversation + files"),desc:t("Rewind and restore files to before this turn"),restoreFiles:!0,action:()=>p(!0)}];return i.jsxs(vi,{open:n,onOpenChange:s,children:[i.jsxs(bi,{className:Sv,title:t("Rewind to this message"),children:[i.jsx(va,{className:"h-3 w-3"}),t("Rewind")]}),i.jsx(wi,{side:"bottom",align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",children:g.map(x=>i.jsxs("button",{type:"button",onClick:()=>{s(!1),x.action()},className:"flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-muted/60",children:[i.jsx(x.icon,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block",children:x.label}),i.jsx("span",{className:"block text-xs text-muted-foreground",children:x.desc})]})]},x.label))}),i.jsx(gs,{open:o!==null,onOpenChange:x=>{x||r(null)},title:t("Rewind to this message?"),description:o?.restoreFiles?t("Later messages leave the current branch and working-tree files are restored to before this turn."):t("Later messages leave the current branch; the text returns to the input box."),confirmLabel:t("Rewind"),onConfirm:()=>{o&&f(o.restoreFiles,o.conversationId,o.entryId)}})]})}function bY({turnKey:e,timestamp:t,turnDurationMs:n,onToggle:s}){const{t:o}=ne();return i.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground/80 select-none",children:[i.jsxs("button",{type:"button",onClick:()=>s?.(e,!1),className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground cursor-pointer border border-border/40",title:o("Expand"),children:[i.jsx(un,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{children:o("Expand")})]}),typeof t=="number"&&i.jsx("span",{children:Hh(t)}),n!==void 0&&i.jsxs("span",{children:["· ",o("took {{duration}}",{duration:qn(n)})]})]})}function wY({turnKey:e,messageIndex:t,timestamp:n,canCollapse:s,deliveryState:o,onToggleTurn:r}){const{t:a}=ne(),l=we(c=>c.autoCollapseTurns);return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/75 select-none",children:[i.jsx(vY,{messageIndex:t}),i.jsx(xY,{messageIndex:t}),o&&i.jsx("span",{children:a(o==="rejected"?"Not sent":"Delivery unconfirmed")}),l&&s&&r&&i.jsxs("button",{type:"button",onClick:()=>r(e,!0),className:W(Sv,"cursor-pointer opacity-0 group-hover/user:opacity-100"),title:a("Collapse"),children:[i.jsx($n,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{children:a("Collapse")})]}),typeof n=="number"&&i.jsx("span",{children:Hh(n)})]})}function yY({item:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=ne(),o=qi(),r=e.perf?CY(e.perf,s,e.turnDurationMs!==void 0):"",a=ie(p=>Ms(p)?.id??null),l=Number(e.key.split("-")[0]),c={text:e.text,messageIndex:l,sessionId:o?o.sessionId:a},d=Fq(!o&&e.turnEnd&&e.turnDurationMs!==void 0?a:null,l),[u,h]=m.useState(!1);return i.jsxs("div",{"data-enso":"message-assistant",className:"group text-(length:--chat-body-size)",children:[i.jsx(Ts,{text:e.text,streaming:e.streaming,searchQuery:t,activeNth:n,leaf:{messageIndex:c.messageIndex,sessionId:c.sessionId}}),e.turnEnd&&!e.streaming&&o?.turnFooter?.(Number(e.key.split("-")[0])),!e.streaming&&i.jsxs("div",{className:W("mt-1 flex items-center gap-2 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",u&&"opacity-100"),children:[i.jsx(S0,{position:"left",...c}),i.jsx(SY,{text:e.text}),i.jsx(S0,{position:"right",...c}),e.turnEnd&&i.jsx(gY,{messageIndex:Number(e.key.split("-")[0])}),e.timestamp&&!e.turnEnd&&i.jsx("span",{children:Hh(e.timestamp)}),e.turnDurationMs!==void 0&&(d?i.jsxs("button",{type:"button","aria-expanded":u,onClick:()=>h(p=>!p),className:"flex items-center gap-0.5 transition-colors hover:text-foreground",children:[s("took {{duration}}",{duration:qn(e.turnDurationMs)}),i.jsx(un,{className:W("h-3 w-3 transition-transform",u&&"rotate-90")})]}):i.jsxs("span",{children:[e.timestamp&&!e.turnEnd&&"· ",s("took {{duration}}",{duration:qn(e.turnDurationMs)})]})),r&&i.jsxs("span",{children:["· ",r]})]}),u&&d&&a&&i.jsx(Vq,{conversationId:a,messageIndex:l})]})}function SY({text:e}){const{t}=ne(),[n,s]=m.useState(!1);return i.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),1e3)})},className:"flex items-center gap-1 transition-colors hover:text-foreground",title:t("Copy"),children:n?i.jsx(Yn,{className:"h-3 w-3"}):i.jsx(ih,{className:"h-3 w-3"})})}const uS=e=>String(e).padStart(2,"0"),Hh=e=>{const t=new Date(e);return`${uS(t.getHours())}:${uS(t.getMinutes())}`},hS=e=>{const t=e/1e3;return t<10?String(Math.round(t*10)/10):String(Math.round(t))};function CY(e,t,n=!1){const s=[];return(!n||e.turnMs!==void 0)&&s.push(`${hS(e.runMs)}s`),e.ttftMs!==void 0&&s.push(`TTFT ${hS(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:qn(e.turnMs)})),s.join(" · ")}function kY({itemKey:e,text:t,streaming:n,durationMs:s,startedAt:o}){const{t:r}=ne(),a=we(u=>u.expandLiveReasoning),[l,c]=m.useState(null),d=AR(l,n,a);return i.jsxs("div",{"data-enso":"thinking","data-live":n||void 0,children:[i.jsxs("button",{type:"button",onClick:()=>c(!d),className:W("flex min-h-6 items-center gap-2 text-[13px] transition-colors hover:text-foreground",ba),children:[i.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:i.jsx(NR,{className:W("size-3",n&&"animate-pulse text-brand")})}),n?i.jsx("span",{className:W("text-foreground",oa),children:r("Thinking…")}):s!==null?i.jsx("span",{children:r("Thought for {{duration}}",{duration:qn(s)})}):i.jsx("span",{children:r("Thought process")}),n&&i.jsx(FI,{itemKey:e,since:o}),i.jsx(un,{className:W("h-3 w-3 transition-transform",d&&"rotate-90")})]}),d&&i.jsx(TR,{text:t,streaming:n,itemKey:e})]})}function jY({item:e}){const{t}=ne(),[n,s]=m.useState(!1),[o,r]=m.useState(void 0),a=/^Background task (\S+) finished \((.+?), ran (.+?)\)/.exec(e.summary),l=a?`${a[1]} · ${a[2]} · ${a[3]}`:e.summary,c=/(?:read ((?:\/|[A-Za-z]:[\\/]).+?\.log) for the complete log|Full log: ((?:\/|[A-Za-z]:[\\/])\S+?\.log))/.exec(e.detail)?.slice(1).find(Boolean)??null;return m.useEffect(()=>{!n||!c||o!==void 0||window.electronAPI.files.read(c).then(d=>{r(typeof d=="string"?d:null)}).catch(()=>r(null))},[n,c,o]),i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>s(d=>!d),className:"flex w-full items-center gap-3",title:e.detail,children:[i.jsx("span",{className:"h-px flex-1 bg-border"}),i.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[i.jsx(Yn,{className:"h-3 w-3 text-green-600 dark:text-green-500"}),l,i.jsx(un,{className:W("h-3 w-3 transition-transform",n&&"rotate-90")})]}),i.jsx("span",{className:"h-px flex-1 bg-border"})]}),n&&i.jsxs("div",{className:"mt-1.5 rounded-lg border border-border/60 bg-muted/20",children:[i.jsx("pre",{className:"border-b border-border/60 px-3 py-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:e.detail}),i.jsx("pre",{className:"max-h-64 overflow-auto px-3 py-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground",children:c?o===void 0?t("Loading…"):ki(o??t("(log unavailable)")):t("(no log available)")})]})]})}function _Y({state:e}){const{t}=ne();return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx(Xt,{className:"h-3 w-3 animate-spin"}),i.jsx("span",{children:t(e==="queued"?"Compacts after this turn":"Compacting…")})]})}function NY({item:e}){const{t}=ne(),[n,s]=m.useState(!1),o=e.kind==="compaction",r=e.tokensBefore===null?null:Qn(e.tokensBefore),a=g7(e.tokensBefore,e.tokensAfter),l=a!==null&&e.tokensBefore!==null&&e.tokensAfter!==void 0?t("{{kind}} · {{before}} → {{after}} · freed {{percent}}%",{kind:t(e.memory?"Memory context compacted":e.verified?"Verified context compacted":"Context compacted"),before:Qn(e.tokensBefore),after:Qn(e.tokensAfter),percent:a}):e.memory?r===null?t("Memory context compacted"):t("Memory context compacted ({{tokens}} tokens before)",{tokens:r}):e.verified?r===null?t("Verified context compacted"):t("Verified context compacted ({{tokens}} tokens before)",{tokens:r}):r===null?t("Context compacted"):t("Context compacted ({{tokens}} tokens before)",{tokens:r});return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>s(c=>!c),className:W("flex items-center gap-3",o&&"w-full"),title:e.memory?t("Summary rendered from continuous memory. Messages above are no longer in the model context; use recall for sources."):e.verified?t("Verified summary from smart compaction. Messages above are no longer in the model context."):t(o?"Messages above are no longer in the model context; only this summary is.":"Latest compaction summary — expand to read what the model kept."),children:[o&&i.jsx("span",{className:"h-px flex-1 bg-border"}),i.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[i.jsx(r4,{className:"h-3 w-3"}),l,i.jsx(un,{className:W("h-3 w-3 transition-transform",n&&"rotate-90")})]}),o&&i.jsx("span",{className:"h-px flex-1 bg-border"})]}),n&&i.jsx("pre",{className:"mt-1.5 max-h-80 overflow-auto rounded-lg border border-border/60 bg-muted/20 px-3 py-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:e.summary||t("(summary unavailable)")})]})}function TY({item:e,onToggle:t}){const{t:n}=ne(),s=we(f=>f.compactReadOnlyTools),o=[];e.stats.commands>0&&o.push(n("ran {{count}} commands",{count:e.stats.commands})),e.stats.reads>0&&o.push(n("read {{count}} files",{count:e.stats.reads})),e.stats.searches>0&&o.push(n("searched {{count}} times",{count:e.stats.searches})),e.stats.others>0&&o.push(n("{{count}} other calls",{count:e.stats.others}));const r=[];s&&(e.stats.reads>0&&r.push(n("{{count}} files",{count:e.stats.reads})),e.stats.searches>0&&r.push(n("{{count}} searches",{count:e.stats.searches})));const a=e.activity,l=[];a&&(a.thinking>0&&l.push(n("{{count}} thinking steps",{count:a.thinking})),e.count>0&&l.push(n("{{count}} tool calls",{count:e.count})));const c=e.explore,d=e.exploring||!!(a&&e.live),u=c?Bo("explore_fold",n):a?a.workedMs>0?n("Worked for {{duration}}",{duration:qn(a.workedMs)}):n("Activity"):s?e.exploring?n("Exploring"):n("Explored"):n("{{count}} tool calls",{count:e.count}),h=c?[c.goal,n("{{count}} tool calls",{count:e.count})].filter(Boolean):e.summary&&!e.exploring?[e.summary]:a?l:s?r:o,p=i.jsxs("button",{type:"button",onClick:()=>{c?.steps&&t?.(C0(e.key)),t?.(e.key)},title:c?.goal,"data-explore-head":c?"":void 0,"data-enso":"tool-row",className:W("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",ba),children:[i.jsx(TI,{state:e.exploring?"running":"ok"}),i.jsx("span",{className:W("shrink-0 text-muted-foreground group-hover/step:text-foreground",d&&W(oa,"text-foreground"),e.exploring&&"font-medium"),children:u}),i.jsx("span",{className:W("min-w-0 flex-1 truncate",d&&oa),children:h.join(" · ")}),i.jsx(un,{className:W("h-3 w-3 shrink-0 transition-transform",e.expanded&&"rotate-90")})]});return!c||!e.expanded?p:i.jsxs(i.Fragment,{children:[p,i.jsxs("div",{"data-slot":"tool-details",className:"t-acc-reveal mt-1 mb-1.5 ml-5 overflow-hidden rounded-lg border border-border/70 bg-card text-sm shadow-xs",children:[c.goal&&i.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[i.jsx("div",{className:"mb-0.5 text-[11px] text-muted-foreground",children:n("Goal")}),i.jsx("p",{className:"whitespace-pre-wrap",children:c.goal})]}),c.report&&i.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[i.jsx("div",{className:"mb-0.5 text-[11px] text-muted-foreground",children:n("Result")}),i.jsx(Ts,{text:c.report})]}),i.jsxs("button",{type:"button",onClick:()=>t?.(C0(e.key)),className:"flex w-full items-center gap-1.5 px-3 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground",children:[i.jsx(un,{className:W("h-3 w-3 shrink-0 transition-transform",c.steps&&"rotate-90")}),i.jsx("span",{children:c.steps?n("Hide process"):n("Show process")}),i.jsxs("span",{children:["· ",n("{{count}} tool calls",{count:e.count})]})]})]})]})}function Va({children:e,className:t,follow:n}){const s=m.useRef(null),o=m.useRef(null),r=m.useRef(n),a=m.useRef(n),l=m.useRef(null),c=m.useRef(null),d=m.useRef(0);a.current=n;const u=m.useCallback(()=>{r.current=!1,l.current=null,cancelAnimationFrame(d.current)},[]),h=m.useCallback(()=>{!a.current||!r.current||(cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{const p=s.current;if(!p||!a.current||!r.current)return;const f=Math.max(0,p.scrollHeight-p.clientHeight);l.current=f,p.scrollTop=f}))},[]);return m.useEffect(()=>{n?(r.current=!0,h()):(l.current=null,cancelAnimationFrame(d.current))},[n,h]),m.useEffect(h),m.useEffect(()=>{const p=o.current;if(!p)return;const f=new ResizeObserver(h);return f.observe(p),()=>f.disconnect()},[h]),m.useEffect(()=>()=>cancelAnimationFrame(d.current),[]),i.jsx("div",{ref:s,onWheel:p=>{p.deltaY<0&&u()},onPointerDown:p=>{p.target===p.currentTarget&&u()},onTouchStart:p=>{c.current=p.touches[0]?.clientY??null},onTouchMove:p=>{const f=p.touches[0]?.clientY;f!==void 0&&c.current!==null&&f>c.current&&u(),c.current=f??null},onTouchEnd:()=>{c.current=null},onScroll:p=>{if(!a.current)return;const f=p.currentTarget;if(f.scrollHeight-f.scrollTop-f.clientHeight<=2){r.current=!0,l.current=null;return}const x=l.current;if(x!==null&&f.scrollTop>=x-2){l.current=null,h();return}u()},className:W("max-h-96 overflow-auto [overflow-anchor:none]",t),children:i.jsx("div",{ref:o,children:e})})}function IY(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??""}catch{return String(e)}}function DY({source:e,output:t,view:n}){const s=n?.status==="completed"?IY(n.value):n?.error??t;return i.jsxs("div",{className:"space-y-1 px-3 py-1",children:[e?i.jsx(k0,{code:e,language:"javascript"}):null,n&&n.calls.length>0?i.jsx("div",{className:"flex flex-wrap gap-1",children:[...new Map(n.calls.map(o=>[o.name,o])).keys()].map(o=>{const r=n.calls.filter(c=>c.name===o),a=r.find(c=>!c.ok),l=`${o} ×${r.length}`;return i.jsx("span",{className:W("rounded-md border px-1.5 py-0.5 font-mono text-[10px]",a?"border-destructive/40 text-destructive":"text-muted-foreground"),title:r.map(c=>c.summary).filter(Boolean).join(`
72
- `),children:a?`${l} · ${a.error??"error"}`:l},o)})}):null,s?n?.status==="completed"&&typeof n.value!="string"?i.jsx(k0,{code:s,language:"json"}):i.jsx("pre",{className:"font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:ki(s)}):null,n?.console?i.jsx("pre",{className:"border-l-2 pl-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:ki(n.console)}):null]})}function pS({path:e,fallback:t}){const[n,s]=m.useState(!1);return n?t:i.jsx("div",{"data-slot":"read-image",className:"w-full min-w-0 px-3 py-3",children:i.jsx(AI,{src:Mf(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 EY({item:e}){const{t}=ne(),n=qi(),s=we(z=>z.compactReadOnlyTools),o=we(z=>z.expandLiveEdits),r=s&&e.name!=="bash"&&yj(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=bT[e.name],f=Sj(e.name),g=e.state!=="error"&&e.todos?.length===0,x=g?t("Todo list cleared"):e.subagentOp?[t(r8[e.subagentOp]),e.summary].filter(Boolean).join(" · "):e.summary,v=e.nestedPending&&e.state==="running"?`${x} · ${e.nestedPending} pending`:d?.calls.length&&e.state!=="error"?IR(d.calls):x,y=!g&&!!(e.output||e.source||u||e.ask),b=e.state==="running"&&e.waiting==="subagent"&&!n,w=a||l||c||y||b||h,C=o&&(a||l||h)&&e.state==="running",[_,N]=m.useState(C),[k,S]=m.useState(!1),A=m.useRef(null),T=Uq();m.useEffect(()=>{if(!k)return;const z=A.current;if(!z)return;const R=e.key,$=T.report,X=new IntersectionObserver(([H])=>$(R,H?.isIntersecting===!0),{root:T.scroller.current});return X.observe(z),()=>{X.disconnect(),$(R,!1)}},[k,e.key,T]);const I=_&&e.name==="memory_search"?BK(e.output):null,P=_&&e.name==="memory_capture"?VK(e.output,e.memoryContent):null,D=_&&e.name==="subagent"&&e.state!=="error"?Mq(e.subagentOp,e.output):null,O=m.useRef(c);return m.useEffect(()=>{const z=DR(e,O.current);O.current=c,(C||o&&z)&&N(!0)},[C,o,c,e]),e.todos&&e.todos.length>0?i.jsx(MY,{todos:e.todos}):e.name.startsWith("goal_")?i.jsx(PY,{item:e}):e.plan&&e.state!=="error"?i.jsx(AY,{plan:e.plan}):i.jsxs("div",{ref:A,"data-enso":"tool-row","data-tool-style":r?"compact":"full","data-user-open":k?"true":void 0,children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{type:"button",disabled:!w,onClick:()=>{const z=!_;N(z),S(z),T.report(e.key,z)},className:W("group/step flex min-h-6 min-w-0 flex-1 items-center gap-2 text-left text-[13px]",ba,w&&"cursor-pointer"),children:[i.jsx(TI,{state:e.state}),i.jsx("span",{className:W("shrink-0 text-muted-foreground transition-colors group-hover/step:text-foreground",e.state==="running"&&W(oa,"text-foreground")),children:p?t(p):f?.tool??e.name}),i.jsx("span",{className:W("min-w-0 flex-1 truncate font-mono text-[12px]",e.state==="error"?"text-destructive":"text-muted-foreground",e.state==="running"&&oa),children:e.state==="error"&&e.output?x&&e.name==="apply_patch"&&c?`${v} · ${gS(e.output)}`:gS(e.output):x?v:null}),e.backgroundTaskId&&i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",title:e.backgroundTaskId,children:t("Moved to background")}),e.shellFailure&&e.state!=="running"&&i.jsx(Sq,{failure:e.shellFailure}),e.state==="reviewing"?i.jsx("span",{className:W("shrink-0 text-[11px] text-foreground",oa),children:t("Assistant reviewing…")}):e.state==="running"&&e.startedAt!==null?i.jsxs(i.Fragment,{children:[e.callId&&(e.name==="bash"||e.name==="powershell")&&i.jsx(FY,{callId:e.callId,startedAt:e.startedAt,output:e.output??""}),i.jsx(FI,{itemKey:e.key,since:e.startedAt??void 0})]}):(e.agentMeta||e.durationMs!==null)&&i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:[e.agentMeta?.modelId,e.agentMeta?.outputTokens?`${e.agentMeta.outputTokens} tok`:null,e.durationMs!==null?qn(e.durationMs):null].filter(Boolean).join(" · ")}),w&&i.jsx(un,{className:W("h-3 w-3 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] group-hover/step:opacity-100",_&&"rotate-90 opacity-100")})]}),e.state==="running"&&e.callId&&!n&&i.jsx(RY,{callId:e.callId,waiting:!!e.waiting}),(a||l||c)&&(e.state==="ok"||c)&&i.jsx("button",{type:"button",title:t("Open in side panel"),className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:()=>Cj(),children:i.jsx($x,{className:"h-3 w-3"})})]}),e.generatedImages?.length?i.jsx("div",{"data-slot":"generated-images",className:"mt-2 mb-3 ml-5 grid gap-3",children:e.generatedImages.map(z=>i.jsx(pS,{path:z,fallback:i.jsx("p",{className:"break-all px-3 py-2 text-xs text-muted-foreground",children:z})},z))}):null,_&&w&&i.jsxs("div",{"data-slot":"tool-details",className:"t-acc-reveal mt-1 mb-1.5 ml-5 overflow-hidden rounded-lg border border-border/70 bg-card shadow-xs",children:[f&&i.jsxs("div",{className:"truncate border-b border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",children:[f.server,".",f.tool]}),b&&i.jsx(GY,{agentIds:e.subagentTitles?Object.keys(e.subagentTitles):void 0}),a&&e.edits&&i.jsx(Va,{follow:e.state==="running",children:i.jsx(eS,{path:e.summary,blocks:e.edits})}),c&&e.fileChanges&&i.jsx(Va,{follow:e.state==="running",children:e.fileChanges.map((z,R)=>i.jsxs("div",{children:[i.jsxs("div",{className:W("flex items-center gap-2 border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",(R>0||a)&&"border-t"),children:[i.jsx("span",{className:"uppercase",children:z.type}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:z.path,children:z.path}),z.truncated&&i.jsx("span",{children:t("Truncated preview")})]}),i.jsx(eS,{path:z.path,blocks:[z],snapshot:z})]},`${z.type}:${hv(z.path,z.oldText,z.newText)}`))}),ER(e)&&i.jsx(Va,{follow:!1,className:"border-t border-border/60",children:i.jsx("pre",{className:"px-3 py-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:ki(e.output??"")})}),l&&e.writeContent&&i.jsx(Va,{follow:e.state==="running",className:W((a||c)&&"border-t border-border/60"),children:i.jsx(Yd,{path:e.summary,contents:e.writeContent})}),!a&&!l&&!c&&(y||h)&&i.jsxs(Va,{follow:e.state==="running",children:[PR(e.name)?i.jsx(DY,{source:e.source,output:e.output,view:d}):e.name==="bash"||e.name==="powershell"?i.jsx(Rq,{command:e.summary,output:e.output??"",failure:e.shellFailure}):e.name==="read"&&h&&e.imagePath?i.jsx(pS,{path:e.imagePath,fallback:i.jsx(Yd,{path:e.summary,contents:e.output??""})},e.imagePath):e.name==="read"?i.jsx(Yd,{path:e.summary,contents:e.output??""}):e.name==="subagent"&&e.state!=="error"&&!u&&!D?i.jsx("div",{className:"px-3 py-2 text-sm",children:i.jsx(Ts,{text:e.output??""})}):I?i.jsx(Jm,{hits:I}):P?i.jsx(OK,{view:P}):i.jsxs(i.Fragment,{children:[e.ask&&i.jsx(l7,{ask:e.ask,waiting:e.state==="running"}),u&&i.jsx("div",{className:"px-3 py-2 text-sm",children:i.jsx(Ts,{text:u})}),D?i.jsx(Dq,{view:D,titles:e.subagentTitles}):e.output&&i.jsx("pre",{className:"px-3 py-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:ki(e.output)})]}),i.jsx(hq,{value:e.rtk}),i.jsx(a7,{value:e.approvalReview})]})]})]})}function PY({item:e}){const{t}=ne(),n=e.name.replace("goal_",""),s=t(n==="complete"?"Goal completed":n==="blocked"?"Goal blocked":"Goal waiting");return i.jsxs("div",{className:W("flex items-start gap-2 rounded-lg border px-3 py-2 text-sm",n==="complete"&&"border-green-500/50 bg-green-500/5",n==="blocked"&&"border-destructive/50 bg-destructive/5",n==="wait"&&"border-amber-500/50 bg-amber-500/5"),children:[i.jsx(Ma,{className:W("mt-0.5 h-4 w-4 shrink-0",n==="complete"&&"text-green-600 dark:text-green-500",n==="blocked"&&"text-destructive",n==="wait"&&"text-amber-500")}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium",children:s}),e.summary&&i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground text-xs",children:e.summary})]})]})}function AY({plan:e}){const{t}=ne(),[n,s]=m.useState(!1);return i.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 px-3 py-2",children:[i.jsxs("button",{type:"button",onClick:()=>s(o=>!o),className:"flex w-full min-w-0 items-center gap-2 text-left text-xs",children:[i.jsx(Sa,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-medium text-muted-foreground",children:t("Plan")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:e.title}),i.jsx(un,{className:W("h-3 w-3 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")})]}),n&&i.jsx("div",{className:"mt-2 border-border/60 border-t pt-2 text-sm",children:i.jsx(Ts,{text:e.text})})]})}function MY({todos:e}){const{t}=ne(),n=e.filter(s=>s.status==="completed").length;return i.jsxs("div",{"data-enso":"todo",className:"rounded-lg border bg-card px-3 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[i.jsx(bj,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"font-medium text-foreground",children:t("Todos")}),i.jsxs("span",{className:"ml-auto tabular-nums",children:[n,"/",e.length]})]}),i.jsx(DI,{done:n,total:e.length,className:"mt-1.5 mb-2"}),i.jsx(II,{todos:e})]})}const fS=new Map;function RY({callId:e,waiting:t}){const{t:n}=ne(),s=ie(c=>Ms(c)?.id??""),[o,r]=m.useState(!1);if(m.useEffect(()=>{if(!o)return;const c=setTimeout(()=>r(!1),5e3);return()=>clearTimeout(c)},[o]),!s)return null;const a=n(t?o?"Stopping wait…":"Stop waiting":o?"Moving to background…":"Move to background"),l=t?wj:P$;return i.jsxs("button",{type:"button",disabled:o,title:a,className:"flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-60",onClick:()=>{r(!0),window.electronAPI.agent.backgroundTool(s,e).then(c=>{c.ok||r(!1)},()=>r(!1))},children:[i.jsx(l,{className:"h-3 w-3"}),a]})}const LY=5e3,OY=[];function zY(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 GY({agentIds:e}){const{t}=ne(),n=ie(l=>Ms(l)?.id??""),s=my(l=>l.byConversation[n]??OY),[o,r]=m.useState(!1);if(m.useEffect(()=>{if(!n)return;let l=!0;const c=p=>{l&&(my.getState().replace(n,p),r(!0))},d=()=>window.electronAPI.agent.subagentProgress(n).then(c,()=>{}),u=window.electronAPI.agent.onSubagentProgress(p=>{p.sessionId===n&&c(p.runs)});d();const h=setInterval(d,LY);return()=>{l=!1,clearInterval(h),u()}},[n]),!o)return null;const a=e?.length?s.filter(l=>e.includes(l.agentId)):s;return i.jsxs("div",{className:"border-b border-border/60 px-3 py-2 text-xs",children:[a.length===0?i.jsx("div",{className:"text-muted-foreground",children:t("No running subagents")}):a.map(l=>i.jsxs("div",{className:"py-0.5",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"max-w-[40%] shrink-0 truncate font-medium",children:l.title??l.agentId.slice(0,8)}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:zY(l,t)}),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:qn(l.elapsedMs)})]}),l.text&&i.jsx("div",{className:"line-clamp-2 break-words pl-2 text-[11px] text-muted-foreground/80",children:l.text.replace(/\s+/g," ")})]},l.runId)),i.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground/80",children:t("Stopping the wait does not stop subagents; the assistant is notified when they finish.")})]})}function FI({itemKey:e,since:t}){const n=qi(),s=ie(c=>Ms(c)?.id??""),o=n?n.sessionId??"":s,r=m.useRef(null);if(r.current===null){const c=`${o}:${e}`;r.current=t??fS.get(c)??Date.now(),t===void 0&&fS.set(c,r.current)}const a=t??r.current,[,l]=m.useState(0);return m.useEffect(()=>{const c=setInterval(()=>l(d=>d+1),1e3);return()=>clearInterval(c)},[]),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:qn(Date.now()-a)})}function FY({callId:e,startedAt:t,output:n}){const s=qi(),o=ie(r=>s?void 0:Ms(r)?.toolDeadlineAt?.[e]);return i.jsx(yq,{startedAt:t,deadlineAt:o,output:n})}function mS(e){return e.kind==="tool-group"?!0:e.kind==="tool"&&!e.todos?.length&&!e.name.startsWith("goal_")}const gS=e=>ki(e.split(`
73
- `,1)[0]??""),HY=100;function BY(e,t,n,s,o=HY){if(s||!n)return{hiddenSince:t,delayMs:null};const r=t??e;return{hiddenSince:r,delayMs:Math.max(0,o-(e-r))}}const VY=1e6;function $Y(e,t,n=VY){if(t.length===0)return{anchor:null,firstItemIndex:n,remount:!1};if(!e)return{anchor:{keys:t,index:n},firstItemIndex:n,remount:!1};const s=new Map(t.map((o,r)=>[o,r]));for(let o=0;o<e.keys.length;o++){const r=s.get(e.keys[o]);if(r===void 0)continue;const a=e.index+o-r;return{anchor:{keys:t,index:a},firstItemIndex:a,remount:!1}}return{anchor:{keys:t,index:n},firstItemIndex:n,remount:!0}}function WY(e,t){return t}const UY=new Set(["text","thinking","tool","tool-group"]);function KY(e,t,n,s){const o=m.useRef(j0),[r,a]=m.useState(()=>Date.now()),l=s.compact,c=s.autoCollapseCompletedTurns,d=s.collapseCompletedActivity===!0,u=s.collapseLiveActivity===!0,h=s.turnOverrides,p={compact:l,autoCollapseCompletedTurns:c,turnOverrides:h},f=u?ZR(e,t,s,o.current,r):null;o.current=f?.witness??j0;const g=f?.wakeAt??null,x=QR(e,t,n,{...p,collapseCompletedActivity:d,collapseLiveActivity:u,releasedLiveActivity:f?.released,heldOpenTools:s.heldOpenTools});return m.useEffect(()=>{if(g===null||g<=r)return;const v=window.setTimeout(()=>a(g),g-r);return()=>window.clearTimeout(v)},[g,r]),x}const qY=[{icon:r6,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:UN,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:_j,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:Yo,title:"Summarize recent changes",hint:"A digest based on git log",prompt:"Summarize the recent changes in this repository based on git log."}];function YY({onPick:e}){const{t}=ne();return i.jsx("div",{className:"mx-auto grid w-full max-w-[560px] grid-cols-1 gap-2.5 text-left @min-[36rem]:grid-cols-2",children:qY.map(({icon:n,title:s,hint:o,prompt:r})=>i.jsxs("button",{type:"button",onClick:()=>e(t(r)),"data-slot":"welcome-suggestion",className:"group flex items-start gap-3 rounded-xl border bg-card px-3.5 py-3 text-left shadow-xs transition-[border-color,box-shadow,transform] duration-200 hover:-translate-y-px hover:border-brand/25 hover:shadow-float",children:[i.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-lg bg-brand/8 text-brand dark:bg-brand/14",children:i.jsx(n,{className:"size-3.5"})}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-[13px] font-medium",children:t(s)}),i.jsx("span",{className:"block text-xs text-muted-foreground",children:t(o)})]})]},s))})}const Ni="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",xS=1e3;function vS({className:e,children:t}){const[n,s]=m.useState(!1);return m.useEffect(()=>{const o=requestAnimationFrame(()=>s(!0));return()=>cancelAnimationFrame(o)},[]),i.jsx("div",{className:W("t-stagger",n&&"is-shown",e),children:t})}const bS=40,XY={index:"LAST",align:"end"},JY={top:600,bottom:600},ZY=e=>e?"auto":!1;function QY({style:e,...t}){const n=e?.visibility==="hidden",[s,o]=m.useState(!1),r=m.useRef(null);return m.useEffect(()=>{const a=BY(Date.now(),r.current,n,s);if(r.current=a.hiddenSince,a.delayMs===null)return;const l=window.setTimeout(()=>o(!0),a.delayMs);return()=>window.clearTimeout(l)},[n,s]),i.jsx("div",{...t,style:n&&s?{...e,visibility:"visible"}:e})}function Bh({ref:e,items:t,busy:n,loading:s=!1,running:o,runStartedAt:r,lastOutputAt:a,error:l,emptyTitle:c,emptyDescription:d,onSuggestion:u,onRetryResume:h,onRetrySync:p,virtualize:f=!0,onStartReached:g,historyLoading:x=!1,hasOlder:v,olderCursor:y,searchQuery:b="",activeHit:w=null}){const{t:C}=ne(),_=m.useRef(null),[N,k]=m.useState(!0),[S,A]=m.useState(!1),T=m.useRef(!0),I=m.useRef(null),P=m.useRef(0),D=m.useRef(0),O=m.useRef(null),z=m.useRef(!1),R=m.useRef(!1),$=m.useRef(0),[X,H]=m.useState(null),te=m.useRef(0),V=m.useCallback(be=>{cancelAnimationFrame(te.current),te.current=requestAnimationFrame(()=>H(be()))},[]);m.useEffect(()=>()=>cancelAnimationFrame(te.current),[]);const[Y,q]=m.useState(new Set),ee=m.useRef(new Set),[ge,Ce]=m.useState(()=>new Set),Re=m.useCallback((be,et)=>{const tt=ee.current;et!==tt.has(be)&&(et?tt.add(be):tt.delete(be),Ce(new Set(tt)))},[]),fe=m.useRef({report:Re,scroller:I});fe.current.report=Re;const U=m.useCallback(be=>{q(et=>{const tt=new Set(et);return tt.has(be)?tt.delete(be):tt.add(be),tt})},[]),[oe,Se]=m.useState(new Map),G=we(be=>be.autoCollapseTurns),Q=we(be=>be.collapseCompletedActivity),ae=we(be=>be.collapseLiveActivity),Z=we(be=>be.liveActivityFoldDelaySec),ce=we(be=>be.compactReadOnlyTools),De=KY(t,o,Y,{compact:ce,autoCollapseCompletedTurns:G,collapseCompletedActivity:Q,collapseLiveActivity:ae,liveActivityFoldDelaySec:Z,heldOpenTools:ge,turnOverrides:oe}),Oe=m.useRef({state:HU,collapse:new Map,reveal:new Map}),Ne=m.useMemo(()=>{const be=Oe.current,et=Jt=>I.current?.querySelector(`[data-nav-key="${CSS.escape(Jt)}"]`),tt=BU(be.state,De,(Jt,E)=>{const L=et(Jt)?.getBoundingClientRect().top,M=et(E)?.getBoundingClientRect().bottom;return L===void 0||M===void 0?0:M-L}),wt=Date.now();be.state=tt.next;for(const{key:Jt,...E}of tt.collapses)be.collapse.set(Jt,{at:wt,...E});for(const Jt of tt.expands)be.reveal.set(Jt,wt);return tt.children},[De]),Ze=m.useRef(null),bt=m.useRef(0),Ut=m.useRef(null),Et=$Y(Ze.current,De.map(be=>be.key));Ze.current=Et.anchor,Et.remount&&(bt.current+=1,Ut.current=null);const _t=Et.firstItemIndex,B=m.useCallback((be,et)=>{Se(tt=>tt.get(be)===et?tt:new Map(tt).set(be,et))},[]),Te=m.useMemo(()=>{const be=[];for(let et=0;et<t.length;et++){const tt=t[et];if(tt.kind!=="user")continue;let wt="";for(let Jt=et+1;Jt<t.length;Jt++){const E=t[Jt];if(E.kind==="user")break;if(E.kind==="text"){wt=E.text;break}}be.push({key:tt.key,question:tt.text||"[image]",answer:wt})}return be},[t]),We=m.useCallback(()=>{const be=I.current;be&&be.scrollHeight-be.scrollTop-be.clientHeight>2&&(z.current=!0,be.scrollTop=be.scrollHeight)},[]),kt=m.useCallback(()=>{cancelAnimationFrame(P.current);const be=Date.now()+1200;let et=null;const tt=()=>{cancelAnimationFrame(P.current),z.current=!1,et?.removeEventListener("touchstart",tt),et?.removeEventListener("wheel",tt)},wt=()=>{if(R.current){tt();return}!et&&I.current&&(et=I.current,et.addEventListener("touchstart",tt,{passive:!0,once:!0}),et.addEventListener("wheel",tt,{passive:!0,once:!0})),We(),T.current=!0,k(!0),Date.now()<be?P.current=requestAnimationFrame(wt):tt()};wt(),k(!0),T.current=!0},[We]);m.useEffect(()=>()=>{cancelAnimationFrame(P.current),cancelAnimationFrame(D.current),window.clearTimeout($.current)},[]);const Gt=()=>{R.current=!0,window.clearTimeout($.current)},de=()=>{window.clearTimeout($.current),$.current=window.setTimeout(()=>{R.current=!1},400)},mt=()=>{Gt(),de()},Lt=()=>{cancelAnimationFrame(P.current),cancelAnimationFrame(D.current),z.current=!1,T.current=!1,k(!1)},Fe=m.useCallback(be=>{if(O.current?.disconnect(),O.current=null,!be)return;const et=new ResizeObserver(()=>{if(!T.current&&!z.current)return;cancelAnimationFrame(D.current);let tt=8;const wt=()=>{We();const Jt=I.current;(Jt?Jt.scrollHeight-Jt.scrollTop-Jt.clientHeight:0)<=2||(--tt>0?D.current=requestAnimationFrame(wt):kt())};wt()});et.observe(be),O.current=et,kt()},[We,kt]);m.useEffect(()=>()=>O.current?.disconnect(),[]);const Nt=be=>De.findIndex(et=>et.key===be||et.kind==="tool-group"&&HI(et,be)),Ft=be=>{if(!f){I.current?.querySelector(`[data-nav-key="${CSS.escape(be)}"]`)?.scrollIntoView({block:"center"});return}const et=Nt(be);et>=0&&_.current?.scrollToIndex({index:WY(_t,et),align:"center"})},on=m.useRef(null),re=be=>{if(Lt(),Nt(be)>=0){on.current=null,Ft(be);return}let et=null,tt=!1;for(const wt of t)if(wt.kind==="user"&&(et=wt.key),wt.key===be){tt=!0;break}!tt||!et||(on.current=be,B(et,!1))};m.useLayoutEffect(()=>{const be=on.current;!be||Nt(be)<0||(on.current=null,Ft(be))},[De]),m.useImperativeHandle(e,()=>({scrollToBottom:kt,pinToBottom:We,isAtBottom:()=>T.current,getScroller:()=>f?null:I.current,scrollToKey:re}));const Ue=m.useRef(!1),dt=`${y}:${_t}`,Dt=m.useRef(dt);Dt.current!==dt&&(Dt.current=dt,Ue.current=!1);const it=()=>{!g||Ue.current||(Ue.current=!0,g())};m.useEffect(()=>{f&&!x&&Ut.current===_t&&it()},[y,x]);const K=m.useMemo(()=>({query:b,activeKey:w?.key??"",activeNth:w?.nth??-1}),[b,w?.key,w?.nth]),pe=(be,et)=>{const tt=De[et+1];if(tt!==void 0&&mS(be)&&mS(tt))return"pb-0";if(!ce)return"pb-4";const wt=tt!==void 0&&cS(tt);return cS(be)?wt?"pb-1":"pb-2":be.kind==="text"&&wt?"pb-1":"pb-4"},Ie=(be,et)=>{const tt=De[et-1],wt=tt?.kind==="user"&&!tt.collapsed&&UY.has(be.kind)?tt:void 0,Jt=Date.now(),E=Oe.current.collapse.get(be.key),L=E&&Jt-E.at<xS?E:void 0,M=Ne.get(be.key),j=M&&Oe.current.reveal.get(M.group),F=M&&j!==void 0&&Jt-j<xS;return i.jsxs("div",{"data-nav-key":be.key,"data-fold-collapse":L?L.pair?"pair":"toggle":void 0,style:L?{"--fold-from":`${L.height}px`}:F?{"--fold-i":M.index}:void 0,className:W(Ni,pe(be,et),F&&"t-fold-reveal","[overflow-wrap:anywhere]"),children:[wt&&i.jsx(cY,{model:wt.replyModel,at:wt.replyAt,privacyMask:wt.replyPrivacyMask}),i.jsx(oX,{itemKey:be.key,children:i.jsx(dY,{item:be,onToggleGroup:U,onToggleTurn:B})})]},be.key)},Ae=m.useRef(!1);v===!0&&(Ae.current=!0);const He=e2(t.length>0,x,v,Ae.current,!f&&S);m.useLayoutEffect(()=>{if(f){A(!1);return}const be=I.current;A(!!be&&t2(v===!0,x,be.scrollHeight,be.clientHeight))},[f,v,x,_t,De.length,t.length]);const nt={pageChrome:He,onLoadMore:He==="more"?it:void 0,busy:n,loading:!!s,since:VU({loading:!!s,runStartedAt:r}),error:l,onRetryResume:h};return i.jsx(n2.Provider,{value:K,children:i.jsx(Wq,{value:fe.current,children:i.jsxs("div",{"data-enso":"timeline",className:"@container relative min-h-0 flex-1",onWheel:mt,onKeyDown:mt,onTouchStart:Gt,onTouchEnd:de,onPointerDown:be=>{be.target===I.current&&(Gt(),window.addEventListener("pointerup",de,{once:!0}))},children:[i.jsx(UU,{items:Te,activeKey:X,onJump:re}),t.length===0&&!n?i.jsxs(vS,{className:"flex h-full flex-col items-center justify-center gap-2 overflow-y-auto px-4 text-center",children:[i.jsx("span",{className:"t-stagger-line t-stagger-line--1 mb-3",children:i.jsx("span",{className:"flex size-11 items-center justify-center rounded-[13px] border border-brand/20 bg-brand/8 text-brand dark:bg-brand/14",children:i.jsx(FU,{className:"size-6"})})}),i.jsx("p",{className:"t-stagger-line t-stagger-line--1 text-[22px] font-semibold tracking-tight",children:c}),l?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"t-stagger-line t-stagger-line--2 max-w-md text-sm text-destructive whitespace-pre-wrap",children:C(l)}),h&&i.jsx(me,{size:"sm",variant:"outline",onClick:h,children:C("Retry resume")})]}):i.jsxs(i.Fragment,{children:[p?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"t-stagger-line t-stagger-line--2 max-w-md text-sm text-muted-foreground",children:C("Session is not ready yet — no history to show.")}),i.jsx(me,{size:"sm",variant:"outline",onClick:p,children:C("Retry sync")})]}):d!==""?i.jsx("p",{className:"t-stagger-line t-stagger-line--2 text-sm text-muted-foreground",children:d??C("Ask the agent…")}):null,u&&i.jsx("div",{className:"t-stagger-line t-stagger-line--3 mt-5 w-full",children:i.jsx(YY,{onPick:u})})]})]}):t.length===0&&l?i.jsxs(vS,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[i.jsx("p",{className:"t-stagger-line t-stagger-line--1 max-w-md text-sm text-destructive whitespace-pre-wrap",children:C(l)}),h&&i.jsx(me,{size:"sm",variant:"outline",onClick:h,children:C("Retry resume")})]}):t.length===0?i.jsxs("div",{"data-timeline-loading":"",className:"flex h-full flex-col items-center justify-center gap-2.5 text-center",children:[i.jsx(Xt,{className:"h-5 w-5 animate-spin text-muted-foreground"}),i.jsx("p",{className:"text-sm text-muted-foreground",children:C("Preparing session…")})]}):f?i.jsx(kU,{ref:_,data:De,defaultItemHeight:80,computeItemKey:(be,et)=>et.key,firstItemIndex:_t,startReached:it,followOutput:ZY,atBottomThreshold:bS,atBottomStateChange:be=>{if(!be&&T.current&&!R.current){kt();return}k(be),T.current=be},increaseViewportBy:JY,initialTopMostItemIndex:XY,rangeChanged:({startIndex:be})=>{Ut.current=be,be>_t+4&&(Ue.current=!1),V(()=>{const et=Math.max(0,be-_t);let tt=null;for(let wt=0;wt<=Math.min(et+1,De.length-1);wt++)De[wt]?.kind==="user"&&(tt=De[wt].key);return tt})},scrollerRef:be=>{I.current=be instanceof HTMLElement?be:null},className:"h-full select-text",context:nt,components:tX,itemContent:(be,et)=>Ie(et,be-_t)},bt.current):i.jsx("div",{ref:be=>{I.current=be},onScroll:be=>{const et=be.currentTarget;if(z.current){z.current=!1,T.current=!0,k(!0);return}if(!R.current){T.current&&We();return}const tt=et.scrollHeight-et.scrollTop-et.clientHeight<=bS;tt!==T.current&&(T.current=tt,k(tt)),g&&(et.scrollTop<80&&!Ue.current?(Ue.current=!0,g()):et.scrollTop>240&&(Ue.current=!1))},className:"h-full select-text overflow-y-auto [overflow-anchor:none]",children:i.jsxs("div",{ref:Fe,children:[i.jsx(BI,{context:nt}),De.map((be,et)=>Ie(be,et)),i.jsx(VI,{context:nt})]})}),!N&&t.length>0&&i.jsxs("button",{type:"button",onClick:kt,className:"absolute bottom-4 left-1/2 z-10 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full border bg-card px-3 text-xs text-muted-foreground shadow-float transition-colors hover:text-foreground",children:[i.jsx(ah,{className:"h-3 w-3"}),C("Scroll to bottom")]})]})})})}function HI(e,t){return e.children.some(n=>n.key===t||n.kind==="tool-group"&&HI(n,t))}function eX({chrome:e,onLoadMore:t}){const{t:n}=ne();return e==="none"?i.jsx("div",{className:"h-6"}):i.jsx("div",{className:W(Ni,"flex items-center justify-center gap-2 py-3"),children:e==="loading"?i.jsxs(i.Fragment,{children:[i.jsx(Xt,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}),i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Loading earlier messages…")})]}):e==="more"?i.jsx("button",{type:"button",className:"text-xs text-muted-foreground underline-offset-2 hover:underline",onClick:t,children:n("Load earlier messages")}):i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Beginning of conversation")})})}function BI({context:e}){return i.jsx(eX,{chrome:e.pageChrome,onLoadMore:e.onLoadMore})}function VI({context:e}){const{t}=ne(),{busy:n,loading:s,since:o,error:r,onRetryResume:a}=e;return i.jsxs("div",{className:W(Ni,"pb-6 [overflow-wrap:anywhere]"),children:[n&&i.jsxs("div",{className:"flex min-h-[26px] items-center gap-2 text-[13px]",children:[i.jsx(nX,{}),i.jsx("span",{className:"animate-pulse text-foreground motion-reduce:animate-none",children:t(s?"Loading…":"Working…")}),o!==void 0&&i.jsx(iX,{since:o})]}),r&&i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("p",{className:"min-w-0 flex-1 text-sm text-destructive whitespace-pre-wrap",children:t(r)}),i.jsx(GI,{}),a&&i.jsx(me,{size:"sm",variant:"outline",onClick:a,children:t("Retry resume")})]})]})}const tX={List:QY,Header:BI,Footer:VI};function nX(){return i.jsxs("span",{className:"relative flex size-[22px] shrink-0 items-center justify-center",children:[i.jsx("span",{className:"absolute size-2 animate-ping rounded-full bg-brand/50"}),i.jsx("span",{className:"relative size-2 rounded-full bg-brand"})]})}const sX=e=>{const t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},iX=m.memo(function({since:t}){const[,n]=m.useState(0);return m.useEffect(()=>{const s=setInterval(()=>n(o=>o+1),1e3);return()=>clearInterval(s)},[]),i.jsx("span",{className:"font-mono text-[11px] text-muted-foreground tabular-nums",children:sX(Date.now()-t)})});class oX extends m.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidUpdate(t){t.itemKey!==this.props.itemKey&&this.state.failed&&this.setState({failed:!1})}render(){return this.state.failed?i.jsxs("p",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-1.5 text-xs text-destructive",children:["message render failed · ",this.props.itemKey]}):this.props.children}}const ra={type:"spring",stiffness:400,damping:30},Ou={type:"tween",duration:.22,ease:[.2,0,0,1]},ef={initial:{height:0,opacity:0},animate:{height:"auto",opacity:1,transition:Ou},exit:{height:0,opacity:0,transition:Ou}};function rX(e){return e.resizing?!0:e.previousConversationId!==void 0&&e.conversationId!==void 0&&e.previousConversationId!==e.conversationId}function $I(e){return e.skip?{duration:0}:e.cover||e.targetW===0?Ou:ra}const WI=e=>{const t=window.electronAPI.speech,n=crypto.randomUUID(),s=t.onPartial(r=>{r.sessionId===n&&e(r.text,r.correcting===!0)});let o=!1;return{push:r=>{o||t.pushAudio(n,r)},finish:()=>(o=!0,t.finishSession(n).finally(s)),cancel:()=>{o||(o=!0,s(),t.cancelSession(n))}}},aX={ts:za,tsx:za,js:za,jsx:za,mjs:za,json:Bg,html:n6,css:_0,scss:_0,md:jo,sh:zf,bash:zf,yml:mi,yaml:mi,toml:mi},lX={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 Ac(e,t,n=!1){if(t)return n?oi:Nc;const s=e.split(".").pop()?.toLowerCase()??"";return aX[s]??C6}function Mc(e,t){if(t)return"text-amber-500";const n=e.split(".").pop()?.toLowerCase()??"";return lX[n]??"text-muted-foreground"}const cX={artifacts:[],media:[]},tf=new Map,nf=new Map,dX=new Set(["image","markdown","html","text"]),uX=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`;function hX(e){const t=JSON.stringify(e),[n,s]=m.useState(()=>tf.get(t)??cX);return m.useEffect(()=>{if(tf.has(t))return;let o=!0;return window.electronAPI.bots.artifacts.list(JSON.parse(t)).then(r=>{if(!o||!r.ok)return;const a={artifacts:r.artifacts,media:r.media??[]};(a.artifacts.length>0||a.media.length>0)&&tf.set(t,a),s(a)}).catch(()=>{}),()=>{o=!1}},[t]),n}function pX(e){const{t}=ne();return(n,s)=>{window.electronAPI.bots.artifacts.open({...e,rel:n.rel,action:s}).then(o=>{o.ok||ze({type:"error",title:o.error==="not-openable"?t("This file type is only shown in Finder"):t("Could not open the file")})})}}function zu({target:e}){const{artifacts:t,media:n}=hX(e);return i.jsxs(i.Fragment,{children:[n.length>0&&i.jsx(mX,{target:e,media:n}),t.length>0&&i.jsx(vX,{target:e,artifacts:t})]})}function fX(){const{t:e}=ne();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 UI(e,t,n){const s=JSON.stringify(e),o=t&&n==="thumb"?nf.get(t):void 0,[r,a]=m.useState(o?{ok:!0,kind:"image",dataUrl:o}:null);return m.useEffect(()=>{const l=t&&n==="thumb"?nf.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"&&nf.set(t,d.dataUrl),c&&a(d)}).catch(()=>c&&a({ok:!1,error:"unavailable"})),()=>{c=!1}},[s,t,n]),r}function mX({target:e,media:t}){const{t:n}=ne(),s=fX(),[o,r]=m.useState(null),a=t.some(l=>l.ok&&l.source==="desktop");return i.jsxs("div",{className:"mt-2","data-bot-media":"",children:[i.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map((l,c)=>l.ok?i.jsx(gX,{target:e,item:l,label:s(l),onOpen:()=>r(l)},l.mediaId):i.jsxs("div",{className:"flex w-40 flex-col gap-1 rounded-lg border border-destructive/60 border-dashed p-2 text-destructive text-xs",children:[i.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[i.jsx(YN,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:l.name??s(l)})]}),i.jsx("span",{children:l.error==="quota"?n("Chat image storage is full (200 MiB); not saved"):n("Not sent: still over 10 MiB after compression")})]},`failed-${c}`))}),a&&i.jsx("p",{className:"mt-1 text-warning text-xs",children:n("Desktop screenshots may capture sensitive content from other windows.")}),i.jsx(xX,{target:e,item:o,label:o?s(o):"",onClose:()=>r(null)})]})}function gX({target:e,item:t,label:n,onOpen:s}){const o=UI(e,t.mediaId,"thumb"),r=t.caption??t.name??n;return i.jsxs("button",{type:"button",title:r,onClick:s,className:"relative h-24 w-36 overflow-hidden rounded-lg border bg-muted",children:[o?.ok&&o.kind==="image"?i.jsx("img",{src:o.dataUrl,alt:r,className:"h-full w-full object-cover"}):o?i.jsx(YN,{className:"m-auto h-4 w-4 text-muted-foreground"}):i.jsx(Xt,{className:"m-auto h-4 w-4 animate-spin text-muted-foreground"}),n&&i.jsx("span",{className:W("absolute top-1 left-1 rounded px-1 text-[10px] leading-4",t.source==="desktop"?"bg-warning text-warning-foreground":"bg-black/60 text-white"),children:n}),(t.caption||t.name)&&i.jsx("span",{className:"absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-black/70 to-transparent px-1.5 pt-3 pb-0.5 text-left text-[10px] text-white",children:t.caption??t.name})]})}function xX({target:e,item:t,label:n,onClose:s}){const{t:o}=ne(),r=UI(e,t?.mediaId??null,"full"),a=t?.caption??t?.name??n;return i.jsx(xn,{open:t!==null,onOpenChange:l=>!l&&s(),children:i.jsxs(vn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[i.jsx(bn,{children:i.jsxs(wn,{className:"flex min-w-0 items-center gap-2 pr-8",children:[i.jsx("span",{className:"truncate",children:a}),i.jsx("span",{className:"shrink-0 font-normal text-muted-foreground text-xs",children:n})]})}),t?.source==="desktop"&&i.jsx("p",{className:"text-warning text-xs",children:o("Desktop screenshots may capture sensitive content from other windows.")}),t?.source==="file"&&i.jsx("p",{className:"text-muted-foreground text-xs",children:o("Copied into this chat: later edits or deletion of the original do not change it. Deleted together with the chat.")}),i.jsx(KI,{name:a,content:r})]})})}function vX({target:e,artifacts:t}){const{t:n}=ne(),s=pX(e),[o,r]=m.useState(null);return i.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5","data-bot-artifacts":"",children:[t.map(a=>{const l=Ac(a.name,!1),c=dX.has(a.kind)||a.kind==="pdf";return i.jsxs("div",{"data-slot":"bot-card",className:"group/artifact flex max-w-64 items-center gap-1 rounded-lg border bg-card py-1 pr-1 pl-2 text-xs",children:[i.jsxs("button",{type:"button",title:a.rel,disabled:!c,onClick:()=>a.kind==="pdf"?s(a,"preview"):r(a),className:"flex min-w-0 items-center gap-1.5 text-left enabled:hover:underline disabled:cursor-default",children:[i.jsx(l,{className:W("h-3.5 w-3.5 shrink-0",Mc(a.name,!1))}),i.jsx("span",{className:"truncate",children:a.name}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:uX(a.size)})]}),i.jsx("button",{type:"button",title:n("Show in Finder"),onClick:()=>s(a,"reveal"),className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(oi,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",title:n("Open with default app"),onClick:()=>s(a,"open"),className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(Nj,{className:"h-3.5 w-3.5"})})]},a.rel)}),i.jsx(bX,{target:e,artifact:o,onOpen:s,onClose:()=>r(null)})]})}function bX({target:e,artifact:t,onOpen:n,onClose:s}){const{t:o}=ne(),[r,a]=m.useState(null),l=t?.rel,c=JSON.stringify(e);return m.useEffect(()=>{if(a(null),!l)return;let d=!0;return window.electronAPI.bots.artifacts.read({...JSON.parse(c),rel:l}).then(u=>d&&a(u)).catch(()=>d&&a({ok:!1,error:"unavailable"})),()=>{d=!1}},[c,l]),i.jsx(xn,{open:t!==null,onOpenChange:d=>!d&&s(),children:i.jsxs(vn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[i.jsx(bn,{children:i.jsxs(wn,{className:"flex min-w-0 items-center gap-2 pr-8",children:[i.jsx("span",{className:"truncate",children:t?.name}),i.jsx("span",{className:"truncate font-normal text-muted-foreground text-xs",children:t?.rel}),i.jsx("span",{className:"flex-1"}),t&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",title:o("Show in Finder"),onClick:()=>n(t,"reveal"),className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(oi,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",title:o("Open with default app"),onClick:()=>n(t,"open"),className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(Nj,{className:"h-4 w-4"})})]})]})}),i.jsx(KI,{name:t?.name??"",content:r})]})})}function KI({name:e,content:t}){const{t:n}=ne();return i.jsxs("div",{className:"min-h-0 flex-1 select-text overflow-auto border-t","data-bot-artifact-preview":"",children:[!t&&i.jsx("div",{className:"flex justify-center p-6 text-muted-foreground",children:i.jsx(Xt,{className:"h-4 w-4 animate-spin"})}),t&&!t.ok&&i.jsx("p",{className:"p-6 text-muted-foreground text-sm",children:t.error==="too-large"?n("The file is too large to preview"):n("Could not open the file")}),t?.ok&&t.kind==="image"&&i.jsx("img",{src:t.dataUrl,alt:e,className:"mx-auto max-h-full max-w-full object-contain p-4"}),t?.ok&&t.kind==="markdown"&&i.jsx("div",{className:"px-6 py-4 text-sm",children:i.jsx(Ts,{text:t.text})}),t?.ok&&t.kind==="html"&&i.jsx("iframe",{title:e,sandbox:"",srcDoc:t.text,className:"h-full w-full bg-white"}),t?.ok&&t.kind==="text"&&i.jsx("div",{className:"p-2 text-xs",children:i.jsx(Yd,{path:e,contents:t.text})})]})}const qI="enso:design-annotations:v1",YI="enso:annotate-prefs:v1",wS=r2(e=>e.pageKey),yS=[],SS=new WeakMap,Ro={annotateHovered:!1,annotateEntered:!1,annotateUseCount:0,annotateSendImmediately:!0};function XI(e){try{return typeof localStorage>"u"?null:localStorage.getItem(e)}catch{return null}}function JI(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(e,t)}catch{}}function wX(){const e=XI(YI);if(!e)return Ro;try{const t=JSON.parse(e);return{annotateHovered:typeof t.annotateHovered=="boolean"?t.annotateHovered:Ro.annotateHovered,annotateEntered:typeof t.annotateEntered=="boolean"?t.annotateEntered:Ro.annotateEntered,annotateUseCount:typeof t.annotateUseCount=="number"&&Number.isFinite(t.annotateUseCount)?t.annotateUseCount:Ro.annotateUseCount,annotateSendImmediately:typeof t.annotateSendImmediately=="boolean"?t.annotateSendImmediately:Ro.annotateSendImmediately}}catch{return Ro}}function $a(e){JI(YI,JSON.stringify(e))}const CS=s2(XI(qI)),yX=wX();function id(e,t){JI(qI,o2({queues:e,pages:t}))}const Kn=Qu((e,t)=>({...yX,queues:CS.queues,pages:CS.pages,sessions:new Map,familiarity:()=>{const n=t();return i2(n.annotateEntered,n.annotateUseCount)},markHovered:()=>{const n=t();if(n.annotateHovered)return;const s={annotateHovered:!0,annotateEntered:n.annotateEntered,annotateUseCount:n.annotateUseCount,annotateSendImmediately:n.annotateSendImmediately};$a(s),e({annotateHovered:!0})},markEntered:()=>{const n=t();if(n.annotateEntered)return;const s={annotateHovered:n.annotateHovered,annotateEntered:!0,annotateUseCount:n.annotateUseCount,annotateSendImmediately:n.annotateSendImmediately};$a(s),e({annotateEntered:!0})},setSendImmediately:n=>{const s=t();if(s.annotateSendImmediately===n)return;const o={annotateHovered:s.annotateHovered,annotateEntered:s.annotateEntered,annotateUseCount:s.annotateUseCount,annotateSendImmediately:n};$a(o),e({annotateSendImmediately:n})},annotationsFor:(n,s)=>{const o=t().queues.get(n);if(!o||o.items.length===0)return yS;if(!s)return o.items;let r=SS.get(o.items);r||(r=new Map,SS.set(o.items,r));const a=r.get(s);if(a)return a;const l=o.items.filter(d=>d.browserId===s),c=l.length===0?yS:l;return r.set(s,c),c},pageKeyOf:n=>t().pages.get(n),setBrowserUrl:(n,s)=>{if(!s)return;const o=Tj(s),r=t().pages;if(r.get(n)===o)return;const a=new Map(r);a.delete(n),a.set(n,o),id(t().queues,a),e({pages:a})},dispatchQueue:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=wS(r,s);if(a===r)return;const l=new Map(o.queues);l.delete(n),a.items.length>0&&l.set(n,a),id(l,o.pages),e({queues:l})},addAnnotation:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=wS(r,{type:"add",draft:s});if(a===r)return;const l=new Map(o.queues);l.delete(n),a.items.length>0&&l.set(n,a),id(l,o.pages);const c=o.annotateUseCount+1;return $a({annotateHovered:o.annotateHovered,annotateEntered:o.annotateEntered,annotateUseCount:c,annotateSendImmediately:o.annotateSendImmediately}),e({queues:l,annotateUseCount:c}),a.items.find(d=>d.id===s.id)},updateAnnotation:(n,s,o,r)=>{t().dispatchQueue(n,{type:"update",id:s,comment:o,images:r})},removeAnnotations:(n,s)=>{t().dispatchQueue(n,{type:"remove",ids:s})},clearAnnotations:(n,s)=>{if(!s){t().dispatchQueue(n,{type:"clear"});return}const o=t().annotationsFor(n,s).map(r=>r.id);o.length>0&&t().dispatchQueue(n,{type:"remove",ids:o})},restoreAnnotations:(n,s)=>{t().dispatchQueue(n,{type:"restore",items:s})},registerSession:(n,{url:s,...o})=>{t().setBrowserUrl(n,s);const r=new Map(t().sessions);return r.set(n,{...o,pinned:new Set}),e({sessions:r}),()=>{const a=t().sessions;if(a.get(n)?.exit!==o.exit)return;const l=new Map(a);l.delete(n),e({sessions:l})}},setPinnedIds:(n,s)=>{const o=t().sessions,r=o.get(n);if(!r)return;const a=new Set(s);if(r.pinned.size===a.size&&[...r.pinned].every(c=>a.has(c)))return;const l=new Map(o);l.set(n,{...r,pinned:a}),e({sessions:l})},exitAgentSessions:n=>{for(const s of t().sessions.values())s.agent===n&&s.exit()},resetForTests:()=>{$a(Ro),id(new Map,new Map),e({...Ro,queues:new Map,pages:new Map,sessions:new Map})}})),aa=typeof navigator<"u"&&navigator.platform?navigator.platform.startsWith("Mac"):!0,ng=aa?"⌘⇧D":"Ctrl+Shift+D";function sf({className:e}){return i.jsx("svg",{viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",className:W("h-3.5 w-3.5 shrink-0",e),children:i.jsx("path",{d:"M14.434 6.765c.793 0 1.076 1.051.388 1.448l-3.593 2.074v4.15c0 .793-1.052 1.075-1.449.387L5.8 7.93c-.299-.517.075-1.164.672-1.164zM13 .875c1.174 0 2.125.951 2.125 2.125v1c0 .345-.28.625-.625.625s-.625-.28-.625-.625V3c0-.483-.392-.875-.875-.875H3c-.483 0-.875.392-.875.875v10c0 .483.392.875.875.875h3c.345 0 .625.28.625.625s-.28.625-.625.625H3C1.826 15.125.875 14.174.875 13V3C.875 1.826 1.826.875 3 .875zm-5.708 7.14 2.687 4.651v-2.565c0-.331.176-.638.462-.803l2.223-1.283z"})})}async function SX(e){return e.markup.length===0||!e.base64?e.base64:new Promise(t=>{const n=new Image;n.onload=()=>{try{const s=document.createElement("canvas");s.width=Math.max(1,n.naturalWidth||n.width),s.height=Math.max(1,n.naturalHeight||n.height);const o=s.getContext("2d");if(!o){t(e.base64);return}o.drawImage(n,0,0);const r=s.width/Math.max(1,e.cropWidth);o.scale(r,r),o.fillStyle=Kr,o.strokeStyle=Kr,o.lineWidth=Hf,o.lineCap="round",o.lineJoin="round";for(const l of e.markup)for(const c of Ff(l,"complete")){const d=new Path2D(c.d);c.paint==="fill"?o.fill(d):o.stroke(d)}const a=s.toDataURL("image/png");t(a.slice(a.indexOf(",")+1))}catch{t(e.base64)}},n.onerror=()=>t(e.base64),n.src=e.base64.startsWith("data:")?e.base64:`data:image/png;base64,${e.base64}`})}function CX({active:e}){const t=m.useRef(null),[n,s]=m.useState(null),o=m.useRef(e),[r,a]=m.useState({width:0,height:0});m.useEffect(()=>{o.current!==e&&(o.current=e,s(e?"in":"out"))},[e]),m.useEffect(()=>{const c=t.current;if(!c)return;const d=()=>{const h=c.getBoundingClientRect();a({width:Math.round(h.width),height:Math.round(h.height)})};d();const u=new ResizeObserver(d);return u.observe(c),()=>u.disconnect()},[]);const l=m.useMemo(()=>r.width>4&&r.height>4?p2(r.width,r.height,{topLeft:6,topRight:6,bottomRight:6,bottomLeft:6}):null,[r.width,r.height]);return!n&&!e?i.jsx("div",{ref:t,className:"pointer-events-none absolute inset-0"}):i.jsx("div",{ref:t,"aria-hidden":"true","data-component":"design-frame-ring","data-trace":n??(e?"in":"out"),className:"pointer-events-none absolute inset-0 z-20 overflow-hidden",children:l&&i.jsxs("svg",{width:r.width,height:r.height,"aria-hidden":"true",className:"block h-full w-full overflow-visible",onAnimationEnd:()=>{e||s(null)},children:[i.jsx("path",{d:l.right,pathLength:1,fill:"none",stroke:"rgb(58, 150, 221)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:1,strokeDashoffset:n==="out"?1:0,transition:n==="out"?"stroke-dashoffset 350ms cubic-bezier(0.65, 0, 0.35, 1)":"stroke-dashoffset 550ms cubic-bezier(0.65, 0, 0.35, 1)"}}),i.jsx("path",{d:l.left,pathLength:1,fill:"none",stroke:"rgb(58, 150, 221)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:1,strokeDashoffset:n==="out"?1:0,transition:n==="out"?"stroke-dashoffset 350ms cubic-bezier(0.65, 0, 0.35, 1)":"stroke-dashoffset 550ms cubic-bezier(0.65, 0, 0.35, 1)"}})]})})}function kX({drawing:e,pick:t,markupTool:n,editorOpen:s,onMarkupToolChange:o,onExit:r}){const a=d2({drawing:e,pick:t?{region:t.region}:null,markupToolHeld:n!==null,editorOpen:s}),c=m.useMemo(()=>u2(aa),[])[a],d=h=>h.map((p,f)=>typeof p=="string"?i.jsx("span",{children:p},f):i.jsx("strong",{className:"font-semibold text-foreground",children:p.key},f)),u=h=>{switch(h){case"pencil":return i.jsx($s,{className:"h-3.5 w-3.5"});case"circle":return i.jsx(Vx,{className:"h-3.5 w-3.5"});case"square":return i.jsx(mc,{className:"h-3.5 w-3.5"});case"arrow-right-up":return i.jsx(M$,{className:"h-3.5 w-3.5"})}};return i.jsxs("div",{"data-component":"design-hint-row",style:{backgroundColor:"var(--background)"},className:"flex h-8 shrink-0 items-center justify-between gap-2 border-b px-2.5 text-xs",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx("button",{type:"button",onClick:r,"aria-label":"Exit design mode",title:`Exit Design Mode (${ng})`,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-black/5 hover:text-foreground dark:hover:bg-white/10",children:i.jsx(dn,{className:"h-3.5 w-3.5"})}),i.jsx("span",{"data-hint":"",className:"truncate text-[12px] text-muted-foreground transition-all duration-150",children:d(c)})]}),i.jsx("div",{role:"toolbar","aria-label":"Screenshot markup tools",className:"flex shrink-0 items-center gap-0.5 rounded-md border bg-background/90 p-0.5 shadow-2xs",children:h2.map(h=>{const p=n===h.tool;return i.jsx("button",{type:"button","aria-label":h.label,"aria-pressed":p,title:h.label,onClick:()=>o(p?null:h.tool),className:W("flex h-5 w-5 items-center justify-center rounded-sm transition-colors",p?"bg-[#3a96dd] text-white":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:u(h.icon)},h.tool)})})]})}function jX({tabId:e,conversationId:t,active:n,disabled:s,queueOpen:o,onQueueOpenChange:r,onToggleDesignMode:a,onOpenPinFromQueue:l,onSendQueue:c}){const{t:d}=ne(),u=Kn(_=>_.familiarity()),h=Kn(_=>_.annotateHovered),p=Kn(_=>_.markHovered),f=Kn(_=>_.annotationsFor(t)),g=Kn(_=>_.annotationsFor(t,e)),x=Kn(_=>_.removeAnnotations),v=Kn(_=>_.clearAnnotations),[y,b]=m.useState(!1),w=n?f:g,C=w.length;return C===0&&!n?i.jsxs("div",{className:"relative flex shrink-0 items-center",children:[i.jsxs("button",{type:"button",disabled:s,"aria-label":"Annotate","aria-pressed":n,title:`Annotate (${ng}) — Point at anything and tell the agent what to fix`,onPointerEnter:()=>{p(),u==="never"&&b(!0)},onPointerLeave:()=>b(!1),onClick:()=>{b(!1),a(!0)},className:W("relative flex h-6 items-center justify-center gap-1 overflow-hidden rounded text-xs font-medium transition-colors disabled:opacity-40",u==="many"?"w-6 text-muted-foreground hover:bg-muted hover:text-foreground":"px-2 text-foreground hover:bg-muted",u==="never"&&!h&&"border border-sky-500/40 bg-sky-500/10"),children:[i.jsx(sf,{}),u!=="many"&&i.jsx("span",{children:"Annotate"}),u==="never"&&!h&&!s&&i.jsx("span",{"aria-hidden":"true","data-gradient-sweep":"",className:"pointer-events-none absolute inset-0 bg-linear-to-r from-transparent via-sky-400/20 to-transparent animate-pulse"})]}),y&&!s&&i.jsxs("div",{"data-enso-float":"",role:"tooltip","aria-label":"Try Annotate",className:"absolute top-full right-0 z-50 mt-1.5 w-64 rounded-lg border bg-popover p-3 text-popover-foreground shadow-xl",children:[i.jsx("div",{className:"mb-2 flex h-24 items-center justify-center rounded-md border border-sky-500/20 bg-sky-500/5",children:i.jsxs("div",{className:"flex flex-col items-center gap-1 text-sky-500",children:[i.jsx(sf,{className:"h-6 w-6"}),i.jsx("span",{className:"rounded bg-sky-500 px-1.5 py-0.5 text-[10px] font-semibold text-white",children:"Click · Drag · Draw · Edit CSS"})]})}),i.jsx("h2",{className:"text-xs font-semibold",children:"Try Annotate"}),i.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Point at anything on the page and tell the agent what to fix."})]})]}):i.jsxs("div",{className:"relative flex shrink-0 items-center","data-design-annotation-queue":"",children:[C>0?i.jsxs("div",{className:"flex h-6 items-center overflow-hidden rounded-md border border-[#3a96dd]/40 bg-[#3a96dd] text-white shadow-2xs",children:[i.jsxs("button",{type:"button",onClick:()=>c(n?void 0:new Set(g.map(_=>_.id))),title:d("Send annotations to chat"),className:"flex h-full items-center gap-1 px-2 text-xs font-medium transition-opacity hover:opacity-90",children:[i.jsx("span",{children:"Send"}),i.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-white/20 px-1 text-[10px] font-semibold tabular-nums",children:C})]}),i.jsx("button",{type:"button","aria-label":`Open annotation queue (${C})`,"aria-expanded":o,onClick:()=>r(!o),className:"flex h-full items-center border-l border-white/20 px-1 transition-colors hover:bg-black/10",children:i.jsx($n,{className:"h-3 w-3"})})]}):i.jsxs("button",{type:"button",onClick:()=>a(!1),"aria-label":"Annotate","aria-pressed":n,title:`Exit Design Mode (${ng})`,className:"flex h-6 items-center gap-1 rounded bg-[#3a96dd]/15 px-2 text-xs font-medium text-[#3a96dd]",children:[i.jsx(sf,{}),u!=="many"&&i.jsx("span",{children:"Annotate"})]}),o&&C>0&&i.jsxs("div",{"data-enso-float":"","data-design-owns-escape":"",className:"absolute top-full right-0 z-50 mt-1.5 w-72 overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-xl",children:[i.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-xs",children:[i.jsx("span",{className:"font-medium text-muted-foreground",children:C===1?"1 edit":`${C} edits`}),i.jsx("button",{type:"button",onClick:()=>{v(t,n?void 0:e),r(!1)},className:"text-[11px] text-muted-foreground transition-colors hover:text-destructive",children:"Clear All"})]}),i.jsx("div",{className:"max-h-64 divide-y overflow-y-auto",children:w.map(_=>{const N=_.kind==="region"&&_.images[0]?`data:${_.images[0].mimeType};base64,${_.images[0].data}`:null,k=_.kind==="element"&&_.elements.length>1?_.elements.length-1:0,S=_.comment.trim()||(_.kind==="element"&&_.elements[0]?c2(_.elements[0]):_.kind==="region"?`Screenshot region ${Math.round(_.region.rect.width)} × ${Math.round(_.region.rect.height)}`:"Annotation");return i.jsxs("div",{className:"group flex items-center gap-2 px-2.5 py-2 text-xs hover:bg-muted/60",children:[i.jsxs("button",{type:"button",onClick:()=>{r(!1),l(_)},className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-t-full rounded-br-full rounded-bl-xs bg-[#3a96dd] text-[11px] font-semibold text-white tabular-nums",children:_.number}),N&&i.jsx("img",{src:N,alt:"",className:"h-5 w-7 shrink-0 rounded border object-cover"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:S}),k>0&&i.jsxs("span",{className:"shrink-0 rounded bg-muted px-1 py-0.5 text-[10px] text-muted-foreground",children:["+",k]})]}),i.jsx("button",{type:"button","aria-label":"Delete annotation",onClick:()=>x(t,[_.id]),className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-destructive/10 hover:text-destructive",children:i.jsx(Vs,{className:"h-3 w-3"})})]},_.id)})})]})]})}function _X({stage:e,pinned:t,onTogglePinned:n,onClose:s,onStageChange:o}){const[r,a]=m.useState(""),l=m.useMemo(()=>Dj(e),[e]),c=m.useMemo(()=>{const h={...e.baseline.values};for(const[p,f]of e.edits)f&&(h[p]=f);return h},[e.baseline.values,e.edits]),d=m.useMemo(()=>{const h=r.trim().toLowerCase();return T2.filter(p=>I2(p,{rendersText:e.baseline.rendersText,values:c})&&p.name.includes(h))},[r,e.baseline.rendersText,c]),u=h=>{const p=P2(e,h);o(p.staging,p.filed)};return i.jsxs("div",{className:"flex flex-col border-t bg-background/95",children:[i.jsxs("div",{className:"flex items-center gap-1.5 border-b px-2.5 py-1.5",children:[i.jsx("input",{type:"text",value:r,onChange:h=>a(h.target.value),placeholder:"Filter CSS properties...",className:"min-w-0 flex-1 rounded border bg-muted/40 px-2 py-0.5 text-[11px] outline-none focus:border-ring"}),l.canReset&&i.jsx("button",{type:"button","aria-label":"Reset all CSS edits",title:"Reset all CSS edits",onClick:()=>u({kind:"resetAll"}),className:"flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(da,{className:"h-3 w-3"})}),i.jsx("button",{type:"button","aria-label":"Pin CSS inspector","aria-pressed":t,title:t?"Unpin inspector":"Pin inspector to top right",onClick:n,className:W("flex h-5 w-5 items-center justify-center rounded transition-colors",t?"bg-[#3a96dd]/15 text-[#3a96dd]":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:i.jsx(hi,{className:"h-3 w-3"})}),i.jsx("button",{type:"button","aria-label":"Close CSS inspector",onClick:s,className:"flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(dn,{className:"h-3 w-3"})})]}),i.jsx("div",{className:"max-h-52 divide-y overflow-y-auto px-2 py-1 text-[11px]",children:d.map(h=>{const p=e.edits.get(h.name),f=p===null,g=l.isEdited(h.name),x=l.isAuthored(h.name),v=f?e.baseline.values[h.name]??"":p??e.baseline.values[h.name]??"",y=h.name.endsWith("color"),b=`css-presets-${h.name}`;return i.jsxs("div",{className:"flex items-center gap-1.5 py-1",children:[i.jsx("input",{type:"checkbox",checked:!f&&(g||x),"aria-label":`Toggle ${h.name}`,onChange:w=>{w.target.checked?u({kind:"enable",property:h.name}):u({kind:"disable",property:h.name})},className:"h-3 w-3 shrink-0 accent-[#3a96dd]"}),i.jsx("span",{className:W("w-28 shrink-0 truncate font-mono text-[10px]",f&&"line-through opacity-50",g?"font-semibold text-[#3a96dd]":x?"text-foreground":"text-muted-foreground"),title:h.name,children:h.name}),y&&i.jsx("input",{type:"color","aria-label":`${h.name} color picker`,value:/^#[0-9a-fA-F]{6}$/.test(v)?v:"#3a96dd",onChange:w=>u({kind:"edit",property:h.name,value:w.target.value}),className:"h-4 w-4 shrink-0 cursor-pointer rounded border bg-transparent p-0"}),i.jsx("input",{type:"text",list:h.presets?.length?b:void 0,value:v,disabled:f,onChange:w=>u({kind:"edit",property:h.name,value:w.target.value}),onKeyDown:w=>{if(w.key!=="ArrowUp"&&w.key!=="ArrowDown")return;const C=D2(v,w.key==="ArrowUp"?1:-1,w.shiftKey,h);C!==null&&(w.preventDefault(),w.stopPropagation(),u({kind:"edit",property:h.name,value:C}))},className:W("min-w-0 flex-1 rounded border bg-transparent px-1.5 py-0.5 font-mono text-[10px] outline-none focus:border-ring",f&&"opacity-40")}),h.presets&&h.presets.length>0&&i.jsxs("datalist",{id:b,children:[h.presets.map(w=>i.jsx("option",{value:w},w)),e.baseline.variables.lengths.map(w=>i.jsx("option",{value:`var(${w.name})`},w.name)),y&&e.baseline.variables.colors.map(w=>i.jsx("option",{value:`var(${w.name})`},w.name))]}),(g||f)&&i.jsx("button",{type:"button","aria-label":`Reset ${h.name}`,title:"Reset property",onClick:()=>u({kind:"reset",property:h.name}),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(da,{className:"h-2.5 w-2.5"})})]},h.name)})})]})}function NX({tabId:e,conversationId:t,stageSize:n,draftPick:s,openPin:o,markupTool:r,warningShown:a,onWarningShownChange:l,onDraftPickChange:c,onMoveSelection:d,onCancelDraft:u,onCloseOpenPin:h,onSendQueue:p,onStrokeStateChange:f,active:g}){const{t:x}=ne(),v=Kn(re=>re.annotateSendImmediately),y=Kn(re=>re.setSendImmediately),b=Kn(re=>re.addAnnotation),w=Kn(re=>re.updateAnnotation),C=Kn(re=>re.removeAnnotations),_=Kn(re=>re.annotationsFor(t)),N=m.useMemo(()=>o?_.find(re=>re.id===o.id)??null:null,[_,o]),k=m.useMemo(()=>f2(N?.comment??""),[N?.comment]),[S,A]=m.useState(""),[T,I]=m.useState([]),[P,D]=m.useState(!1),[O,z]=m.useState(!1),[R,$]=m.useState(null),[X,H]=m.useState({x:0,y:0}),[te,V]=m.useState(!1),[Y,q]=m.useState(null),[ee,ge]=m.useState("move"),[Ce,Re]=m.useState(null),fe=m.useRef(null),U=m.useRef(null),oe=m.useRef(null),Se=m.useRef(null),G=m.useId(),Q=o?`pin:${o.id}`:s?"draft":"none";m.useEffect(()=>{A(k.prose),I(N?N.images.slice(1):[]),D(!1),$(null),H({x:0,y:0}),l(!1),window.setTimeout(()=>oe.current?.focus(),10)},[Q]),m.useEffect(()=>{const re=m2(_.filter(Ue=>Ue.browserId===e));window.electronAPI.browser.previewDesignCss(e,"queue",re)},[_,e]);const ae=m.useMemo(()=>N?N.kind==="element"?N.elements:[]:s?.description.elements??[],[N,s]),Z=ae.length===1?ae[0]:null,ce=m.useCallback(async()=>{if(!Z)return;if(P){D(!1);return}const re=await window.electronAPI.browser.readDesignCss(e,Z.uniqueId);if(!re){ze({type:"warning",title:x("Could not read CSS for this element")});return}$(g2(re,k.css)),D(!0)},[Z,P,e,k.css,x]);m.useEffect(()=>{if(!g||!s?.region)return;const re=Ue=>{if(!(aa?Ue.metaKey:Ue.ctrlKey)||Ue.altKey||Ue.key.toLowerCase()!=="z")return;const Dt=document.activeElement===oe.current&&S.length>0;if(_2({markCount:s.markup.length+s.redoMarkup.length,toolHeld:r!==null,noteOwnsUndo:Dt}))if(Ue.preventDefault(),Ue.stopPropagation(),Ue.shiftKey){const it=s.redoMarkup.at(-1);if(!it)return;c({...s,markup:[...s.markup,it],redoMarkup:s.redoMarkup.slice(0,-1)})}else{const it=s.markup.at(-1);if(!it)return;c({...s,markup:s.markup.slice(0,-1),redoMarkup:[...s.redoMarkup,it]})}};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[g,s,r,S.length,c]),m.useEffect(()=>{if(!Y||!s)return;const re={left:0,top:0,width:n.width,height:n.height},Ue=(it,K)=>{const pe=it.key===" "?"Space":it.key==="Shift"||it.key==="Alt"||it.key==="Escape"?it.key:null;pe&&(pe==="Space"&&it.preventDefault(),q(Ie=>Ie?E0(Ie,{type:"key",key:pe,down:K},re):null))},dt=it=>Ue(it,!0),Dt=it=>Ue(it,!1);return window.addEventListener("keydown",dt,!0),window.addEventListener("keyup",Dt,!0),()=>{window.removeEventListener("keydown",dt,!0),window.removeEventListener("keyup",Dt,!0)}},[Y,s,n.width,n.height]);const De=m.useMemo(()=>R?Dj(R):null,[R]),Oe=!!(De&&De.changes.size>0),Ne=S.trim().length>0,Ze=N!==null,bt=Ze?S.trim()!==k.prose.trim()||!!De?.isDirty:Ne||Oe||(s?.markup.length??0)>0,Ut=m.useMemo(()=>De?N0(S,De.changes):k.css.size>0?N0(S,k.css):S.trim(),[S,De,k.css]),Et=Ze?!0:Ut.length>0||s?.region!==null&&(s?.markup.length??0)>0,_t=N2({sendImmediately:v,isOnStack:Ze}),B=Oe&&!Ne?T0[_t].css:T0[_t].note,Te=m.useCallback(()=>{const re=ae;if(re.length===0)return;let Ue=!1;re.forEach((dt,Dt)=>{const it=`ui-${Date.now()}-${Dt}`,K=Gf(dt),pe=Dt===0&&s?.description.image?{data:s.description.image.data,mimeType:s.description.image.mimeType}:void 0;Yx({kind:"ui-element",id:it,label:K,path:dt.path||dt.tagName.toLowerCase(),text:(dt.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||Ij(dt),imageId:`img-${it}`},pe)&&(Ue=!0)}),Ue?(_o(),u()):ze({type:"warning",title:x("No Composer for this selection")})},[ae,s?.description.image,u,x]),We=m.useCallback(async()=>{if(!(te||!Et)){V(!0);try{if(Ze&&N){const K=N.images.length>0?[N.images[0],...T]:[...T];w(t,N.id,Ut,K),window.electronAPI.browser.previewDesignCss(e,"draft",{}),h(),v&&p(new Set([N.id]));return}if(!s)return;const re=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ann-${Date.now()}`,Ue=Kn.getState().pageKeyOf(e)??"http://localhost/",dt=s.description.image,Dt=[];if(dt){const K=s.region&&s.markup.length>0?await SX({base64:dt.data,markup:s.markup,cropWidth:s.region.width}):dt.data;Dt.push({id:`img-${re}`,data:K,mimeType:dt.mimeType,name:dt.name,width:dt.width,height:dt.height})}Dt.push(...T);let it;if(s.region){const K=s.description.regionAnchor??{tagName:"BODY",id:"",uniqueId:"region-root",className:"",innerText:"",path:"body",attributes:[],rect:{top:s.region.top,left:s.region.left,width:s.region.width,height:s.region.height},styles:{color:"",backgroundColor:"",fontSize:"",fontFamily:"",display:"block",position:"static"}};it=b(t,{id:re,kind:"region",comment:Ut,browserId:e,pageKey:Ue,images:Dt,region:{rect:s.region,anchor:K,markup:s.markup}})}else it=b(t,{id:re,kind:"element",comment:Ut,browserId:e,pageKey:Ue,images:Dt,elements:s.description.elements});window.electronAPI.browser.previewDesignCss(e,"draft",{}),u(),v&&it&&p(new Set([it.id]))}finally{V(!1)}}},[te,Et,Ze,N,T,w,t,Ut,e,h,v,p,s,b,u]),kt=m.useCallback(()=>{if(bt&&!a){l(!0);return}l(!1),window.electronAPI.browser.previewDesignCss(e,"draft",{}),Ze?h():u()},[bt,a,l,e,Ze,h,u]),Gt=re=>{for(const Ue of re){if(!Ue.type.startsWith("image/"))continue;const dt=new FileReader;dt.onload=()=>{const Dt=dt.result,it=Dt.slice(Dt.indexOf(",")+1);I(K=>[...K,{id:`att-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,data:it,mimeType:Ue.type,name:Ue.name}])},dt.readAsDataURL(Ue)}},de=Y?Y.rect:s?.region??null,mt=Math.min(320,Math.max(240,n.width-16)),Lt=P?360:148,Fe=m.useMemo(()=>{if(o)return x2(o.badge,n,{width:mt,height:Lt});if(de)return I0({x:de.left,y:de.top,width:de.width,height:de.height},n,mt,Lt);if(s&&s.elements.length>0){const re=s.elements.map(pe=>pe.rect.x),Ue=s.elements.map(pe=>pe.rect.y),dt=s.elements.map(pe=>pe.rect.x+pe.rect.width),Dt=s.elements.map(pe=>pe.rect.y+pe.rect.height),it=Math.min(...re),K=Math.min(...Ue);return I0({x:it,y:K,width:Math.max(...dt)-it,height:Math.max(...Dt)-K},n,mt,Lt)}return{x:16,y:16}},[o,de,s,n,mt,Lt]),Nt=O?Math.max(8,n.width-mt-8):Math.max(8,Math.min(Fe.x+X.x,n.width-mt-8)),Ft=O?8:Math.max(8,Math.min(Fe.y+X.y,n.height-120));if(!s&&!o)return null;const on=s?.description.frame?`data:${s.description.frame.mimeType};base64,${s.description.frame.data}`:null;return i.jsxs("div",{"data-enso-float":"",className:"absolute inset-0 z-30 select-none overflow-hidden",onMouseDown:re=>{re.target===re.currentTarget&&kt()},children:[s&&de&&i.jsxs(i.Fragment,{children:[on&&i.jsx("img",{src:on,alt:"",draggable:!1,className:"pointer-events-none absolute inset-0 h-full w-full object-fill"}),i.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 bg-slate-950/35",style:{clipPath:`polygon(0% 0%, 0% 100%, ${de.left}px 100%, ${de.left}px ${de.top}px, ${de.left+de.width}px ${de.top}px, ${de.left+de.width}px ${de.top+de.height}px, ${de.left}px ${de.top+de.height}px, ${de.left}px 100%, 100% 100%, 100% 0%)`}}),i.jsxs("div",{role:"application","aria-label":"Selected screenshot region",style:{left:de.left,top:de.top,width:de.width,height:de.height,cursor:r!==null?"crosshair":k2(Y?Y.handle:ee,Y!==null)},onPointerMove:re=>{const Ue=re.currentTarget.getBoundingClientRect(),dt={x:re.clientX-Ue.left,y:re.clientY-Ue.top};if(r!==null){if(!Ce||!fe.current)return;const Dt={x:Math.max(0,Math.min(de.width,dt.x)),y:Math.max(0,Math.min(de.height,dt.y))};if(Ce.kind==="pen")Re({kind:"pen",points:S2(Ce.points,Dt)});else{const it=re.shiftKey?C2({kind:Ce.kind,from:fe.current,to:Dt}):Dt;Re({kind:Ce.kind,from:fe.current,to:it})}return}if(Y){const Dt=re.currentTarget.parentElement?.getBoundingClientRect(),it={x:re.clientX-(Dt?.left??0),y:re.clientY-(Dt?.top??0)};q(K=>K?E0(K,{type:"move",point:it,altKey:re.altKey,shiftKey:re.shiftKey},{left:0,top:0,width:n.width,height:n.height}):null);return}ge(D0(dt,de))},onPointerDown:re=>{if(re.button!==0)return;re.preventDefault(),re.stopPropagation(),re.currentTarget.setPointerCapture(re.pointerId);const Ue=re.currentTarget.getBoundingClientRect(),dt={x:Math.max(0,Math.min(de.width,re.clientX-Ue.left)),y:Math.max(0,Math.min(de.height,re.clientY-Ue.top))};if(r!==null){fe.current=dt,f(!0),Re(r==="pen"?{kind:"pen",points:[dt]}:{kind:r,from:dt,to:dt});return}const Dt=re.currentTarget.parentElement?.getBoundingClientRect(),it={x:re.clientX-(Dt?.left??0),y:re.clientY-(Dt?.top??0)},K=D0(dt,de);q(y2({handle:K,point:it,rect:de,modifiers:{altKey:re.altKey,shiftKey:re.shiftKey}}))},onPointerUp:async()=>{if(Ce){const re=v2(s.markup,Ce);Re(null),fe.current=null,f(!1),re.length!==s.markup.length&&c({...s,markup:re,redoMarkup:[]});return}if(Y){const re=b2({rect:Y.rect,viewport:n}),Ue=w2({markup:s.markup,from:s.region??re,to:re,markupScale:1});q(null);const dt=await window.electronAPI.browser.describeSelection(e,{x:re.left,y:re.top,width:re.width,height:re.height});c({...s,region:re,markup:Ue,description:dt.image?dt:s.description})}},className:"absolute box-border border-2 border-[#3a96dd] border-dashed shadow-lg",children:[i.jsxs("svg",{role:"img","aria-label":"Draw on screenshot region",width:de.width,height:de.height,className:"pointer-events-none block h-full w-full overflow-visible",children:[s.markup.map((re,Ue)=>Ff(re,"complete").map((dt,Dt)=>i.jsx("path",{d:dt.d,"data-design-markup-stroke":"",fill:dt.paint==="fill"?Kr:"none",stroke:dt.paint==="stroke"?Kr:"none",strokeWidth:dt.paint==="stroke"?Hf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`${Ue}-${Dt}`))),Ce&&Ff(Ce,"active").map((re,Ue)=>i.jsx("path",{d:re.d,"data-design-markup-stroke":"active",fill:re.paint==="fill"?Kr:"none",stroke:re.paint==="stroke"?Kr:"none",strokeWidth:re.paint==="stroke"?Hf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`active-${Ue}`))]}),r===null&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"pointer-events-none absolute -top-1.5 -left-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -top-1.5 -right-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -bottom-1.5 -left-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -right-1.5 -bottom-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"})]})]})]}),i.jsxs("div",{style:{left:Nt,top:Ft,width:mt},onMouseDown:re=>re.stopPropagation(),className:"glass-browser-design-input absolute z-40 flex flex-col overflow-hidden rounded-2xl border border-border/80 bg-popover/95 text-popover-foreground shadow-[0_14px_38px_-8px_rgba(0,0,0,0.32),0_4px_14px_-2px_rgba(0,0,0,0.16)] backdrop-blur-xl transition-shadow duration-150 focus-within:border-[#3a96dd]/55 focus-within:ring-2 focus-within:ring-[#3a96dd]/15 dark:border-white/12",children:[i.jsxs("div",{onPointerDown:re=>{re.button!==0||O||re.target instanceof Element&&re.target.closest("button, input")||(re.preventDefault(),re.currentTarget.setPointerCapture(re.pointerId),U.current={pointerId:re.pointerId,startX:re.clientX,startY:re.clientY,nudgeX:X.x,nudgeY:X.y})},onPointerMove:re=>{const Ue=U.current;!Ue||Ue.pointerId!==re.pointerId||H({x:Ue.nudgeX+(re.clientX-Ue.startX),y:Ue.nudgeY+(re.clientY-Ue.startY)})},onPointerUp:()=>{U.current=null},className:W("flex items-center justify-between gap-2 px-3 pt-2.5 pb-1",!O&&"cursor-grab active:cursor-grabbing"),children:[i.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:de||N?.kind==="region"?i.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-[#3a96dd]/25 bg-[#3a96dd]/12 px-2 py-0.5 text-[11px] font-medium text-[#3a96dd]",children:[s?.description.image&&i.jsx("img",{src:`data:${s.description.image.mimeType};base64,${s.description.image.data}`,alt:"",className:"h-4 w-5 rounded-[3px] object-cover ring-1 ring-black/10 dark:ring-white/15"}),i.jsxs("span",{children:["Region"," ",Math.round(de?.width??(N?.kind==="region"?N.region.rect.width:0))," ","×"," ",Math.round(de?.height??(N?.kind==="region"?N.region.rect.height:0))]})]}):ae.map((re,Ue)=>{const dt=dp[(re.hueIndex??Ue)%dp.length]??dp[0],Dt=up[(re.hueIndex??Ue)%up.length]??up[0];return i.jsxs("span",{style:{backgroundColor:dt.bg,borderColor:Dt.stroke,color:dt.border},title:`${j2(re)} — ${re.path}`,className:"inline-flex max-w-48 items-center gap-1.5 truncate rounded-md border px-2 py-0.5 font-mono text-[11px] font-medium shadow-2xs",children:[i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full",style:{backgroundColor:dt.border}}),i.jsx("span",{className:"truncate",children:Gf(re)})]},re.uniqueId||`${re.tagName}-${Ue}`)})}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 rounded-lg bg-muted/50 p-0.5",children:[!Ze&&!de&&ae.length===1&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:()=>d("parent"),title:"Select parent element (Shift+Enter or \\)","aria-label":"Select parent element",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(d6,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",onClick:()=>d("previous"),title:"Select previous sibling (Shift+Tab)","aria-label":"Select previous sibling",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(pc,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",onClick:()=>d("next"),title:"Select next sibling (Tab)","aria-label":"Select next sibling",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(Ej,{className:"h-3 w-3"})})]}),ae.length>0&&i.jsx("button",{type:"button",onClick:Te,title:`Add element to chat (${aa?"⌘L":"Ctrl+L"})`,"aria-label":"Add element to chat",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(Ho,{className:"h-3 w-3"})}),Z&&i.jsx("button",{type:"button",onClick:()=>{ce()},"aria-label":"Edit CSS properties","aria-pressed":P,title:"Edit CSS properties",className:W("flex h-5 w-5 items-center justify-center rounded-md transition-colors",P||Oe?"bg-[#3a96dd]/15 text-[#3a96dd]":"text-muted-foreground hover:bg-background/80 hover:text-foreground"),children:i.jsx(y4,{className:"h-3 w-3"})}),Ze&&N&&i.jsx("button",{type:"button","aria-label":"Delete annotation",title:"Delete annotation",onClick:()=>{C(t,[N.id]),h()},className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/15 hover:text-destructive",children:i.jsx(Vs,{className:"h-3 w-3"})})]})]}),T.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 px-3 pt-1.5",children:T.map(re=>i.jsxs("div",{className:"group relative h-11 w-15 overflow-hidden rounded-lg border border-border/70 shadow-2xs",children:[i.jsx("img",{src:`data:${re.mimeType};base64,${re.data}`,alt:"",className:"h-full w-full object-cover"}),i.jsx("button",{type:"button","aria-label":"Remove attached image",onClick:()=>I(Ue=>Ue.filter(dt=>dt.id!==re.id)),className:"absolute top-0.5 right-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-black/70 text-white opacity-0 transition-opacity group-hover:opacity-100",children:i.jsx(dn,{className:"h-2.5 w-2.5"})})]},re.id))}),i.jsxs("div",{className:"px-3 py-1.5",children:[i.jsx("textarea",{ref:oe,rows:2,value:S,onChange:re=>{A(re.target.value),a&&l(!1);const Ue=re.currentTarget;Ue.style.height="auto",Ue.style.height=`${Math.min(144,Math.max(44,Ue.scrollHeight))}px`},onPaste:re=>{const Ue=Array.from(re.clipboardData.files);Ue.length>0&&(re.preventDefault(),Gt(Ue))},onKeyDown:re=>{if(re.nativeEvent.isComposing)return;const Ue=aa?re.metaKey:re.ctrlKey;if(Ue&&re.key.toLowerCase()==="l"){re.preventDefault(),re.stopPropagation(),Te();return}if(re.key==="Enter"&&!re.shiftKey){if(Et||Ue){re.preventDefault(),re.stopPropagation(),We();return}if(!Ze&&!de&&ae.length>0){re.preventDefault(),re.stopPropagation(),d("child");return}}if(!Et&&!Ze&&!de&&ae.length>0){if(re.key==="Enter"&&re.shiftKey||re.key==="\\"){re.preventDefault(),re.stopPropagation(),d("parent");return}if(re.key==="Tab"){re.preventDefault(),re.stopPropagation(),d(re.shiftKey?"previous":"next");return}}Ze&&N&&!Ne&&!Oe&&(re.key==="Backspace"||re.key==="Delete")&&!re.altKey&&!re.ctrlKey&&!re.metaKey&&!re.repeat&&(re.preventDefault(),re.stopPropagation(),C(t,[N.id]),h())},placeholder:Oe?"Add a note (optional)…":"Describe the change…",className:"min-h-[44px] w-full resize-none bg-transparent text-[13px] leading-5 outline-none placeholder:text-muted-foreground/60"}),Oe&&!P&&De&&i.jsx("section",{"aria-label":"CSS edits",className:"mt-1.5 flex flex-wrap gap-1 text-[10px] text-[#3a96dd]",children:[...De.changes].map(([re,Ue])=>i.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-[#3a96dd]/20 bg-[#3a96dd]/10 px-1.5 py-0.5 font-mono",children:[i.jsxs("span",{className:"font-medium",children:[re,":"]}),Ue.to===null?i.jsx("span",{children:"removed"}):i.jsxs(i.Fragment,{children:[i.jsx("del",{className:"opacity-65",children:Ue.from}),i.jsx("span",{className:"opacity-60",children:"→"}),i.jsx("ins",{className:"font-semibold no-underline",children:Ue.to})]})]},re))})]}),P&&R&&Z&&i.jsx(_X,{stage:R,pinned:O,onTogglePinned:()=>z(re=>!re),onClose:()=>D(!1),onStageChange:(re,Ue)=>{$(re),window.electronAPI.browser.previewDesignCss(e,"draft",{[Z.uniqueId]:Ue})}}),a&&i.jsxs("div",{"data-design-input-notice":"",className:"flex items-center justify-between gap-2 border-t bg-amber-500/10 px-2.5 py-1.5 text-[11px]",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("span",{className:"font-semibold text-amber-600 dark:text-amber-400",children:"Discard comment?"})," ",i.jsx("span",{className:"text-muted-foreground",children:"This comment isn't saved yet."})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>l(!1),className:"rounded border bg-background px-2 py-0.5 text-[10px] font-medium hover:bg-muted",children:"Keep Editing"}),i.jsx("button",{type:"button",onClick:()=>{l(!1),window.electronAPI.browser.previewDesignCss(e,"draft",{}),Ze?h():u()},className:"rounded bg-destructive px-2 py-0.5 text-[10px] font-medium text-white hover:opacity-90",children:"Discard"})]})]}),i.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border/50 bg-muted/20 px-3 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2.5",children:[i.jsx("input",{ref:Se,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:re=>{Gt(Array.from(re.target.files??[])),re.target.value=""}}),i.jsx("button",{type:"button",onClick:()=>Se.current?.click(),"aria-label":"Attach image to annotation",title:"Attach image",className:"flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:i.jsx(Eh,{className:"h-3.5 w-3.5"})}),i.jsxs("label",{htmlFor:G,className:"group flex cursor-pointer items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[i.jsx("input",{id:G,type:"checkbox",checked:!v,onChange:re=>y(!re.target.checked),className:"sr-only"}),i.jsx("span",{"aria-hidden":"true",className:W("relative inline-flex h-3.5 w-6 shrink-0 items-center rounded-full transition-colors duration-150",v?"bg-muted-foreground/30":"bg-[#3a96dd]"),children:i.jsx("span",{className:W("inline-block h-2.5 w-2.5 rounded-full bg-white shadow-2xs transition-transform duration-150",v?"translate-x-0.5":"translate-x-3")})}),i.jsx("span",{children:"Batch edits"})]})]}),i.jsxs("button",{type:"button",disabled:te||!Et,"aria-label":B,title:`${B} (Enter)`,onClick:()=>{We()},className:"flex h-7 items-center gap-1.5 rounded-lg bg-[#3a96dd] px-3 text-[11px] font-medium text-white shadow-xs transition-all hover:bg-[#3286c9] active:scale-[0.98] disabled:bg-muted disabled:text-muted-foreground disabled:opacity-50",children:[_t==="add-to-stack"?i.jsx(as,{className:"h-3 w-3"}):_t==="save-note"?i.jsx(Yn,{className:"h-3 w-3"}):i.jsx(fc,{className:"h-3 w-3"}),i.jsx("span",{children:B})]})]})]})]})}function TX({tabId:e,conversationId:t,url:n,designMode:s,onDesignModeState:o,active:r}){const{t:a}=ne(),[l,c]=m.useState(!1),[d,u]=m.useState(null),[h,p]=m.useState(null),[f,g]=m.useState(null),[x,v]=m.useState(!1),[y,b]=m.useState(!1),[w,C]=m.useState(!1),_=Kn(z=>z.annotationsFor(t,e)),N=Kn(z=>z.annotationsFor(t)),k=m.useRef(n);m.useEffect(()=>{n&&Kn.getState().setBrowserUrl(e,n),k.current!==n&&(k.current=n,u(null),p(null),b(!1),c(!1),v(!1))},[e,n]);const S=m.useCallback(async z=>{z?Kn.getState().markEntered():(u(null),p(null),g(null),b(!1),c(!1));const R=await window.electronAPI.browser.setDesignMode(e,z);o(R)},[e,o]);m.useEffect(()=>{if(!s||!n)return;const z=Tj(n),R=_.filter($=>$.pageKey===z).map(a2);window.electronAPI.browser.setAnnotationPins(e,z,R)},[s,n,_,e]);const A=m.useCallback(z=>{if(g(z),z!==null&&d&&d.region===null&&d.elements.length>0){const R=d.elements.map(ee=>ee.rect.x),$=d.elements.map(ee=>ee.rect.y),X=d.elements.map(ee=>ee.rect.x+ee.rect.width),H=d.elements.map(ee=>ee.rect.y+ee.rect.height),te=Math.max(0,Math.min(...R)-12),V=Math.max(0,Math.min(...$)-12),Y=Math.max(24,Math.max(...X)-te+12),q=Math.max(24,Math.max(...H)-V+12);u({...d,region:{left:te,top:V,width:Y,height:q}})}},[d]);m.useEffect(()=>window.electronAPI.browser.onDesignMode(z=>{if(z.tabId===e){if(z.type==="cancelled"){u(null),p(null),g(null),c(!1);return}if(z.type==="drawing"){c(z.drawing);return}if(z.type==="pins"){Kn.getState().setPinnedIds(e,z.ids);return}if(z.type==="pin-click"){u(null),b(!1),z.pin&&p({id:z.id,badge:z.pin});return}if(z.type==="select"){if(c(!1),p(null),b(!1),z.addToChat&&z.description.elements.length>0){z.description.elements.forEach((R,$)=>{const X=`ui-${Date.now()}-${$}`,H=Gf(R),te=$===0&&z.description.image?{data:z.description.image.data,mimeType:z.description.image.mimeType}:void 0;Yx({kind:"ui-element",id:X,label:H,path:R.path||R.tagName.toLowerCase(),text:(R.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||Ij(R),imageId:`img-${X}`},te)}),_o(),window.electronAPI.browser.clearSelection(e);return}u({elements:z.elements,region:z.region?{left:z.region.x,top:z.region.y,width:z.region.width,height:z.region.height}:null,viewportWidth:z.viewportWidth,description:z.description,markup:[],redoMarkup:[]})}}}),[e]);const T=m.useCallback(()=>{u(null),g(null),b(!1),window.electronAPI.browser.clearSelection(e)},[e]),I=m.useCallback(()=>{p(null),b(!1),window.electronAPI.browser.openAnnotationPin(e,null,!1)},[e]),P=m.useCallback(async z=>{const R=await window.electronAPI.browser.moveSelection(e,z);R.elements.length!==0&&u($=>$?{...$,elements:R.elements,description:R.description}:null)},[e]),D=m.useCallback(async z=>{if(z.browserId!==e){ze({type:"info",title:a("Turn on design mode in this note's browser tab to open it")});return}s||await S(!0);const R=await window.electronAPI.browser.openAnnotationPin(e,z.id,!0);R&&(u(null),p({id:z.id,badge:R}))},[e,s,S,a]),O=m.useCallback(z=>{const R=Kn.getState(),$=R.annotationsFor(t),X=z?$.filter(Y=>z.has(Y.id)):[...$];if(X.length===0)return;const H=l2(X,Y=>Y.pageKey),te=H.ordered.map(Y=>Y.id);if(R.removeAnnotations(t,te),!kW({text:H.text,images:H.images,mentions:[]})){R.restoreAnnotations(t,H.ordered),ze({type:"warning",title:a("Note not sent"),description:a("The note stays in the queue.")});return}R.annotationsFor(t).length===0&&s&&S(!1)},[t,s,S,a]);return m.useEffect(()=>{if(!r)return;const z=R=>{if((aa?R.metaKey:R.ctrlKey)&&R.shiftKey&&!R.altKey&&R.key.toLowerCase()==="d"){R.preventDefault(),R.stopPropagation(),S(!s);return}if(!s||R.key!=="Escape")return;const X=R.target instanceof Element?R.target:null,H=X?.closest('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"], [aria-expanded="true"], [data-design-owns-escape]')!==null&&X?.closest("[data-design-owns-escape]")!==null,te=X?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')!==null;if(w){R.preventDefault(),R.stopPropagation(),C(!1);return}switch(E2({queueOwnsEscape:w,targetOwnsEscape:H,targetIsInput:te,markupStrokeActive:x,markupToolHeld:f!==null,warningShown:y,draftOpen:d!==null,editorOpen:h!==null})){case"pass-through":return;case"cancel-stroke":R.preventDefault(),R.stopPropagation(),v(!1);return;case"put-down-tool":R.preventDefault(),R.stopPropagation(),g(null);return;case"dismiss-warning":R.preventDefault(),R.stopPropagation(),b(!1);return;case"cancel-draft":R.preventDefault(),R.stopPropagation(),T();return;case"close-editor":R.preventDefault(),R.stopPropagation(),I();return;case"exit":R.preventDefault(),R.stopPropagation(),S(!1);return}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[r,s,w,x,f,y,d,h,S,T,I]),{drawing:l,draftPick:d,openPin:h,markupTool:f,warningShown:y,queueOpen:w,allConversationAnnotations:N,setQueueOpen:C,setWarningShown:b,setDraftPick:u,setDesignMode:S,handleMarkupToolChange:A,moveSelection:P,cancelDraft:T,closeOpenPin:I,openPinFromQueue:D,sendQueue:O,setMarkupStrokeActive:v}}const IX=(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,kS=(e,t)=>t.some(n=>IX(e,n)),DX=new Set(["dialog-popup","dialog-viewport","dialog-backdrop","alert-dialog-popup","alert-dialog-viewport","alert-dialog-backdrop"]);function EX(e){if(e.getAttribute("data-enso-float")!==null)return!0;const t=e.getAttribute("data-slot");return t?DX.has(t)||t.endsWith("-popup")||t.endsWith("-positioner"):!1}function jS(e,t){const n=[];for(const s of Array.from(e.querySelectorAll("*"))){if(!EX(s))continue;const o=s.getBoundingClientRect();o.width>0&&o.height>0&&n.push({x:o.left,y:o.top,width:o.width,height:o.height})}return n}const ZI=m.createContext({visible:!0,active:!0});function PX({dockConversationId:e,api:t,children:n}){const s=ie(u=>u.activeId===e),o=fn(u=>!!u.uiByConversation[e]?.open),r=m.useCallback(u=>{const h=t.onDidActiveChange(u),p=t.onDidVisibilityChange(u);return()=>{h.dispose(),p.dispose()}},[t]),a=m.useSyncExternalStore(r,()=>t.isActive),l=m.useSyncExternalStore(r,()=>t.isVisible),c=s&&o&&l,d=m.useMemo(()=>({visible:c,active:c&&a}),[c,a]);return i.jsx(ZI.Provider,{value:d,children:n})}function QI(){return m.useContext(ZI)}const Gu=new Map,sg=new Set;function _S(){for(const e of sg)e()}function AX(e){return sg.add(e),()=>{sg.delete(e)}}function MX(e){const t=Gu.get(e);if(!t?.visible)return!1;let n=0,s;for(const[o,r]of Gu)r.kind!==t.kind||!r.visible||(n+=1,r.active&&(s=o));return n<=1||s===e}function eD(e,t=!0){const{visible:n,active:s}=QI(),o=m.useRef(null);o.current===null&&(o.current=Symbol(e));const r=o.current;m.useEffect(()=>{if(t)return Gu.set(r,{kind:e,visible:n,active:s}),_S(),()=>{Gu.delete(r),_S()}},[s,t,r,e,n]);const a=m.useSyncExternalStore(AX,()=>MX(r));return t&&a}const RX={tabId:null,url:"",title:"",favicon:null,loading:!1,canGoBack:!1,canGoForward:!1,locked:!1,devtoolsOpen:!1,designMode:!1,holder:null},of=(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,NS=80,LX=.42;function TS(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=OX(e,t.bottom);return s>0?{...n,radius:s}:n}function OX(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 zX(){const{t:e}=ne();return i.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-muted-foreground text-sm",children:[i.jsx(bo,{className:"h-6 w-6"}),i.jsx("p",{children:e("The built-in browser is not available in full view. Check it on the computer.")})]})}function tD(e){return window.electronAPI.remote?i.jsx(zX,{}):i.jsx(GX,{...e})}function GX({conversationId:e,panelApi:t,active:n}){const{t:s}=ne(),o=ie(q=>A2(q.conversations,e)),r=fn(q=>q.uiByConversation[o]?.open??!1),a=ie(q=>q.activeId===o),l=n??(r&&a),c=eD("browser",n===void 0),d=n??c,[u,h]=m.useState(RX),[p,f]=m.useState(""),[g,x]=m.useState(!1),[v,y]=m.useState(null),[b,w]=m.useState(LX),[C,_]=m.useState({width:800,height:600}),N=m.useRef(null),k=m.useRef(null),S=m.useRef(null),A=m.useRef(void 0),T=m.useRef(!1),I=m.useRef(void 0),P=m.useRef(!1),D=m.useRef(!1);D.current=u.locked;const O=m.useRef(!1);O.current=u.devtoolsOpen;const z=(u.url.startsWith("http")||u.url.startsWith("file:"))&&!u.loading,R=m.useRef(!1);R.current=z;const $=m.useRef(null),X=t.id,H=TX({tabId:X,conversationId:e,url:u.url,designMode:u.designMode,onDesignModeState:h,active:d});m.useEffect(()=>{const q=N.current;if(!q)return;const ee=()=>{const Ce=q.getBoundingClientRect();Ce.width>0&&Ce.height>0&&_({width:Math.round(Ce.width),height:Math.round(Ce.height)})};ee();const ge=new ResizeObserver(ee);return ge.observe(q),()=>ge.disconnect()},[]),m.useEffect(()=>window.electronAPI.browser.onState(q=>{q.tabId===X&&h(q.state)}),[X]),m.useEffect(()=>window.electronAPI.browser.onDesignMode(q=>{if(q.tabId!==X||q.type==="cancelled"||q.type==="select"||q.type==="drawing"||q.type==="pin-click"||q.type==="pins")return;let ee=!1;if(q.type==="annotated")ee=q.image?NW(q.image):!1;else{const ge=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ui-${Date.now()}`;ee=Yx({kind:"ui-element",id:ge,label:q.payload.label||q.payload.tag||"element",path:q.payload.path||q.payload.tag||"element",text:q.payload.text||q.payload.label||q.payload.tag||"element",imageId:`img-${ge}`},q.image)}ee?_o():ze({type:"warning",title:s("No Composer for this selection")})}),[X,s]),m.useEffect(()=>{g||f(u.url)},[u.url,g]),m.useEffect(()=>{const q=u.title.trim()||s("Browser");t.setTitle(q),t.updateParameters({...t.getParameters(),favicon:u.favicon})},[t,u.title,u.favicon,s]),m.useEffect(()=>{let q=0,ee=!1;document.getElementById("root"),Pj();const ge=()=>{if(ee)return;const Ce=l&&t.isActive&&t.isVisible&&document.visibilityState==="visible",Re=Ce?TS(N.current):null,fe=Re!==null&&(D.current||kS(Re,jS(document)));(A.current===void 0||!of(A.current,Re)||fe!==T.current)&&(A.current=Re,T.current=fe,window.electronAPI.browser.setViewport(X,e,Re,fe).then(h));const U=R.current?Re:null;of($.current,U)||($.current=U,fn.getState().setBrowserHole(`${X}:guest`,U));const oe=Ce&&O.current?TS(k.current):null,Se=oe!==null&&kS(oe,jS(document));(I.current===void 0||!of(I.current,oe)||Se!==P.current)&&(fn.getState().setBrowserHole(`${X}:devtools`,oe),I.current=oe,P.current=Se,window.electronAPI.browser.setDevToolsViewport(X,e,oe,Se).then(h)),q=requestAnimationFrame(ge)};return q=requestAnimationFrame(ge),()=>{ee=!0,cancelAnimationFrame(q);const{setBrowserHole:Ce}=fn.getState();Ce(`${X}:guest`,null),Ce(`${X}:devtools`,null),$.current=null,A.current!==null&&(A.current=null,window.electronAPI.browser.setViewport(X,e,null)),I.current!==null&&(I.current=null,window.electronAPI.browser.setDevToolsViewport(X,e,null))}},[e,X,t,l]);const te=async()=>{x(!1);const q=p.trim();if(!q)return;const ee=await window.electronAPI.browser.navigate(X,e,q);y(ee.ok?null:ee.error??s("Navigation failed"))},V=q=>{const ee=N.current,ge=k.current;if(!ee||!ge)return;q.currentTarget.setPointerCapture(q.pointerId);const Ce=q.clientY,Re=ee.getBoundingClientRect().height,fe=ge.getBoundingClientRect().height,U=Re+fe,oe=G=>{const Q=Math.min(U-NS,Math.max(NS,fe-(G.clientY-Ce)));w(Q/U)},Se=()=>{window.removeEventListener("pointermove",oe),window.removeEventListener("pointerup",Se)};window.addEventListener("pointermove",oe),window.addEventListener("pointerup",Se)},Y="flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent";return i.jsxs("div",{className:"flex h-full flex-col",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b bg-background px-2",children:[i.jsx("button",{type:"button",className:Y,disabled:u.locked||!u.canGoBack,onClick:()=>{window.electronAPI.browser.goBack(X)},"aria-label":s("Back"),children:i.jsx(pc,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:Y,disabled:u.locked||!u.canGoForward,onClick:()=>{window.electronAPI.browser.goForward(X)},"aria-label":s("Forward"),children:i.jsx(Ej,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:Y,disabled:u.locked||!u.tabId,onClick:()=>{window.electronAPI.browser.reload(X)},"aria-label":s("Reload"),children:i.jsx(ej,{className:W("h-3.5 w-3.5",u.loading&&"animate-spin")})}),i.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-md border bg-background px-2 py-0.5 text-xs focus-within:border-ring",onSubmit:q=>{q.preventDefault(),te()},children:[i.jsx(bo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("input",{value:p,onChange:q=>f(q.target.value),onFocus:q=>{x(!0),q.target.select()},onBlur:()=>x(!1),placeholder:s("Enter a URL"),spellCheck:!1,disabled:u.locked,className:"min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground disabled:opacity-60"})]}),i.jsx(jX,{tabId:X,conversationId:e,active:u.designMode,disabled:!u.tabId||u.locked||u.devtoolsOpen,queueOpen:H.queueOpen,onQueueOpenChange:H.setQueueOpen,onToggleDesignMode:q=>{H.setDesignMode(q)},onOpenPinFromQueue:q=>{H.openPinFromQueue(q)},onSendQueue:H.sendQueue}),i.jsx("button",{type:"button",className:W(Y,u.devtoolsOpen&&"bg-muted text-foreground"),disabled:!u.tabId,onClick:()=>{window.electronAPI.browser.setDevTools(X,!u.devtoolsOpen).then(h)},"aria-label":s("Toggle Developer Tools"),"aria-pressed":u.devtoolsOpen,children:i.jsx(UN,{className:"h-3.5 w-3.5"})}),u.locked&&i.jsxs("span",{className:"flex shrink-0 items-center gap-1 rounded bg-amber-500/15 px-1.5 py-0.5 text-[10px] text-amber-600 dark:text-amber-400",children:[i.jsx(Nw,{className:"h-3 w-3"}),s("Enso is in control")]})]}),u.designMode&&i.jsx(kX,{drawing:H.drawing,pick:H.draftPick,markupTool:H.markupTool,editorOpen:H.openPin!==null,onMarkupToolChange:H.handleMarkupToolChange,onExit:()=>{H.setDesignMode(!1)}}),v&&i.jsx("div",{className:"border-b bg-destructive/10 px-3 py-1 text-xs text-destructive",children:v}),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col","data-slot":"browser-native-stack",children:[i.jsxs("div",{ref:N,className:W("relative min-h-0",u.devtoolsOpen?"shrink-0":"flex-1",z?"bg-transparent":"bg-background"),style:u.devtoolsOpen?{flex:`${1-b} 1 0`}:void 0,children:[i.jsx(CX,{active:u.designMode}),u.designMode&&i.jsx(NX,{tabId:X,conversationId:e,stageSize:C,draftPick:H.draftPick,openPin:H.openPin,markupTool:H.markupTool,warningShown:H.warningShown,onWarningShownChange:H.setWarningShown,onDraftPickChange:H.setDraftPick,onMoveSelection:q=>{H.moveSelection(q)},onCancelDraft:H.cancelDraft,onCloseOpenPin:H.closeOpenPin,onSendQueue:H.sendQueue,onStrokeStateChange:H.setMarkupStrokeActive,active:d}),!u.url.startsWith("http")&&!u.url.startsWith("file:")&&i.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-center text-sm text-muted-foreground",children:[i.jsx(bo,{className:"h-6 w-6 opacity-40"}),i.jsx("p",{children:s("Enter a URL above, or let the agent open a page with browser_navigate.")})]}),u.locked&&i.jsxs("div",{className:"group absolute inset-0 z-10 flex cursor-default items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/40"}),i.jsxs("button",{type:"button",className:"relative flex items-center gap-1.5 rounded-full border bg-background px-4 py-2 text-sm shadow-lg opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted",onClick:()=>{window.electronAPI.browser.setLocked(e,!1)},children:[i.jsx(Nw,{className:"h-3.5 w-3.5"}),s("Take control")]})]})]}),u.devtoolsOpen&&i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:S,className:"h-1.5 shrink-0 cursor-row-resize bg-border hover:bg-ring",onPointerDown:V}),i.jsx("div",{ref:k,className:"min-h-0 bg-transparent",style:{flex:`${b} 1 0`}})]})]})]})}function FX({chatId:e,visible:t}){const{t:n}=ne(),s=ue(p=>p.browserTabs[e]),o=ue(p=>p.browserTitles),r=ue(p=>p.browserHolders),{openBrowserTab:a,selectBrowserTab:l,closeBrowserTab:c,setBrowserTitle:d}=ue.getState(),u=s?.active;m.useEffect(()=>{u||a(e)},[u,e,a]);const h=m.useMemo(()=>u?{id:u,isActive:!0,isVisible:!0,setTitle:p=>d(u,p),getParameters:()=>{},updateParameters:()=>{}}:null,[u,d]);return i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs("div",{className:"flex h-8 shrink-0 items-center gap-0.5 overflow-x-auto border-b px-1.5",children:[s?.tabs.map(p=>{const f=r[p],g=o[p]||n("Browser");return i.jsxs("div",{className:W("flex h-6 min-w-0 max-w-44 shrink items-center rounded-md text-xs",p===u?"bg-brand/10 text-foreground dark:bg-brand/15":"text-muted-foreground hover:bg-muted/60 hover:text-foreground"),children:[i.jsxs("button",{type:"button",title:f?`${g}
74
- ${n("{{name}} is using this tab",{name:f.name})}`:g,onClick:()=>l(e,p),className:"flex h-full min-w-0 items-center gap-1.5 pl-2",children:[i.jsx(bo,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:g}),f&&i.jsxs("span",{className:"max-w-16 shrink-0 truncate text-muted-foreground",children:["· ",f.name]})]}),i.jsx("button",{type:"button","aria-label":n("Close"),title:n("Close"),onClick:()=>{c(e,p)},className:"mx-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-60 hover:bg-foreground/10 hover:opacity-100",children:i.jsx(dn,{className:"h-3 w-3"})})]},p)}),i.jsx("button",{type:"button","aria-label":n("New tab"),title:n("New tab"),onClick:()=>a(e),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(as,{className:"h-3.5 w-3.5"})})]}),h&&i.jsx(tD,{conversationId:M2(e),panelApi:h,active:t},h.id)]})}const HX=[[0,59],[0,23],[1,31],[1,12],[0,7]],lr=6e4,BX=60*lr,VX=5e4;function rf(e,t,n){if(!/^\d+$/u.test(e))return;const s=Number(e);return s>=t&&s<=n?s:void 0}function $X(e,t,n){const s=new Set;for(const o of e.split(",")){const[r,a,l]=o.split("/");if(l!==void 0)return;const c=a===void 0?1:rf(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=rf(h,t,n),u=p===void 0?a===void 0?d:n:rf(p,t,n)}if(d===void 0||u===void 0||d>u)return;for(let h=d;h<=u;h+=c)s.add(h)}return[...s].sort((o,r)=>o-r)}function Vh(e){const t=e.trim().split(/\s+/u);if(t.length!==5)return;const n=t.map((c,d)=>$X(c,...HX[d]));if(n.some(c=>c===void 0))return;const[s,o,r,a,l]=n;return{source:t.join(" "),minute:s,hour:o,dayOfMonth:r,month:a,dayOfWeek:[...new Set(l.map(c=>c%7))].sort((c,d)=>c-d),domStar:t[2].startsWith("*"),dowStar:t[4].startsWith("*")}}function WX(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 UX(e,t){let n=Math.floor(t/lr)*lr+lr;for(let s=0;s<VX;s+=1){const o=new Date(n);let r;if(!e.month.includes(o.getMonth()+1))r=new Date(o.getFullYear(),o.getMonth()+1,1).getTime();else if(!WX(e,o))r=new Date(o.getFullYear(),o.getMonth(),o.getDate()+1).getTime();else if(!e.hour.includes(o.getHours()))r=n-o.getMinutes()*lr+BX;else if(!e.minute.includes(o.getMinutes()))r=n+lr;else return n;n=Math.max(r,n+lr)}}const af=e=>String(e).padStart(2,"0"),KX=["日","一","二","三","四","五","六"],qX=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Cv(e,t){const n=typeof e=="string"?Vh(e):e;if(!n)return String(e);const[s,o,r,a,l]=n.source.split(" "),c=t==="zh";if(a!=="*")return n.source;const d=/^\*\/(\d+)$/u.exec(s);if(o==="*"&&r==="*"&&l==="*"){if(s==="*")return c?"每分钟":"Every minute";if(d)return c?`每 ${d[1]} 分钟`:`Every ${d[1]} minutes`;if(n.minute.length===1&&/^\d+$/u.test(s)){const h=af(n.minute[0]);return c?`每小时 ${h} 分`:`Every hour at :${h}`}return n.source}if(!/^\d+$/u.test(s)||!/^\d+$/u.test(o))return n.source;const u=`${af(n.hour[0])}:${af(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=>KX[p]).join("、")} ${u}`:`Every ${h.map(p=>qX[p]).join(", ")} at ${u}`}if(l==="*"&&/^\d+$/u.test(r)){const h=n.dayOfMonth[0];return c?`每月 ${h} 日 ${u}`:`Monthly on day ${h} at ${u}`}return n.source}const YX=/[A-Za-z0-9._%+-]/,IS=/[A-Za-z0-9_-]/,XX=/```[\s\S]*?(?:```|$)|`[^`\n]*`/g;function nD(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 JX(e,t){if(typeof e!="string")return{ids:[],all:!1};const n=e.normalize("NFC").replace(XX,a=>" ".repeat(a.length)),s=[...t.map(a=>({key:nu(a.name),id:a.id})),...Aj.map(a=>({key:nu(a),id:null}))].sort((a,l)=>l.key.length-a.key.length),o=[];let r=!1;for(let a=n.indexOf("@");a!==-1;a=n.indexOf("@",a+1)){if(a>0&&YX.test(n[a-1]))continue;const l=s.find(({key:c})=>{const d=a+1+c.length;if(n.slice(a+1,d).toLowerCase()!==c)return!1;const u=n[d];return!(u&&IS.test(c.at(-1)??"")&&IS.test(u))});l&&(l.id===null?r=!0:o.includes(l.id)||o.push(l.id))}return{ids:o,all:r}}function ZX(e,t){const n=nD(t),{ids:s,all:o}=JX(e,n);return o?{ids:[...new Set(n.map(r=>r.id))],all:o}:{ids:s,all:o}}function QX(e,t){const n=nu(typeof e=="string"?e.replace(/^@/,""):"");return nD(t).filter(s=>nu(s.name).startsWith(n))}function ig(e,t){return/(?:^|\s)\$([^\s$]*)$/.exec(e.slice(0,t))?.[1]??null}function sD(e){const t=new Set,n=[];for(const s of e){const o=s.name.trim().toLowerCase();!o||t.has(o)||(t.add(o),n.push(s))}return n}function eJ(e,t,n){const s=n??t;if(s===null)return[];const o=s.toLowerCase();return sD(e.filter(r=>n!==null?r.name.startsWith("/skill:")&&r.name.slice(7).toLowerCase().includes(o):r.name.toLowerCase().includes(o))).slice(0,10)}const tJ=500,nJ=72,Il=28;function iD({phase:e,heldMs:t,cancelZone:n}){return e!=="recording"&&e!=="starting"?"none":n?"cancel":e==="starting"||t<tJ?"too-short":"finish"}function DS(e,t){return e-t>=nJ}function $h(e,t){const n=[...e,t].slice(-Il);return n.length<Il?[...new Array(Il-n.length).fill(0),...n]:n}const sJ=300,iJ=12,oJ=-50,rJ=3;function oD(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 aJ(){let e=Number.POSITIVE_INFINITY;return t=>{const n=t.length/su*1e3,s=oD(t);return e=Math.min(s,e+rJ*n/1e3),s>Math.max(e+iJ,oJ)}}function lJ(e){if(e===su)return r=>r;const t=e/su;let n=new Float32Array(0),s=0,o=0;return r=>{const a=new Float32Array(n.length+r.length);a.set(n),a.set(r,n.length);const l=s+a.length,c=[];for(;;){const u=Math.floor(o*t),h=Math.floor((o+1)*t);if(h>l)break;let p=0;for(let f=u;f<h;f++)p+=a[f-s];c.push(h>u?p/(h-u):a[u-s]??0),o++}const d=Math.floor(o*t);return n=a.slice(d-s),s=d,Float32Array.from(c)}}function cJ(e){return Math.min(1,Math.max(0,(oD(e)+55)/45))}const dJ=2e3;function uJ(e=dJ){const t=aJ();let n=0,s=0;return o=>{const r=o.length/su*1e3;return t(o)?(n+=r,s=0):s+=r,n>=sJ&&s>=e}}class rD extends Error{}let ui=null;function og(){return(!ui||ui.state==="closed")&&(ui=new AudioContext),ui.state!=="running"&&ui.resume().catch(()=>{}),ui}async function hJ(){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 ES(){const e=ui;ui=null,e?.close().catch(()=>{})}const lf={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};async function pJ(e){const t=navigator.mediaDevices;if(!e||e===R2)return t.getUserMedia({audio:lf});try{return await t.getUserMedia({audio:{...lf,deviceId:{exact:e}}})}catch(n){const s=n instanceof Error?n.name:"";if(s==="NotAllowedError"||s==="SecurityError")throw n;return t.getUserMedia({audio:lf})}}const fJ=5e3;async function mJ(e,t={}){const n=!t.context,s=t.context??new AudioContext,o=t.context!=null&&t.context===ui,r=s.resume(),a=()=>{!n&&!o||(ui===s&&(ui=null),s.close().catch(()=>{}))};let l;try{l=await pJ(t.deviceId),await Promise.race([r,new Promise((w,C)=>setTimeout(()=>C(new Error("audio context stayed suspended")),3e3))])}catch(w){for(const C of l?.getTracks()??[])C.stop();throw a(),w}const c=l.getTracks();if(s.state==="closed"){for(const w of c)w.stop();throw new Error("audio context closed")}const d=s.createMediaStreamSource(l),u=s.createScriptProcessor(4096,1,1),h=lJ(s.sampleRate);let p=0,f=()=>{};const g=new Promise(w=>{f=w}),x=setTimeout(f,fJ),v=()=>{clearTimeout(x),f()};u.onaudioprocess=w=>{const C=w.inputBuffer.getChannelData(0);for(let N=0;N<C.length;N++)p=Math.max(p,Math.abs(C[N]));p>0&&v(),t.onLevel?.(cJ(C));const _=h(new Float32Array(C));_.length>0&&e(_)},d.connect(u),u.connect(s.destination);let y=!1;const b=()=>{if(!y){y=!0,v(),u.onaudioprocess=null,u.disconnect(),d.disconnect();for(const w of c)w.stop();a()}};return{live:g,cancel:b,stop:async()=>{if(b(),p===0)throw new rD("silent recording")}}}const aD="Microphone access denied. Allow it in system settings.",gJ={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 lD(e){const t=e?.name;return t==="NotFoundError"||t==="OverconstrainedError"?"No microphone found.":t==="NotAllowedError"||t==="SecurityError"?aD:"Voice input failed."}function cD({startSession:e,requestMicAccess:t,onText:n}){const{t:s}=ne(),[o,r]=m.useState("idle"),[a,l]=m.useState(0),[c,d]=m.useState(null),[u,h]=m.useState(""),[p,f]=m.useState(!1),g=m.useRef(null),x=m.useRef(null),v=m.useRef(async()=>{}),y=m.useRef(0);m.useEffect(()=>()=>{y.current++,g.current?.cancel(),x.current?.cancel()},[]),m.useEffect(()=>{if(!c)return;const _=setTimeout(()=>d(null),4e3);return()=>clearTimeout(_)},[c]);const b=m.useCallback(()=>{y.current++,g.current?.cancel(),x.current?.cancel(),g.current=null,x.current=null,h(""),f(!1),r("idle")},[]),w=m.useCallback(async()=>{const _=g.current,N=x.current;if(!(!_||!N)){g.current=null,r("transcribing");try{await _.stop();const k=await N.finish();k.ok?k.text?n(k.text):d(s("No speech detected.")):d(s(gJ[k.error]))}catch(k){N.cancel(),d(s(k instanceof rD?aD:"Voice input failed."))}finally{x.current=null,h(""),f(!1),r("idle")}}},[n,s]);return v.current=w,m.useEffect(()=>{if(o!=="recording")return;const _=setInterval(()=>l(N=>N+1),1e3);return()=>clearInterval(_)},[o]),m.useEffect(()=>{o==="recording"&&a>=L2&&w()},[a,w,o]),{phase:o,elapsed:a,error:c,setError:d,partial:u,correcting:p,start:async({autoStop:_=!1,...N}={})=>{if(d(null),!navigator.mediaDevices?.getUserMedia){d(s("Voice input needs a secure (HTTPS) connection."));return}const k=++y.current;h(""),f(!1),l(0),r("starting");let S=null;try{if(t&&!await t())throw new DOMException("microphone denied","NotAllowedError");if(k!==y.current)return;const A=e((P,D)=>{x.current===A&&(h(P),f(D))});S=A,x.current=A;const T=_?uJ():null,I=await mJ(P=>{A.push(P),T?.(P)&&x.current===A&&v.current()},N);if(k!==y.current){I.cancel();return}if(g.current=I,await I.live,k!==y.current)return;r("recording")}catch(A){if(k!==y.current)return;S?.cancel(),x.current=null,r("idle"),d(s(lD(A)))}},finish:w,cancel:b}}const xJ=6,PS=8,vJ=448;function bJ(e,t){const n=Math.min(vJ,t.width*.8);return{left:Math.max(PS,Math.min(e.left,t.width-PS-n)),bottom:t.height-e.top+xJ,maxWidth:n}}const AS=120,dD=12,wJ=Array.from({length:dD},(e,t)=>`bar-${t}`),MS=$h([],0),yJ=300;function RS(e){const t=e.getBoundingClientRect();return bJ(t,{width:window.innerWidth,height:window.innerHeight})}function uD({anchor:e,status:t,children:n}){const[s,o]=m.useState(()=>RS(e));return m.useLayoutEffect(()=>{let r=0;const a=()=>{const l=RS(e);o(c=>c.left===l.left&&c.bottom===l.bottom&&c.maxWidth===l.maxWidth?c:l),r=requestAnimationFrame(a)};return a(),()=>cancelAnimationFrame(r)},[e]),qs.createPortal(i.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 rg="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 hD({startSession:e,requestMicAccess:t,disabled:n,holdBinding:s,holdScope:o,onText:r}){const{t:a}=ne(),{phase:l,elapsed:c,error:d,setError:u,partial:h,correcting:p,start:f,finish:g,cancel:x}=cD({startSession:e,requestMicAccess:t,onText:r}),v=m.useRef(null),[y,b]=m.useState(MS),w=we(S=>S.voiceInputDevice),C=(S=!1)=>(b(MS),f({autoStop:S,deviceId:w,onLevel:A=>b(T=>$h(T,A))})),_=m.useRef({phase:l,start:C,finish:g,cancel:x});_.current={phase:l,start:C,finish:g,cancel:x},m.useEffect(()=>{if(!s||n)return;let S=null,A;const T=()=>{clearTimeout(A),A=void 0},I=()=>{A!==void 0&&(T(),s==="space"&&document.execCommand("insertText",!1," "))},P=()=>{if(T(),S===null)return;const z=_.current,R=iD({phase:z.phase,heldMs:performance.now()-S,cancelZone:!1});S=null,R==="finish"?z.finish():R!=="none"&&z.cancel(),R==="too-short"&&u(a("Speech was too short."))},D=z=>{if(z.isComposing||z.keyCode===229)return;if(Ol(z,{allowBare:!0})!==s){I();return}const R=o.current;if(!R||!(z.target instanceof Node)||!R.contains(z.target))return;const $=S===null&&A===void 0;$&&(z.repeat||_.current.phase!=="idle")||(z.preventDefault(),S!==null&&z.stopPropagation(),$&&(A=setTimeout(()=>{A=void 0,S=performance.now(),_.current.start()},yJ)))},O=z=>{S===null&&!A||!O2(s,z)||(z.preventDefault(),I(),P())};return window.addEventListener("keydown",D,!0),window.addEventListener("keyup",O,!0),window.addEventListener("blur",P),()=>{window.removeEventListener("keydown",D,!0),window.removeEventListener("keyup",O,!0),window.removeEventListener("blur",P),T(),S!==null&&_.current.cancel()}},[n,s,o,u,a]),m.useEffect(()=>{if(l!=="recording")return;const S=A=>{A.key==="Escape"&&(A.preventDefault(),A.stopPropagation(),x())};return window.addEventListener("keydown",S,!0),()=>window.removeEventListener("keydown",S,!0)},[x,l]);const N=h.length>AS?`…${h.slice(-AS)}`:h,k=l==="transcribing"?a(p?"Correcting…":"Transcribing…"):null;return i.jsxs("div",{ref:v,className:"relative flex shrink-0 items-center",children:[l==="recording"?i.jsxs(i.Fragment,{children:[i.jsxs("button",{type:"button",onClick:()=>{g()},"aria-label":a("Stop recording"),title:a("Stop recording"),className:"flex h-7 shrink-0 items-center gap-1.5 rounded-md px-1.5 text-destructive transition-colors hover:bg-destructive/10",children:[i.jsx("span",{"aria-hidden":!0,className:"flex h-3.5 items-center gap-[2px]",children:wJ.map((S,A)=>i.jsx("span",{className:"w-[2px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:3+y[Il-dD+A]*11}},S))}),i.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(c/60),":",String(c%60).padStart(2,"0")]}),i.jsx(mc,{className:"h-3 w-3 fill-current"})]}),i.jsx("button",{type:"button",onClick:x,"aria-label":a("Cancel recording"),title:`${a("Cancel recording")} (Esc)`,className:rg,children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]}):i.jsx("button",{type:"button",disabled:n||l!=="idle",onClick:()=>{C(!0)},"aria-label":k??a("Voice input"),title:k??(s?`${a("Voice input")} · ${a("Hold {{key}} to talk",{key:ti(s)})}`:a("Voice input")),className:rg,children:l==="idle"?i.jsx(Mj,{className:"h-3.5 w-3.5"}):i.jsx(vr,{className:"h-3.5 w-3.5"})}),v.current&&(d||h)?i.jsx(uD,{anchor:v.current,status:!!d,children:d??(p?i.jsxs("span",{className:"flex items-start gap-1.5",children:[i.jsx(vr,{"aria-hidden":!0,className:"mt-0.5 size-3 shrink-0"}),i.jsxs("span",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[a("Correcting…")," "]}),N]})]}):N)}):null]})}const pD=["agents","members","chats"];function SJ(e){return[...pD.flatMap(t=>e[t].map(n=>({candidate:n,group:t}))),...e.files.map(t=>({candidate:t,group:"files"}))]}function fD(e,t){const n=pD.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"}))]:SJ(e).map(s=>({type:"item",candidate:s.candidate,group:s.group}))}const CJ=20;function kJ(e,t,n){return e.filter(s=>s.id!==n&&!s.parentId&&!!s.sessionFile).sort((s,o)=>{const r=s.projectId===t?0:1,a=o.projectId===t?0:1;return r!==a?r-a:o.createdAt-s.createdAt}).slice(0,CJ).map(s=>({kind:"chat",id:s.id,label:s.title.split(`
75
- `)[0].trim()||"Untitled chat",sessionFile:s.sessionFile}))}function jJ(e){return e.map(t=>({...t,kind:"agent-type",id:t.typeKey,label:t.displayName}))}function _J(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 NJ(e,t,n,s=[]){const o=e.trim().toLocaleLowerCase(),r=o?t.filter(c=>`${c.label}
76
- ${c.description}
77
- ${c.source}
78
- ${c.typeKey}`.toLocaleLowerCase().includes(o)):[...t],a=o?n.filter(c=>`${c.label}
79
- ${c.relativePath}`.toLocaleLowerCase().includes(o)):[...n],l=o?s.filter(c=>c.label.toLocaleLowerCase().includes(o)):[...s];return{agents:r.filter(c=>c.source!=="bot"),members:r.filter(c=>c.source==="bot"),files:a,chats:l}}function mD(e,t,n=[],s={}){const[o,r]=m.useState([]),[a,l]=m.useState([]),c=t!==null,{searchFiles:d,agents:u=!0}=s;return m.useEffect(()=>{if(!c||!u)return;r([]);let h=!1;return window.electronAPI.agentRegistry.list().then(p=>{const f=Rj(p);h||r(f?jJ(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(_J(f))}).catch(()=>{h||l([])})},150);return()=>{h=!0,window.clearTimeout(p)}},[e,t,d]),m.useMemo(()=>t===null?{agents:[],members:[],files:[],chats:[]}:NJ(t,o,a,n),[o,a,n,t])}const LS={bot:"Mention a member",all:"Mention a member",chat:"Reference a chat",file:"Files",skill:"Skills"},TJ=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 IJ({chatId:e,placeholder:t,members:n,chatOptions:s=[],skills:o=[],running:r,disabled:a=!1,toolbar:l,hint:c,voice:d,requestMicAccess:u,onSend:h,onStop:p}){const{t:f}=ne(),g=m.useRef(null),x=m.useRef(null),v=m.useRef(null),y=m.useRef(!1),[b,w]=m.useState(()=>P0(localStorage,e)),[C,_]=m.useState([]),[N,k]=m.useState(null),[S,A]=m.useState(0),[T,I]=m.useState(!1),P=we(G=>G.keybindings),{"voice-hold":D,"send-message":O}=Fi(P),{text:z}=b,R=G=>w(Q=>({...Q,...G}));m.useEffect(()=>{x.current?.focus()},[]),m.useEffect(()=>{z2(localStorage,e,b)},[e,b]),m.useEffect(()=>G2(G=>{G===e&&w(P0(localStorage,G))}),[e]),m.useLayoutEffect(()=>{const G=x.current;G&&(G.style.height="auto",G.style.height=`${Math.min(G.scrollHeight,220)}px`)},[z]);const $=m.useCallback(G=>window.electronAPI.bots.searchFiles({chatId:e,query:G}).then(Q=>Q.ok?Q.files:[]),[e]),X=mD(void 0,N?.kind==="at"?N.query:null,[],{searchFiles:$,agents:!1}).files,H=(()=>{if(!N)return[];const G=N.query.toLowerCase();if(N.kind==="skill")return o.filter(ae=>ae.name.toLowerCase().includes(G)).slice(0,10).map(ae=>({kind:"skill",skill:ae}));const Q=n?QX(N.query,n).map(ae=>({kind:"bot",bot:ae})):[];return n&&Aj.some(ae=>ae.startsWith(G))&&Q.push({kind:"all"}),b.chats.length<F2&&Q.push(...s.filter(ae=>!b.chats.includes(ae.id)&&ae.title.toLowerCase().includes(G)).slice(0,6).map(ae=>({kind:"chat",chat:ae}))),Q.push(...X.slice(0,8).map(ae=>({kind:"file",path:ae.relativePath,name:ae.label}))),Q})(),te=(G,Q)=>{const ae=o.length?ig(G,Q):null;if(ae!==null){k({kind:"skill",start:Q-ae.length-1,query:ae}),A(0);return}const Z=/(^|[^A-Za-z0-9._%+-])@([^\s@]*)$/u.exec(G.slice(0,Q));if(!Z)return k(null);k({kind:"at",start:Q-Z[2].length-1,query:Z[2]}),A(0)},V=G=>{if(!N)return;const Q=x.current,ae=Q?.selectionStart??z.length,Z=z.slice(0,N.start),ce=z.slice(ae);let De="";const Oe={};G.kind==="bot"||G.kind==="all"?De=`@${G.kind==="all"?f("everyone"):G.bot.name} `:G.kind==="file"?(De=`@${G.path} `,Oe.files=[...new Set([...b.files,G.path])]):G.kind==="chat"?Oe.chats=[...b.chats,G.chat.id]:Oe.skill=G.skill.id,R({...Oe,text:Z+De+ce}),k(null);const Ne=Z.length+De.length;requestAnimationFrame(()=>{Q?.focus(),Q?.setSelectionRange(Ne,Ne)})},Y=G=>{const Q=x.current,ae=Q?.selectionStart??z.length,Z=Q?.selectionEnd??z.length;R({text:z.slice(0,ae)+G+z.slice(Z)}),requestAnimationFrame(()=>{Q?.focus(),Q?.setSelectionRange(ae+G.length,ae+G.length)})},q=G=>{for(const Q of G){if(!Q.type.startsWith("image/"))continue;const ae=new FileReader;ae.onload=()=>{const Z=ae.result;_(ce=>[...ce,{data:Z.slice(Z.indexOf(",")+1),mimeType:Q.type}])},ae.readAsDataURL(Q)}},ee=G=>{const Q=x.current,ae=Q?.selectionStart??z.length,Z=Q?.selectionEnd??z.length;window.electronAPI.bots.savePastedText({chatId:e,text:G}).catch(()=>({ok:!1,error:"unavailable"})).then(ce=>{const De=ce.ok?`@${ce.path} `:G;w(Oe=>({...Oe,text:Oe.text.slice(0,ae)+De+Oe.text.slice(Z)})),requestAnimationFrame(()=>{Q?.focus(),Q?.setSelectionRange(ae+De.length,ae+De.length)})})},ge=new Map(s.map(G=>[G.id,G])),Ce=b.skill?o.find(G=>G.id===b.skill||G.name===b.skill):void 0,Re=Ce&&n?n.filter(G=>ZX(z,n).ids.includes(G.id)&&!Ce.owners.includes(G.id)):[],fe=!a&&!T&&(z.trim().length>0||C.length>0||b.chats.length>0||!!b.skill),U=async()=>{if(!fe)return;const G=b,Q=C,ae=G.text.trim();w(H2),_([]),k(null),I(!0);try{await h({text:ae,images:Q,files:G.files.filter(ce=>ae.includes(`@${ce}`)),chats:G.chats,...G.skill?{skill:Ce?.id??G.skill}:{}})||(w(ce=>ce.text||ce.chats.length||ce.skill?ce:G),_(ce=>ce.length?ce:Q))}finally{I(!1)}},oe=G=>{const Q=G.nativeEvent.isComposing||y.current;if(N&&H.length>0&&!Q){if(G.key==="ArrowDown"||G.key==="ArrowUp"){G.preventDefault();const ae=G.key==="ArrowDown"?1:-1;A(Z=>(Z+ae+H.length)%H.length);return}if(G.key==="Enter"||G.key==="Tab"){G.preventDefault(),V(H[Math.min(S,H.length-1)]);return}if(G.key==="Escape"){G.preventDefault(),k(null);return}}!Q&&Oj(G,O)&&(G.preventDefault(),U())},Se=G=>(n??[]).filter(Q=>G.includes(Q.id)).map(Q=>Q.name).join(", ");return i.jsxs("div",{ref:g,"data-slot":"composer",className:"relative rounded-2xl border bg-background shadow-float",onDragOver:G=>G.preventDefault(),onDrop:G=>{G.preventDefault(),q([...G.dataTransfer.files])},children:[N&&H.length>0&&i.jsx("div",{className:"absolute bottom-full left-3 z-10 mb-1.5 max-h-80 w-80 overflow-y-auto rounded-xl border bg-popover p-1 shadow-lg",children:H.map((G,Q)=>{const ae=LS[G.kind],Z=Q===0||LS[H[Q-1].kind]!==ae;return i.jsxs("div",{children:[Z&&i.jsx("div",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:f(ae)}),i.jsx("button",{type:"button",onMouseDown:ce=>{ce.preventDefault(),V(G)},onMouseEnter:()=>A(Q),className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",Q===S&&"bg-muted"),children:i.jsx(DJ,{item:G,ownerNames:Se,grouped:!!n})})]},TJ(G))})}),(b.chats.length>0||b.skill)&&i.jsxs("div",{className:"flex flex-wrap gap-1.5 px-3 pt-3",children:[b.skill&&i.jsx(OS,{icon:i.jsx(ii,{className:"h-3 w-3"}),label:Ce?.name??b.skill,tone:"skill",onRemove:()=>R({skill:void 0})}),b.chats.map(G=>i.jsx(OS,{icon:i.jsx(xa,{className:"h-3 w-3"}),label:ge.get(G)?.title??f("Unavailable chat"),onRemove:()=>R({chats:b.chats.filter(Q=>Q!==G)})},G))]}),Re.length>0&&i.jsx("div",{className:"px-4 pt-1.5 text-warning text-xs",children:f("{{names}} cannot use this skill; they will be told it is unavailable",{names:Re.map(G=>G.name).join(", ")})}),C.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:C.map((G,Q)=>i.jsxs("div",{className:"group relative h-14 w-14 overflow-hidden rounded-lg border",children:[i.jsx("img",{src:`data:${G.mimeType};base64,${G.data}`,alt:"",className:"h-full w-full object-cover"}),i.jsx("button",{type:"button","aria-label":f("Remove"),onClick:()=>_(ae=>ae.filter((Z,ce)=>ce!==Q)),className:"absolute top-0.5 right-0.5 hidden rounded-full bg-background/90 p-0.5 group-hover:block",children:i.jsx(dn,{className:"h-3 w-3"})})]},Q))}),i.jsx("textarea",{ref:x,value:z,rows:1,disabled:a,placeholder:t,onChange:G=>{R({text:G.target.value}),te(G.target.value,G.target.selectionStart)},onSelect:G=>te(G.currentTarget.value,G.currentTarget.selectionStart),onBlur:()=>k(null),onKeyDown:oe,onCompositionStart:()=>{y.current=!0},onCompositionEnd:()=>{y.current=!1},onPaste:G=>{const Q=[...G.clipboardData.files].filter(ae=>ae.type.startsWith("image/"));if(Q.length===0){const ae=G.clipboardData.getData("text/plain");if(!Lj(ae))return;G.preventDefault(),ee(ae);return}G.preventDefault(),q(Q)},className:"block max-h-56 min-h-12 w-full resize-none bg-transparent px-4 pt-3 pb-1 text-sm outline-none placeholder:text-muted-foreground disabled:opacity-60"}),i.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 pb-2",children:[i.jsx("button",{type:"button",onClick:()=>v.current?.click(),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground",title:f("Attach image"),"aria-label":f("Attach image"),children:i.jsx(Eh,{className:"h-4 w-4"})}),i.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:G=>{q([...G.target.files??[]]),G.target.value=""}}),d&&i.jsx(hD,{startSession:d,requestMicAccess:u,disabled:a,holdBinding:D||void 0,holdScope:g,onText:Y}),l,i.jsx("div",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",children:c}),r&&p&&!fe?i.jsx("button",{type:"button",onClick:p,className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground",title:f("Stop"),"aria-label":f("Stop"),children:i.jsx(mc,{className:"h-3 w-3 fill-current"})}):i.jsx("button",{type:"button",disabled:!fe,onClick:()=>{U()},className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground disabled:opacity-40",title:f("Send"),"aria-label":f("Send"),children:i.jsx(fc,{className:"h-4 w-4"})})]})]})}function DJ({item:e,ownerNames:t,grouped:n}){const{t:s}=ne();switch(e.kind){case"all":return i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"grid h-6 w-6 place-items-center rounded-full bg-muted text-[11px]",children:"@"}),i.jsx("span",{children:s("everyone")})]});case"bot":return i.jsxs(i.Fragment,{children:[i.jsx(tn,{bot:e.bot,size:"sm"}),i.jsx("span",{className:"min-w-0 truncate",children:e.bot.name}),i.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:e.bot.title})]});case"chat":return i.jsxs(i.Fragment,{children:[i.jsx(xa,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 truncate",children:e.chat.title}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:e.chat.kind==="group"?s("Group chat"):s("Direct chat")})]});case"file":return i.jsxs(i.Fragment,{children:[i.jsx(jo,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0",children:e.name}),i.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:e.path})]});case"skill":return i.jsxs(i.Fragment,{children:[i.jsx(ii,{className:"h-4 w-4 shrink-0 text-info"}),i.jsx("span",{className:"shrink-0",children:e.skill.name}),i.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:n?t(e.skill.owners):e.skill.description})]})}}function OS({icon:e,label:t,tone:n,onRemove:s}){const{t:o}=ne();return i.jsxs("span",{className:W("inline-flex h-6 max-w-56 items-center gap-1 rounded-md px-1.5 text-xs",n==="skill"?"bg-info/15 text-info":"bg-muted text-foreground"),children:[e,i.jsx("span",{className:"min-w-0 truncate",children:t}),i.jsx("button",{type:"button","aria-label":o("Remove"),onClick:s,className:"rounded opacity-70 hover:opacity-100",children:i.jsx(dn,{className:"h-3 w-3"})})]})}const EJ={thinking:"Thinking",typing:"Writing reply",tool:"Calling tools",retrying:"Retrying"},zS={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"},PJ={running:"Running",done:"Done",error:"Error",denied:"Denied",timeout:"Timed out · denied"},AJ={running:"text-primary",done:"text-success",error:"text-destructive",denied:"text-warning",timeout:"text-warning"},MJ=e=>e<1e4?`${(Math.max(0,e)/1e3).toFixed(1)}s`:wo(e);function gD({conversationId:e,leading:t,trailing:n,className:s}){const{t:o}=ne(),r=ue(p=>e?p.sessions[e]:void 0),a=ue(p=>e?p.queue.find(f=>f.conversationId===e):void 0),l=m.useMemo(()=>B2(r,!!a),[r,a]),c=!!(l&&l.state!=="queued"),[d,u]=m.useState(()=>Date.now());m.useEffect(()=>{if(!c)return;u(Date.now());const p=window.setInterval(()=>u(Date.now()),1e3);return()=>window.clearInterval(p)},[c]);const h=l?l.state!=="queued"?o(EJ[l.state]):o(a?.reason&&Object.hasOwn(zS,a.reason)?zS[a.reason]:"Queued"):null;return i.jsxs("div",{className:W("min-w-0 text-muted-foreground text-xs",s),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[t,h&&i.jsx("span",{className:"truncate",children:h}),c&&l?.startedAt!==void 0&&i.jsx("span",{className:"shrink-0 tabular-nums",children:wo(d-l.startedAt)}),n]}),l&&l.steps.length>0&&i.jsxs("div",{className:"mt-1 flex flex-col gap-0.5",children:[l.more>0&&i.jsxs("span",{children:["+",l.more]}),l.steps.map(p=>{const f=p.durationMs??(p.startedAt!==void 0?d-p.startedAt:void 0);return i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:"shrink-0 font-medium text-foreground",children:Bo(p.name,o)}),p.detail&&i.jsx("span",{className:"truncate font-mono",children:p.detail}),i.jsx("span",{className:W("shrink-0",AJ[p.status]),children:o(p.status==="timeout"&&p.name==="ask_user"?"Timed out · no answer":PJ[p.status])}),f!==void 0&&i.jsx("span",{className:"shrink-0 tabular-nums",children:MJ(f)})]},p.id)})]})]})}const RJ=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),LJ=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),OJ=[],zJ={auto:"Automatic",delegator:"By delegator",human:"Manual"};function Wh({state:e,interrupted:t,autoRetry:n}){const{t:s}=ne();if(n&&e==="failed")return i.jsx("span",{className:"rounded bg-warning/25 px-1.5 text-[11px] text-warning-foreground dark:bg-warning/15 dark:text-warning",children:s("Will retry automatically")});const o=e==="running"||e==="queued"?"bg-info/15 text-info":e==="completed"?"bg-success/15 text-success":e==="failed"?"bg-destructive/15 text-destructive":e==="blocked"?"bg-warning/15 text-warning":"bg-muted text-muted-foreground",r={queued:s("Queued"),running:s("In progress"),completed:s("Completed"),failed:s(t?"Interrupted":"Failed"),canceled:s("Canceled"),blocked:s("Stuck run")};return i.jsx("span",{className:W("rounded px-1.5 text-[11px]",o),children:r[e]??e})}function xD({check:e,className:t}){const{t:n}=ne();return i.jsxs("div",{className:W("flex min-w-0 items-center gap-1.5 text-muted-foreground text-xs",t),children:[i.jsx("span",{className:"shrink-0",children:n("Acceptance check")}),i.jsx("code",{className:"min-w-0 truncate rounded bg-muted px-1",title:e.text,children:e.text}),e.passed!==void 0&&i.jsx("span",{className:W("shrink-0 rounded px-1.5 text-[11px]",e.passed?"bg-success/15 text-success":"bg-destructive/15 text-destructive"),children:e.passed?n("Passed"):n("Not passed")})]})}function Rc(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 GJ(e,t){window.electronAPI.bots.cancelDelegation(e).then(n=>{n.ok||ze({type:"error",title:t("Cancel failed"),description:n.error}),ue.getState().refreshDelegations()})}function Dl(e,t,n){window.electronAPI.bots.retryDelegation(e,n).then(s=>{s.ok?s.warning&&ze({type:"warning",title:s.warning}):ze({type:"error",title:t("Retry failed"),description:s.error}),ue.getState().refreshDelegations()})}function Uh(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 FJ({record:e,delegations:t}){const{t:n}=ne(),s=$2(e);if(!s)return null;const o=Fj(e,t);return i.jsx("span",{className:"rounded border px-1 py-px text-[10px]",title:e.retryNote?n("Delegator note: {{note}}",{note:e.retryNote}):void 0,children:W2(e)?n("Retrying automatically · attempt {{n}}",{n:o}):n("Retry #{{n}} · {{source}}",{n:o,source:n(zJ[s])})})}function Kh({record:e,entry:t,retried:n,append:s,taskSeq:o,fill:r,bots:a,onOpenConversation:l}){const{t:c}=ne(),d=ue(O=>O.delegations)??OJ,u=e?.state??t?.state??"queued",h=Uh(!s&&zl(u)),p=a.get(e?.parentBotId??t?.from??""),f=a.get(e?.targetBotId??t?.to??""),g=U2(s?"completed":u),x=V2(e),v=!s&&x&&zl(u),y=!s&&u==="blocked"?e?.blocked:void 0,b=ue(O=>y&&e?.taskId?O.delegations.some(z=>z.taskId===e.taskId&&z.createdAt>e.createdAt):!1),w=ue(O=>O.openTask),C=!!t?.taskId&&!s,[_,N]=m.useState(!C),k=e?zj(e,d):!1,S=!s&&e?.chatId&&e.resultSeq!==void 0?{chatId:e.chatId,seq:e.resultSeq}:void 0,A=s||S?void 0:e?u==="completed"?e.result:u==="blocked"?void 0:Rc(e,c):t?.summary,T=c("{{from}} → {{to}} · Delegation",{from:p?.name??c("Deleted member"),to:f?.name??c("Deleted member")}),I=i.jsxs(i.Fragment,{children:[C&&i.jsx(un,{"aria-hidden":!0,className:W("size-3.5 shrink-0 transition-transform",_&&"rotate-90")}),i.jsx(tn,{bot:p,size:"xs"}),i.jsx("span",{className:"min-w-0 truncate text-foreground",title:p?.name,children:p?.name??c("Deleted member")}),i.jsx("span",{children:"→"}),i.jsx(tn,{bot:f,size:"xs",presence:x?.state}),i.jsx("span",{className:"min-w-0 truncate text-foreground",title:f?.name,children:f?.name??c("Deleted member")}),i.jsxs("span",{children:["· ",c("Delegation")]}),s?i.jsx("span",{className:"rounded bg-info/15 px-1.5 text-[11px] text-info",children:o===void 0?c("Merged into the current run"):c("Merged into the current run of #{{n}}",{n:o})}):v?i.jsx(Gj,{info:x}):i.jsx(Wh,{state:u,interrupted:e?.failure==="interrupted",autoRetry:k}),e&&!s&&i.jsx(FJ,{record:e,delegations:d}),e&&!s&&i.jsx("span",{children:wo((e.finishedAt??h)-e.createdAt)}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:RJ(s?.at??t?.at??e?.createdAt??h)})]}),P="flex flex-wrap items-center gap-1.5 whitespace-nowrap text-muted-foreground text-xs",D=s?.text??e?.task;return i.jsxs("div",{"data-slot":"bot-card",className:W("rounded-xl border bg-card px-3 py-2.5",r?"w-full min-w-0":"max-w-lg"),children:[C?i.jsx("button",{type:"button","aria-expanded":_,"aria-label":c(_?"Collapse delegation result":"Expand delegation result"),className:W(P,"w-full rounded text-left hover:text-foreground"),onClick:()=>N(O=>!O),children:I}):i.jsx("div",{className:P,children:I}),!_&&D&&i.jsx("div",{className:"mt-1 truncate text-muted-foreground text-xs",children:D}),_&&D&&i.jsx("div",{className:"mt-1.5 line-clamp-3 text-sm [overflow-wrap:anywhere]",children:D}),_&&i.jsxs(i.Fragment,{children:[e?.check&&!s&&i.jsx(xD,{check:e.check,className:"mt-1.5"}),A&&i.jsx("div",{className:"mt-1.5 line-clamp-4 whitespace-pre-wrap text-muted-foreground text-xs [overflow-wrap:anywhere]",children:A}),y&&e&&i.jsxs("div",{className:"mt-1.5 rounded-md bg-warning/10 px-2 py-1 text-xs",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap",children:c("Blocked · needs: {{need}}",{need:y.need})}),i.jsx("div",{className:"text-muted-foreground",children:b?c("Answered; the work continues"):y.waitFor==="parent"?c("Waiting for {{name}} to reply",{name:p?.name??c("Deleted member")}):c("Waiting for your reply")})]}),k&&e?.autoRetryAt!==void 0&&i.jsx("div",{className:"mt-1 text-warning-foreground text-xs dark:text-warning",children:c("Retrying automatically at {{time}} (attempt {{n}})",{time:LJ(e.autoRetryAt),n:Fj(e,d)+1})}),S&&i.jsx("button",{type:"button",onClick:()=>ue.getState().focusSeq(S.chatId,S.seq),className:"mt-1.5 text-muted-foreground text-xs underline-offset-2 hover:text-foreground hover:underline",children:c("Result posted to the group · View")}),e&&i.jsxs("div",{className:"mt-2 flex flex-wrap justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>l(e.childConversationId,T),children:c("View process")}),y&&!b&&e.chatId&&e.taskId&&i.jsx(me,{size:"xs",variant:"outline",onClick:()=>e.chatId&&e.taskId&&w(e.chatId,e.taskId),children:c("Reply")}),g.cancel&&i.jsx(me,{size:"xs",variant:"outline",onClick:()=>GJ(e.id,c),children:c("Cancel")}),g.retry&&!n&&i.jsx(me,{size:"xs",variant:"outline",title:k?c("Skip the wait and retry now. The scheduled automatic retry is canceled."):void 0,onClick:()=>Dl(e.id,c),children:c(k?"Retry now":"Retry")}),g.resumeOrRestart&&!n&&i.jsxs(i.Fragment,{children:[i.jsx(me,{size:"xs",variant:"outline",onClick:()=>Dl(e.id,c,"resume"),children:c("Continue")}),i.jsx(me,{size:"xs",variant:"outline",onClick:()=>Dl(e.id,c,"restart"),children:c("Start over")})]})]})]})]})}function vD(e){const t=ue(d=>d.chats.find(u=>u.id===e)),n=ue(d=>d.sessions),s=ue(d=>d.queue),o=ue(d=>d.silences),r=ue(d=>d.delegations),a=ue(d=>d.browserHolders),l=ue(d=>d.browserTabs[t?.parentId??e]?.tabs),c=ue(d=>q2(d.timelines[e]?.entries??[]));return m.useMemo(()=>({chat:t??{id:e,sessions:{}},delegations:r,sessions:n,queue:s,silences:o,clearedAt:c,holders:a,tabIds:l??[]}),[t,e,r,n,s,o,c,a,l])}function HJ(e,t){const n=vD(e);return m.useMemo(()=>K2(t,n),[t,n])}function BJ(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 bD(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 Wa({label:e,children:t}){return i.jsxs("div",{className:"flex gap-2",children:[i.jsx("span",{className:"w-12 shrink-0 text-muted-foreground",children:e}),i.jsx("span",{className:"min-w-0 flex-1 break-words",children:t})]})}function wD({info:e,bot:t}){const{t:n}=ne(),s=ue(c=>e.delegation?c.bots.find(d=>d.id===e.delegation?.parentBotId):void 0),o=e.delegation,r=BJ(e,n),a=ue(c=>e.browserTab?c.browserTitles[e.browserTab]||n("Browser"):void 0),l=e.wait&&"conversationId"in e.wait?e.wait.conversationId:void 0;return i.jsxs(kI,{align:"start",className:"w-72 flex-col gap-1.5 p-3 text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"font-semibold text-sm",children:t?.name??n("Deleted member")}),i.jsx(Gj,{info:e})]}),e.state==="idle"?i.jsx("div",{className:"text-muted-foreground",children:n("Nothing in progress")}):i.jsxs(i.Fragment,{children:[o&&i.jsxs(i.Fragment,{children:[i.jsx(Wa,{label:n("Task"),children:i.jsx("span",{className:"line-clamp-2",children:o.task})}),i.jsx(Wa,{label:n("From"),children:s?.name??n("Deleted member")}),i.jsx(Wa,{label:n("Time"),children:wo((o.finishedAt??Date.now())-o.createdAt)})]}),r&&i.jsx(Wa,{label:n("Waiting on"),children:r}),a&&i.jsx(Wa,{label:n("Browser"),children:i.jsx("span",{className:"line-clamp-1",children:a})}),e.quietSince!==void 0&&i.jsx("div",{className:"text-muted-foreground",children:n("Still running, no output for {{time}}",{time:wo(Date.now()-e.quietSince)})}),o&&e.state==="stuck"&&o.state==="failed"&&i.jsx("div",{className:"text-muted-foreground",children:Rc(o,n)}),o&&e.state==="done"&&o.result&&i.jsx("div",{className:"line-clamp-3 text-muted-foreground",children:o.result}),l&&i.jsx(me,{size:"xs",className:"mt-1 self-start",onClick:()=>bD(l),children:n("Go handle it")})]})]})}function yD({chatId:e,botId:t,bot:n,size:s="sm"}){const{t:o}=ne(),r=HJ(e,t);return i.jsxs(bv,{children:[i.jsxs(wv,{render:i.jsx("span",{className:"relative inline-flex shrink-0"}),children:[i.jsx(tn,{bot:n,size:s,presence:r.state}),i.jsx("span",{className:"sr-only",children:Bf(r,o)})]}),i.jsx(wD,{info:r,bot:n})]})}function VJ({chatId:e,memberIds:t,bots:n,onOpenLive:s}){const{t:o}=ne(),r=vD(e),a=m.useMemo(()=>Y2(t,r),[t,r]);return a.length===0?null:i.jsx("div",{className:"mb-1.5 flex flex-wrap items-center gap-1",children:a.map(({botId:l,info:c})=>{const d=n.get(l),u=d?.name??o("Deleted member"),h=X2(c),p=J2(c);return i.jsxs(bv,{children:[i.jsxs(wv,{render:i.jsx("button",{type:"button",onClick:()=>p?.kind==="pending"?bD(p.conversationId):p&&s(p.conversationId,l),className:"flex h-7 min-w-0 items-center gap-1.5 rounded-full px-1 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground"}),children:[i.jsx(tn,{bot:d,size:"xs",presence:c.state}),h?i.jsx("span",{className:"max-w-56 truncate pr-1.5",children:[u,Bf(c,o),h].join(" · ")}):i.jsx("span",{className:"sr-only",children:`${u} · ${Bf(c,o)}`})]}),i.jsx(wD,{info:c,bot:d})]},l)})})}const SD=[137,80,78,71,13,10,26,10];function wa(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}let od=null;function $J(e){if(!od){od=new Uint32Array(256);for(let n=0;n<256;n+=1){let s=n;for(let o=0;o<8;o+=1)s=s&1?3988292384^s>>>1:s>>>1;od[n]=s>>>0}}let t=4294967295;for(const n of e)t=od[(t^n)&255]^t>>>8;return(t^4294967295)>>>0}function CD(e){return SD.every((t,n)=>e[n]===t)?"png":e[0]===255&&e[1]===216&&e[2]===255?"jpeg":wa(e.subarray(0,4))==="RIFF"&&wa(e.subarray(8,12))==="WEBP"?"webp":null}function kD(e){if(CD(e)!=="png")return null;const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=[];for(let s=8;s+12<=e.length;){const o=t.getUint32(s),r=s+12+o;if(r>e.length)return null;const a=wa(e.subarray(s+4,s+8));if(n.push({type:a,data:e.subarray(s+8,s+8+o),raw:e.subarray(s,r)}),s=r,a==="IEND")return n}return null}const jD=e=>{if(e.type!=="tEXt")return null;const t=e.data.indexOf(0);return t>0?wa(e.data.subarray(0,t)):null};function GS(e,t){const n=kD(e)?.find(s=>jD(s)===t);return n?wa(n.data.subarray(t.length+1)):null}function FS(e,t){const n=new Uint8Array(12+t.length),s=new DataView(n.buffer);s.setUint32(0,t.length);for(let o=0;o<4;o+=1)n[4+o]=e.charCodeAt(o);return n.set(t,8),s.setUint32(8+t.length,$J(n.subarray(4,8+t.length))),n}function WJ(e,t,n,s=[]){const o=kD(e);if(!o)return null;const r=new Set([t,...s]),a=o.filter(h=>{const p=jD(h);return h.type!=="IEND"&&!(p&&r.has(p))}),l=Uint8Array.from(`${t}\0${n}`,h=>h.charCodeAt(0)&255),c=[Uint8Array.from(SD),...a.map(h=>h.raw),FS("tEXt",l),FS("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 UJ(e){return btoa(wa(new TextEncoder().encode(e)))}function KJ(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 qJ(e){return{budgetCost:e?.dailyCostUsd!==void 0?String(e.dailyCostUsd):"",budgetTokens:e?.dailyTokens!==void 0?String(e.dailyTokens):""}}function _D(e){const t={},n=e.budgetCost.trim();if(n){const o=Number(n);if(!Number.isFinite(o)||o<=0)return{ok:!1};t.dailyCostUsd=o}const s=e.budgetTokens.trim();if(s){const o=Number(s);if(!Number.isSafeInteger(o)||o<=0)return{ok:!1};t.dailyTokens=o}return{ok:!0,budget:Object.keys(t).length>0?t:null}}function YJ(e){return{delegationTimeout:e.delegationTimeoutMinutes!==void 0?String(e.delegationTimeoutMinutes):"",maxTurnTokens:e.maxTokensPerTurn!==void 0?String(e.maxTokensPerTurn):""}}function kv(e){const t=e.delegationTimeout.trim()?Number(e.delegationTimeout):null,n=e.maxTurnTokens.trim()?Number(e.maxTurnTokens):null;return t!==null&&!Z2(t)||n!==null&&!Q2(n)?{ok:!1}:{ok:!0,delegationTimeoutMinutes:t,maxTokensPerTurn:n}}function HS(e){return[...e.normalize("NFC").trim().replace(/\s+/gu,"_").replace(/[^\p{L}\p{N}_-]/gu,"").replace(/_+/gu,"_").replace(/^_+|_+$/gu,"")].slice(0,tL).join("")}const Lo=e=>typeof e=="string"?e.trim():"",cf=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function BS(e){const t=e.split(`
80
- `).find(s=>s.trim())??"",n=/^.*?[.!?。!?](?=\s|$)/u.exec(t.trim());return(n?n[0]:t.trim()).slice(0,80)}function XJ(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 JJ(e){return{...typeof e.title=="string"?{title:e.title.trim()}:{},...Lo(e.scope)?{scope:Lo(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}:{},...eL.includes(e.approvalMode)?{approvalMode:e.approvalMode}:{},...typeof e.memory=="boolean"?{memoryEnabled:e.memory}:{}}}function ZJ(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=cf(n.data)?n.data:n,o=Lo(s.name);if(!o)return{ok:!1,error:"not-a-card"};const r=cf(s.extensions)?s.extensions.enso:void 0;if(cf(r)){const d=typeof s.description=="string"?s.description:"";return{ok:!0,draft:{name:HS(o),title:"",scope:BS(d),persona:d,...JJ(r)}}}const a=d=>d.replace(/\{\{char\}\}/giu,o).replace(/\{\{user\}\}/giu,"the user"),l=a(Lo(s.description)),c=[l,Lo(s.personality)&&`Personality: ${a(Lo(s.personality))}`,Lo(s.scenario)&&`Scenario: ${a(Lo(s.scenario))}`].filter(Boolean);return{ok:!0,draft:{name:HS(o),title:"",scope:BS(l),persona:c.join(`
81
-
82
- `)}}}const Rr=256,VS=4;function ND({hasImage:e,nested:t=!1,disabled:n=!1,onPick:s,onRemove:o}){const{t:r}=ne(),a=m.useRef(null),[l,c]=m.useState(null);return i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[i.jsxs(me,{size:"xs",variant:"outline",disabled:n,onClick:()=>a.current?.click(),children:[i.jsx(Eh,{}),r("Upload avatar")]}),e&&i.jsxs(me,{size:"xs",variant:"ghost",disabled:n,onClick:o,children:[i.jsx(dn,{}),r("Remove avatar")]}),i.jsx("input",{ref:a,type:"file",accept:"image/png,image/jpeg,image/webp",hidden:!0,onChange:d=>{const u=d.target.files?.[0];d.target.value="",u&&nL(u).then(c,()=>ze({type:"error",title:r("This image cannot be used as an avatar.")}))}}),i.jsx(QJ,{source:l,nested:t,onCancel:()=>c(null),onDone:d=>{c(null),s(d)}})]})}function QJ({source:e,nested:t=!1,onCancel:n,onDone:s}){const{t:o}=ne(),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?Rr/Math.min(l.w,l.h)*v:1,p=v=>{if(!l)return v;const y=h(v.zoom),b=(l.w*y-Rr)/2,w=(l.h*y-Rr)/2;return{zoom:v.zoom,x:Math.max(-b,Math.min(b,v.x)),y:Math.max(-w,Math.min(w,v.y))}},f=v=>u(y=>p({...y,zoom:Math.max(1,Math.min(VS,v))})),g=()=>{const v=r.current;if(!v||!l)return;const y=h(d.zoom),b=Rr/y;s(iL(v,l.w/2-b/2-d.x/y,l.h/2-b/2-d.y/y,b))},x=h(d.zoom);return i.jsx(xn,{open:e!==null,onOpenChange:v=>!v&&n(),children:i.jsxs(vn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:o("Crop avatar")}),i.jsx(Rs,{children:o("Drag to move, scroll to zoom.")})]}),i.jsxs(An,{className:"flex flex-col items-center gap-4",children:[i.jsxs("div",{"data-avatar-crop":!0,className:"relative cursor-grab touch-none select-none overflow-hidden rounded-lg bg-muted active:cursor-grabbing",style:{width:Rr,height:Rr},onPointerDown:v=>{v.currentTarget.setPointerCapture(v.pointerId),a.current={id:v.pointerId,x:v.clientX,y:v.clientY}},onPointerMove:v=>{const y=a.current;!y||y.id!==v.pointerId||(a.current={...y,x:v.clientX,y:v.clientY},u(b=>p({...b,x:b.x+v.clientX-y.x,y:b.y+v.clientY-y.y})))},onPointerUp:()=>{a.current=null},onWheel:v=>f(d.zoom*(v.deltaY<0?1.1:1/1.1)),children:[e&&i.jsx("img",{ref:r,src:e,alt:"",draggable:!1,onLoad:v=>c({w:v.currentTarget.naturalWidth,h:v.currentTarget.naturalHeight}),onError:()=>{ze({type:"error",title:o("This image cannot be used as an avatar.")}),n()},className:"pointer-events-none absolute top-1/2 left-1/2 max-w-none",style:l?{width:l.w*x,height:l.h*x,transform:`translate(-50%, -50%) translate(${d.x}px, ${d.y}px)`}:{visibility:"hidden"}}),i.jsx("span",{className:"pointer-events-none absolute inset-0 rounded-full shadow-[0_0_0_9999px_rgb(0_0_0/0.55)] ring-2 ring-white/80"})]}),i.jsx(sL,{min:1,max:VS,step:.01,value:d.zoom,"aria-label":o("Zoom"),onValueChange:v=>f(Array.isArray(v)?v[0]:v)})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(me,{size:"sm",disabled:!l,onClick:g,children:o("Use this avatar")})]})]})})}const eZ=["tools","approvalMode","skillIds","mcpServerIds","canDelegateTo","acceptFrom"],tZ=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every(n=>t.includes(n)):e===t;function $S(e,t){return eZ.flatMap(n=>{const s=t[n];return!s||tZ(e[n],s.value)?[]:[{field:n,from:e[n],to:s.value,reason:s.reason}]})}function nZ(e,t,n){const s={...e};for(const o of t)n.includes(o.field)&&Object.assign(s,{[o.field]:o.to});return s}const TD={tools:"all",approvalMode:"auto-edits",skillIds:[],mcpServerIds:[],canDelegateTo:"any",acceptFrom:"any",memoryEnabled:!0,budgetCost:"",budgetTokens:"",delegationTimeout:"",maxTurnTokens:""};function ID({value:e,onChange:t,profile:n,botId:s,zIndex:o}){const{t:r}=ne(),l=ue(c=>c.bots).filter(c=>c.id!==s&&!c.archivedAt);return i.jsxs("div",{className:"space-y-4",children:[i.jsx(sZ,{value:e,onApply:t,profile:n,botId:s}),i.jsxs("div",{children:[i.jsx(Yt,{children:r("Tools")}),i.jsx(Vg,{value:e.tools,options:[{value:"all",label:r("All tools")},{value:"readonly",label:r("Read-only")}],onChange:c=>t({tools:c})})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:r("Approval mode")}),i.jsx(Hj,{value:e.approvalMode,onChange:c=>t({approvalMode:c}),zIndex:o})]}),i.jsx(DD,{value:e,onChange:t}),i.jsx(WS,{label:r("Can delegate to"),value:e.canDelegateTo,bots:l,onChange:c=>t({canDelegateTo:c})}),i.jsx(WS,{label:r("Accepts delegation from"),value:e.acceptFrom,bots:l,onChange:c=>t({acceptFrom:c})}),i.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[i.jsx("span",{children:r("Long-term memory")}),i.jsx(pi,{checked:e.memoryEnabled,onCheckedChange:c=>t({memoryEnabled:c})})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:r("Daily budget")}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsx(Zt,{type:"number",min:0,step:"0.01",inputMode:"decimal",value:e.budgetCost,placeholder:r("Cost (USD), empty = unlimited"),"aria-label":r("Daily cost limit (USD)"),onChange:c=>t({budgetCost:c.target.value})}),i.jsx(Zt,{type:"number",min:0,step:"1",inputMode:"numeric",value:e.budgetTokens,placeholder:r("Tokens, empty = unlimited"),"aria-label":r("Daily token limit"),onChange:c=>t({budgetTokens:c.target.value})})]}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:r("Resets at local midnight. Once reached, new messages to this member are refused and a running reply is stopped.")})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:r("Per-turn token limit")}),i.jsx(Zt,{type:"number",min:1,step:"1",inputMode:"numeric",value:e.maxTurnTokens,placeholder:r("Tokens, empty = unlimited"),"aria-label":r("Per-turn token limit"),onChange:c=>t({maxTurnTokens:c.target.value})}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:r("A single reply that uses more tokens than this (counted while streaming) is stopped.")})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:r("Delegation time limit (minutes)")}),i.jsx(Zt,{type:"number",min:1,max:1440,step:"1",inputMode:"numeric",value:e.delegationTimeout,placeholder:r("Empty = 240"),"aria-label":r("Delegation time limit (minutes)"),onChange:c=>t({delegationTimeout:c.target.value})}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:r("When other members delegate to this one, the task fails with a timeout after this long. A delegator can ask for less, not more.")})]})]})}function qh(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 sZ({value:e,onApply:t,profile:n,botId:s}){const{t:o,locale:r}=ne(),[a,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState([]),p=c?$S(e,c):[],f=async()=>{if(![n.name,n.title,n.scope,n.persona].some(x=>x.trim())){ze({type:"warning",title:o("Fill in a name, title or responsibilities first.")});return}l(!0);try{const x=await window.electronAPI.bots.suggestAbilities({name:n.name,title:n.title,scope:n.scope,persona:n.persona,language:r==="zh"?"zh":"en",...s?{botId:s}:{}});if(!x.ok){ze({type:"error",title:qh(x,o),...x.detail?{description:x.detail}:{}});return}if($S(e,x.suggestion).length===0){ze({type:"info",title:o("Current abilities already match the suggestion.")});return}h([]),d(x.suggestion)}finally{l(!1)}},g=()=>{const x=p.map(y=>y.field).filter(y=>!u.includes(y)),v=nZ(e,p,x);t(Object.fromEntries(x.map(y=>[y,v[y]]))),d(null)};return i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:o("Let a model suggest abilities from the name, title, responsibilities and persona.")}),i.jsxs(me,{size:"xs",variant:"outline",disabled:a,onClick:()=>{f()},children:[a?i.jsx(Xt,{className:"animate-spin"}):i.jsx(ii,{}),o("Auto-configure abilities")]})]}),c&&p.length>0&&i.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/40 p-2.5",children:[i.jsx("p",{className:"font-medium text-xs",children:o("Suggested changes")}),p.map(x=>i.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[i.jsx(gc,{className:"mt-0.5",checked:!u.includes(x.field),onCheckedChange:v=>h(y=>v?y.filter(b=>b!==x.field):[...y,x.field])}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-1.5",children:[i.jsx("span",{className:"font-medium",children:iZ(x.field,o)}),i.jsx(oZ,{change:x})]}),x.reason&&i.jsx("p",{className:"text-muted-foreground",children:x.reason})]})]},x.field)),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(me,{size:"xs",variant:"outline",onClick:()=>d(null),children:o("Cancel")}),i.jsx(me,{size:"xs",disabled:p.every(x=>u.includes(x.field)),onClick:g,children:o("Apply")})]})]})]})}function iZ(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 oZ({change:e}){const{t}=ne(),n=we(p=>p.skills),s=we(p=>p.mcpServers),o=ue(p=>p.bots),r=(p,f)=>i.jsxs("span",{className:"text-muted-foreground",children:[p," → ",i.jsx("span",{className:"text-foreground",children:f})]});if(e.field==="tools"){const p=f=>t(f==="all"?"All tools":"Read-only");return r(p(e.from),p(e.to))}if(e.field==="approvalMode"){const p=f=>t(Gl[f].labelKey);return r(p(e.from),p(e.to))}const a=e.field==="skillIds"?n:e.field==="mcpServerIds"?s:o,l=p=>a.find(f=>f.id===p)?.name??p,c=e.from,d=e.to;if(c==="any"||d==="any"){const p=f=>f==="any"?t("All members"):f.length===0?t("None selected"):f.map(l).join(", ");return r(p(c),p(d))}const u=d.filter(p=>!c.includes(p)),h=c.filter(p=>!d.includes(p));return i.jsxs("span",{className:"space-x-1.5",children:[u.map(p=>i.jsxs("span",{className:"text-success",children:["+",l(p)]},`+${p}`)),h.map(p=>i.jsx("span",{className:"text-destructive line-through",children:l(p)},`-${p}`))]})}function DD({value:e,onChange:t}){const{t:n}=ne(),s=we(a=>a.skills),o=we(a=>a.mcpServers),r=(a,l)=>a.includes(l)?a.filter(c=>c!==l):[...a,l];return i.jsxs(i.Fragment,{children:[i.jsx(A0,{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:R0(e.skillIds,a,l)}),placeholder:n("Filter skills..."),renderDetail:a=>i.jsx(M0,{rows:[[n("Source"),a.source],[n("Path"),a.path],[n("Description"),a.description]]})}),i.jsx(A0,{title:n("MCP Servers"),emptyText:n("No MCP servers yet"),items:o,getName:a=>a.name,getSource:a=>a.source,isChecked:a=>e.mcpServerIds.includes(a.id),onToggle:a=>t({mcpServerIds:r(e.mcpServerIds,a.id)}),onSetFiltered:(a,l)=>t({mcpServerIds:R0(e.mcpServerIds,a,l)}),placeholder:n("Filter MCP servers..."),renderDetail:a=>i.jsx(M0,{rows:[[n("Source"),a.source],["Transport",a.transport],["URL",a.url]]})})]})}function WS({label:e,value:t,bots:n,onChange:s}){const{t:o}=ne();return i.jsxs("div",{children:[i.jsx(Yt,{children:e}),i.jsx(Vg,{value:t==="any"?"any":"some",options:[{value:"any",label:o("All members")},{value:"some",label:o("Selected members")}],onChange:r=>s(r==="any"?"any":[])}),t!=="any"&&i.jsxs("div",{className:"mt-1.5 space-y-1",children:[n.length===0&&i.jsx("p",{className:"text-muted-foreground text-xs",children:o("No other members")}),n.map(r=>i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx(gc,{checked:t.includes(r.id),onCheckedChange:a=>s(a?[...t,r.id]:t.filter(l=>l!==r.id))}),i.jsx(tn,{bot:r,size:"xs"}),r.name]},r.id))]})]})}function rZ({bot:e}){const{t}=ne(),n=ue(r=>r.usage?.bots[e.id]);if(m.useEffect(()=>{ue.getState().refreshUsage()},[]),!n)return null;const s=[[t("Today"),n.today],[t("Last 7 days"),n.week],[t("Last 30 days"),n.month]],o=e.budget;return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-lg border bg-card p-3",children:[i.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.map(([r,a])=>i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"text-muted-foreground text-xs",children:r}),i.jsx("div",{className:"truncate font-medium text-sm tabular-nums",children:hp(a.tokens)}),i.jsx("div",{className:"truncate text-muted-foreground text-xs tabular-nums",children:pp(a.cost)})]},r))}),o&&i.jsxs("div",{className:n.exhausted?"mt-2 text-destructive text-xs":"mt-2 text-muted-foreground text-xs",children:[[o.dailyTokens!==void 0&&`${hp(n.today.tokens)} / ${hp(o.dailyTokens)} tokens`,o.dailyCostUsd!==void 0&&`${pp(n.today.cost??0)} / ${pp(o.dailyCostUsd)}`].filter(Boolean).join(" · "),n.exhausted&&` · ${t("Today's budget is used up")}`]})]})}function ED({spaceId:e,emptyText:t}){const[n,s]=m.useState(null),o=m.useCallback(async()=>{const r=await window.electronAPI.memory.list({spaceId:e,limit:100,offset:0});s(r.items)},[e]);return m.useEffect(()=>(s(null),o(),window.electronAPI.memory.onChanged(()=>{o()})),[o]),n===null?i.jsx(Xt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):n.length===0?i.jsx("p",{className:"text-muted-foreground text-xs",children:t}):i.jsx("div",{className:"space-y-1.5",children:n.map(r=>i.jsx(aZ,{item:r,onDeleted:()=>s(a=>a?.filter(l=>l.id!==r.id)??null)},r.id))})}function aZ({item:e,onDeleted:t}){const{t:n}=ne(),[s,o]=m.useState(null),[r,a]=m.useState(!1),l=async()=>{a(!0);const d=await window.electronAPI.memory.detail(e.id);a(!1),d?o({title:d.title,content:d.content}):ze({type:"error",title:n("Memory not found")})},c=async()=>{if(!s)return;a(!0);const d=await window.electronAPI.memory.update(e.id,s);a(!1),d.ok?o(null):ze({type:"error",title:n("Save failed"),description:d.error})};return s?i.jsxs("div",{"data-slot":"bot-card",className:"space-y-1.5 rounded-lg border bg-card px-2.5 py-2",children:[i.jsx(Zt,{size:"sm",value:s.title,placeholder:n("Memory title"),onChange:d=>o({...s,title:d.target.value})}),i.jsx(ni,{rows:5,value:s.content,placeholder:n("Memory content"),onChange:d=>o({...s,content:d.target.value})}),i.jsxs("div",{className:"flex justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",disabled:r,onClick:()=>o(null),children:n("Cancel")}),i.jsxs(me,{size:"xs",disabled:r||!s.content.trim(),onClick:()=>{c()},children:[r&&i.jsx(Xt,{className:"animate-spin"}),n("Save")]})]})]}):i.jsxs("div",{"data-slot":"bot-card",className:"group flex items-start gap-2 rounded-lg border bg-card px-2.5 py-2",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"truncate font-medium text-xs",children:e.title}),i.jsx("div",{className:"line-clamp-3 text-muted-foreground text-xs",children:e.contentSummary})]}),i.jsxs("div",{className:"flex shrink-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100",children:[i.jsx("button",{type:"button",title:n("Edit"),"aria-label":n("Edit"),disabled:r,onClick:()=>{l()},className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:r?i.jsx(Xt,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx($s,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",title:n("Delete"),"aria-label":n("Delete"),onClick:()=>{window.electronAPI.memory.delete(e.id).then(d=>{d.ok?t():ze({type:"error",title:d.error??n("Delete failed")})})},className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive",children:i.jsx(Vs,{className:"h-3.5 w-3.5"})})]})]})}function PD({target:e,emptyText:t}){const{t:n}=ne(),s="botId"in e?e.botId:void 0,o="chatId"in e?e.chatId:void 0,[r,a]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),h=m.useRef(!1);h.current=l!==null;const p=m.useCallback(async()=>{const g=await window.electronAPI.bots.notes.get(s?{botId:s}:{chatId:o??""});g.ok&&a(g.notes)},[s,o]);m.useEffect(()=>(a(null),c(null),p(),window.electronAPI.bots.onEvent(g=>{g.kind!=="notes"||h.current||(s?!g.chatId:g.chatId===o)&&p()})),[p,s,o]);const f=async()=>{if(!r||l===null)return;u(!0);const g=await window.electronAPI.bots.notes.save({...s?{botId:s}:{chatId:o??""},content:l,version:r.version});if(u(!1),g.ok){a(g.notes),c(null);return}ze({type:"error",title:g.error==="conflict"?n("Notes were updated elsewhere; reloaded the latest version"):n("Save failed")}),g.error==="conflict"&&(c(null),p())};return r?l!==null?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx(ni,{rows:8,value:l,maxLength:r.maxChars,onChange:g=>c(g.target.value)}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"mr-auto text-muted-foreground text-xs",children:[l.length," / ",r.maxChars]}),i.jsx(me,{size:"xs",variant:"ghost",disabled:d,onClick:()=>c(null),children:n("Cancel")}),i.jsx(me,{size:"xs",disabled:d,onClick:()=>{f()},children:n("Save")})]})]}):i.jsxs("div",{className:"group space-y-1.5",children:[r.content?i.jsx("div",{"data-slot":"bot-card",className:"max-h-64 overflow-y-auto whitespace-pre-wrap rounded-lg border bg-card px-2.5 py-2 text-xs",children:r.content}):i.jsx("p",{className:"text-muted-foreground text-xs",children:t}),i.jsx(me,{size:"xs",variant:"outline",onClick:()=>c(r.content),children:n("Edit notes")})]}):i.jsx(Xt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}function AD({value:e,onApply:t}){const{t:n,locale:s}=ne(),[o,r]=m.useState(!1),a=async()=>{if(!e.name.trim()||!e.title.trim()){ze({type:"warning",title:n("Fill in a name and title first.")});return}r(!0);try{const l=await window.electronAPI.bots.suggestPersona({name:e.name,title:e.title,scope:e.scope,persona:e.persona,language:s==="zh"?"zh":"en"});if(!l.ok){ze({type:"error",title:qh(l,n),...l.detail?{description:l.detail}:{}});return}const{persona:c,scope:d}=l.suggestion,u={persona:e.persona,scope:e.scope};t({persona:c,...d?{scope:d}:{}}),ze({type:"success",title:n(d?"Persona and responsibilities generated":"Persona generated"),timeout:1e4,actions:[{label:n("Undo"),onClick:()=>t(u)}]})}finally{r(!1)}};return i.jsxs(me,{size:"xs",variant:"ghost",className:"-my-1 h-6 text-muted-foreground",disabled:o,onClick:()=>{a()},children:[o?i.jsx(Xt,{className:"animate-spin"}):i.jsx(ii,{}),n("Generate with AI")]})}function US(e){const t=Vh(e);if(!t)return;const[n,s,o,r,a]=t.source.split(" ");if(!/^\d+$/u.test(n)||!/^\d+$/u.test(s)||o!=="*"||r!=="*")return;const l={hour:t.hour[0],minute:t.minute[0]};return a==="*"?{kind:"daily",days:[],...l}:a==="1-5"?{kind:"weekdays",days:[],...l}:/^\d+(,\d+)*$/u.test(a)?{kind:"weekly",days:[...new Set(t.dayOfWeek.map(d=>d%7))].sort((d,u)=>d-u),...l}:void 0}function lZ(e){const{kind:t,hour:n,minute:s}=e;if(!Number.isInteger(n)||n<0||n>23||!Number.isInteger(s)||s<0||s>59)return;const o=[...new Set(e.days)].filter(a=>Number.isInteger(a)&&a>=0&&a<=6);if(t==="weekly"&&!o.length)return;const r=t==="daily"?"*":t==="weekdays"?"1-5":o.sort().join(",");return`${s} ${n} * * ${r}`}function cZ(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 dZ(e){return e.status==="review"&&!!(e.delegationId&&e.assigneeBotId)}function uZ(e,t){return e.filter(n=>n.chatId===t).sort((n,s)=>n.createdAt-s.createdAt)}const rd=e=>e.finishedAt??e.createdAt;function hZ(e,t){const n=e.filter(o=>o.chatId===t),s=o=>zl(o.state)||zj(o,e);return{active:n.filter(s).sort((o,r)=>o.createdAt-r.createdAt),completed:n.filter(o=>o.state==="completed").sort((o,r)=>rd(r)-rd(o)),failed:n.filter(o=>["failed","canceled","blocked"].includes(o.state)&&!s(o)).sort((o,r)=>rd(r)-rd(o))}}function pZ(e,t,n){const s=new Map(t.map(o=>[o.id,o]));return[...e].sort((o,r)=>o.createdAt-r.createdAt).map(o=>({run:o,record:s.get(o.id),time:o.state==="queued"&&o.startedAt===void 0?{queued:!0,ms:n-o.createdAt}:{queued:!1,ms:(o.finishedAt??n)-(o.startedAt??o.createdAt)}}))}function fZ(e,t){const n=oL(e);if(!n)return;const s=t.find(r=>r.id===e.delegationId);if(n.reason==="failed"){const r=Bj(e);return{reason:"failed",...s?{record:s}:{},since:r?.finishedAt??s?.finishedAt??e.updatedAt}}const o=(e.blockedStreak?.[e.assigneeBotId??""]??0)>=rL;return{reason:"need",need:n.need||s?.blocked?.need||"",waitFor:!o&&s?.blocked?.waitFor==="parent"?s.parentBotId:"human",...o?{humanOnly:!0}:{},since:s?.finishedAt??s?.blocked?.at??e.updatedAt}}const mZ=["0 9 * * *","0 9 * * 1-5","0 9 * * 1","0 * * * *"];function gZ(e,t,n){const s=Vh(e);if(s)return{source:s.source,description:Cv(s,t),next:UX(s,n)}}function xZ(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 vZ(e){return e.title.trim()?e.prompt.trim()?Vh(e.schedule)?e.chatId?null:"chat":"schedule":"prompt":"title"}function Fu(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 ya("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?ya(n,t):t("This routine is blocked. Fix the problem and enable it again.");default:return e}}function ya(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 MD(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 jv(){const{t:e}=ne(),[t,n]=m.useState(!1),s=async(r,a,l)=>{n(!0);try{const c=await a();c.ok?l&&ze({type:"success",title:l}):ze({type:"error",title:r,description:Fu(c.error,e,c.reason)})}finally{n(!1)}},o=window.electronAPI.bots.routines;return{busy:t,review:(r,a)=>s(e("Routine not saved"),()=>o.review({botId:r.botId,id:r.id,approve:a})),resume:r=>s(e("Routine not saved"),async()=>{const a=await o.save({botId:r.botId,id:r.id,title:r.title,prompt:r.prompt,schedule:r.schedule,chatId:r.chatId,enabled:!0});return a.ok&&a.routine.status==="blocked"?{ok:!1,error:"blocked",reason:a.routine.blockedReason}:a}),run:(r,a)=>s(e("Routine did not run"),()=>o.runNow({botId:r.botId,id:r.id,dryRun:a}),e(a?"Dry run started":"Routine started"))}}function RD({routine:e}){const{t,locale:n}=ne(),s=ue(r=>r.bots),o=e.doneBy?s.find(r=>r.id===e.doneBy):void 0;return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"mt-2 font-medium text-sm",children:e.title}),i.jsxs("div",{className:"mt-0.5 text-muted-foreground text-xs",children:[Cv(e.schedule,n),e.doneBy?` · ${t("Done by {{name}}",{name:o?.name??t("Deleted member")})}`:""]}),i.jsx("div",{className:"mt-1 line-clamp-3 whitespace-pre-wrap text-xs",children:e.prompt})]})}function bZ({alert:e}){const{t}=ne(),n=ue(p=>p.bots),s=ue(p=>p.chats),o=ue(p=>p.setView),{busy:r,review:a,resume:l,run:c}=jv(),{routine:d}=e,u=n.find(p=>p.id===d.botId),h=s.find(p=>p.id===d.chatId);return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:u,size:"sm"}),i.jsx("span",{className:"text-foreground",children:u?.name??t("Deleted member")}),h?.kind==="group"&&i.jsxs("span",{children:["· ",Cs(h,n,t)]}),i.jsx(_v,{routine:d})]}),i.jsx(RD,{routine:d}),e.kind==="blocked"&&i.jsx("div",{className:"mt-1 text-destructive text-xs",children:ya(d.blockedReason,t)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[h&&i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>o({kind:"chat",chatId:h.id}),children:t("Go to chat")}),e.kind==="approval"?i.jsxs(i.Fragment,{children:[i.jsx(me,{size:"xs",variant:"outline",disabled:r,onClick:()=>c(d,!0),children:t("Dry run")}),i.jsx(me,{size:"xs",variant:"outline",disabled:r,onClick:()=>a(d,!1),children:t("Reject")}),i.jsx(me,{size:"xs",disabled:r,onClick:()=>a(d,!0),children:t("Approve")})]}):i.jsx(me,{size:"xs",disabled:r,onClick:()=>l(d),children:t("Enable again")})]})]})}function _v({routine:e}){const{t}=ne(),[n,s]=e.status==="draft"?[t("Pending approval"),"bg-warning/20 text-warning"]:e.status==="blocked"?[t("Blocked"),"bg-destructive/15 text-destructive"]:e.status==="paused"?[t("Paused"),"bg-muted text-muted-foreground"]:[t("Enabled"),"bg-success/15 text-success"];return i.jsx("span",{className:W("rounded px-1.5 text-[11px]",s),children:n})}function wZ({text:e,target:t}){const{t:n}=ne(),s=ue(l=>l.routines.find(c=>c.id===t.id&&c.botId===t.botId)),{busy:o,review:r,run:a}=jv();return i.jsxs("div",{"data-slot":"bot-card",className:"w-full max-w-md self-center rounded-xl border bg-card px-3 py-2 text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[i.jsx("span",{className:"min-w-0 flex-1",children:e}),s?i.jsx(_v,{routine:s}):i.jsx("span",{className:"text-[11px]",children:n("Routine removed")})]}),s&&i.jsx(RD,{routine:s}),s?.status==="draft"&&i.jsxs("div",{className:"mt-2 flex justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",disabled:o,onClick:()=>a(s,!0),children:n("Dry run")}),i.jsx(me,{size:"xs",variant:"outline",disabled:o,onClick:()=>r(s,!1),children:n("Reject")}),i.jsx(me,{size:"xs",disabled:o,onClick:()=>r(s,!0),children:n("Approve")})]})]})}const Nv=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function LD(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 yZ(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 SZ(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 OD({botId:e,chatId:t}){const{t:n,locale:s}=ne(),o=ue(w=>w.chats),r=ue(w=>w.bots),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(null),[p,f]=m.useState(null),g=jv(),x=m.useCallback(async()=>{const w=await window.electronAPI.bots.routines.list(e?{botId:e}:{}).catch(()=>null),C=w?.ok?w.routines:[];l(t?uZ(C,t):C)},[e,t]);m.useEffect(()=>(l(null),x(),window.electronAPI.bots.onEvent(w=>{w.kind==="routine"&&x()})),[x]);const v=async(w,C)=>{const{id:_,title:N,prompt:k,schedule:S}=w,A=await window.electronAPI.bots.routines.save({botId:w.botId,id:_,title:N,prompt:k,schedule:S,chatId:w.chatId,enabled:C});A.ok?A.routine.status==="blocked"&&ze({type:"error",title:n("Routine blocked"),description:ya(A.routine.blockedReason,n)}):ze({type:"error",title:n("Routine not saved"),description:Fu(A.error,n)}),x()},y=async w=>{h(null);const C=await window.electronAPI.bots.routines.remove({botId:w.botId,id:w.id});C.ok||ze({type:"error",title:n("Routine not deleted"),description:Fu(C.error,n)}),x()};if(a===null)return i.jsx(Xt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const b=w=>r.find(C=>C.id===w)?.name??n("Deleted member");return i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs(me,{size:"xs",variant:"outline",onClick:()=>d("new"),children:[i.jsx(as,{}),n("New routine")]}),a.length===0&&i.jsx("p",{className:"text-muted-foreground text-xs",children:n("No routines yet")}),a.map(w=>{const C=o.find(S=>S.id===w.chatId),_=w.status==="draft",N=aL(w)&&(w.status==="enabled"||w.status==="paused"),k=C?n("Posts to {{chat}}",{chat:Cs(C,r,n)}):n("Target chat missing");return i.jsxs("div",{"data-slot":"bot-card",className:W("rounded-lg border bg-card px-2.5 py-2 text-xs",w.status==="paused"&&"opacity-70"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:w.title}),i.jsx(_v,{routine:w}),!_&&i.jsx(pi,{checked:w.status==="enabled",onCheckedChange:S=>{v(w,S)},title:w.status==="enabled"?n("Enabled"):n("Paused")})]}),i.jsx("div",{className:"mt-0.5 text-muted-foreground",children:[t?b(w.botId):"",Cv(w.schedule,s),w.doneBy?n("Done by {{name}}",{name:b(w.doneBy)}):"",t?"":k].filter(Boolean).join(" · ")}),w.proposedBy&&_&&i.jsx("div",{className:"mt-0.5 text-warning",children:n("Proposed by {{name}}, waiting for your approval",{name:b(w.proposedBy)})}),w.status==="blocked"&&i.jsx("div",{className:"mt-0.5 text-destructive",children:ya(w.blockedReason,n)}),i.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-2 text-muted-foreground",children:[i.jsx("span",{children:w.lastRunAt?n("Last run {{time}} · {{result}}",{time:Nv(w.lastRunAt),result:MD(w.lastResult,n)}):n("Never run")}),w.missed?i.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-warning",children:n("Missed {{n}} times",{n:w.missed})}):null,!w.catchUp&&i.jsx("span",{children:n("No catch-up")})]}),i.jsxs("div",{className:"mt-1.5 flex flex-wrap justify-end gap-1",children:[_?i.jsxs(i.Fragment,{children:[i.jsx(me,{size:"xs",variant:"ghost",disabled:g.busy,onClick:()=>{g.review(w,!1)},children:n("Reject")}),i.jsx(me,{size:"xs",disabled:g.busy,onClick:()=>{g.review(w,!0)},children:n("Approve")})]}):i.jsxs(me,{size:"xs",variant:"ghost",disabled:!N||g.busy,onClick:()=>{g.run(w,!1)},children:[i.jsx($g,{}),n("Run now")]}),i.jsxs(me,{size:"xs",variant:"ghost",disabled:g.busy,title:n("Run once without affecting the schedule"),onClick:()=>{g.run(w,!0)},children:[i.jsx(_j,{}),n("Dry run")]}),i.jsxs(me,{size:"xs",variant:p===w.id?"secondary":"ghost",onClick:()=>f(p===w.id?null:w.id),children:[i.jsx(Yo,{}),n("History")]}),i.jsxs(me,{size:"xs",variant:"ghost",onClick:()=>d(w),children:[i.jsx($s,{}),n("Edit")]}),i.jsxs(me,{size:"xs",variant:"ghost",onClick:()=>h(w),children:[i.jsx(Vs,{}),n("Delete")]})]}),p===w.id&&i.jsx(CZ,{routine:w})]},w.id)}),c&&i.jsx(_Z,{botId:e,chatId:t,routine:c==="new"?void 0:c,onClose:w=>{d(null),w&&x()}}),i.jsx(gs,{open:u!==null,onOpenChange:w=>!w&&h(null),title:n('Delete routine "{{title}}"?',{title:u?.title??""}),description:n("It will no longer run. This cannot be undone."),confirmLabel:n("Delete"),onConfirm:()=>u&&void y(u)})]})}function CZ({routine:e}){const{t}=ne(),n=ue(l=>l.setView),[s,o]=m.useState(null),{botId:r,id:a}=e;return m.useEffect(()=>{let l=!0;const c=()=>{window.electronAPI.bots.routines.runs({botId:r,id:a}).then(u=>l&&o(u.ok?u.runs:[])).catch(()=>l&&o([]))};c();const d=window.electronAPI.bots.onEvent(u=>{u.kind==="routine"&&c()});return()=>{l=!1,d()}},[r,a]),s===null?i.jsx(Xt,{className:"mt-2 h-3.5 w-3.5 animate-spin"}):s.length===0?i.jsx("p",{className:"mt-2 text-muted-foreground",children:t("No runs yet")}):i.jsx("ul",{className:"mt-2 space-y-1 border-t pt-2",children:s.map(l=>i.jsxs("li",{className:"flex flex-wrap items-center gap-x-2 text-muted-foreground",children:[i.jsx("span",{className:"tabular-nums",children:Nv(l.startedAt)}),i.jsx("span",{children:yZ(l.trigger,t)}),i.jsxs("span",{className:W(l.result==="ok"&&"text-success",(l.result==="error"||l.result==="blocked"||l.result==="budget")&&"text-destructive"),children:[MD(l.result,t),SZ(l)]}),l.conversationId&&i.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>n({kind:"chat",chatId:l.chatId}),children:t("Open chat")}),l.error&&i.jsx("span",{className:"w-full truncate text-destructive",title:l.error,children:l.result==="blocked"?ya(l.error,t):l.error})]},l.runId))})}const kZ=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],KS=e=>String(e).padStart(2,"0");function jZ({value:e,onChange:t}){const{t:n,locale:s}=ne(),o=US(e),[r,a]=m.useState(!o),[l,c]=m.useState(o??{kind:"daily",days:[1],hour:9,minute:0}),d=gZ(e,s,Date.now()),u=f=>{c(f);const g=lZ(f);g&&t(g)},h=[{value:"daily",label:n("Every day")},{value:"weekdays",label:n("Weekdays")},{value:"weekly",label:n("Every week on")}],p=()=>{if(!r)return a(!0);const f=US(e);f?c(f):u(l),a(!1)};return i.jsxs("div",{children:[i.jsx(Yt,{hint:r?n("cron: minute hour day month weekday, local time"):void 0,action:i.jsx(me,{size:"xs",variant:"ghost",onClick:p,children:n(r?"Simple":"Advanced (cron)")}),children:n("Schedule")}),r?i.jsx(Zt,{className:"font-mono",value:e,placeholder:"0 9 * * 1-5",onChange:f=>t(f.target.value)}):i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[i.jsxs(bs,{items:h,value:l.kind,onValueChange:f=>u({...l,kind:f,days:l.days.length?l.days:[1]}),children:[i.jsx(ws,{className:"w-32",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:h.map(f=>i.jsx(rs,{value:f.value,children:f.label},f.value))})]}),l.kind==="weekly"&&kZ.map((f,g)=>{const x=l.days.includes(g);return i.jsx(me,{size:"xs",variant:x?"default":"outline",onClick:()=>{const v=x?l.days.filter(y=>y!==g):[...l.days,g].sort();v.length&&u({...l,days:v})},children:n(f)},f)}),i.jsx(Zt,{type:"time",className:"w-28",value:`${KS(l.hour)}:${KS(l.minute)}`,onChange:f=>{const[g,x]=f.target.value.split(":").map(Number);Number.isInteger(g)&&Number.isInteger(x)&&u({...l,hour:g,minute:x})}})]}),i.jsx("p",{className:W("mt-1 text-xs",d?"text-muted-foreground":"text-destructive"),children:d?`${d.description} · ${d.next?n("Next run {{time}}",{time:Nv(d.next)}):n("Never runs")}`:LD("schedule",n)})]})}function _Z({botId:e,chatId:t,routine:n,onClose:s}){const{t:o}=ne(),r=ue($=>$.chats),a=ue($=>$.bots),l=m.useMemo(()=>(r.find(X=>X.id===t)?.members??[]).flatMap(X=>{const H=a.find(te=>te.id===X&&te.archivedAt===void 0);return H?[H]:[]}),[r,a,t]),[c,d]=m.useState(n?.botId??e??l[0]?.id??""),u=m.useMemo(()=>xZ(r,c),[r,c]),[h,p]=m.useState(n?.title??""),[f,g]=m.useState(n?.prompt??""),[x,v]=m.useState(n?.schedule??mZ[0]),[y,b]=m.useState(n?.chatId??t??u[0]?.id??""),[w,C]=m.useState(n?.doneBy??""),[_,N]=m.useState(n?.catchUp??!0),[k,S]=m.useState(null),[A,T]=m.useState(!1),I=$=>{const X=r.find(H=>H.id===$);return X?`${Cs(X,a,o)} · ${X.kind==="group"?o("Group chat"):o("Private chat")}`:o("Target chat missing")},P=u.some($=>$.id===y)||!y?u.map($=>$.id):[y,...u.map($=>$.id)],D=m.useMemo(()=>(r.find(X=>X.id===y)?.members??[]).flatMap(X=>{const H=a.find(te=>te.id===X&&te.archivedAt===void 0);return H&&H.id!==c?[H]:[]}),[r,a,y,c]),O=[{value:"",label:o("The member itself")},...D.map($=>({value:$.id,label:$.name}))],z=D.some($=>$.id===w)?w:"",R=async()=>{if(!c)return S(o("Choose a member."));const $=vZ({title:h,prompt:f,schedule:x,chatId:y});if($)return S(LD($,o));T(!0),S(null);try{const X=await window.electronAPI.bots.routines.save({botId:c,title:h,prompt:f,schedule:x,chatId:y,catchUp:_,doneBy:z||null,...n?{id:n.id,enabled:n.status!=="paused"}:{}});X.ok?s(!0):S(Fu(X.error,o))}finally{T(!1)}};return i.jsx(xn,{open:!0,onOpenChange:$=>!$&&s(!1),children:i.jsxs(vn,{className:"max-h-[85vh] max-w-lg",children:[i.jsx(bn,{children:i.jsx(wn,{children:o(n?"Edit routine":"New routine")})}),i.jsxs(An,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Yt,{children:o("Routine title")}),i.jsx(Zt,{value:h,onChange:$=>p($.target.value)})]}),i.jsxs("div",{children:[i.jsx(Yt,{hint:o("Sent to the member as the task each time it runs"),children:o("Prompt")}),i.jsx(ni,{rows:4,value:f,onChange:$=>g($.target.value)})]}),i.jsx(jZ,{value:x,onChange:v}),t?i.jsxs("div",{children:[i.jsx(Yt,{children:o("Member")}),i.jsxs(bs,{items:l.map($=>({value:$.id,label:$.name})),value:c,disabled:!!n,onValueChange:$=>d($),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:l.map($=>i.jsx(rs,{value:$.id,children:$.name},$.id))})]})]}):i.jsxs("div",{children:[i.jsx(Yt,{children:o("Target chat")}),P.length===0?i.jsx("p",{className:"text-muted-foreground text-xs",children:o("This member is not in any chat yet. Start a private chat first.")}):i.jsxs(bs,{items:P.map($=>({value:$,label:I($)})),value:y,onValueChange:$=>b($),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:P.map($=>i.jsx(rs,{value:$,children:I($)},$))})]})]}),D.length>0&&i.jsxs("div",{children:[i.jsx(Yt,{hint:o("Another member of the target chat runs it, as a delegation"),children:o("Done by")}),i.jsxs(bs,{items:O,value:z,onValueChange:$=>C($),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:O.map($=>i.jsx(rs,{value:$.value,children:$.label},$.value||"self"))})]})]}),i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx(Yt,{hint:o("If the app was closed at the scheduled time, run the latest missed one once on startup"),children:o("Catch up missed runs")}),i.jsx(pi,{checked:_,onCheckedChange:N})]}),k&&i.jsx("p",{className:"text-destructive text-sm",children:k})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:()=>s(!1),children:o("Cancel")}),i.jsxs(me,{size:"sm",disabled:A,onClick:()=>{R()},children:[A&&i.jsx(Xt,{className:"animate-spin"}),o("Save")]})]})]})})}function df(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,...qJ(e.budget),...YJ(e)}}function NZ(e){const t=_D(e),n=kv(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 TZ(e,t){const n=iu(e),s=n?await fetch(n).then(r=>r.blob()).then(Uj).catch(()=>null):null,o=WJ(lL(s??await cL(e.name,e.avatar.color)),"chara",UJ(JSON.stringify(XJ(e,t))),["ccv3"]);if(!o)throw new Error("png");dL(new Blob([new Uint8Array(o)],{type:"image/png"}),`${e.name}.png`)}function IZ({botId:e,chat:t,onOpenHistory:n}){const{t:s}=ne(),o=ue(I=>I.bots.find(P=>P.id===e)),r=ue(I=>I.bots),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(!1),[p,f]=m.useState(!1),[g,x]=m.useState(!1),[v,y]=m.useState(null),b=m.useCallback(async()=>{const I=await window.electronAPI.bots.get(e);I.ok&&(ue.getState().upsertBot(I.bot),l(I.persona),d(df(I.bot,I.persona)),h(!1))},[e]);m.useEffect(()=>{l(null),d(null),b()},[b]);const w=m.useMemo(()=>o&&a!==null?df(o,a):null,[o,a]),C=u&&!!(c&&w&&JSON.stringify(c)!==JSON.stringify(w));if(m.useEffect(()=>{!u&&w&&d(w)},[o?.version]),!o||!c)return i.jsx("div",{className:"flex flex-1 items-center justify-center",children:i.jsx(Xt,{className:"h-4 w-4 animate-spin text-muted-foreground"})});const _=I=>{d(P=>P&&{...P,...I}),h(!0)},N=Wg(c.name,r,s,o.id),k=async I=>{x(!0);try{await Wj(o.id,I)||ze({type:"error",title:s("Avatar update failed")})}finally{x(!1)}},S=()=>{TZ(o,a??"").then(()=>ze({type:"success",title:s('Persona embedded in the PNG. Restore it in a new member via "Import character card".')})).catch(()=>ze({type:"error",title:s("Export failed")}))},A=async()=>{const I=NZ(c);if(!I){ze({type:"error",title:kv(c).ok?s("Budget must be a positive number"):s("Check the per-turn token limit and delegation time limit")});return}f(!0);try{const P=await window.electronAPI.bots.update({botId:o.id,expectedVersion:o.version,draft:I});if(P.ok){ue.getState().upsertBot(P.bot),l(c.persona),d(df(P.bot,c.persona)),h(!1);return}ze({type:"error",title:dl(P.reason,P.error,s),...P.reason==="conflict"?{actions:[{label:s("Refresh"),onClick:()=>{b()}}]}:{}})}finally{f(!1)}},T=async()=>{const I=v;if(y(null),I==="archive"){const D=await window.electronAPI.bots.archive(o.id,!0);D.ok?ue.getState().upsertBot(D.bot):ze({type:"error",title:dl(D.reason,D.error,s)});return}const P=await window.electronAPI.bots.remove(o.id);if(P.ok){ue.getState().setView(null),await Promise.all([ue.getState().refreshCatalog(),ue.getState().refreshChats()]);return}if(P.reason==="boss"){const D=ue.getState().chats,O=(P.chatIds??[]).map(z=>D.find(R=>R.id===z)).filter(z=>!!z).map(z=>Cs(z,r,s));ze({type:"warning",title:s("{{name}} owns group chats",{name:o.name}),description:s("Choose another owner in {{groups}} first.",{groups:O.join("、")})});return}ze({type:"error",title:dl(P.reason,P.error,s)})};return i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 pt-4",children:[i.jsx(tn,{bot:{id:o.id,name:c.name||o.name,avatar:{...o.avatar,color:c.color}},size:"lg"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate font-semibold text-base",children:o.name}),i.jsx("div",{className:"truncate text-muted-foreground text-sm",children:o.title}),i.jsxs("div",{className:"mt-1 flex flex-wrap gap-1.5",children:[i.jsxs(Vf,{children:[i.jsxs($f,{render:i.jsx(me,{size:"xs",variant:"outline",onClick:S}),children:[i.jsx(cc,{}),s("Export character card")]}),i.jsx(Wf,{className:"max-w-72",children:s('Exports a SillyTavern V2 PNG: the avatar as image, persona embedded. Restore it in a new member via "Import character card".')})]}),i.jsx(ND,{hasImage:!!o.avatar.image,disabled:g,onPick:I=>{k(I)},onRemove:()=>{k(null)}})]})]})]}),i.jsxs(lh,{defaultValue:"profile",className:"mt-3 flex min-h-0 flex-1 flex-col",children:[i.jsxs(ch,{variant:"underline",className:"shrink-0 px-2",children:[i.jsx(Ps,{value:"profile",children:s("Profile")}),i.jsx(Ps,{value:"abilities",children:s("Abilities")}),i.jsx(Ps,{value:"memory",children:s("Memory")}),i.jsx(Ps,{value:"routines",children:s("Routines")}),i.jsx(Ps,{value:"history",children:s("History")})]}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-3",children:[i.jsxs(lo,{value:"profile",className:"space-y-3",children:[i.jsx(rZ,{bot:o}),i.jsxs("div",{children:[i.jsx(Yt,{hint:s("Used for @ in groups; must be unique"),children:s("Name")}),i.jsx(Zt,{value:c.name,onChange:I=>_({name:I.target.value})}),N&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:N})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:s("Title")}),i.jsx(Zt,{value:c.title,onChange:I=>_({title:I.target.value})})]}),i.jsxs("div",{children:[i.jsx(Yt,{hint:s("Used for routing and the delegation directory"),children:s("Responsibilities")}),i.jsx(ni,{rows:2,value:c.scope,onChange:I=>_({scope:I.target.value})})]}),i.jsxs("div",{children:[i.jsx(Yt,{action:i.jsx(AD,{value:c,onApply:_}),children:s("Persona")}),i.jsx(ni,{rows:8,value:c.persona,onChange:I=>_({persona:I.target.value})})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:s("Avatar color")}),i.jsx(Vj,{value:c.color,onChange:I=>_({color:I})})]}),i.jsxs("div",{className:"flex gap-2 border-t pt-3",children:[i.jsxs(me,{size:"xs",variant:"outline",onClick:()=>y("archive"),children:[i.jsx(Oi,{}),s("Archive member")]}),i.jsxs(me,{size:"xs",variant:"destructive-outline",onClick:()=>y("delete"),children:[i.jsx(Vs,{}),s("Delete permanently")]})]})]}),i.jsxs(lo,{value:"abilities",className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Yt,{children:s("Model")}),i.jsx($j,{engine:c.engine,onChange:I=>_({engine:I})})]}),i.jsx(ID,{value:c,onChange:_,profile:c,botId:o.id})]}),i.jsxs(lo,{value:"memory",children:[i.jsxs("div",{className:"mb-4",children:[i.jsx(Yt,{hint:s("Injected into every new conversation"),children:s("Core notes")}),i.jsx(PD,{target:{botId:o.id},emptyText:s("No notes yet. Key preferences and facts are summarized here automatically after memories are organized.")})]}),i.jsx(ED,{spaceId:`bot:${o.id}`,emptyText:s("No memories yet")})]}),i.jsx(lo,{value:"routines",children:i.jsx(OD,{botId:o.id})}),i.jsx(lo,{value:"history",children:i.jsx(DZ,{chat:t,botId:o.id,onOpen:I=>n(I,o.name)})})]})]}),C&&i.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t bg-muted/50 px-4 py-2.5",children:[i.jsx(me,{size:"sm",variant:"outline",onClick:()=>{w&&d(w),h(!1)},children:s("Discard")}),i.jsxs(me,{size:"sm",disabled:p||!!N,onClick:()=>{A()},children:[p&&i.jsx(Xt,{className:"animate-spin"}),s("Save")]})]}),i.jsx(gs,{open:v!==null,onOpenChange:I=>!I&&y(null),title:v==="delete"?s("Delete {{name}}?",{name:o.name}):s("Archive {{name}}?",{name:o.name}),description:s(v==="delete"?"The member, their private chats, persona, memories and workspace are deleted. This cannot be undone.":"Archived members stop replying and are hidden from the list. You can restore them later."),confirmLabel:s(v==="delete"?"Delete permanently":"Archive member"),onConfirm:()=>{T()}})]})}function DZ({chat:e,botId:t,onOpen:n}){const{t:s}=ne(),[o,r]=m.useState(null);return m.useEffect(()=>{let a=!0;return window.electronAPI.bots.chatSessions(e.id).then(l=>{a&&r(l.ok?l.sessions.filter(c=>c.botId===t):[])}),()=>{a=!1}},[e.id,t]),o===null?i.jsx(Xt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):o.length===0?i.jsx("p",{className:"text-muted-foreground text-xs",children:s("No conversations yet")}):i.jsx("div",{className:"space-y-1",children:o.map((a,l)=>i.jsxs("button",{type:"button",onClick:()=>n(a.conversationId),"data-slot":"bot-card-button",className:"flex w-full items-center justify-between rounded-lg border bg-card px-2.5 py-2 text-left text-xs hover:bg-muted",children:[i.jsx("span",{children:s("Conversation {{n}}",{n:o.length-l})}),i.jsx("span",{className:"text-muted-foreground",children:a.current?s("Current"):s("Read-only")})]},a.conversationId))})}function Hu(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 zD(e,t,n,s){const o=await window.electronAPI.bots.tasks.reply({chatId:e,id:t,text:n}),r=ue.getState();return r.refreshTasks(e),r.refreshDelegations(),r.refreshInbox(),o.ok||ze({type:"error",title:s("Reply not sent"),description:Hu(o.error,s)}),o.ok}function Tv({placeholder:e,onSend:t,className:n}){const{t:s}=ne(),[o,r]=m.useState(""),[a,l]=m.useState(!1),c=Fi(we(u=>u.keybindings))["send-message"],d=async()=>{const u=o.trim();if(!(!u||a)){l(!0);try{await t(u)&&r("")}finally{l(!1)}}};return i.jsxs("div",{className:W("mt-1.5 flex items-end gap-1",n),children:[i.jsx(ni,{value:o,rows:1,size:"sm",maxLength:Ug,placeholder:e,"aria-label":e,title:c?`${s("Send")} ${ti(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&&Oj(u,c)&&(u.preventDefault(),d())}}),i.jsx(me,{size:"icon-sm",variant:o.trim()?"default":"ghost","aria-label":s("Send reply"),disabled:!o.trim()||a,onClick:()=>{d()},children:a?i.jsx(Xt,{className:"animate-spin"}):i.jsx(qx,{})})]})}function GD(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 FD=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),HD=(e,t)=>e.ok===void 0?t("Processing"):e.ok?t("Delivered"):t("Not delivered");function EZ({appends:e}){const{t}=ne();return i.jsx("ul",{className:"mt-0.5 ml-6 space-y-0.5",children:e.map(n=>i.jsxs("li",{className:"flex items-center gap-1.5 text-muted-foreground",children:[i.jsx("span",{className:"shrink-0 tabular-nums",children:FD(n.at)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",title:n.text,children:n.text}),i.jsx("span",{className:W("shrink-0 rounded px-1.5 text-[11px]",n.ok===void 0?"bg-info/15 text-info":n.ok?"bg-success/15 text-success":"bg-destructive/15 text-destructive"),children:HD(n,t)})]},n.deliveryId))})}function PZ({runs:e,bots:t,onOpenConversation:n}){const{t:s}=ne(),o=ue(f=>f.delegations),r=Uh(e.some(f=>zl(f.state))),[a,l]=m.useState(!1),[c,d]=m.useState(null),u=pZ(e,o,r),h=a?u:u.slice(-5),p=f=>t.get(f)?.name??s("Deleted member");return i.jsxs("section",{className:"mt-1.5 border-t pt-1.5",children:[i.jsxs("h5",{className:"mb-1 text-[11px] text-muted-foreground",children:[s("Run history")," · ",u.length]}),i.jsx("ul",{className:"space-y-1",children:h.map(({run:f,record:g,time:x})=>{const v=f.state==="failed"?Rc(g??f,s):void 0,y=g?.appends??[];return i.jsxs("li",{className:W(f.nested&&"ml-3 border-l pl-2"),children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-muted-foreground",children:[i.jsx(tn,{bot:t.get(f.botId),size:"xs"}),i.jsx("span",{className:"text-foreground",children:p(f.botId)}),i.jsxs("span",{children:["· ",f.nested?s("Sub-delegation"):GD(f.trigger,s)]}),x.queued?i.jsx("span",{className:"rounded bg-info/15 px-1.5 text-[11px] text-info",children:s("Queued {{time}}",{time:wo(x.ms)})}):i.jsxs(i.Fragment,{children:[i.jsx(Wh,{state:f.state,interrupted:f.failure==="interrupted"}),i.jsx("span",{children:wo(x.ms)})]}),f.appends&&i.jsx("button",{type:"button","aria-expanded":c===f.id,disabled:!y.length,title:y.map(b=>`${FD(b.at)} ${b.text} · ${HD(b,s)}`).join(`
83
- `),onClick:()=>d(c===f.id?null:f.id),className:"rounded px-1 text-info hover:bg-info/10 disabled:hover:bg-transparent",children:s("+{{n}} appended",{n:f.appends})}),i.jsx("span",{className:"flex-1"}),g&&i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>n(g.childConversationId,s("{{from}} → {{to}} · Delegation",{from:p(g.parentBotId),to:p(g.targetBotId)})),children:s("View process")})]}),c===f.id&&y.length>0&&i.jsx(EZ,{appends:y}),v&&i.jsx("div",{className:"mt-0.5 line-clamp-2 whitespace-pre-wrap text-destructive",children:v})]},f.id)})}),u.length>h.length&&i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>l(!0),children:s("Show all ({{n}})",{n:u.length})})]})}const ag=5,AZ=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function ao({title:e,count:t,limit:n,children:s}){const{t:o}=ne(),[r,a]=m.useState(!1),l=n&&!r?Math.min(n,t):t;return i.jsxs("section",{className:"mt-4 first:mt-0",children:[i.jsxs("h4",{className:"mb-1.5 font-medium text-[11px] text-muted-foreground uppercase tracking-wide",children:[e," · ",t]}),i.jsx("div",{className:"space-y-1.5",children:s(l)}),t>l&&i.jsx(me,{size:"xs",variant:"ghost",className:"mt-1",onClick:()=>a(!0),children:o("Show all ({{n}})",{n:t})})]})}function MZ({chat:e,onOpenConversation:t}){const{t:n}=ne(),s=ue(S=>S.tasks[e.id]),o=ue(S=>S.bots),r=ue(S=>S.delegations),[a,l]=m.useState(null),[c,d]=m.useState(null),[u,h]=m.useState(null),p=ue(S=>S.taskFocus),[f,g]=m.useState(null),x=m.useRef(null),v=Uh(!!s?.some(S=>S.status==="blocked")),y=m.useMemo(()=>new Map(o.map(S=>[S.id,S])),[o]),b=e.members.flatMap(S=>{const A=y.get(S);return A&&A.archivedAt===void 0?[A]:[]});m.useEffect(()=>{ue.getState().refreshTasks(e.id)},[e.id]),m.useEffect(()=>{!p||p.chatId!==e.id||!s||(ue.getState().clearTaskFocus(p.nonce),s.some(S=>S.id===p.taskId)&&(g(p.taskId),requestAnimationFrame(()=>x.current?.querySelector(`[data-task-id="${CSS.escape(p.taskId)}"]`)?.scrollIntoView({block:"center",behavior:"smooth"}))))},[p,s,e.id]),m.useEffect(()=>{if(!f)return;const S=setTimeout(()=>g(null),2e3);return()=>clearTimeout(S)},[f]);const w=async(S,A)=>{const T=await S();T.ok||ze({type:"error",title:A,description:Hu(T.error??"",n)}),ue.getState().refreshTasks(e.id)},C=window.electronAPI.bots.tasks,_=S=>({chatId:e.id,id:S.id});if(!s)return i.jsx(Xt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const N=cZ(s),k=S=>i.jsx(RZ,{task:S,bots:y,members:b,onOpenConversation:t,block:fZ(S,r),now:v,highlighted:f===S.id,onEdit:()=>l(S),onAssign:A=>{w(()=>C.assign({..._(S),botId:A}),n("Task not assigned"))},onComplete:()=>{w(()=>C.complete(_(S)),n("Task not updated"))},onAccept:()=>{w(()=>C.review({..._(S),accept:!0}),n("Task not updated"))},onReturn:A=>h({task:S,rework:A}),onCancel:()=>{w(()=>C.cancel(_(S)),n("Task not updated"))},onDelete:()=>d(S),onReply:A=>zD(e.id,S.id,A,n)},S.id);return i.jsxs("div",{ref:x,children:[i.jsxs(me,{size:"xs",variant:"outline",className:"mb-3",onClick:()=>l("new"),children:[i.jsx(as,{}),n("New task")]}),s.length===0&&i.jsx("p",{className:"text-muted-foreground text-xs",children:n("No tasks yet. Members can also add and claim tasks with the board tool.")}),N.todo.length>0&&i.jsx(ao,{title:n("To do"),count:N.todo.length,children:()=>N.todo.map(k)}),N.doing.length>0&&i.jsx(ao,{title:n("Doing"),count:N.doing.length,children:()=>N.doing.map(k)}),N.blocked.length>0&&i.jsx(ao,{title:n("Stuck tasks"),count:N.blocked.length,children:()=>N.blocked.map(k)}),N.review.length>0&&i.jsx(ao,{title:n("Awaiting review"),count:N.review.length,children:()=>N.review.map(k)}),N.done.length>0&&i.jsx(ao,{title:n("Completed"),count:N.done.length,limit:ag,children:S=>N.done.slice(0,S).map(k)}),N.canceled.length>0&&i.jsx(ao,{title:n("Canceled"),count:N.canceled.length,limit:0,children:S=>N.canceled.slice(0,S).map(k)}),a&&i.jsx(zZ,{chatId:e.id,task:a==="new"?void 0:a,onClose:S=>{l(null),S&&ue.getState().refreshTasks(e.id)}}),u&&i.jsx(OZ,{task:u.task,assignee:y.get(u.task.assigneeBotId??"")?.name??n("Deleted member"),rework:u.rework,onClose:()=>h(null),onReturn:S=>C.review({..._(u.task),accept:!1,reason:S,...u.rework?{rework:!0}:{}}).then(A=>(A.ok&&(h(null),ue.getState().refreshTasks(e.id)),A.ok?null:Hu(A.error,n)))}),i.jsx(gs,{open:c!==null,onOpenChange:S=>!S&&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 S=c;d(null),S&&w(()=>C.remove(_(S)),n("Task not deleted"))}})]})}function RZ({task:e,bots:t,members:n,onOpenConversation:s,onEdit:o,onAssign:r,onComplete:a,onAccept:l,onReturn:c,onCancel:d,onDelete:u,onReply:h,block:p,now:f,highlighted:g}){const{t:x}=ne(),v=e.status==="todo"||e.status==="doing"||e.status==="blocked",y=e.status==="review",b=Bj(e),w=e.assigneeBotId?t.get(e.assigneeBotId):void 0,C=e.createdBy==="human"?x("You"):t.get(e.createdBy)?.name??x("Deleted member");return i.jsxs("div",{"data-slot":"bot-card","data-task-id":e.id,className:W("group rounded-lg border bg-card px-2.5 py-2 text-xs transition-shadow",!v&&!y&&"opacity-75",g&&"ring-2 ring-brand/60"),children:[i.jsxs("div",{className:"flex items-start gap-1.5",children:[i.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["#",e.seq]}),i.jsx("span",{className:"min-w-0 flex-1 break-words font-medium text-sm",children:e.title}),i.jsxs($i,{children:[i.jsx(Wi,{className:"rounded p-1 text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 data-popup-open:opacity-100",children:i.jsx(Dh,{className:"h-3.5 w-3.5"})}),i.jsxs(Ui,{align:"end",children:[i.jsxs(mn,{onClick:o,children:[i.jsx($s,{}),x("Edit")]}),v&&(!e.delegationId||e.status==="blocked"||b)&&n.length>0&&i.jsxs(qj,{children:[i.jsxs(Yj,{children:[i.jsx(ql,{}),e.assigneeBotId?x("Reassign to"):x("Assign to")]}),i.jsx(Xj,{children:n.map(_=>i.jsxs(mn,{disabled:_.id===e.assigneeBotId,onClick:()=>r(_.id),children:[i.jsx(tn,{bot:_,size:"xs"}),_.name]},_.id))})]}),v&&!b&&i.jsxs(mn,{onClick:a,children:[i.jsx(Yn,{}),x("Mark done")]}),(v||y)&&i.jsxs(mn,{onClick:d,children:[i.jsx(dn,{}),x("Cancel task")]}),i.jsx(ja,{}),i.jsxs(mn,{variant:"destructive",onClick:u,children:[i.jsx(Vs,{}),x("Delete")]})]})]})]}),e.detail&&i.jsx("div",{className:"mt-1 line-clamp-3 whitespace-pre-wrap text-muted-foreground",children:e.detail}),e.result&&i.jsx("div",{className:W("mt-1 rounded px-1.5 py-1 text-foreground",e.status!=="done"&&e.check?.passed===!1?"bg-destructive/10":"bg-success/10"),children:i.jsx("div",{className:"line-clamp-3 whitespace-pre-wrap",children:e.result})}),e.returnReason&&i.jsx("div",{className:"mt-1 rounded bg-warning/10 px-1.5 py-1 text-foreground",children:i.jsx("div",{className:"line-clamp-3 whitespace-pre-wrap",children:x("Returned: {{reason}}",{reason:e.returnReason})})}),p&&i.jsx(LZ,{block:p,now:f,assignee:w,bots:t,members:n,assigneeBotId:e.assigneeBotId,onRetry:()=>b&&Dl(b.id,x),onAssign:r,onCancel:d,onReply:h}),!p&&(y||e.status==="doing"&&e.delegationId)&&i.jsx(Tv,{placeholder:x(y?"Comment…":"Add to the current run…"),onSend:h}),e.check&&i.jsx(xD,{check:e.check,className:"mt-1"}),y&&i.jsxs("div",{className:"mt-1.5 flex gap-1.5",children:[i.jsxs(me,{size:"xs",onClick:l,children:[i.jsx(Yn,{}),x("Accept result")]}),i.jsxs(me,{size:"xs",variant:"outline",onClick:()=>c(!1),children:[i.jsx(va,{}),x("Return")]}),dZ(e)&&i.jsxs(me,{size:"xs",variant:"outline",onClick:()=>c(!0),children:[i.jsx(Kg,{}),x("Return for rework")]})]}),i.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-muted-foreground",children:[w||e.assigneeBotId?i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(tn,{bot:w,size:"xs"}),w?.name??x("Deleted member")]}):i.jsx("span",{children:x("Unassigned")}),e.delegationId&&i.jsxs("span",{children:["· ",x("Delegation")]}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{title:x("Created by {{name}}",{name:C}),children:AZ(e.updatedAt)})]}),e.runs&&e.runs.length>0&&i.jsx(PZ,{runs:e.runs,bots:t,onOpenConversation:s})]})}function LZ({block:e,now:t,assignee:n,assigneeBotId:s,bots:o,members:r,onRetry:a,onAssign:l,onCancel:c,onReply:d}){const{t:u}=ne(),h=n?.name??u("Deleted member"),p=u("Stuck for {{time}}",{time:wo(t-e.since)});if(e.reason==="need"){const g=e.waitFor==="human"?u("Waiting for your reply"):u("Waiting for {{name}} to reply",{name:o.get(e.waitFor)?.name??u("Deleted member")});return i.jsxs("div",{className:"mt-1.5 rounded-md border border-warning/30 bg-warning/10 px-2 py-1.5 text-foreground",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:u("Blocked · needs: {{need}}",{need:e.need})}),i.jsxs("div",{className:"mt-0.5 text-muted-foreground",children:[g," · ",p]}),e.humanOnly&&i.jsx("div",{className:"mt-0.5 text-muted-foreground",children:u("Stuck several times in a row; only you can answer now.")}),i.jsx(Tv,{placeholder:u("Answer {{name}}; they continue after your reply…",{name:h}),onSend:d})]})}const f=e.record?.state==="failed"&&Rc(e.record,u)||u("Failed");return i.jsxs("div",{className:"mt-1.5 rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-foreground",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:u("Blocked · run failed: {{reason}}",{reason:f})}),i.jsxs("div",{className:"mt-0.5 text-muted-foreground",children:[u("Waiting for you to handle it")," · ",p]}),i.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[i.jsxs(me,{size:"xs",variant:"outline",onClick:a,children:[i.jsx(da,{}),u("Retry")]}),r.length>0&&i.jsxs($i,{children:[i.jsxs(Wi,{render:i.jsx(me,{size:"xs",variant:"outline"}),children:[i.jsx(ql,{}),u("Reassign")]}),i.jsx(Ui,{align:"start",children:r.map(g=>i.jsxs(mn,{disabled:g.id===s,onClick:()=>l(g.id),children:[i.jsx(tn,{bot:g,size:"xs"}),g.name]},g.id))})]}),i.jsxs(me,{size:"xs",variant:"outline",onClick:c,children:[i.jsx(dn,{}),u("Cancel task")]})]})]})}function OZ({task:e,assignee:t,rework:n,onClose:s,onReturn:o}){const{t:r}=ne(),[a,l]=m.useState(""),[c,d]=m.useState(null),[u,h]=m.useState(!1),p=async()=>{if(!a.trim())return d(r("Enter a reason."));h(!0);try{d(await o(a.trim()))}finally{h(!1)}};return i.jsx(xn,{open:!0,onOpenChange:f=>!f&&s(),children:i.jsxs(vn,{className:"max-w-lg",children:[i.jsx(bn,{children:i.jsx(wn,{children:n?r("Return task #{{n}} for rework",{n:e.seq}):r("Return task #{{n}}",{n:e.seq})})}),i.jsxs(An,{className:"space-y-2",children:[i.jsx(Yt,{children:r("Reason for returning")}),i.jsx(ni,{rows:4,autoFocus:!0,value:a,maxLength:Ug,onChange:f=>l(f.target.value)}),i.jsx("p",{className:"text-muted-foreground text-xs",children:n?r("{{name}} continues in the same conversation with this reason, and the result comes back for review.",{name:t}):r("The task goes back to To do with this reason and can be reassigned.")}),c&&i.jsx("p",{className:"text-destructive text-sm",children:c})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:s,children:r("Cancel")}),i.jsxs(me,{size:"sm",disabled:u,onClick:()=>{p()},children:[u&&i.jsx(Xt,{className:"animate-spin"}),r(n?"Return for rework":"Return")]})]})]})})}function zZ({chatId:e,task:t,onClose:n}){const{t:s}=ne(),[o,r]=m.useState(t?.title??""),[a,l]=m.useState(t?.detail??""),[c,d]=m.useState(t?.check?.text??""),[u,h]=m.useState(null),[p,f]=m.useState(!1),g=async()=>{if(!o.trim())return h(s("Enter a title."));f(!0);try{const x=await window.electronAPI.bots.tasks.save({chatId:e,title:o.trim(),detail:a.trim(),check:c.trim(),...t?{id:t.id}:{}});x.ok?n(!0):h(Hu(x.error,s))}finally{f(!1)}};return i.jsx(xn,{open:!0,onOpenChange:x=>!x&&n(!1),children:i.jsxs(vn,{className:"max-w-lg",children:[i.jsx(bn,{children:i.jsx(wn,{children:t?s("Edit task #{{n}}",{n:t.seq}):s("New task")})}),i.jsxs(An,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Yt,{children:s("Task title")}),i.jsx(Zt,{value:o,maxLength:uL,onChange:x=>r(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:s("Details")}),i.jsx(ni,{rows:4,value:a,maxLength:Ug,onChange:x=>l(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:s("Acceptance check (optional)")}),i.jsx(Zt,{value:c,maxLength:hL,onChange:x=>d(x.target.value)}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:s("Done only when the member's tool output contains this text, e.g. a command printing ALL_TESTS_PASS.")})]}),u&&i.jsx("p",{className:"text-destructive text-sm",children:u})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsxs(me,{size:"sm",disabled:p,onClick:()=>{g()},children:[p&&i.jsx(Xt,{className:"animate-spin"}),s("Save")]})]})]})})}function GZ({chat:e,onOpenConversation:t}){const{t:n}=ne(),s=ue(c=>c.delegations),o=ue(c=>c.bots),r=m.useMemo(()=>new Map(o.map(c=>[c.id,c])),[o]),a=m.useMemo(()=>hZ(s,e.id),[s,e.id]),l=c=>i.jsx(Kh,{record:c,retried:Kj(c,s),bots:r,onOpenConversation:t},c.id);return!a.active.length&&!a.completed.length&&!a.failed.length?i.jsx("p",{className:"text-muted-foreground text-xs",children:n("No delegations in this group yet")}):i.jsxs("div",{children:[a.active.length>0&&i.jsx(ao,{title:n("In progress"),count:a.active.length,children:()=>a.active.map(l)}),a.completed.length>0&&i.jsx(ao,{title:n("Completed"),count:a.completed.length,limit:ag,children:c=>a.completed.slice(0,c).map(l)}),a.failed.length>0&&i.jsx(ao,{title:n("Failed · interrupted · canceled"),count:a.failed.length,limit:ag,children:c=>a.failed.slice(0,c).map(l)})]})}const FZ=(e,t)=>e.workspace.kind===t.kind&&(t.kind!=="project"||e.workspace.kind==="project"&&e.workspace.projectId===t.projectId);function BD({chat:e,className:t}){const{t:n}=ne(),s=we(f=>f.projects),o=ue(f=>f.bots),r=ue(f=>f.upsertChat),[a,l]=m.useState(!1),[c,d]=m.useState(null),u=Jj(e,s,o,n),h=[e.kind==="direct"?{input:{kind:"member-home"},label:n("Member's own workspace")}:{input:{kind:"chat-home"},label:n("Standalone workspace")},...dh(s).map(f=>({input:{kind:"project",projectId:f.id},label:Ns(f)}))],p=async f=>{const g=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,workspace:f});g.ok?r(g.chat):ze({type:"error",title:Is(g.error,n)})};return i.jsxs(i.Fragment,{children:[i.jsxs(vi,{open:a,onOpenChange:l,children:[i.jsxs(bi,{className:W("flex h-7 min-w-0 max-w-56 @max-[28rem]:max-w-32 @max-[21rem]:max-w-24 items-center gap-1.5 whitespace-nowrap rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground",t),title:n("Workspace"),children:[i.jsx(Nc,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:u}),i.jsx($n,{className:"h-3 w-3 shrink-0 opacity-60"})]}),i.jsxs(wi,{side:"bottom",align:"end",className:"w-64 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsxs("button",{type:"button",onClick:()=>{l(!1),window.electronAPI.bots.openWorkspace({chatId:e.id}).then(f=>{f.ok||ze({type:"error",title:Is(f.error,n)})})},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted",children:[i.jsx(oi,{className:"h-3.5 w-3.5 shrink-0"}),n("Open folder")]}),i.jsx("div",{className:"my-1 border-t"}),i.jsx("div",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:n("Change workspace")}),i.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map(f=>{const g=FZ(e,f.input);return i.jsxs("button",{type:"button",onClick:()=>{l(!1),g||d(f.input)},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:f.label}),g&&i.jsx(Yn,{className:"h-3.5 w-3.5 shrink-0 text-brand"})]},f.input.kind==="project"?f.input.projectId:f.input.kind)})})]})]}),i.jsx(gs,{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 sr({title:e,children:t}){return i.jsxs("section",{className:"mt-5",children:[i.jsx("h4",{className:"mb-1.5 font-medium text-[11px] text-muted-foreground uppercase tracking-wide",children:e}),t]})}function uf({label:e,value:t}){return i.jsxs("div",{className:"flex justify-between gap-3 border-b border-dashed py-1.5 text-xs",children:[i.jsx("span",{className:"shrink-0 text-muted-foreground",children:e}),i.jsx("span",{className:"min-w-0 truncate text-right",children:t})]})}async function VD(e,t){const n={};for(const s of e.members){const o=await window.electronAPI.bots.get(s);if(!o.ok)return null;n[s]=o.persona}return gL(e,t,n,new Date().toISOString())}async function HZ(e,t){const n=await VD(e,t);if(!n)return!1;const s=URL.createObjectURL(new Blob([JSON.stringify(n,null,2)],{type:"application/json"})),o=document.createElement("a");return o.href=s,o.download=`${e.title||"team"}.team.json`,o.click(),URL.revokeObjectURL(s),!0}async function BZ(e,t){const n=await VD(e,t),s=n&&pL(fL(n.team));return s?mL(o=>({...o,teams:xL(o.teams,s,crypto.randomUUID())})):!1}function VZ({chat:e,thread:t=e,onOpenConversation:n}){const{t:s}=ne(),o=ue(D=>D.bots),r=ue(D=>D.runtime[t.id]),a=ue(D=>D.upsertChat),l=ue(D=>D.openDirect),c=we(D=>D.projects),d=m.useMemo(()=>new Map(o.map(D=>[D.id,D])),[o]),[u,h]=m.useState(e.title),[p,f]=m.useState(String(e.routing.maxHops)),[g,x]=m.useState(String(e.routing.maxTurnsPerBot)),[v,y]=m.useState(!1),[b,w]=m.useState("info"),C=ue(D=>D.taskFocus);m.useEffect(()=>{C?.chatId===e.id&&w("board")},[C,e.id]),m.useEffect(()=>{h(e.title),f(String(e.routing.maxHops)),x(String(e.routing.maxTurnsPerBot))},[e.title,e.routing.maxHops,e.routing.maxTurnsPerBot]);const _=async D=>{const O=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,...D});O.ok?a(O.chat):(ze({type:"error",title:Is(O.error,s)}),ue.getState().refreshChats())},N=e.members.map(D=>({id:D,bot:d.get(D)})),k=e.routing.muted??[],S=o.filter(D=>!D.archivedAt&&!e.members.includes(D.id)),A=D=>D?d.get(D)?.name??"?":"—",T=e.workspace.kind==="project"?c.find(D=>e.workspace.kind==="project"&&D.id===e.workspace.projectId):void 0,I=p!==String(e.routing.maxHops)||g!==String(e.routing.maxTurnsPerBot),P=[{value:"boss",label:s("Group owner replies")},{value:"smart",label:s("Smart pick")}];return i.jsxs(lh,{value:b,onValueChange:D=>w(String(D)),className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs(ch,{variant:"underline",className:"shrink-0 px-2 pt-2",children:[i.jsx(Ps,{value:"info",children:s("Group info")}),i.jsx(Ps,{value:"board",children:s("Task board")}),i.jsx(Ps,{value:"delegations",children:s("Delegations")}),i.jsx(Ps,{value:"routines",children:s("Routines")})]}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:[i.jsx(lo,{value:"board",children:i.jsx(MZ,{chat:e,onOpenConversation:n})}),i.jsx(lo,{value:"delegations",children:i.jsx(GZ,{chat:t,onOpenConversation:n})}),i.jsx(lo,{value:"routines",children:i.jsx(OD,{chatId:e.id})}),i.jsxs(lo,{value:"info",children:[i.jsx(Zt,{className:"mt-2",value:u,placeholder:s("Group name"),onChange:D=>h(D.target.value),onBlur:()=>u.trim()!==e.title&&void _({title:u.trim()}),onKeyDown:D=>D.key==="Enter"&&D.currentTarget.blur()}),i.jsxs(sr,{title:s("Members"),children:[N.map(({id:D,bot:O})=>i.jsxs("div",{className:"group flex items-center gap-2 rounded-lg py-1.5",children:[i.jsxs("button",{type:"button",onClick:()=>{l(D)},className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(yD,{chatId:t.id,botId:D,bot:O}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[i.jsx("span",{className:"truncate",children:O?.name??s("Deleted member")}),e.bossBotId===D&&i.jsx("span",{className:"shrink-0 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:s("Owner")}),k.includes(D)&&i.jsxs("span",{title:s("Replies only when @-mentioned by name"),className:"flex shrink-0 items-center gap-0.5 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:[i.jsx(_w,{className:"h-2.5 w-2.5"}),s("Muted")]})]}),i.jsx("div",{className:"truncate text-muted-foreground text-xs",children:O?.scope||O?.title})]})]}),i.jsxs($i,{children:[i.jsx(Wi,{className:"rounded p-1 text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 data-popup-open:opacity-100",children:i.jsx(Dh,{className:"h-3.5 w-3.5"})}),i.jsxs(Ui,{align:"end",children:[i.jsxs(mn,{disabled:e.bossBotId===D,onClick:()=>{_({bossBotId:D})},children:[i.jsx(Zj,{}),s("Make owner")]}),i.jsxs(mn,{disabled:e.bossBotId===D,onClick:()=>{_({routing:{muted:k.includes(D)?k.filter(z=>z!==D):[...k,D]}})},children:[i.jsx(_w,{}),k.includes(D)?s("Unmute"):s("Mute")]}),i.jsxs(mn,{disabled:e.bossBotId===D||e.members.length<=2,onClick:()=>{_({members:e.members.filter(z=>z!==D)})},children:[i.jsx(L4,{}),s("Remove from group")]})]})]})]},D)),i.jsxs(vi,{open:v,onOpenChange:y,children:[i.jsxs(bi,{disabled:S.length===0,className:"mt-1 flex h-7 items-center gap-1 rounded-md border px-2 text-muted-foreground text-xs hover:bg-muted hover:text-foreground disabled:opacity-50",children:[i.jsx(as,{className:"h-3.5 w-3.5"}),s("Add member")]}),i.jsx(wi,{side:"bottom",align:"start",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:S.map(D=>i.jsxs("button",{type:"button",onClick:()=>{y(!1),_({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:[i.jsx(tn,{bot:D,size:"sm"}),i.jsx("span",{className:"min-w-0 truncate",children:D.name})]},D.id))})]})]}),i.jsxs(sr,{title:s("Reply queue"),children:[i.jsx(uf,{label:s("Current"),value:r?.current?`${A(r.current)}(${s("relay {{n}}/{{max}}",{n:r.hops,max:e.routing.maxHops})})`:r?.routing?s("Choosing who replies…"):"—"}),i.jsx(uf,{label:s("Waiting"),value:r?.queue.length?r.queue.map(D=>A(D)).join("、"):"—"}),i.jsx(uf,{label:s("Per-member limit"),value:s("{{n}} replies",{n:e.routing.maxTurnsPerBot})})]}),i.jsx(sr,{title:s("Workspace"),children:i.jsxs("div",{"data-slot":"bot-card",className:"rounded-lg border bg-card px-2.5 py-2",children:[i.jsx(BD,{chat:e,className:"w-full max-w-none"}),i.jsxs("p",{className:"mt-1.5 text-muted-foreground text-xs",children:[T?`${T.path} · `:"",s("Shared by all members")]})]})}),i.jsxs(sr,{title:s("Routing limits"),children:[i.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:s("Without @")}),i.jsxs(bs,{items:P,value:e.routing.mode,onValueChange:D=>{D!==e.routing.mode&&_({routing:{mode:D}})},children:[i.jsx(ws,{size:"sm",className:"w-40",children:i.jsx(ys,{})}),i.jsx(Ss,{children:P.map(D=>i.jsx(rs,{value:D.value,children:D.label},D.value))})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:s("@ relay limit")}),i.jsx(Zt,{type:"number",min:1,max:20,value:p,onChange:D=>f(D.target.value)})]}),i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:s("Replies per member")}),i.jsx(Zt,{type:"number",min:1,max:10,value:g,onChange:D=>x(D.target.value)})]})]}),I&&i.jsx(me,{size:"xs",className:"mt-2",onClick:()=>{_({routing:{maxHops:Math.round(Number(p))||e.routing.maxHops,maxTurnsPerBot:Math.round(Number(g))||e.routing.maxTurnsPerBot}})},children:s("Save")})]}),i.jsx(sr,{title:s("Group notes"),children:i.jsx(PD,{target:{chatId:e.id},emptyText:s("No group notes yet. Group conventions and decisions are summarized here automatically after memories are organized.")})}),i.jsx(sr,{title:s("Group memory"),children:i.jsx(ED,{spaceId:`chat:${e.id}`,emptyText:s("No group memories yet")})}),i.jsxs(sr,{title:s("Team"),children:[i.jsxs(me,{size:"xs",variant:"outline",onClick:()=>{HZ(e,o).then(D=>D||ze({type:"error",title:s("Export failed")}))},children:[i.jsx(cc,{}),s("Export team")]}),i.jsxs(me,{size:"xs",variant:"outline",className:"ml-1.5",onClick:()=>{BZ(e,o).then(D=>ze(D?{type:"success",title:s("Saved as team template")}:{type:"error",title:s("Could not save as team template")}))},children:[i.jsx(G$,{}),s("Save as team template")]}),i.jsx("p",{className:"mt-1.5 text-muted-foreground text-xs",children:s("Group settings and member personas only. Memory, sessions, timeline, tasks, routines, models, skills and MCP are not included.")})]})]})]})]})}function $Z(e,t=0){const n=new Map;for(const s of e)if(!(s.seq<=t)&&((s.kind==="human"||s.newConversation)&&n.clear(),s.kind==="bot"&&s.botId&&n.delete(s.botId),s.failure&&n.set(s.failure.botId,s.id),s.retryOf))for(const[o,r]of n)r===s.retryOf&&n.delete(o);return new Set(n.values())}function WZ(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 UZ(e,t){const n=String(t),s=`${n}-`;return e.find(o=>o.key===n||o.key.startsWith(s))?.key}function KZ(e){return e.earliest===void 0?"wait":e.target>=e.earliest?"scroll":e.loading?"wait":e.hasOlder?"load":"give-up"}function qZ(e){return e.range===void 0||e.loading?"wait":e.range&&e.target>=e.range[0]&&e.target<=e.range[1]?"scroll":e.jumped?"give-up":"jump"}function YZ(e,t){const n=[];let s=0;for(const[o,r]of t)o<s||r<=o||r>e.length||(o>s&&n.push({text:e.slice(s,o),match:!1}),n.push({text:e.slice(o,r),match:!0}),s=r);return s<e.length&&n.push({text:e.slice(s),match:!1}),n}function XZ({chatId:e,bots:t}){const{t:n}=ne(),s=ue(a=>a.queue),[o,r]=m.useState(null);return s.filter(a=>a.chatId===e&&a.deliveryId).map(a=>{const l=t.get(a.botId)?.name??n("Deleted member");return i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsxs("span",{children:[l," · ",n("Queued")]}),a.canInterject&&i.jsx(me,{size:"sm",variant:"ghost",disabled:o!==null,onClick:async()=>{if(a.deliveryId){r(a.deliveryId);try{const c=await window.electronAPI.bots.interjectQueued(e,a.deliveryId);c.ok||ze({type:"error",title:c.error})}catch{ze({type:"error",title:n("Failed to send")})}finally{r(null)}}},children:n("Insert into {{name}}’s current task",{name:l})})]},a.deliveryId)})}const JZ=(e,t)=>t?e.find(n=>n.conversationId===t):void 0,ZZ=(e,t)=>Math.max(0,Math.floor((t-e)/1e3));function $D({since:e}){const{t}=ne(),[n,s]=m.useState(()=>Date.now());return m.useEffect(()=>{const o=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(o)},[]),i.jsx(i.Fragment,{children:t("Quiet for {{n}}s",{n:ZZ(e,n)})})}function WD({conversationId:e,className:t}){const n=ue(s=>JZ(s.silences,e)?.since);return n===void 0?null:i.jsx("span",{className:t??"shrink-0 text-warning",children:i.jsx($D,{since:n})})}const Xd=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),QZ={smart:"Smart pick","smart:build":"Smart pick · build","smart:answer":"Smart pick · answer","smart:discuss":"Smart pick · discuss",summary:"Owner summary","wrap-up":"Owner wrap-up"};function eQ({chat:e,bots:t,timeline:n,runtime:s,delegations:o,focus:r,onFocusDone:a,onLoadOlder:l,onLoadNewer:c,onLoadAround:d,onJumpLatest:u,onOpenConversation:h,onOpenLive:p}){const{t:f}=ne(),g=m.useRef(null),x=m.useRef(!0),v=m.useRef(h);v.current=h;const y=m.useCallback((Z,ce)=>v.current(Z,ce),[]),b=m.useRef(null),w=m.useRef(!1),C=n?.entries??[],_=m.useRef({chatId:e.id,loaded:C,delegations:o});_.current={chatId:e.id,loaded:C,delegations:o};const N=m.useCallback(Z=>{const{chatId:ce,loaded:De,delegations:Oe}=_.current,Ne=yL(De,Z);if(Ne!==void 0)return ue.getState().focusSeq(ce,Ne);const Ze=Oe.find(bt=>bt.id===Z);ze({type:"info",title:Ze&&Ze.deliveredAt===void 0?f("The delegation card is posted after the delegator receives the result."):f("The delegation card is not in the loaded messages.")})},[f]),k=$Z(C,e.epochSeq??0),S=n?.history,A=e.epochSeq??0,[T,I]=m.useState(!1);m.useEffect(()=>I(!1),[e.id,A]);const P=A>0&&!T&&!S,D=m.useMemo(()=>P?C.filter(Z=>Z.seq>=A):C,[C,P,A]),O=m.useMemo(()=>SL(D),[D]),z=()=>{P&&n?.hasOlder&&!n.loading&&!C.some(Z=>Z.seq<A)&&(Ce(),l()),I(P)},R=m.useMemo(()=>{const Z=new Map;if(!S)for(const ce of O)ce.kind==="entry"&&ce.entry.kind==="bot"&&!ce.continued&&Z.set(ce.entry.botId,ce.entry.id);return new Set(Z.values())},[O,S]),$=m.useMemo(()=>new Map(o.map(Z=>[Z.id,{record:Z,retried:Kj(Z,o)}])),[o]),X=m.useMemo(()=>e_(o,e.id),[o,e.id]),H=m.useMemo(()=>CL(D,kL(X)),[D,X]),te=ue(Z=>Z.tasks[e.id]),V=X.some(Z=>Z.appends?.length);m.useEffect(()=>{V&&!te&&ue.getState().refreshTasks(e.id)},[V,te,e.id]);const Y=({key:Z,record:ce,append:De})=>i.jsx(Kh,{record:ce,append:De,taskSeq:De&&te?.find(Oe=>Oe.id===ce.taskId)?.seq,fill:!0,bots:t,onOpenConversation:h},Z),q=s?.current?t.get(s.current):void 0,ee=s?.current?e.sessions[s.current]?.conversationId:void 0,ge=ue(Z=>ee?Z.sessions[ee]?.messages.length:void 0);m.useLayoutEffect(()=>{const Z=g.current;Z&&(Z.scrollTop=Z.scrollHeight),x.current=!0},[e.id]);const Ce=()=>{const Z=g.current;if(!Z)return;const ce=Z.getBoundingClientRect().top;for(const De of Z.querySelectorAll("[data-seq]")){const Oe=De.getBoundingClientRect();if(!(Oe.bottom<=ce)){b.current={seq:Number(De.dataset.seq),top:Oe.top-ce};return}}};m.useLayoutEffect(()=>{const Z=g.current;if(!Z)return;const ce=b.current;!n?.loading&&!n?.loadingNewer&&(b.current=null);const Oe=w.current&&!S;w.current=!!S;const Ne=ce&&Z.querySelector(`[data-seq="${ce.seq}"]`);if(ce&&Ne){Z.scrollTop+=Ne.getBoundingClientRect().top-Z.getBoundingClientRect().top-ce.top;return}Oe&&(x.current=!0),x.current&&!S&&(Z.scrollTop=Z.scrollHeight)},[D,S,n?.loading,n?.loadingNewer,X.length,q?.id,ge,s?.routing]);const Re=()=>{const Z=g.current;if(!Z||!n)return;const ce=Z.scrollHeight-Z.scrollTop-Z.clientHeight;x.current=ce<40,b.current&&Ce(),!(D.length===0||P&&(C[0]?.seq??0)<=A)&&(Z.scrollTop<80&&n.hasOlder&&!n.loading&&(Ce(),l()),ce<80&&S&&!n.loadingNewer&&(Ce(),c()))},[fe,U]=m.useState(null),oe=m.useRef(null),[Se,G]=m.useState(null);m.useLayoutEffect(()=>{if(!r||oe.current===r.nonce)return;if(P&&r.seq<A){I(!0);return}const Z=D[0]?.seq,ce=D.at(-1)?.seq,De=Se?.nonce===r.nonce?Se:null,Oe=qZ({target:r.seq,range:n?Z===void 0||ce===void 0?null:[Z,ce]:void 0,loading:!!(De&&!De.done),jumped:!!De?.done});if(Oe!=="wait"){if(Oe==="jump"){const Ne=r.nonce;x.current=!1,b.current=null,G({nonce:Ne,done:!1}),d(r.seq).finally(()=>G(Ze=>Ze?.nonce===Ne?{nonce:Ne,done:!0}:Ze));return}oe.current=r.nonce,a?.(r.nonce),Oe==="scroll"&&(x.current=!1,b.current=null,U(r.seq),g.current?.querySelector(`[data-seq="${r.seq}"]`)?.scrollIntoView({block:"center"}))}},[r,D,n===void 0,Se,P]),m.useEffect(()=>{if(fe===null)return;const Z=window.setTimeout(()=>U(null),2500);return()=>window.clearTimeout(Z)},[fe]);const Q=()=>{x.current=!0,b.current=null,u()},ae=S&&n?n.lastSeq-S.sinceSeq:0;return i.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[i.jsx("div",{ref:g,onScroll:Re,className:"min-h-0 flex-1 select-text overflow-y-auto",children:i.jsx("div",{className:"@container",children:i.jsxs("div",{"data-slot":"bot-timeline",className:W(Ni,"flex flex-col gap-3 py-4"),children:[n?.loading&&i.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:i.jsx(Xt,{className:"h-4 w-4 animate-spin"})}),n&&!n.hasOlder&&!P&&D.length>0&&i.jsx("div",{className:"text-center text-[11px] text-muted-foreground",children:f("Beginning of the chat")}),!n&&i.jsx("div",{className:"flex justify-center py-6 text-muted-foreground",children:i.jsx(Xt,{className:"h-4 w-4 animate-spin"})}),n&&D.length===0&&i.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:f("Say something. Mention a member with @, or the group owner replies.")}),H.head.map(Y),O.map(Z=>Z.kind==="day"?i.jsx("div",{className:"py-1 text-center text-[11px] text-muted-foreground",children:new Date(Z.at).toLocaleDateString()},Z.key):i.jsxs(m.Fragment,{children:[A>0&&!S&&Z.entry.seq===A&&i.jsxs("button",{type:"button",onClick:z,className:"flex items-center gap-1 self-center rounded-md px-2 py-1 text-muted-foreground text-xs hover:bg-muted hover:text-foreground",children:[P?i.jsx(un,{className:"h-3.5 w-3.5"}):i.jsx($n,{className:"h-3.5 w-3.5"}),P?f("Earlier conversation · {{n}} messages",{n:A-1}):f("Collapse earlier conversation")]}),i.jsx("div",{"data-seq":Z.entry.seq,className:W("-mx-2 flex flex-col rounded-lg px-2 transition-colors duration-500",fe===Z.entry.seq&&"bg-brand/10"),children:i.jsx(tQ,{chatId:e.id,entry:Z.entry,continued:Z.continued,latest:R.has(Z.entry.id),retryable:k.has(Z.entry.id)&&e.archivedAt===void 0,retryBusy:!!(s?.current||s?.routing),bots:t,records:$,onOpenConversation:y,onLocateDelegation:N})}),H.after.get(Z.entry.id)?.map(Y)]},Z.key)),n?.loadingNewer&&i.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:i.jsx(Xt,{className:"h-4 w-4 animate-spin"})}),!S&&!q&&s?.routing&&i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(qS,{}),f("Choosing who replies…")]}),!S&&i.jsx(XZ,{chatId:e.id,bots:t}),!S&&q&&i.jsxs("button",{type:"button",disabled:!ee,title:f("View live"),onClick:()=>ee&&p(ee,q.id),className:"-mx-2 flex gap-2.5 rounded-lg px-2 py-1 text-left hover:bg-muted/60 disabled:pointer-events-none",children:[i.jsx(tn,{bot:q,size:"sm",busy:!0}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"text-muted-foreground text-xs",children:[i.jsx("span",{className:"mr-1.5 font-semibold text-foreground",children:q.name}),f("Replying")]}),i.jsx(gD,{conversationId:ee,leading:i.jsx(qS,{}),trailing:i.jsxs(i.Fragment,{children:[i.jsx(WD,{conversationId:ee}),ee&&i.jsx("span",{className:"shrink-0 underline-offset-2 hover:underline",children:f("View live")})]})})]})]})]})})}),S&&i.jsxs("button",{type:"button",onClick:Q,className:"absolute bottom-4 left-1/2 z-10 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full border bg-card px-3 text-muted-foreground text-xs shadow-float transition-colors hover:text-foreground",children:[i.jsx(ah,{className:"h-3 w-3"}),ae>0?f("Back to latest · {{n}} new",{n:ae}):f("Back to latest")]})]})}function qS(){return i.jsx("span",{className:"flex gap-0.5",children:[0,1,2].map(e=>i.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground",style:{animationDelay:`${e*.2}s`}},e))})}const tQ=m.memo(function({chatId:t,entry:n,continued:s,latest:o,bots:r,records:a,onOpenConversation:l,onLocateDelegation:c,retryable:d,retryBusy:u}){const{t:h}=ne(),[p,f]=m.useState(!1),g=async()=>{if(!p){f(!0);try{const x=await window.electronAPI.bots.retry(t,n.id);x.ok||ze({type:"error",title:h("Retry failed"),description:Is(x.error,h)})}catch{ze({type:"error",title:h("Retry failed")})}finally{f(!1)}}};switch(n.kind){case"system":return n.newConversation?i.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground text-xs",children:[i.jsx("div",{className:"h-px flex-1 bg-border"}),h("New conversation")," · ",Xd(n.at),i.jsx("div",{className:"h-px flex-1 bg-border"})]}):n.routine?i.jsx(wZ,{text:n.text,target:n.routine}):i.jsxs("div",{"data-slot":"bot-notice",className:"self-center rounded-full bg-muted px-2.5 py-0.5 text-center text-muted-foreground text-xs",children:[n.text,d&&i.jsx(me,{size:"xs",variant:"outline",className:"ml-2",disabled:u||p,onClick:g,children:h("Retry")})]});case"human":return i.jsxs("div",{className:"flex w-full flex-col items-end",children:[n.text&&i.jsx("div",{className:W(ol,"whitespace-pre-wrap break-words"),children:i.jsx(Jd,{text:n.text,bots:r})}),n.images?.length?i.jsx(zu,{target:{chatId:t,entryId:n.id}}):null,(n.refs?.skill||n.refs?.chats?.length)&&i.jsx(oQ,{refs:n.refs}),!s&&i.jsx("span",{className:"mt-0.5 text-[11px] text-muted-foreground",children:Xd(n.at)})]});case"progress":return i.jsx(sQ,{chatId:t,entry:n,bots:r,failed:a.get(n.delegationId)?.record.state==="failed"});case"delegation":return i.jsx(Kh,{record:a.get(n.delegationId)?.record,retried:a.get(n.delegationId)?.retried,entry:n,fill:!0,bots:r,onOpenConversation:l});case"bot":{const x=r.get(n.botId);return i.jsxs("div",{className:W("flex w-full gap-2.5",s&&"-mt-1.5"),children:[s?i.jsx("span",{className:"w-6 shrink-0"}):o?i.jsx(yD,{chatId:t,botId:n.botId,bot:x}):i.jsx(tn,{bot:x,size:"sm"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[!s&&i.jsxs("div",{className:"mb-0.5 text-muted-foreground text-xs",children:[i.jsx("span",{className:"mr-1.5 font-semibold text-foreground",children:x?.name??h("Deleted member")}),x?.title?`${x.title} · `:"",Xd(n.at),n.model&&i.jsx("span",{className:"ml-1.5 rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10px]",children:n.model}),n.delegationId&&i.jsx("button",{type:"button",title:h("Locate the delegation card"),onClick:()=>n.delegationId&&c(n.delegationId),className:"ml-1.5 rounded bg-info/15 px-1 py-px text-[10px] text-info hover:bg-info/25",children:h("Delegation result")}),n.routedBy&&i.jsx("span",{title:h(n.routedBy==="summary"?"Asked to sum up after the assigned members replied":"Picked automatically because nobody was @-mentioned"),className:"ml-1.5 rounded border px-1 py-px text-[10px]",children:h(QZ[n.routedBy])})]}),i.jsx("div",{className:"text-sm",children:i.jsx(Ts,{text:n.text})}),i.jsx(zu,{target:{chatId:t,entryId:n.id}}),i.jsx(iQ,{entry:n,onOpen:()=>l(n.conversationId,x?.name??"")})]})]})}}}),nQ={started:{icon:U$,className:"border-brand/50 text-brand"},blocked:{icon:yr,className:"border-warning/60 text-warning"},failed:{icon:vL,className:"border-destructive/60 text-destructive"},delivered:{icon:zg,className:"border-success/60 text-success"}};function sQ({chatId:e,entry:t,bots:n,failed:s}){const{t:o}=ne(),r=ue(u=>u.openTask),a=n.get(t.botId),l=nQ[t.phase==="blocked"&&s?"failed":t.phase],c=l.icon,d=WZ(t.text,t.taskSeq);return i.jsxs("div",{"data-slot":"bot-progress","data-phase":t.phase,className:"flex w-full gap-2.5",children:[i.jsx(tn,{bot:a,size:"sm"}),i.jsxs("div",{className:W("flex min-w-0 max-w-lg items-start gap-1.5 rounded-md border-l-2 bg-muted/50 px-2 py-1 text-xs",l.className),children:[i.jsx(c,{"aria-hidden":!0,className:"mt-px size-3.5 shrink-0"}),i.jsxs("div",{className:"line-clamp-2 min-w-0 break-words text-muted-foreground",children:[i.jsx("span",{className:"font-medium text-foreground",children:a?.name??o("Deleted member")})," ",d?i.jsxs(i.Fragment,{children:[i.jsx(Jd,{text:d[0],bots:n}),i.jsx("button",{type:"button","aria-label":o("Open task card #{{n}}",{n:t.taskSeq}),className:"rounded px-0.5 font-medium text-foreground underline decoration-dotted underline-offset-2 hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>r(e,t.taskId),children:d[1]}),i.jsx(Jd,{text:d[2],bots:n})]}):i.jsx(Jd,{text:t.text,bots:n})]}),i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:Xd(t.at)})]})]})}function Jd({text:e,bots:t}){const n=m.useMemo(()=>{const s=[...t.values()].map(a=>a.name).sort((a,l)=>l.length-a.length),o=s.map(a=>a.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")),r=s.length?new RegExp(`(@(?:${o.join("|")}|所有人|everyone|all))`,"giu"):null;return Zk(e).flatMap(a=>a.type==="file"?[a]:(r?a.text.split(r):[a.text]).map((l,c)=>l.startsWith("@")&&c%2===1?{type:"mention",part:l}:l))},[e,t]);return i.jsx(i.Fragment,{children:n.map((s,o)=>typeof s=="string"?s:s.type==="file"?i.jsxs("span",{className:W(xv("file"),"mx-0.5 leading-4"),title:s.path,children:[i.jsx(jo,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:Qj})]},o):i.jsx("span",{className:"font-medium underline underline-offset-2",children:s.part},o))})}function iQ({entry:e,onOpen:t}){const{t:n}=ne(),[s,o]=m.useState(!1),[r,a]=m.useState(null);m.useEffect(()=>{if(!s||r)return;let c=!0;const d=h=>{const p=bL(h,e.text);if(c){if(!p)return a({error:n("No process recorded.")});a({steps:wL(h.slice(p.start,p.end)),exact:p.exact})}},u=ue.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:un;return i.jsxs("div",{className:"mt-1",children:[i.jsxs("button",{type:"button",onClick:()=>o(c=>!c),className:"flex items-center gap-1 text-muted-foreground text-xs hover:text-foreground",children:[i.jsx(l,{className:"h-3 w-3"}),n("View process"),r&&"steps"in r&&` · ${n("{{n}} steps",{n:r.steps.length})}`]}),s&&i.jsxs("div",{"data-slot":"bot-card",className:"mt-1.5 rounded-lg border bg-card px-3 py-2 font-mono text-muted-foreground text-xs leading-relaxed",children:[!r&&i.jsx(Xt,{className:"h-3.5 w-3.5 animate-spin"}),r&&"error"in r&&i.jsx("span",{children:r.error}),r&&"steps"in r&&i.jsxs(i.Fragment,{children:[!r.exact&&i.jsx("div",{className:"mb-1 font-sans italic",children:n("Could not locate this reply; showing the latest turn.")}),r.steps.length===0&&i.jsx("div",{className:"font-sans",children:n("No tool calls in this turn.")}),r.steps.map(c=>i.jsxs("div",{className:W("truncate",c.error&&"text-destructive"),children:[c.error?"✗":"·"," ",Bo(c.name,n),c.detail&&i.jsxs("span",{className:"text-foreground/80",children:[" ",c.detail]})]},c.id))]}),i.jsx("button",{type:"button",onClick:t,className:"mt-1.5 font-sans text-foreground underline-offset-2 hover:underline",children:n("Open full conversation")})]})]})}function oQ({refs:e}){const{t}=ne(),n=ue(a=>a.chats),s=ue(a=>a.bots),o=we(a=>a.skills),r="inline-flex h-6 max-w-56 items-center gap-1 rounded-md px-1.5 text-xs";return i.jsxs("div",{className:"mt-1 flex flex-wrap justify-end gap-1.5",children:[e.skill&&i.jsxs("span",{className:W(r,"bg-info/15 text-info"),children:[i.jsx(ii,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:o.find(a=>a.id===e.skill)?.name??e.skill})]}),e.chats?.map(a=>{const l=n.find(c=>c.id===a);return i.jsxs("span",{className:W(r,"bg-muted"),title:t("Referenced chat"),children:[i.jsx(xa,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:l?Cs(l,s,t):t("Unavailable chat")})]},a)})]})}function Yh({retry:e,onCancel:t}){const{t:n}=ne(),[s,o]=m.useState(()=>Date.now());m.useEffect(()=>{const a=setInterval(()=>o(Date.now()),500);return()=>clearInterval(a)},[]);const r=Math.max(0,Math.ceil((e.at+e.delayMs-s)/1e3));return i.jsxs("div",{className:"mb-1 flex items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-2.5 py-1.5 text-xs",children:[i.jsx(Ko,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-amber-500 [animation-duration:2s]"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",title:e.error,children:[e.maxAttempts>0?n("Auto-retrying ({{attempt}}/{{max}})",{attempt:e.attempt,max:e.maxAttempts}):n("Auto-retrying ({{attempt}})",{attempt:e.attempt}),i.jsxs("span",{className:"text-muted-foreground",children:[" · ",r>0?n("retrying in {{seconds}}s",{seconds:r}):n("retrying…")," — ",e.error]})]}),t&&i.jsx("button",{type:"button",title:n("Cancel auto-retry"),onClick:t,className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]})}function YS(e,t){return t.projectId?t.projectId:e.workspace.kind==="member-home"?void 0:e.workspace.projectId}function rQ(e,t,n){for(const s of e??[])for(const o of Object.values(s.sessions))if(o.conversationId===n)return YS(s,o);for(const s of t??[]){if(s.childConversationId!==n||!s.chatId)continue;const o=e?.find(a=>a.id===s.chatId),r=o?.sessions[s.targetBotId];if(o&&r)return YS(o,r)}}function UD(e,t){const n=ue(o=>e?rQ(o.chats,o.delegations,e):void 0),s=t??n;return!e||!s?null:{conversationId:e,projectId:s}}function KD(e){const{t}=ne(),n=ue(r=>r.delegations),s=e?jL(n,e):[],o=s.map(r=>`${r.key}:${r.at}:${r.trigger}`).join("|");return m.useMemo(()=>s.map(r=>({key:r.key,at:r.at,text:t("Run {{n}} · {{source}}",{n:r.n,source:GD(r.trigger,t)})})),[o,t])}const aQ=2500;function qD({focus:e,timelineRef:t,items:n,baseIndex:s,hasMessages:o,loading:r,loadOlder:a,onDone:l}){const[c,d]=m.useState(null),u=m.useRef(null);return m.useEffect(()=>{if(!e||u.current===e.nonce)return;const h=KZ({target:e.messageIndex,earliest:o?s:void 0,hasOlder:s>0,loading:r});if(h==="wait")return;if(h==="load"){a();return}u.current=e.nonce,l?.(e.nonce);const p=h==="scroll"?UZ(n,e.messageIndex):void 0;p&&(window.setTimeout(()=>t.current?.scrollToKey(p),60),d({key:p,query:e.query}))},[e,n,s,o,r,a,l,t]),m.useEffect(()=>{if(!c)return;const h=window.setTimeout(()=>d(null),aQ);return()=>window.clearTimeout(h)},[c]),{searchQuery:c?.query??"",activeHit:c?{key:c.key,nth:0}:null}}function YD({conversationId:e,speaker:t,emptyTitle:n,emptyDescription:s,className:o,focus:r,onFocusDone:a,turnFooter:l,controls:c,runDividers:d,dataSlot:u}){const h=ue(S=>S.sessions[e]),p=ue(S=>!!S.sessionHistoryLoading[e]),f=m.useRef(null),g=h?.status==="running",x=m.useMemo(()=>h?Sr(h.messages,g,h.customEntries,void 0,{historyBaseIndex:h.historyBaseIndex,toolOutputs:h.toolOutputs,pendingApprovals:h.pendingApprovals,toolStartedAt:h.toolStartedAt,runDividers:d}):[],[h,g,d]);m.useEffect(()=>{f.current?.isAtBottom()&&f.current.pinToBottom()},[x]);const v=m.useMemo(()=>()=>{ue.getState().loadOlderSession(e)},[e]),y=qD({focus:r,timelineRef:f,items:x,baseIndex:h?.historyBaseIndex??0,hasMessages:(h?.messages.length??0)>0,loading:p,loadOlder:v,onDone:a}),{name:b,color:w,image:C}=t,_=m.useMemo(()=>({sessionId:e,canRewind:!!c,canRetry:!!c,canFork:!1,speaker:{name:b,color:w,image:C},turnFooter:l,...c?{botControls:c}:{}}),[e,b,w,C,l,c]),N=(h?.historyBaseIndex??0)>0,k=UD(e);return i.jsx(gv.Provider,{value:k,children:i.jsx(Fh.Provider,{value:_,children:i.jsxs("div",{"data-slot":u,className:W("@container flex min-h-0 flex-1 flex-col",o),children:[i.jsx(Bh,{ref:f,items:x,busy:g,loading:!1,running:g,runStartedAt:h?.runStartedAt,lastOutputAt:h?.lastOutputAt,error:h?.status==="failed"?h.error:void 0,emptyTitle:n,emptyDescription:s,historyLoading:p,hasOlder:N,olderCursor:h?.historyBaseIndex,onStartReached:N?()=>{ue.getState().loadOlderSession(e)}:void 0,searchQuery:y.searchQuery,activeHit:y.activeHit},e),h?.retry&&i.jsx("div",{className:Ni,children:i.jsx(Yh,{retry:h.retry})})]})})})}function lQ({conversationId:e,title:t,speaker:n,emptyTitle:s,emptyDescription:o,footer:r,onClose:a}){const l=KD(e);return i.jsx(xn,{open:e!==null,onOpenChange:c=>!c&&a(),children:i.jsxs(vn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[i.jsx(bn,{children:i.jsx(wn,{children:t})}),e&&i.jsx(YD,{className:"border-t",conversationId:e,speaker:n,emptyTitle:s??t,emptyDescription:o,runDividers:l}),r&&i.jsx("div",{className:Ni,children:r})]})})}function Iv({conversationId:e,title:t,speaker:n,focus:s,turnFooter:o,read:r,botSession:a=!0,onClose:l}){const{t:c}=ne(),[d,u]=m.useState(null),[h,p]=m.useState(),[f,g]=m.useState(),[x,v]=m.useState(!1),y=m.useRef(!1),b=m.useRef(null),w=m.useCallback(O=>r?r(O):window.electronAPI.bots.sessionHistory({conversationId:e??"",...O!==void 0?{beforeIndex:O}:{}}),[e,r]);m.useEffect(()=>{if(u(null),g(void 0),p(void 0),!e)return;let O=!0;return w().then(z=>{O&&(z.ok?(u({messages:z.messages,baseIndex:z.baseIndex}),p(z.projectId)):g(z.code==="not-found"?c("This conversation has no history yet."):z.error))}),()=>{O=!1}},[e,w,c]);const C=m.useCallback(async()=>{if(!(!e||!d||d.baseIndex<=0||y.current)){y.current=!0,v(!0);try{const O=await w(d.baseIndex);O.ok&&O.baseIndex+O.messages.length===d.baseIndex&&u({messages:[...O.messages,...d.messages],baseIndex:O.baseIndex})}finally{y.current=!1,v(!1)}}},[e,w,d]),_=KD(e),N=m.useMemo(()=>d?Sr(d.messages,!1,[],void 0,{historyBaseIndex:d.baseIndex,runDividers:_}):[],[d,_]),k=m.useCallback(()=>{C()},[C]),S=qD({focus:s,timelineRef:b,items:N,baseIndex:d?.baseIndex??0,hasMessages:!!d?.messages.length,loading:x||d===null,loadOlder:k}),A=n?.name,T=n?.color,I=n?.image,P=m.useMemo(()=>({sessionId:e,canRewind:!1,canRetry:!1,botSession:a,speaker:A&&T?{name:A,color:T,image:I}:void 0,turnFooter:o}),[a,e,A,T,I,o]),D=UD(a?e:null,h);return i.jsx(gv.Provider,{value:D,children:i.jsx(xn,{open:e!==null,onOpenChange:O=>!O&&l(),children:i.jsxs(vn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[i.jsx(bn,{children:i.jsx(wn,{children:t})}),i.jsx(Fh.Provider,{value:P,children:i.jsx("div",{className:"@container flex min-h-0 flex-1 flex-col border-t",children:f?i.jsx("p",{className:"p-6 text-muted-foreground text-sm",children:f}):i.jsx(Bh,{ref:b,items:N,busy:d===null,loading:d===null,running:!1,emptyTitle:t,hasOlder:!!(d&&d.baseIndex>0),historyLoading:x,olderCursor:d?.baseIndex,onStartReached:d&&d.baseIndex>0?()=>{C()}:void 0,searchQuery:S.searchQuery,activeHit:S.activeHit})})})]})})})}function $o(e,t,n=Date.now()){const s=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),o=e-n,r=Math.abs(o);return r<6e4?s.format(0,"second"):r<36e5?s.format(Math.trunc(o/6e4),"minute"):r<864e5?s.format(Math.trunc(o/36e5),"hour"):r<30*864e5?s.format(Math.trunc(o/864e5),"day"):r<365*864e5?s.format(Math.trunc(o/(30*864e5)),"month"):s.format(Math.trunc(o/(365*864e5)),"year")}const lg="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 cQ({group:e,thread:t}){const{t:n}=ne(),s=ue(S=>S.chats),o=ue(S=>S.sessions),r=ue(S=>S.timelines),a=ue(S=>S.queue),l=ue(S=>S.reads),c=ue(S=>S.bots),[d,u]=m.useState(!1),[h,p]=m.useState(null),[f,g]=m.useState(null),x=e.archivedAt!==void 0,v=m.useMemo(()=>Object.fromEntries(c.map(S=>[S.id,S.name])),[c]),y=S=>S.threadTitle??(S.parentId?n("New topic"):n("Main topic")),b=n8(s,e).map(S=>{const A=qg(S,{sessions:o,timeline:r[S.id],queue:a,names:v});return{id:S.id,title:y(S),preview:A.preview,activityAt:Math.max(A.activityAt,S.createdAt),unread:S.id!==t.id&&sl(A.marker,l[A.key]),running:A.running,canRename:!x,canDelete:!!S.parentId}}),w=xT(b,{currentId:t.id,rootId:e.id}),C=b.length-w.length,_=S=>ue.getState().openThread(e.id,S),N=async()=>{await ue.getState().createThread(e.id)||ze({type:"error",title:n("Could not create topic")})},k=async S=>{const A=await window.electronAPI.bots.deleteThread(S);A.ok||ze({type:"error",title:Is(A.error,n)}),ue.getState().refreshChats()};return i.jsxs(i.Fragment,{children:[i.jsxs($i,{children:[i.jsxs(Wi,{className:W(lg,"max-w-56 @max-[28rem]:max-w-32 @max-[21rem]:max-w-24"),children:[i.jsx("span",{className:"truncate",children:y(t)}),b.some(S=>S.unread)&&i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-info"}),i.jsx($n,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs(Ui,{align:"end",className:"w-72",children:[i.jsxs(Yg,{children:[i.jsx(Xg,{children:n("Topics")}),w.map(S=>i.jsxs(mn,{onClick:()=>_(S.id),children:[i.jsx(Yn,{className:W(S.id!==t.id&&"invisible")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:S.title}),i.jsx(Dv,{entry:S})]},S.id))]}),i.jsx(ja,{}),C>0&&i.jsxs(mn,{onClick:()=>u(!0),children:[i.jsx(Ux,{}),n("All topics ({{n}})",{n:b.length})]}),i.jsxs(mn,{disabled:x,onClick:()=>{N()},children:[i.jsx(Ho,{}),n("New topic")]}),i.jsxs(mn,{disabled:x,onClick:()=>p({id:t.id,title:y(t)}),children:[i.jsx($s,{}),n("Rename topic")]}),t.parentId&&i.jsxs(mn,{variant:"destructive",onClick:()=>g(t.id),children:[i.jsx(Vs,{}),n("Delete topic")]})]})]}),i.jsxs("button",{type:"button",disabled:x,onClick:()=>{N()},className:W(lg,"shrink-0"),title:n("New topic"),"aria-label":n("New topic"),children:[i.jsx(Ho,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New topic")})]}),d&&i.jsx(XD,{heading:n("Topics"),placeholder:n("Search topics..."),empty:n("No matching topics"),filters:!0,entries:b,currentId:t.id,onClose:()=>u(!1),onOpen:S=>{_(S),u(!1)},onRename:S=>p({id:S.id,title:S.title}),onDelete:S=>g(S.id)}),i.jsx(gs,{open:f!==null,onOpenChange:S=>!S&&g(null),title:n("Delete this topic?"),description:n("Its messages and member sessions are removed; replies in progress are stopped. Group notes, memory and the task board stay."),confirmLabel:n("Delete"),onConfirm:()=>f&&void k(f),zIndexLevel:d?"nested":"base"}),h!==null&&i.jsx(dQ,{initial:h.title,nested:d,onClose:()=>p(null),onSave:async S=>{const A=await window.electronAPI.bots.renameThread(h.id,S);if(!A.ok){ze({type:"error",title:Is(A.error,n)});return}ue.getState().upsertChat(A.chat),p(null)}})]})}function Dv({entry:e}){const{locale:t}=ne();return i.jsxs(i.Fragment,{children:[e.running&&i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-warning"}),e.unread&&i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-info"}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:$o(e.activityAt,t)})]})}function XD({heading:e,placeholder:t,empty:n,filters:s=!1,entries:o,currentId:r,onClose:a,onOpen:l,onRename:c,onDelete:d}){const{t:u}=ne(),[h,p]=m.useState(""),[f,g]=m.useState("all"),x=$w(o,h,f),v=b=>$w(o,"",b).length,y="shrink-0 rounded p-1 text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100";return i.jsx(xn,{open:!0,onOpenChange:b=>!b&&a(),children:i.jsxs(vn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(bn,{children:[i.jsxs(wn,{className:"flex items-baseline gap-2",children:[e,i.jsx("span",{className:"font-sans text-muted-foreground text-sm tabular-nums",children:o.length})]}),i.jsxs(uh,{"data-size":"sm",className:"mt-1",children:[i.jsx(hh,{children:i.jsx(si,{})}),i.jsx(ph,{autoFocus:!0,value:h,placeholder:t,onChange:b=>p(b.target.value)})]}),s&&i.jsx(lh,{value:f,onValueChange:b=>g(b),children:i.jsxs(ch,{children:[i.jsx(Ps,{value:"all",children:u("All")}),i.jsxs(Ps,{value:"unread",children:[u("Unread"),v("unread")>0&&i.jsx("span",{className:"tabular-nums",children:v("unread")})]}),i.jsxs(Ps,{value:"running",children:[u("In progress"),v("running")>0&&i.jsx("span",{className:"tabular-nums",children:v("running")})]})]})})]}),i.jsxs(An,{className:"flex flex-col gap-y-0.5 border-t pt-3!",children:[x.length===0&&i.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:n}),x.map(b=>i.jsxs("div",{className:"group flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted/60",children:[i.jsxs("button",{type:"button",onClick:()=>l(b.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(Yn,{className:W("h-3.5 w-3.5 shrink-0",b.id!==r&&"invisible")}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-sm",children:b.title}),b.preview&&i.jsx("span",{className:"block truncate text-muted-foreground text-xs",children:b.preview})]}),i.jsx(Dv,{entry:b})]}),c&&b.canRename&&i.jsx("button",{type:"button",className:y,onClick:()=>c(b),title:u("Rename topic"),"aria-label":u("Rename topic"),children:i.jsx($s,{className:"h-3.5 w-3.5"})}),d&&b.canDelete?i.jsx("button",{type:"button",className:W(y,"hover:text-destructive"),onClick:()=>d(b),title:u("Delete topic"),"aria-label":u("Delete topic"),children:i.jsx(Vs,{className:"h-3.5 w-3.5"})}):d?i.jsx("span",{className:"w-5.5 shrink-0","aria-hidden":!0}):null]},b.id))]})]})})}function dQ({initial:e,nested:t,onClose:n,onSave:s}){const{t:o}=ne(),[r,a]=m.useState(e),l=()=>{r.trim()&&s(r.trim())};return i.jsx(xn,{open:!0,onOpenChange:c=>!c&&n(),children:i.jsxs(vn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[i.jsx(bn,{children:i.jsx(wn,{children:o("Rename topic")})}),i.jsx(An,{children:i.jsx(Zt,{value:r,autoFocus:!0,maxLength:80,onChange:c=>a(c.target.value),onKeyDown:c=>{c.nativeEvent.isComposing||c.key==="Enter"&&l()}})}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(me,{size:"sm",disabled:!r.trim(),onClick:l,children:o("Save")})]})]})})}function uQ({chat:e,botId:t,running:n,onView:s}){const{t:o}=ne(),[r,a]=m.useState([]),[l,c]=m.useState(!1),[d,u]=m.useState(null),h=e.sessions[t]?.conversationId,p=m.useCallback(()=>{window.electronAPI.bots.chatSessions(e.id).then(w=>{w.ok&&a(w.sessions.filter(C=>C.botId===t))})},[e.id,t]);m.useEffect(p,[p,h,n]);const f=r.map(w=>{const C=w.conversationId===h;return{id:w.conversationId,title:w.title??o(C?"New conversation":"Untitled conversation"),preview:C||w.resumable?"":o("Workspace changed; view only"),activityAt:w.activityAt??(C?Date.now():0),unread:!1,running:C&&n,resumable:w.resumable}}),g=xT(f,{currentId:h??"",rootId:h??""}),x=f.length-g.length,v=f.find(w=>w.id===h)?.title??o("New conversation"),y=async w=>{const C=await window.electronAPI.bots.switchSession(e.id,w);C.ok||ze({type:"error",title:Is(C.error,o)}),await ue.getState().refreshChats(),p()},b=w=>{const C=f.find(_=>_.id===w);!C||w===h||(C.resumable?n?u(w):y(w):s(w,C.title))};return f.length<2?null:i.jsxs(i.Fragment,{children:[i.jsxs($i,{onOpenChange:w=>w&&p(),children:[i.jsxs(Wi,{className:W(lg,"max-w-56"),children:[i.jsx("span",{className:"truncate",children:v}),i.jsx($n,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs(Ui,{align:"end",className:"w-72",children:[i.jsxs(Yg,{children:[i.jsx(Xg,{children:o("Conversations")}),g.map(w=>i.jsxs(mn,{onClick:()=>b(w.id),children:[i.jsx(Yn,{className:W(w.id!==h&&"invisible")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:w.title}),!w.resumable&&w.id!==h&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:o("Read-only")}),i.jsx(Dv,{entry:w})]},w.id))]}),x>0&&i.jsxs(i.Fragment,{children:[i.jsx(ja,{}),i.jsxs(mn,{onClick:()=>c(!0),children:[i.jsx(Ux,{}),o("All conversations ({{n}})",{n:f.length})]})]})]})]}),l&&i.jsx(XD,{heading:o("Conversations"),placeholder:o("Search conversations..."),empty:o("No matching conversations"),entries:f,currentId:h??"",onClose:()=>c(!1),onOpen:w=>{c(!1),b(w)}}),i.jsx(gs,{open:d!==null,onOpenChange:w=>!w&&u(null),title:o("Switch conversation?"),description:o("The reply in progress will be stopped."),confirmLabel:o("Switch"),onConfirm:()=>d&&void y(d)})]})}function JD(e){const{t}=ne(),n=Na(),s=we(c=>c.virtualModels);if(!e?.engine)return t("Default model");const{providerId:o,modelId:r}=e.engine,a=r_(s,e.engine);return a?a.name:n.find(c=>c.id===o)?.models.find(c=>c.id===r)?.label??r}function hQ({chat:e,group:t=e}){const{t:n}=ne(),s=ue(de=>de.bots),o=ue(de=>de.chats),r=ue(de=>de.sessions),a=ue(de=>de.queue),l=ue(de=>de.delegations),c=ue(de=>de.timelines[e.id]),d=ue(de=>de.runtime[e.id]),u=ue(de=>de.markRead),h=ue(de=>de.panelOpen),p=ue(de=>de.panelTab),f=ue(de=>de.browserTabs[t.id]?.tabs.length??0),g=ue(de=>de.panelWidth),x=we(de=>de.skills),v=we(de=>de.voiceInputEnabled),y=we(de=>de.voiceModel),{status:b}=t_(v),w=v&&b?.state!=="unsupported"&&b?.models.find(de=>de.id===y)?.state==="ready",[C,_]=m.useState(!1),[N,k]=m.useState(0),S=_a(),A=m.useRef(null);m.useEffect(()=>{const de=A.current?.parentElement;if(!de)return;const mt=()=>k(de.clientWidth);mt();const Lt=new ResizeObserver(mt);return Lt.observe(de),()=>Lt.disconnect()},[]);const T=S?N:o_(g,N),I=h?T:0,P=m.useCallback(de=>{const mt=A.current?.parentElement;mt&&ue.getState().nudgePanelWidth(-de,mt.clientWidth)},[]),[D,O]=m.useState(null),[z,R]=m.useState(),[$,X]=m.useState(null),H=ue(de=>de.focus?.chatId===e.id?de.focus:null),te=ue(de=>de.clearFocus),V=m.useMemo(()=>new Map(s.map(de=>[de.id,de])),[s]),Y=m.useMemo(()=>Object.fromEntries(s.map(de=>[de.id,de.name])),[s]),q=e.members.map(de=>V.get(de)).filter(de=>!!de),ee=q.map(de=>`${de.id}:${de.skillIds.join(",")}`).join("|"),ge=m.useMemo(()=>x.flatMap(de=>{const mt=q.filter(Lt=>Lt.skillIds.includes(de.id)).map(Lt=>Lt.id);return mt.length?[{id:de.id,name:de.name,description:de.description,owners:mt}]:[]}),[x,ee]),Ce=m.useMemo(()=>o.filter(de=>de.id!==t.id&&!de.parentId&&de.archivedAt===void 0).map(de=>({id:de.id,title:Cs(de,s,n),kind:de.kind})),[o,t.id,s,n]),Re=qg(e,{sessions:r,timeline:c,queue:a,names:Y}),fe=ue(de=>de.reads[Re.key]),U=e.kind==="group"?_L(c,fe):Re.marker,oe=m.useMemo(()=>l.filter(de=>de.chatId===e.id),[l,e.id]),Se=m.useMemo(()=>n_(r,s_(o,l),e.id),[r,o,l,e.id]),Q=D?(de=>{const mt=oe.find(Nt=>Nt.childConversationId===de);if(mt)return V.get(mt.targetBotId);const Lt=Object.entries(e.sessions).find(([,Nt])=>Nt.conversationId===de)?.[0],Fe=c?.entries.find(Nt=>Nt.kind==="bot"&&Nt.conversationId===de);return V.get(Lt??(Fe?.kind==="bot"?Fe.botId:e.kind==="direct"?e.members[0]:""))})(D.id):void 0,ae=$?V.get($.botId):void 0,Z=$?Se.filter(de=>de.conversationId===$.id):[],ce=$?.title??ae?.name??n("Deleted member"),De=$&&l.find(de=>de.childConversationId===$.id)?.state==="queued",Oe=m.useCallback((de,mt)=>{const Lt=NL(ue.getState().delegations,de);Lt?(ue.getState().sessions[de]||ue.getState().trackSession(de),X({id:de,botId:Lt.botId,title:mt})):O({id:de,title:mt})},[]);m.useEffect(()=>{u(Re.key,U)},[u,Re.key,U]),m.useEffect(()=>{if(e.kind==="group"){const de=ue.getState();de.timelines[e.id]?.history&&de.focus?.chatId!==e.id?de.jumpLatest(e.id):de.loadLatest(e.id),ue.getState().refreshRuntime(e.id)}},[e.id,e.kind]);const Ne=e.kind==="direct"?q[0]:void 0,Ze=Ne?e.sessions[Ne.id]?.conversationId:void 0,bt=H?.locator,Ut=H&&bt?.kind==="session"&&bt.conversationId===Ze?{messageIndex:bt.messageIndex,query:H.query,nonce:H.nonce}:void 0,Et=H&&bt?.kind==="timeline"?{seq:bt.seq,query:H.query,nonce:H.nonce}:void 0;m.useEffect(()=>{H?.locator.kind==="session"&&H.locator.conversationId!==Ze&&(O({id:H.locator.conversationId,title:n("History")}),R({messageIndex:H.locator.messageIndex,query:H.query,nonce:H.nonce}),te(H.nonce))},[H,Ze,te,n]);const _t=D?.id,B=m.useCallback(de=>e.kind==="direct"&&_t?i.jsx(zu,{target:{chatId:e.id,conversationId:_t,messageIndex:de}}):null,[e.id,e.kind,_t]),Te=e.archivedAt!==void 0,We=d?.current?V.get(d.current):void 0,kt=(()=>{if(Te)return n("This chat is archived. Restore it before sending.");if(e.kind==="group"){const de=e.routing.mode==="smart"?n("Without @, the best-fit member is picked to reply"):n("Without @, the group owner replies");return We?`${de} · ${n("{{name}} is replying; new messages are routed after they finish",{name:We.name})}`:de}return Re.running&&Ne?n("{{name}} is working; your message joins the current turn",{name:Ne.name}):null})(),Gt=async({text:de,images:mt,...Lt})=>{const Fe=await ue.getState().send(e.id,de,mt,Lt);return Fe.ok?(Fe.queued&&ze({type:"info",title:n("Queued until a session slot frees up")}),ue.getState().timelines[e.id]?.history&&ue.getState().jumpLatest(e.id),!0):(ze({type:"error",title:n("Message not sent"),description:Is(Fe.error,n)}),!1)};return i.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1",children:[i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[i.jsxs("header",{className:"@container flex h-[52px] shrink-0 items-center gap-2.5 border-b px-4",children:[Ne?i.jsx(tn,{bot:Ne,busy:Re.running}):i.jsx(ul,{bots:q,busy:Re.running}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate font-semibold text-sm",children:Cs(e,s,n)}),i.jsx("div",{className:"truncate text-muted-foreground text-xs",children:Ne?i.jsx(fQ,{bot:Ne,running:Re.running,queued:Re.queued,conversationId:e.sessions[Ne.id]?.conversationId}):n("{{n}} members · Owner {{name}}",{n:q.length,name:V.get(e.bossBotId??"")?.name??"—"})})]}),i.jsx("div",{className:"flex-1"}),i.jsx(BD,{chat:t}),Ne?i.jsxs(i.Fragment,{children:[i.jsx(uQ,{chat:e,botId:Ne.id,running:Re.running,onView:(de,mt)=>O({id:de,title:mt})}),i.jsxs("button",{type:"button",disabled:Te,onClick:()=>{window.electronAPI.bots.newSession(e.id).then(de=>{de.ok?ue.getState().refreshChats():ze({type:"error",title:Is(de.error,n)})})},className:"flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",title:n("New conversation"),"aria-label":n("New conversation"),children:[i.jsx(Ho,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New conversation")})]})]}):i.jsx(cQ,{group:t,thread:e})]}),Ne?i.jsxs(i.Fragment,{children:[i.jsx(pQ,{items:e_(oe,e.id),bots:V,onOpenConversation:Oe}),i.jsx(gQ,{chat:e,bot:Ne,focus:Ut,onFocusDone:te})]}):i.jsx(eQ,{chat:e,bots:V,timeline:c,runtime:d,delegations:oe,focus:Et,onFocusDone:te,onLoadOlder:()=>{ue.getState().loadOlder(e.id)},onLoadNewer:()=>{ue.getState().loadNewer(e.id)},onLoadAround:de=>ue.getState().loadAround(e.id,de),onJumpLatest:()=>{ue.getState().jumpLatest(e.id)},onOpenConversation:Oe,onOpenLive:(de,mt)=>X({id:de,botId:mt,title:V.get(mt)?.name??n("Deleted member")})}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:W(Ni,"pb-4"),children:[Ne&&(Re.running||Re.queued)&&i.jsx(gD,{conversationId:e.sessions[Ne.id]?.conversationId,className:"mb-2 rounded-lg border bg-muted/30 px-3 py-2"}),i.jsx(XS,{items:Se,bots:V,showNames:e.kind==="group"}),e.kind==="group"&&i.jsx(VJ,{chatId:e.id,memberIds:e.members,bots:V,onOpenLive:(de,mt)=>X({id:de,botId:mt,title:V.get(mt)?.name??n("Deleted member")})}),i.jsx(IJ,{chatId:e.id,placeholder:Ne?n("Message {{name}}…",{name:Ne.name}):n("@ a member, or just say it…"),members:e.kind==="group"?q:void 0,chatOptions:Ce,skills:ge,voice:w?WI:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,running:Re.running||!!(d?.current||d?.routing),disabled:Te,hint:kt,toolbar:Ne?i.jsx(mQ,{bot:Ne}):null,onSend:Gt,onStop:()=>{ue.getState().stop(e.id)}},e.id)]})})]}),h&&!S&&i.jsx(Du,{onResize:P,onResizingChange:_}),i.jsx(Os.aside,{ref:A,initial:!1,animate:{width:I},style:S?void 0:{maxWidth:`max(0px, calc(100% - ${i_+Jg}px))`},transition:$I({skip:C,cover:S,targetW:I}),className:W("flex min-h-0 shrink-0 flex-col overflow-hidden bg-background",S?"absolute inset-y-0 right-0 z-10":"relative"),children:i.jsxs("div",{className:W("flex h-full min-h-0 flex-col",!h&&"invisible"),style:{width:T},children:[i.jsx("div",{className:"flex h-10 shrink-0 items-center gap-1 border-b px-2",children:["info","browser"].map(de=>i.jsxs("button",{type:"button",onClick:()=>ue.getState().setPanelTab(de),className:W("flex h-7 items-center gap-1.5 rounded-md px-2.5 text-xs transition-colors",p===de?"bg-brand/10 font-medium text-foreground dark:bg-brand/15":"text-muted-foreground hover:text-foreground"),children:[de==="info"?i.jsx(fh,{className:"h-3.5 w-3.5"}):i.jsx(bo,{className:"h-3.5 w-3.5"}),n(de==="info"?Ne?"Member":"Group info":"Browser"),de==="browser"&&f>0&&i.jsx("span",{className:"text-muted-foreground tabular-nums",children:f})]},de))}),p==="browser"?i.jsx(FX,{chatId:t.id,visible:h}):Ne?i.jsx(IZ,{botId:Ne.id,chat:e,onOpenHistory:Oe}):i.jsx(VZ,{chat:t,thread:e,onOpenConversation:Oe})]})}),i.jsx(Iv,{conversationId:D?.id??null,title:D?.title??"",speaker:Q?{name:Q.name,color:Q.avatar.color,image:iu(Q)}:void 0,focus:z,turnFooter:B,onClose:()=>{O(null),R(void 0)}}),i.jsx(lQ,{conversationId:$?.id??null,title:ce,speaker:{name:ae?.name??ce,color:ae?.avatar.color??"#64748b",image:ae?iu(ae):void 0},emptyTitle:De?n("Queued and has not started yet"):void 0,emptyDescription:De?"":void 0,footer:ae&&Z.length>0?i.jsx(XS,{items:Z,bots:V,showNames:!1}):void 0,onClose:()=>X(null)})]})}function pQ({items:e,bots:t,onOpenConversation:n}){const{t:s}=ne();return e.length===0?null:i.jsx("div",{className:"shrink-0 border-b bg-muted/30",children:i.jsxs("div",{className:W(Ni,"py-2"),children:[i.jsx("div",{className:"mb-1.5 text-muted-foreground text-xs",children:s("Delegations in progress · {{n}}",{n:e.length})}),i.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto",children:e.map(o=>i.jsx(Kh,{record:o,bots:t,onOpenConversation:n},o.id))})]})})}function fQ({bot:e,running:t,queued:n,conversationId:s}){const{t:o}=ne(),r=JD(e),a=o(t?"Working":n?"Queued":"Idle");return i.jsxs(i.Fragment,{children:[[e.title,r,a].filter(Boolean).join(" · "),t&&i.jsx(WD,{conversationId:s,className:"ml-1.5 text-warning"})]})}function mQ({bot:e}){const{t}=ne(),n=JD(e),s=Gl[e.approvalMode];return i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"flex h-6 min-w-0 items-center gap-1 rounded-md px-1.5 text-muted-foreground text-xs",children:[i.jsx(ii,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-32 truncate",children:n})]}),i.jsxs("span",{className:"flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 text-muted-foreground text-xs",children:[i.jsx(sh,{className:"h-3 w-3"}),t(s.labelKey)]})]})}function gQ({chat:e,bot:t,focus:n,onFocusDone:s}){const{t:o}=ne(),r=e.sessions[t.id]?.conversationId,a=e.archivedAt!==void 0,l=m.useMemo(()=>{if(a||!r)return;const d=u=>{u.ok||ze({type:"error",title:Is(u.error??"unavailable",o)})};return{subscribe:ue.subscribe,projection:()=>ue.getState().sessions[r],rewind:(u,h)=>{ue.getState().rewind(e.id,u,h).then(d)},retry:()=>{ue.getState().retry(e.id).then(d)}}},[e.id,r,a,o]),c=m.useCallback(d=>r?i.jsx(zu,{target:{chatId:e.id,conversationId:r,messageIndex:d}}):null,[e.id,r]);return r?i.jsx(YD,{conversationId:r,speaker:{name:t.name,color:t.avatar.color,image:iu(t)},emptyTitle:o("Say hi to {{name}}",{name:t.name}),focus:n,onFocusDone:s,turnFooter:c,controls:l,dataSlot:"bot-timeline"}):i.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 px-6 text-center",children:[i.jsx(tn,{bot:t,size:"lg"}),i.jsx("p",{className:"font-medium text-lg",children:t.name}),i.jsx("p",{className:"max-w-sm text-muted-foreground text-sm",children:t.scope||t.title})]})}function XS({items:e,bots:t,showNames:n}){const{t:s}=ne(),o=new Map;for(const r of e)o.set(r.conversationId,[...o.get(r.conversationId)??[],r]);return i.jsx(i.Fragment,{children:[...o.entries()].map(([r,a])=>{const l=t.get(a[0].botId),c=a[0].delegation,d=l?.name??s("Deleted member"),u=a.flatMap(p=>p.kind==="approval"?[p.request]:[]),h=a.flatMap(p=>p.kind==="ask"?[p.request]:[]);return i.jsxs("div",{"data-pending-conversation":r,children:[(n||c)&&i.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:l,size:"xs"}),c?s("{{name}} (on behalf of {{owner}}) needs you",{name:d,owner:t.get(c.parentBotId)?.name??s("Deleted member")}):s("{{name}} needs you",{name:d})]}),i.jsx(Rh,{approvals:u,onRespond:(p,f)=>{window.electronAPI.agent.respondApproval(r,p,f)}}),i.jsx(Lh,{asks:h,onAnswer:(p,f)=>{window.electronAPI.agent.respondAsk(r,p,f)}})]},r)})})}function xQ(e,t){const n={pending:[],budgets:[],routines:[],silences:[],interrupted:[],blocked:[],count:0};for(const s of TL(e)){const o={chatId:s.chatId??"",botId:s.botId??"",...s.delegationId&&s.ownerBotId?{delegation:{id:s.delegationId,parentBotId:s.ownerBotId}}:{}};if(s.kind==="approval"&&s.approval&&s.conversationId)n.pending.push({kind:"approval",conversationId:s.conversationId,request:s.approval,...o});else if(s.kind==="ask"&&s.ask&&s.conversationId)n.pending.push({kind:"ask",conversationId:s.conversationId,request:s.ask,...o});else if(s.kind==="budget")n.budgets.push(s);else if(s.kind==="silence")n.silences.push(s);else if(s.kind==="routine-draft"||s.kind==="routine-blocked"){const r=t.routines.find(a=>a.id===s.routine?.id&&a.botId===s.routine.botId);r&&n.routines.push({kind:s.kind==="routine-draft"?"approval":"blocked",routine:r})}else if(s.kind==="delegation-interrupted"||s.kind==="task-blocked"){const r=t.delegations.find(a=>a.id===s.delegationId);r&&n[s.kind==="task-blocked"?"blocked":"interrupted"].push({item:s,record:r})}}return n.count=n.pending.length+n.budgets.length+n.routines.length+n.silences.length+n.interrupted.length+n.blocked.length,n}function vQ({write:e,bot:t,chatName:n}){const{t:s}=ne(),o=IL(u=>u.review),[r,a]=m.useState(!1),[l,c]=m.useState(null),d=u=>{a(!0),c(null),o(e.id,u).then(h=>{h.ok||c(h.error??s("Failed"))}).finally(()=>a(!1))};return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm"}),i.jsx("span",{className:"text-foreground",children:t?.name??s("Deleted member")}),n&&i.jsxs("span",{children:["· ",n]}),i.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-[11px] text-warning",children:s("Memory write")}),i.jsxs("span",{children:["→ ",e.spaceLabel]}),e.redacted&&i.jsxs("span",{children:["· ",s("Secrets redacted")]})]}),e.title&&i.jsx("div",{className:"mt-2 font-medium text-sm",children:e.title}),i.jsx("pre",{className:"mt-1 max-h-32 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1.5 text-xs",children:e.content}),l&&i.jsx("div",{className:"mt-1 text-destructive text-xs",children:l}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"outline",disabled:r,onClick:()=>d("reject"),children:s("Reject")}),i.jsx(me,{size:"xs",disabled:r,onClick:()=>d("approve"),children:s("Approve")})]})]})}function bQ(){const{t:e}=ne(),t=ue(p=>p.inbox),n=ue(p=>p.chats),s=ue(p=>p.bots),o=ue(p=>p.delegations),r=ue(p=>p.routines),[a,l]=m.useState(null),c=m.useMemo(()=>xQ(t,{routines:r,delegations:o}),[t,r,o]),d=DL(),u=m.useMemo(()=>new Map(s.map(p=>[p.id,p])),[s]),h=p=>{const f=n.find(g=>g.id===p);return f?Cs(f,s,e):""};return i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[i.jsxs("header",{className:"flex h-[52px] shrink-0 items-center gap-2.5 border-b px-4",children:[i.jsx("div",{className:"font-semibold text-sm",children:e("Inbox")}),i.jsx("div",{className:"text-muted-foreground text-xs",children:e("Everything members are waiting on you for")})]}),i.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:i.jsxs("div",{className:"mx-auto w-full max-w-2xl space-y-2.5 px-6 py-4",children:[c.count===0&&d.length===0&&i.jsxs("div",{className:"flex flex-col items-center gap-2 py-16 text-muted-foreground",children:[i.jsx(Wx,{className:"h-6 w-6"}),i.jsx("p",{className:"text-sm",children:e("Nothing needs your attention")})]}),c.pending.map(p=>i.jsx(kQ,{item:p,bot:u.get(p.botId),owner:p.delegation?u.get(p.delegation.parentBotId):void 0,chatName:h(p.chatId)},`${p.conversationId}:${p.request.requestId}`)),c.budgets.map(p=>i.jsx(yQ,{item:p,bot:u.get(p.botId??"")},p.key)),d.map(p=>i.jsx(vQ,{write:p,bot:p.botId?u.get(p.botId):void 0,chatName:h(p.chatId)},p.id)),c.routines.map(p=>i.jsx(bZ,{alert:p},p.routine.id)),c.silences.map(p=>i.jsx(wQ,{item:p,bot:u.get(p.botId??""),chatName:h(p.chatId)},p.key)),c.blocked.length>0&&i.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Stuck delegated tasks")}),c.blocked.map(({item:p,record:f})=>i.jsx(SQ,{inboxKey:p.key,record:f,bots:u,chatName:h(f.chatId)},p.key)),c.interrupted.length>0&&i.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Interrupted delegations")}),c.interrupted.map(({item:p,record:f})=>i.jsx(CQ,{inboxKey:p.key,record:f,bots:u,chatName:h(f.chatId),onOpen:g=>l({id:f.childConversationId,title:g,bot:u.get(f.targetBotId)})},p.key))]})}),i.jsx(Iv,{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}=ne(),o=ue(l=>l.setView),r=ue(l=>l.dismissInbox),a=t?.name??s("Deleted member");return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm",busy:!0}),i.jsx("span",{className:"text-foreground",children:a}),n&&i.jsxs("span",{children:["· ",n]}),e.delegationId&&i.jsxs("span",{children:["· ",s("Delegation")]}),i.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-[11px] text-warning",children:i.jsx($D,{since:e.since??e.createdAt})})]}),i.jsx("div",{className:"mt-2 text-sm",children:s("{{name}} is still running but has produced no output for a while",{name:a})}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>{r(e.key)},children:s("Dismiss")}),e.chatId&&i.jsx(me,{size:"xs",variant:"outline",onClick:()=>e.chatId&&o({kind:"chat",chatId:e.chatId}),children:s("Go to chat")})]})]})}function yQ({item:e,bot:t}){const{t:n}=ne(),s=ue(a=>a.dismissInbox),o=ue(a=>a.openDirect),r=t?.name??n("Deleted member");return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm"}),i.jsx("span",{className:"text-foreground",children:r}),i.jsx("span",{className:"rounded bg-destructive/15 px-1.5 text-[11px] text-destructive",children:n("Budget")})]}),i.jsx("div",{className:"mt-2 text-sm",children:n("{{name}}'s budget for today is used up",{name:r})}),i.jsx("div",{className:"mt-1 text-muted-foreground text-xs",children:e.budget?.reason==="cost"?n("Daily cost limit reached. New messages are refused until local midnight."):n("Daily token limit reached. New messages are refused until local midnight.")}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>{s(e.key)},children:n("Dismiss")}),t&&i.jsx(me,{size:"xs",variant:"outline",onClick:()=>{o(t.id)},children:n("Go to chat")})]})]})}function SQ({inboxKey:e,record:t,bots:n,chatName:s}){const{t:o}=ne(),r=ue(g=>g.openTask),a=ue(g=>g.dismissInbox),l=Uh(!0),c=n.get(t.targetBotId),d=c?.name??o("Deleted member"),u=t.finishedAt??t.blocked?.at??t.createdAt,h=t.blocked?.waitFor==="parent"?o("Waiting for {{name}} to reply",{name:n.get(t.parentBotId)?.name??o("Deleted member")}):o("Waiting for your reply"),{chatId:p,taskId:f}=t;return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:c,size:"xs"}),i.jsx("span",{className:"text-foreground",children:d}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx(Wh,{state:t.state}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:o("Stuck for {{time}}",{time:wo(l-u)})})]}),i.jsx("div",{className:"mt-2 line-clamp-2 text-muted-foreground text-sm",children:t.task}),i.jsxs("div",{className:"mt-2 rounded-md border border-warning/30 bg-warning/10 px-2 py-1.5 text-xs",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:o("Blocked · needs: {{need}}",{need:t.blocked?.need??""})}),i.jsx("div",{className:"mt-0.5 text-muted-foreground",children:h}),p&&f&&i.jsx(Tv,{placeholder:o("Answer {{name}}; they continue after your reply…",{name:d}),onSend:g=>zD(p,f,g,o)})]}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>{a(e)},children:o("Dismiss")}),p&&f&&i.jsx(me,{size:"xs",variant:"outline",onClick:()=>r(p,f),children:o("Open task card")})]})]})}function CQ({inboxKey:e,record:t,bots:n,chatName:s,onOpen:o}){const{t:r}=ne(),a=ue(p=>p.setView),l=ue(p=>p.dismissInbox),c=n.get(t.parentBotId),d=n.get(t.targetBotId),u=c?.name??r("Deleted member"),h=d?.name??r("Deleted member");return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:c,size:"xs"}),i.jsx("span",{className:"text-foreground",children:u}),i.jsx("span",{children:"→"}),i.jsx(tn,{bot:d,size:"xs"}),i.jsx("span",{className:"text-foreground",children:h}),i.jsxs("span",{children:["· ",r("Delegation")]}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx(Wh,{state:t.state,interrupted:!0})]}),i.jsx("div",{className:"mt-2 line-clamp-3 text-sm",children:t.task}),i.jsx("div",{className:"mt-1 text-muted-foreground text-xs",children:Rc(t,r)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>{l(e)},children:r("Dismiss")}),t.chatId&&i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>t.chatId&&a({kind:"chat",chatId:t.chatId}),children:r("Go to chat")}),i.jsx(me,{size:"xs",variant:"outline",onClick:()=>o(r("{{from}} → {{to}} · Delegation",{from:u,to:h})),children:r("View conversation")}),i.jsx(me,{size:"xs",onClick:()=>Dl(t.id,r),children:r("Retry")})]})]})}function kQ({item:e,bot:t,owner:n,chatName:s}){const{t:o}=ne(),r=ue(g=>g.setView),[a,l]=m.useState(""),[c,d]=m.useState(!1),u=g=>{d(!0),g.finally(()=>d(!1))},h=g=>u(window.electronAPI.agent.respondApproval(e.conversationId,e.request.requestId,g)),p=g=>g.trim()&&u(window.electronAPI.agent.respondAsk(e.conversationId,e.request.requestId,g.trim())),f=e.kind==="approval"&&e.request.phase==="reviewing";return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm"}),i.jsx("span",{className:"text-foreground",children:e.delegation?o("{{name}} on behalf of {{owner}}",{name:t?.name??o("Deleted member"),owner:n?.name??o("Deleted member")}):t?.name??o("Deleted member")}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx("span",{className:e.kind==="approval"?"rounded bg-warning/20 px-1.5 text-[11px] text-warning":"rounded bg-info/15 px-1.5 text-[11px] text-info",children:e.kind==="approval"?o("Approval"):o("Question")}),e.kind==="approval"&&e.request.protected&&i.jsx("span",{className:"rounded bg-destructive/15 px-1.5 text-[11px] text-destructive",children:vT(e.request.protected,o)})]}),e.kind==="approval"?i.jsxs("div",{className:"mt-2 text-sm",children:[Bo(e.request.tool,o),i.jsx("pre",{className:"mt-1 max-h-24 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1.5 font-mono text-xs",children:e.request.summary})]}):i.jsx("div",{className:"mt-2 whitespace-pre-wrap text-sm",children:e.request.question}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(me,{size:"xs",variant:"ghost",onClick:()=>r({kind:"chat",chatId:e.chatId}),children:o("Go to chat")}),e.kind==="approval"?f?i.jsx("span",{className:"text-muted-foreground text-xs",children:o("Assistant reviewing…")}):i.jsxs(i.Fragment,{children:[i.jsx(me,{size:"xs",variant:"outline",disabled:c,onClick:()=>h("deny"),children:o("Deny")}),!e.request.protected&&i.jsx(me,{size:"xs",variant:"outline",disabled:c,onClick:()=>h("allowSession"),children:o("Always allow in this session")}),i.jsx(me,{size:"xs",disabled:c,onClick:()=>h("allow"),children:o("Allow")})]}):i.jsxs(i.Fragment,{children:[e.request.options?.map(g=>i.jsx(me,{size:"xs",variant:"outline",disabled:c,onClick:()=>p(g),children:g},g)),i.jsx(Zt,{className:"h-7 w-48",value:a,placeholder:o("Custom answer…"),onChange:g=>l(g.target.value),onKeyDown:g=>{g.nativeEvent.isComposing||c||g.key==="Enter"&&p(a)}}),i.jsx(me,{size:"xs",disabled:c||!a.trim(),onClick:()=>p(a),children:o("Reply")})]})]})]})}function jQ(e){const{openOnInputClick:t=!1,value:n,defaultValue:s,onValueChange:o,mode:r="list",itemToStringValue:a,...l}=e,c=r==="inline"||r==="both",d=r==="inline"||r==="none",u=n!==void 0,[h,p]=m.useState(s??""),[f,g]=m.useState("");m.useEffect(()=>{u&&g("")},[n,u]);let x;c&&f!==""?x=f:u?x=n??"":x=h;const v=EL({locale:l.locale}),y=m.useMemo(()=>l.filter!==void 0?l.filter:v.contains,[l.filter,v]),b=String(u?n:h).trim(),w=m.useMemo(()=>r!=="both"?d?null:y:y===null?null:(N,k,S)=>y(N,b,S),[y,r,b,d]);function C(N,k){g(""),u||p(N),o?.(N,k)}function _(N,k){e.onItemHighlighted?.(N,k),k.reason!==AL&&g(c&&N!=null?ML(N,a):"")}return i.jsx(PL,{...l,itemToStringLabel:a,openOnInputClick:t,selectionMode:"none",fillInputOnItemPress:!0,filter:w,autoComplete:r,inputValue:x,defaultInputValue:s,onInputValueChange:C,onItemHighlighted:_})}const _Q=RL,NQ="⁠",TQ=200;function IQ(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 DQ(){const e=LL(),t=m.useRef(null);return m.useEffect(()=>{if(OL)return;const n=t.current;if(n==null)return;const s=IQ(n);if(s==null)return;const o=s.data,r=`${o}${NQ}`;return s.nodeValue=r,e.start(TQ,()=>{s.nodeValue===r&&(s.nodeValue=o)}),()=>{e.clear(),s.nodeValue===r&&(s.nodeValue=o)}},[t,e]),t}const ZD=m.createContext(void 0);function EQ(){const e=m.useContext(ZD);if(e===void 0)throw new Error(uc(18));return e}const PQ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,items:a,...l}=t,[c,d]=m.useState(),u=m.useMemo(()=>({labelId:c,setLabelId:d,items:a}),[c,d,a]),h=hc("div",t,{ref:n,props:[{role:"group","aria-labelledby":c},l]}),p=i.jsx(ZD.Provider,{value:u,children:h});return a?i.jsx(zL,{items:a,children:p}):p}),AQ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,id:a,...l}=t,{setLabelId:c}=EQ(),d=gj(a);return Fg(()=>(c(d),()=>{c(h=>h===d?void 0:h)}),[d,c]),hc("div",t,{ref:n,props:[{id:d},l]})}),MQ=GL,RQ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,children:a,...l}=t,{filteredItems:c}=FL(),d=HL(),u=DQ(),h=c.length===0?a:null;return hc("div",t,{ref:[n,d.state.emptyRef,u],props:[{children:h,role:"status","aria-live":"polite","aria-atomic":!0},l]})});function LQ(e){const t=e.value.length>0,n=t?e.value.replace(/ /g," "):"",s=e.clearing&&t&&n!==e.mirrorText;return{hasValue:t,mirrorText:n,superseded:s}}const Ev=jQ,El=new WeakMap,Bu=new WeakMap;function OQ(e){const t=El.get(e);t!==void 0&&window.clearTimeout(t),El.delete(e);for(const n of Bu.get(e)??[])n.cancel();Bu.delete(e),e.classList.remove("is-clearing")}function Lr(e,t){const n=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(e));return Number.isFinite(n)?n:t}function Zd(e){const t=e.querySelector("input"),n=e.querySelector(".t-clear-mirror");if(!t||!n)return;const s=LQ({value:t.value,mirrorText:n.textContent??"",clearing:e.classList.contains("is-clearing")});s.superseded&&OQ(e),e.classList.toggle("has-value",s.hasValue),n.textContent=s.mirrorText}function zQ(e){const t=e.closest(".t-clear"),n=t?.querySelector("input"),s=t?.querySelector(".t-clear-mirror"),o=t?.querySelector(".t-clear-placeholder");if(!t||!n||!s||!o||!n.value)return;const r=El.get(t);if(r!==void 0&&window.clearTimeout(r),s.textContent=n.value.replace(/ /g," "),o.textContent=n.placeholder,t.classList.remove("has-value"),t.classList.add("is-clearing"),window.matchMedia("(prefers-reduced-motion: reduce)").matches){t.classList.remove("is-clearing"),s.textContent="";return}const a=getComputedStyle(document.documentElement),l=Lr("--clear-dur",1e3),c=Lr("--clear-out-dur",400),d=Lr("--clear-in-dur",400),u=Lr("--clear-out-fly",12),h=Lr("--clear-in-fly",12),p=Lr("--clear-blur",2),f=a.getPropertyValue("--clear-out-ease").trim()||"ease-out",g=a.getPropertyValue("--clear-in-ease").trim()||"ease-out",x=s.animate([{transform:"translateY(0)",opacity:1,filter:"blur(0)"},{transform:`translateY(${u}px)`,opacity:0,filter:`blur(${p}px)`}],{duration:c,easing:f,fill:"forwards"}),v=o.animate([{transform:`translateY(-${h}px)`,opacity:.9,filter:`blur(${p}px)`},{transform:"translateY(0)",opacity:1,filter:"blur(0)"}],{duration:d,easing:g,fill:"forwards"}),y=window.setTimeout(()=>{x.cancel(),v.cancel(),Bu.delete(t),t.classList.remove("is-clearing"),s.textContent="",El.delete(t),Zd(t)},Math.max(l,c,d));El.set(t,y),Bu.set(t,[x,v])}function Pv({className:e,showTrigger:t=!1,showClear:n=!1,startAddon:s,size:o,...r}){const a=o??"default",l=m.useRef(null);return m.useLayoutEffect(()=>{l.current&&Zd(l.current);const c=window.requestAnimationFrame(()=>{l.current&&Zd(l.current)});return()=>window.cancelAnimationFrame(c)}),i.jsxs("div",{ref:l,className:"t-clear autocomplete-clear-dissolve relative w-full",onInput:c=>Zd(c.currentTarget),children:[s&&i.jsx("div",{"aria-hidden":"true",className:"[&_svg]:-mx-0.5 pointer-events-none absolute inset-y-0 start-px z-10 flex items-center ps-[calc(--spacing(3)-1px)] opacity-80 has-[+[data-size=sm]]:ps-[calc(--spacing(2.5)-1px)] [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4","data-slot":"autocomplete-start-addon",children:s}),i.jsx(BL,{className:W(s&&"data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7.5)-1px)] *:data-[slot=autocomplete-input]:ps-[calc(--spacing(8.5)-1px)] sm:data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7)-1px)] sm:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(8)-1px)]",a==="sm"?"has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-6.5":"has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-7",e),"data-slot":"autocomplete-input",render:i.jsx(Zt,{size:a}),...r}),i.jsx("div",{"aria-hidden":"true",className:W("t-clear-mirror px-[calc(--spacing(3)-1px)] text-base sm:text-sm",a==="sm"&&"px-[calc(--spacing(2.5)-1px)]",s&&(a==="sm"?"ps-[calc(--spacing(7.5)-1px)] sm:ps-[calc(--spacing(7)-1px)]":"ps-[calc(--spacing(8.5)-1px)] sm:ps-[calc(--spacing(8)-1px)]"))}),i.jsx("div",{"aria-hidden":"true",className:W("t-clear-placeholder px-[calc(--spacing(3)-1px)] text-base text-muted-foreground/72 opacity-0 sm:text-sm",a==="sm"&&"px-[calc(--spacing(2.5)-1px)]",s&&(a==="sm"?"ps-[calc(--spacing(7.5)-1px)] sm:ps-[calc(--spacing(7)-1px)]":"ps-[calc(--spacing(8.5)-1px)] sm:ps-[calc(--spacing(8)-1px)]")),children:r.placeholder}),i.jsx("div",{"aria-hidden":"true",className:"t-clear-glow"}),t&&i.jsx(BQ,{className:W("-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",a==="sm"?"end-0":"end-0.5"),children:i.jsx(a_,{})}),n&&i.jsx(HQ,{className:W("-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",a==="sm"?"end-0":"end-0.5"),children:i.jsx(dn,{})})]})}function QD({className:e,children:t,sideOffset:n=4,zIndex:s,...o}){return i.jsx(VL,{children:i.jsx($L,{className:"z-[55] select-none",style:s?{zIndex:s}:void 0,"data-slot":"autocomplete-positioner",sideOffset:n,children:i.jsx("span",{className:W("relative flex max-h-full origin-(--transform-origin) rounded-lg border bg-popover bg-clip-padding transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-lg has-data-starting-style:scale-98 has-data-starting-style:opacity-0 dark:not-in-data-[slot=group]:bg-clip-border",e),children:i.jsx(WL,{className:"flex max-h-[min(var(--available-height),23rem)] w-(--anchor-width) max-w-(--available-width) flex-col","data-slot":"autocomplete-popup",...o,children:t})})})})}function Av({className:e,children:t,...n}){return i.jsx(MQ,{className:W("flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",e),"data-slot":"autocomplete-item",...n,children:t})}function GQ({className:e,...t}){return i.jsx(PQ,{className:W("[[role=group]+&]:mt-1.5",e),"data-slot":"autocomplete-group",...t})}function FQ({className:e,...t}){return i.jsx(AQ,{className:W("px-2 py-1.5 font-medium text-muted-foreground text-xs",e),"data-slot":"autocomplete-group-label",...t})}function Mv({className:e,...t}){return i.jsx(RQ,{className:W("not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",e),"data-slot":"autocomplete-empty",...t})}function Rv({className:e,...t}){return i.jsx(UL,{scrollbarGutter:!0,scrollFade:!0,children:i.jsx(KL,{className:W("not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3",e),"data-slot":"autocomplete-list",...t})})}function HQ({className:e,onClickCapture:t,onPointerDownCapture:n,...s}){return i.jsx(qL,{className:W("-translate-y-1/2 absolute end-0.5 top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-[color,background-color,box-shadow,opacity] pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",e),"data-slot":"autocomplete-clear",onClickCapture:o=>{t?.(o),o.defaultPrevented||zQ(o.currentTarget)},onPointerDownCapture:o=>{n?.(o);const r=o.currentTarget.closest(".t-clear")?.querySelector("input");!o.defaultPrevented&&document.activeElement===r&&o.preventDefault()},...s,children:i.jsx(dn,{})})}function BQ({className:e,...t}){return i.jsx(_Q,{className:e,"data-slot":"autocomplete-trigger",...t})}const eE=m.createContext({inputRef:null}),tE=YL,VQ=XL;function $Q({className:e,...t}){return i.jsx(QL,{className:W("fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",e),"data-slot":"command-dialog-backdrop",...t})}function WQ({className:e,...t}){return i.jsx(e5,{className:W("fixed inset-0 z-50 flex flex-col items-center px-4 py-[max(--spacing(4),4vh)] sm:py-[10vh]",e),"data-slot":"command-dialog-viewport",...t})}function nE({className:e,children:t,...n}){const s=m.useRef(null);return i.jsxs(VQ,{children:[i.jsx(JL,{}),i.jsx($Q,{}),i.jsx(WQ,{children:i.jsx(ZL,{className:W("-translate-y-[calc(1.25rem*var(--nested-dialogs))] relative row-start-2 flex max-h-100 min-h-0 w-full min-w-0 max-w-xl scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border bg-popover bg-clip-padding text-popover-foreground opacity-[calc(1-0.1*var(--nested-dialogs))] shadow-lg transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:bg-muted/50 before:shadow-[0_1px_--theme(--color-black/4%)] data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 **:data-[slot=scroll-area-viewport]:data-has-overflow-y:pe-1 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",e),"data-slot":"command-dialog-popup",initialFocus:s,...n,children:i.jsx(eE.Provider,{value:{inputRef:s},children:t})})})]})}function sE({autoHighlight:e="always",keepHighlight:t=!0,open:n=!0,...s}){return i.jsx(Ev,{autoHighlight:e,keepHighlight:t,open:n,...s})}function iE({className:e,placeholder:t=void 0,endAddon:n,...s}){const{inputRef:o}=m.useContext(eE);return i.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(Pv,{className:W("border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0",e),placeholder:t,ref:o,size:"lg",startAddon:i.jsx(si,{}),...s})}),n]})}function oE({className:e,...t}){return i.jsx(Rv,{className:W("not-empty:scroll-py-2 not-empty:p-2",e),"data-slot":"command-list",...t})}function rE({className:e,...t}){return i.jsx(Mv,{className:W("not-empty:py-6",e),"data-slot":"command-empty",...t})}function aE({className:e,...t}){return i.jsx("div",{className:"-mx-px relative min-h-0 rounded-t-xl border bg-popover bg-clip-padding shadow-xs [clip-path:inset(0_1px)] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",...t})}function Or({className:e,...t}){return i.jsx(GQ,{className:e,"data-slot":"command-group",...t})}function zr({className:e,...t}){return i.jsx(FQ,{className:e,"data-slot":"command-group-label",...t})}function cr({className:e,...t}){return i.jsx(Av,{className:W("py-1.5",e),"data-slot":"command-item",...t})}function JS({className:e,...t}){return i.jsx("span",{className:W("ms-auto font-medium text-muted-foreground/72 text-xs tracking-widest",e),"data-slot":"command-shortcut",...t})}function lE({className:e,...t}){return i.jsx("div",{className:W("flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] px-5 py-3 text-muted-foreground text-xs",e),"data-slot":"command-footer",...t})}const ZS=e=>e.locator.kind==="timeline"?`${e.chatId}:${e.locator.seq}`:`${e.chatId}:${e.locator.conversationId}:${e.locator.messageIndex}`;function cE({className:e}){const{t}=ne(),n=we(r=>r.keybindings),s=Fi(n)["search-workspace"],o=t("Search messages");return i.jsx("button",{type:"button",className:e,onClick:()=>ue.getState().setSearchOpen(!0),title:s?`${o} (${ti(s)})`:o,children:i.jsx(si,{className:"h-4 w-4"})})}function UQ(){const{t:e,locale:t}=ne(),n=ue(v=>v.searchOpen),s=ue(v=>v.setSearchOpen),o=ue(v=>v.bots),r=ue(v=>v.chats),[a,l]=m.useState(""),[c,d]=m.useState(),u=a.trim(),h=m.useMemo(()=>new Map(o.map(v=>[v.id,v])),[o]),p=m.useMemo(()=>new Map(r.map(v=>[v.id,v])),[r]),f=c?.key===u?c:void 0;m.useEffect(()=>{n||(l(""),d(void 0))},[n]),m.useEffect(()=>{if(!n||!u)return;let v=!1;const y=window.setTimeout(()=>{window.electronAPI.bots.search({query:u}).then(b=>{v||d(b.ok?{key:u,hits:b.hits,truncated:b.truncated}:{key:u,hits:[],truncated:!1})}).catch(()=>{v||d({key:u,hits:[],truncated:!1})})},150);return()=>{v=!0,window.clearTimeout(y)}},[n,u]);const g=v=>{v.key==="Escape"&&(v.preventDefault(),v.stopPropagation(),s(!1))},x=Date.now();return i.jsx(tE,{open:n,onOpenChange:s,children:i.jsx(nE,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:g,children:i.jsxs(sE,{children:[i.jsx(iE,{placeholder:e("Search group and direct messages…"),value:a,onChange:v=>l(v.currentTarget.value),onKeyDown:v=>{g(v);const y=f?.hits[0];v.key==="Enter"&&!v.nativeEvent.isComposing&&y&&!document.querySelector('[data-slot="command-dialog-popup"] [data-highlighted]')&&(v.preventDefault(),ue.getState().focusHit(y,u))}}),i.jsxs(aE,{children:[u&&f&&f.hits.length===0&&i.jsx(rE,{children:e("No matching messages")}),i.jsxs(oE,{children:[f?.hits.map(v=>{const y=p.get(v.chatId),b=(y?.members??[]).map(_=>h.get(_)).filter(_=>_!==void 0),w=v.speaker.kind==="human"?e("You"):h.get(v.speaker.botId)?.name??e("Deleted member"),C=v.locator.kind==="session"&&!v.locator.current?` · ${e("History")}`:"";return i.jsxs(cr,{value:ZS(v),className:"items-start gap-2.5",onClick:()=>ue.getState().focusHit(v,u),children:[i.jsx("span",{className:"mt-0.5 shrink-0",children:v.chatKind==="direct"?i.jsx(tn,{bot:b[0]}):i.jsx(ul,{bots:b})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-xs",children:[i.jsx("span",{className:"truncate font-medium",children:y?Cs(y,o,e):e("Deleted chat")}),i.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[w,C]})]}),i.jsx("p",{className:"line-clamp-2 break-words text-muted-foreground text-xs",children:YZ(v.snippet,v.ranges).map((_,N)=>_.match?i.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:_.text},N):i.jsx("span",{children:_.text},N))})]}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:v.at?$o(v.at,t,x):""})]},ZS(v))}),f?.truncated&&i.jsx("p",{className:"px-2 py-1.5 text-center text-muted-foreground text-xs",children:e("Showing the latest {{n}} matches",{n:f.hits.length})})]})]}),i.jsxs(lE,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(l_,{children:[i.jsx(di,{children:"↑"}),i.jsx(di,{children:"↓"})]}),e("Navigate")]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(di,{children:"↵"}),e("Open")]})]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(di,{children:"esc"}),e("Close")]})]})]})})})}function KQ({chat:e,onOpenChange:t}){const{t:n}=ne(),s=ue(f=>f.bots),o=ue(f=>f.chats),r=we(f=>f.projects),[a,l]=m.useState(""),[c,d]=m.useState(!1);if(m.useEffect(()=>{if(!e)return;const f=o.filter(g=>g.kind==="group").map(g=>g.title);l(t5(n("{{title}} copy",{title:Cs(e,s,n)}),f)),d(!1)},[e?.id]),!e)return null;const u=f=>s.find(g=>g.id===f)?.name??"—",h=`${e.routing.mode==="smart"?n("Smart pick"):n("Group owner replies")} · ${n("Relay {{hops}} · {{turns}} replies each",{hops:e.routing.maxHops,turns:e.routing.maxTurnsPerBot})}`,p=async()=>{const f=a.trim();if(f){d(!0);try{const g=await window.electronAPI.bots.cloneChat({chatId:e.id,title:f});if(!g.ok){ze({type:"error",title:Is(g.error,n)});return}const x=ue.getState();x.upsertChat(g.chat),x.setView({kind:"chat",chatId:g.chat.id}),x.loadLatest(g.chat.id),ze({type:"success",title:n("Cloned. The chat history is empty.")}),t(!1)}finally{d(!1)}}};return i.jsx(xn,{open:!0,onOpenChange:t,children:i.jsxs(vn,{className:"max-w-md",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:n("Clone group chat")}),i.jsx(Rs,{children:n("Copies the setup of “{{title}}”. The original stays as is; replies in progress are not stopped.",{title:Cs(e,s,n)})})]}),i.jsxs(An,{className:"space-y-4 text-sm",children:[i.jsxs("div",{children:[i.jsx(Yt,{children:n("Group name")}),i.jsx(Zt,{value:a,autoFocus:!0,onChange:f=>l(f.target.value),onKeyDown:f=>{f.nativeEvent.isComposing||c||f.key==="Enter"&&p()}})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(Yt,{children:n("Will copy")}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Members"),":"]}),e.members.map(u).join("、")]}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Owner"),":"]}),u(e.bossBotId)]}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Routing"),":"]}),h]}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Workspace"),":"]}),e.workspace.kind==="project"?n("Same project: {{name}}",{name:Jj(e,r,s,n)}):n("A new empty folder, separate from the original")]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(Yt,{children:n("Not copied")}),i.jsx("p",{className:"text-muted-foreground",children:n("Chat history, group notes, routines, task board and group memory")})]})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsx(me,{size:"sm",disabled:!a.trim()||c,onClick:()=>{p()},children:n("Clone")})]})]})})}const ir="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function qQ({width:e,onCollapse:t,onNewMember:n,onNewGroup:s,onNewTeam:o,onStartFromGoal:r}){const{t:a,locale:l}=ne(),c=[{label:a("Start from a goal"),icon:Ma,onClick:r},{label:a("New member"),icon:ql,onClick:n},{label:a("New group chat"),icon:fa,onClick:s},{label:a("Create team from template"),icon:Uf,onClick:o}],d=ue(B=>B.bots),u=ue(B=>B.chats),h=ue(B=>B.queue),p=ue(B=>B.sessions),f=ue(B=>B.delegations),g=ue(B=>B.timelines),x=ue(B=>B.reads),v=ue(B=>B.view),y=ue(B=>B.setView),b=ue(B=>B.openDirect),w=ue(B=>B.upsertChat),C=ue(B=>B.upsertBot),[_,N]=m.useState(!1),[k,S]=m.useState(""),[A,T]=m.useState(null),[I,P]=m.useState(null),D=m.useMemo(()=>new Map(d.map(B=>[B.id,B])),[d]),O=m.useMemo(()=>Object.fromEntries(d.map(B=>[B.id,B.name])),[d]),z=m.useMemo(()=>n_(p,s_(u,f)),[p,u,f]),R=m.useMemo(()=>{const B=new Set,Te=new Set;for(const We of f)zl(We.state)&&(We.chatId&&B.add(We.chatId),Te.add(We.targetBotId));return{chatIds:B,botIds:Te}},[f]),$=m.useMemo(()=>n5(u.map(B=>{const Te=qg(B,{sessions:p,timeline:g[B.id],queue:h,names:O});return{chat:B,summary:{...Te,running:Te.running||(B.kind==="group"?R.chatIds.has(B.id):R.botIds.has(B.members[0])),pending:z.filter(We=>We.chatId===B.id).length}}}),x),[u,p,g,h,O,z,R,x]),X=$.filter(B=>!B.chat.archivedAt),H=s5(X.filter(B=>B.chat.kind==="group"&&B.chat.settledAt===void 0)),te=new Map(X.filter(B=>B.chat.kind==="direct").map(B=>[B.chat.members[0],B])),V=d.filter(B=>B.archivedAt===void 0&&te.get(B.id)?.chat.settledAt===void 0).map(B=>({bot:B,row:te.get(B.id)})).sort((B,Te)=>{const We=Number(Te.row?.chat.pinned??!1)-Number(B.row?.chat.pinned??!1),kt=(B.row?.chat.pinOrder??Number.POSITIVE_INFINITY)-(Te.row?.chat.pinOrder??Number.POSITIVE_INFINITY);return We||(B.row?.chat.pinned&&kt?kt:0)||(Te.row?.summary.activityAt??Te.bot.updatedAt)-(B.row?.summary.activityAt??B.bot.updatedAt)}),Y=X.filter(B=>B.chat.settledAt!==void 0&&(B.chat.kind==="group"||D.get(B.chat.members[0])?.archivedAt===void 0)).sort((B,Te)=>(Te.chat.settledAt??0)-(B.chat.settledAt??0)),q=H.filter(B=>B.chat.pinned).map(B=>B.chat.id),ee=V.flatMap(({row:B})=>B?.chat.pinned?[B.chat.id]:[]),[ge,Ce]=m.useState(null),[Re,fe]=m.useState(!0),U=$.filter(B=>B.chat.archivedAt!==void 0),oe=d.filter(B=>B.archivedAt!==void 0),Se=U.length+oe.length,G=k.trim().toLowerCase(),Q=(...B)=>!G||B.some(Te=>Te.toLowerCase().includes(G)),ae=U.filter(({chat:B,summary:Te})=>Q(Cs(B,d,a),Te.preview??"")).sort((B,Te)=>(Te.chat.archivedAt??0)-(B.chat.archivedAt??0)),Z=oe.filter(B=>Q(B.name,B.title,B.scope)).sort((B,Te)=>(Te.archivedAt??0)-(B.archivedAt??0)),ce=Zg(),De=v?.kind==="chat"?v.chatId:null,Oe=async(B,Te)=>{const We=await window.electronAPI.bots.updateChat({chatId:B.id,...Te});We.ok?w(We.chat):ze({type:"error",title:Is(We.error,a)})},Ne=B=>Oe(B,B.pinned?{pinned:!1}:{pinned:!0,pinOrder:Math.max(-1,...u.filter(Te=>Te.pinned).map(Te=>Te.pinOrder??0))+1}),Ze=(B,Te,We)=>{const kt=Object.fromEntries(u.map(Gt=>[Gt.id,Gt.pinOrder]));for(const Gt of r5(B,Te,We,kt)){const de=u.find(mt=>mt.id===Gt.chatId);de&&Oe(de,{pinOrder:Gt.pinOrder})}},bt=(B,Te)=>{const We=Te.indexOf(B.id),kt=$.find(Gt=>Gt.chat.id===B.id)?.summary;return{onSettle:()=>{Oe(B,{settled:B.settledAt===void 0})},onSnooze:Gt=>{Oe(B,{snoozedUntil:Gt})},onMarkUnread:kt&&De!==B.id&&!sl(kt.marker,x[kt.key])&&i5(kt.marker)!==void 0?()=>ue.getState().markUnread(B.id):void 0,onMoveUp:We>0?()=>Ze(Te,B.id,We-1):void 0,onMoveDown:We>=0&&We<Te.length-1?()=>Ze(Te,B.id,We+1):void 0}},Ut=(B,Te)=>B?.pinned?{draggable:!0,onDragStart:We=>{We.dataTransfer.effectAllowed="move",Ce(B.id)},onDragEnd:()=>Ce(null),onDragOver:We=>{ge&&ge!==B.id&&Te.includes(ge)&&We.preventDefault()},onDrop:We=>{We.preventDefault(),ge&&Te.includes(ge)&&Ze(Te,ge,Te.indexOf(B.id)),Ce(null)}}:{},Et=async(B,Te)=>{const We=await window.electronAPI.bots.archive(B.id,Te);We.ok?C(We.bot):ze({type:"error",title:We.error})},_t=B=>B?B.running?a("Working"):B.queued?a("Queued"):B.activityAt?$o(B.activityAt,l):null:null;return i.jsxs("aside",{className:"flex shrink-0 flex-col overflow-hidden border-r bg-background",style:{width:e},children:[i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pt-2 pb-2",children:[i.jsx(hf,{title:a("Group chats"),onAdd:s,addLabel:a("New group chat")}),H.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No group chats yet")}),H.map(({chat:B,summary:Te})=>i.jsx(ff,{chat:B,onPin:()=>{Ne(B)},onArchive:()=>{Oe(B,{archived:!0})},onDelete:()=>T(B),onClone:()=>P(B),manage:bt(B,q),children:i.jsx(pf,{...Ut(B,q),active:De===B.id,avatar:i.jsx(ul,{bots:B.members.map(We=>D.get(We)),busy:Te.running}),title:Cs(B,d,a),pinned:B.pinned,meta:_t(Te),preview:Te.preview,unread:sl(Te.marker,x[Te.key]),pending:Te.pending,onClick:()=>y({kind:"chat",chatId:B.id})})},B.id)),i.jsx(hf,{title:a("Members"),onAdd:n,addLabel:a("New member")}),V.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No members yet")}),V.map(({bot:B,row:Te})=>i.jsx(ff,{chat:Te?.chat,onPin:Te?()=>{Ne(Te.chat)}:void 0,onArchive:Te?()=>{Oe(Te.chat,{archived:!0})}:void 0,onArchiveMember:()=>{Et(B,!0)},manage:Te?bt(Te.chat,ee):void 0,children:i.jsx(pf,{...Ut(Te?.chat,ee),active:!!(Te&&De===Te.chat.id),avatar:i.jsx(tn,{bot:B,busy:Te?.summary.running||R.botIds.has(B.id)}),title:B.name,pinned:Te?.chat.pinned,meta:R.botIds.has(B.id)?a("Working"):_t(Te?.summary),preview:Te?.summary.preview||B.title||B.scope,unread:!!(Te&&sl(Te.summary.marker,x[Te.summary.key])&&De!==Te.chat.id),pending:Te?.summary.pending??0,onClick:()=>{b(B.id)}})},B.id)),Y.length>0&&i.jsx(hf,{title:`${a("Settled")} · ${Y.length}`,onToggle:()=>fe(B=>!B)}),Re&&Y.map(({chat:B,summary:Te})=>{const We=B.kind==="direct"?D.get(B.members[0]):void 0;return i.jsx(ff,{chat:B,onPin:()=>{Ne(B)},onArchive:()=>{Oe(B,{archived:!0})},onClone:B.kind==="group"?()=>P(B):void 0,manage:bt(B,[]),children:i.jsx(pf,{className:"opacity-75",active:De===B.id,avatar:We?i.jsx(tn,{bot:We,busy:Te.running}):i.jsx(ul,{bots:B.members.map(kt=>D.get(kt)),busy:Te.running}),title:We?We.name:Cs(B,d,a),meta:B.snoozedUntil!==void 0?a("Remind {{time}}",{time:$o(B.snoozedUntil,l)}):_t(Te),preview:Te.preview,unread:sl(Te.marker,x[Te.key])&&(B.kind==="group"||De!==B.id),pending:Te.pending,onClick:()=>We?void b(We.id):y({kind:"chat",chatId:B.id})})},B.id)})]}),i.jsxs("div",{className:"@container flex shrink-0 items-center justify-between border-t p-2",children:[t?i.jsx("button",{type:"button",onClick:t,className:ir,title:a("Collapse sidebar"),children:i.jsx(Kx,{className:"h-4 w-4"})}):i.jsx("span",{}),i.jsxs("div",{className:"flex items-center",children:[i.jsx(cE,{className:ir}),c.map(({label:B,icon:Te,onClick:We})=>i.jsx("button",{type:"button",className:W(ir,"hidden @min-[18.5rem]:flex"),onClick:We,title:B,children:i.jsx(Te,{className:"h-4 w-4"})},B)),i.jsxs($i,{children:[i.jsx(Wi,{className:W(ir,"@min-[18.5rem]:hidden"),title:a("More actions"),children:i.jsx(Dh,{className:"h-4 w-4"})}),i.jsx(Ui,{align:"end",side:"top",children:c.map(({label:B,icon:Te,onClick:We})=>i.jsxs(mn,{onClick:We,children:[i.jsx(Te,{}),B]},B))})]}),(ce>0||v?.kind==="inbox")&&i.jsxs("button",{type:"button",className:W(ir,v?.kind==="inbox"&&"bg-brand/10 text-foreground hover:bg-brand/10 dark:bg-brand/15 dark:hover:bg-brand/15"),onClick:()=>y({kind:"inbox"}),title:a("Inbox"),children:[i.jsx(Wx,{className:"h-4 w-4"}),ce>0&&i.jsx(Xh,{count:ce,className:"-top-0.5 -right-1 absolute"})]}),Se>0&&i.jsx("button",{type:"button",className:ir,onClick:()=>{S(""),N(!0)},title:`${a("Archived")} (${Se})`,children:i.jsx(Oi,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:ir,onClick:()=>{window.electronAPI.window.openSettings()},title:a("Settings"),children:i.jsx(mi,{className:"h-4 w-4"})})]})]}),i.jsx(xn,{open:_,onOpenChange:N,children:i.jsxs(vn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(bn,{children:[i.jsxs(wn,{className:"flex items-baseline gap-2",children:[a("Archived"),i.jsx("span",{className:"font-sans text-muted-foreground text-sm tabular-nums",children:Se})]}),i.jsxs(uh,{"data-size":"sm",className:"mt-1",children:[i.jsx(hh,{children:i.jsx(si,{})}),i.jsx(ph,{value:k,placeholder:a("Search conversations..."),onChange:B=>S(B.target.value)})]})]}),i.jsxs(An,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[ae.length+Z.length===0&&i.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:k.trim()?a("No matching conversations"):a("Nothing archived")}),ae.length>0&&i.jsx(QS,{title:a("Chat threads"),count:ae.length,children:ae.map(({chat:B,summary:Te})=>i.jsx(eC,{avatar:B.kind==="group"?i.jsx(ul,{bots:B.members.map(We=>D.get(We))}):i.jsx(tn,{bot:D.get(B.members[0])}),title:Cs(B,d,a),preview:Te.preview,onOpen:()=>{y({kind:"chat",chatId:B.id}),N(!1)},onRestore:()=>{Oe(B,{archived:!1})},onDelete:B.kind==="group"?()=>T(B):void 0},B.id))}),Z.length>0&&i.jsx(QS,{title:a("Members"),count:Z.length,children:Z.map(B=>i.jsx(eC,{avatar:i.jsx(tn,{bot:B}),title:B.name,preview:B.title||B.scope,onRestore:()=>{Et(B,!1)}},B.id))})]})]})}),i.jsx(gs,{open:A!==null,onOpenChange:B=>!B&&T(null),title:a("Delete group chat?"),description:a("The group timeline and its standalone workspace are deleted. Member sessions stay readable in their history."),confirmLabel:a("Delete"),onConfirm:()=>{const B=A;T(null),B&&window.electronAPI.bots.deleteChat(B.id).then(Te=>{Te.ok?(De===B.id&&y(null),ue.getState().refreshChats()):ze({type:"error",title:Is(Te.error,a)})})}}),i.jsx(KQ,{chat:I,onOpenChange:B=>!B&&P(null)})]})}function Xh({count:e,className:t}){return i.jsx("span",{className:W("min-w-4 rounded-full bg-destructive px-1 text-center font-medium text-[10px] text-white leading-4",t),children:e>99?"99+":e})}function QS({title:e,count:t,children:n}){return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 pr-0.5 pl-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate py-1 font-medium text-[10px] text-muted-foreground uppercase tracking-wide",children:e}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:t})]}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:n})]})}function eC({avatar:e,title:t,preview:n,onOpen:s,onRestore:o,onDelete:r}){const{t:a}=ne(),l="shrink-0 rounded p-1 text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground group-hover:opacity-100";return i.jsxs("div",{className:"group flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/60",children:[i.jsxs("button",{type:"button",disabled:!s,onClick:s,className:"flex min-w-0 flex-1 items-center gap-2.5 text-left disabled:cursor-default",children:[e,i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-sm",children:t}),n&&i.jsx("span",{className:"block truncate text-muted-foreground text-xs",children:n})]})]}),i.jsx("button",{type:"button",className:l,onClick:o,title:a("Unarchive"),children:i.jsx(Kl,{className:"h-3.5 w-3.5"})}),r&&i.jsx("button",{type:"button",className:W(l,"hover:text-destructive"),onClick:r,title:a("Delete"),children:i.jsx(Vs,{className:"h-3.5 w-3.5"})})]})}function hf({title:e,onAdd:t,addLabel:n,onToggle:s}){return i.jsxs("div",{className:"flex items-center justify-between px-4 pt-3 pb-1 text-[11px] text-muted-foreground",children:[s?i.jsx("button",{type:"button",onClick:s,className:"hover:text-foreground",children:e}):i.jsx("span",{children:e}),t&&i.jsx("button",{type:"button",onClick:t,title:n,"aria-label":n,className:"rounded p-0.5 transition-colors hover:bg-muted hover:text-foreground",children:i.jsx(as,{className:"h-3.5 w-3.5"})})]})}function pf({active:e,avatar:t,title:n,pinned:s,meta:o,preview:r,unread:a,pending:l=0,action:c,className:d,...u}){return i.jsxs("div",{role:"button",tabIndex:0,...u,onKeyDown:h=>{h.key==="Enter"&&u.onClick?.(h)},className:W("mx-1.5 flex cursor-default items-center gap-2.5 rounded-lg px-2.5 py-1.5 transition-colors",e?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted",d),children:[t,i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"min-w-0 truncate font-medium text-sm",children:n}),s&&i.jsx(hi,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"flex-1"}),l>0?i.jsx(Xh,{count:l}):o&&i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:o})]}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",children:r}),a&&i.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-info"}),c&&i.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),c.onClick()},className:"shrink-0 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-background hover:text-foreground",children:c.label})]})]})]})}function ff({chat:e,children:t,onPin:n,onArchive:s,onDelete:o,onArchiveMember:r,onClone:a,manage:l}){const{t:c}=ne(),d=u=>l?.onSnooze(o5(Date.now())[u]);return i.jsxs(go,{children:[i.jsx(xo,{render:t}),i.jsxs(vo,{className:"min-w-40",children:[n&&i.jsxs($t,{onClick:n,children:[e?.pinned?i.jsx(Tu,{}):i.jsx(hi,{}),e?.pinned?c("Unpin"):c("Pin")]}),l?.onMoveUp&&i.jsxs($t,{onClick:l.onMoveUp,children:[i.jsx(fc,{}),c("Move up")]}),l?.onMoveDown&&i.jsxs($t,{onClick:l.onMoveDown,children:[i.jsx(ah,{}),c("Move down")]}),l&&i.jsxs($t,{onClick:l.onSettle,children:[e?.settledAt!==void 0?i.jsx(da,{}):i.jsx(zg,{}),e?.settledAt!==void 0?c("Back to in progress"):c("Settle")]}),l&&i.jsxs(c_,{children:[i.jsxs(d_,{children:[i.jsx(T$,{}),c("Remind me later")]}),i.jsxs(u_,{className:"min-w-36",children:[i.jsx($t,{onClick:()=>d("hour"),children:c("In 1 hour")}),i.jsx($t,{onClick:()=>d("later"),children:c("In 3 hours")}),i.jsx($t,{onClick:()=>d("tomorrow"),children:c("Tomorrow 9:00")})]})]}),l?.onMarkUnread&&i.jsxs($t,{onClick:l.onMarkUnread,children:[i.jsx(J6,{}),c("Mark as unread")]}),a&&i.jsxs($t,{onClick:a,children:[i.jsx(ih,{}),c("Clone group chat")]}),s&&i.jsxs($t,{onClick:s,children:[i.jsx(Oi,{}),c("Archive chat")]}),r&&i.jsxs($t,{onClick:r,children:[i.jsx(Kl,{}),c("Archive member")]}),o&&i.jsxs(i.Fragment,{children:[i.jsx(mh,{}),i.jsxs($t,{variant:"destructive",onClick:o,children:[i.jsx(Vs,{}),c("Delete group chat")]})]})]})]})}const YQ=30;function tC({onPick:e}){const{t,locale:n}=ne(),s=n==="zh"?"zh":"en",o=h_(),r=ue(C=>C.bots),[a,l]=m.useState(""),[c,d]=m.useState(!1),[u,h]=m.useState(null),[p,f]=m.useState(null),[g,x]=m.useState(""),v=async()=>{if(!(!a.trim()||c)){d(!0),h(null);try{const C=await window.electronAPI.bots.suggestGoal({goal:a.trim(),language:s,...r.length?{members:r.map(({id:_,name:N,title:k,scope:S})=>({id:_,name:N,title:k,scope:S}))}:{},templates:o.slice(0,YQ).map(({id:_,data:N})=>({id:_,title:N.title,summary:N.summary}))});if(!C.ok){h(qh(C,t));return}f(C.suggestion),x(C.suggestion.firstMessage)}finally{d(!1)}}},y=async C=>{if(!c){d(!0),h(null);try{await e(C)}catch{h(t("Could not open chat. Try again."))}finally{d(!1)}}};if(!p)return i.jsxs("div",{className:"w-full max-w-lg space-y-2 text-left",children:[i.jsx(ni,{value:a,autoFocus:!0,rows:3,placeholder:t("e.g. Track competitor news every week and send me a summary"),onChange:C=>l(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.metaKey||C.ctrlKey)&&v()}}),u&&i.jsx("p",{className:"text-destructive text-xs",children:u}),i.jsx("div",{className:"flex justify-end",children:i.jsxs(me,{size:"sm",disabled:!a.trim()||c,onClick:()=>{v()},children:[c?i.jsx(Xt,{className:"animate-spin"}):i.jsx(ii,{}),t("Recommend")]})})]});const b=p.kind==="team"?o.find(C=>C.id===p.templateId)?.data:void 0,w=p.kind==="existing"?r.find(C=>C.id===p.botId):p.kind==="member"?{...p.member,avatar:{color:rr[0]}}:void 0;return i.jsxs("div",{className:"w-full max-w-lg space-y-3 text-left",children:[i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("p",{className:"mb-2 flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(Ma,{className:"h-3.5 w-3.5"}),p.kind==="team"?t("Recommended: a team"):t("Recommended: one member")]}),w?i.jsxs("div",{className:"flex items-start gap-2.5",children:[i.jsx(tn,{bot:w}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("p",{className:"font-medium text-sm",children:[w.name,i.jsx("span",{className:"ml-2 font-normal text-muted-foreground text-xs",children:w.title})]}),w.scope&&i.jsx("p",{className:"text-muted-foreground text-xs",children:w.scope})]})]}):b&&i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"-space-x-1.5 flex",children:b.members.map(C=>i.jsx(tn,{size:"sm",bot:{name:C.name,avatar:{color:C.color}}},C.key))}),i.jsx("p",{className:"font-medium text-sm",children:b.title}),i.jsx("p",{className:"text-muted-foreground text-xs",children:b.summary})]}),p.reason&&i.jsx("p",{className:"mt-2 text-muted-foreground text-xs",children:p.reason})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("p",{className:"text-muted-foreground text-xs",children:t("First message (put into the input box, not sent)")}),i.jsx(ni,{value:g,rows:3,onChange:C=>x(C.target.value)})]}),u&&i.jsx("p",{className:"text-destructive text-xs",children:u}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs(me,{size:"sm",variant:"ghost",disabled:c,onClick:()=>{f(null),h(null)},children:[i.jsx(pc,{}),t("Back")]}),i.jsxs("div",{className:"flex gap-2",children:[p.kind==="existing"&&i.jsx(me,{size:"sm",variant:"outline",disabled:c,onClick:()=>{y({firstMessage:g})},children:t("Create new instead")}),i.jsx(me,{size:"sm",disabled:c||p.kind==="existing"&&!w,onClick:()=>{y(p.kind==="existing"?{firstMessage:g,botId:p.botId}:p.kind==="member"?{firstMessage:g,member:p.member}:{firstMessage:g,templateId:p.templateId})},children:p.kind==="existing"?t("Use this member"):p.kind==="member"?t("Create this member"):t("Create this team")})]})]})]})}const ad=e=>({...TD,name:"",title:"",scope:"",persona:"",color:e,engine:null});function XQ({open:e,onOpenChange:t,seed:n,onCreated:s}){const{t:o}=ne(),r=ue(P=>P.bots),a=a5(),l=m.useRef(null),[c,d]=m.useState({kind:"template",id:"pm"}),[u,h]=m.useState(()=>ad(rr[0])),[p,f]=m.useState(null),[g,x]=m.useState(null),[v,y]=m.useState(!1),[b,w]=m.useState(!1),[C,_]=m.useState(!1),N=()=>{d({kind:"blank"}),h(ad(rr[r.length%rr.length])),f(null),x(null)},k=P=>{if(!P)return N();const D=l5(P.data);d({kind:"template",id:P.id}),h({...TD,name:D.name??"",title:D.title??"",scope:D.scope??"",persona:D.persona??"",color:D.avatar?.color??rr[0],engine:null,approvalMode:D.approvalMode??"auto-edits",tools:D.tools??"all"}),f(null),x(null)};m.useEffect(()=>{e&&(n?(d({kind:"blank"}),h({...ad(rr[r.length%rr.length]),...n}),f(null),x(null)):k(a[0]),y(!1),w(!1),_(!1))},[e]);const S=P=>{h(D=>({...D,...P})),x(null)},A=async P=>{const D=new Uint8Array(await P.arrayBuffer()),O=CD(D)==="png",z=O?KJ(GS(D,"chara")??GS(D,"ccv3")??""):new TextDecoder().decode(D),R=z?ZJ(z):{ok:!1,error:"not-a-card"};if(!R.ok){x(R.error==="invalid-json"&&!O?o("This file is not valid JSON."):o("This file is not a SillyTavern character card."));return}const{color:$,memoryEnabled:X,...H}=R.draft;d({kind:"import"}),h({...ad($??u.color),...H,...X!==void 0?{memoryEnabled:X}:{}}),f(O?await Uj(P).catch(()=>null):null),y(!0),x(null)},T=Wg(u.name,r,o),I=async()=>{if(y(!0),T)return;const P=_D(u);if(!P.ok){x(o("Budget must be a positive number"));return}const D=kv(u);if(!D.ok){x(o("Check the per-turn token limit and delegation time limit"));return}w(!0);try{const O=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},...P.budget?{budget:P.budget}:{}});if(!O.ok){x(dl(O.reason,O.error,o));return}ue.getState().upsertBot(O.bot),p&&!await Wj(O.bot.id,p)&&ze({type:"error",title:o("Avatar update failed")}),t(!1);const z=await ue.getState().openDirect(O.bot.id);z&&s?.(z)}finally{w(!1)}};return i.jsx(xn,{open:e,onOpenChange:t,children:i.jsxs(vn,{className:"max-h-[85vh] max-w-3xl",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:o("New member")}),i.jsx(Rs,{children:o("Members have their own persona, model, tools and memory. Their name is how you @ them in groups.")})]}),i.jsxs(An,{className:"space-y-4",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsx(me,{size:"sm",variant:c.kind==="template"?"default":"outline",disabled:a.length===0,onClick:()=>k(a[0]),children:o("From template")}),i.jsx(me,{size:"sm",variant:c.kind==="blank"?"default":"outline",onClick:N,children:o("Blank")}),i.jsxs(me,{size:"sm",variant:c.kind==="import"?"default":"outline",onClick:()=>l.current?.click(),children:[i.jsx(Bg,{}),o("Import character card")]}),i.jsx("input",{ref:l,type:"file",accept:".json,.png,application/json,image/png",hidden:!0,onChange:P=>{const D=P.target.files?.[0];P.target.value="",D&&A(D)}})]}),c.kind==="template"&&i.jsxs("div",{className:"grid grid-cols-3 gap-2.5",children:[a.map(P=>i.jsxs("button",{type:"button",onClick:()=>k(P),className:W("flex flex-col items-start gap-1 rounded-xl border bg-card p-3 text-left transition-colors hover:bg-muted",c.id===P.id&&"ring-2 ring-info"),children:[i.jsx(tn,{bot:{name:P.data.title,avatar:{color:P.data.color}}}),i.jsx("span",{className:"font-medium text-sm",children:P.data.title}),i.jsx("span",{className:"text-muted-foreground text-xs",children:P.data.summary})]},P.id)),i.jsxs("button",{type:"button",onClick:N,className:"flex items-center justify-center gap-1 rounded-xl border border-dashed p-3 text-muted-foreground text-sm hover:bg-muted",children:[i.jsx(as,{className:"h-4 w-4"}),o("Blank member")]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx(Yt,{hint:o("Used for @ in groups; must be unique"),children:o("Name")}),i.jsx(Zt,{value:u.name,onChange:P=>S({name:P.target.value}),onBlur:()=>y(!0)}),v&&T&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:T})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:o("Title")}),i.jsx(Zt,{value:u.title,onChange:P=>S({title:P.target.value})})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:o("Model")}),i.jsx($j,{engine:u.engine,onChange:P=>S({engine:P}),zIndex:yn.DROPDOWN_IN_MODAL})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:o("Avatar color")}),i.jsxs("div",{className:"flex items-start gap-2.5",children:[i.jsx(tn,{bot:{name:u.name||"?",avatar:{color:u.color}},src:p??void 0,size:"md"}),i.jsxs("div",{className:"min-w-0 space-y-1.5",children:[i.jsx(Vj,{value:u.color,onChange:P=>S({color:P})}),i.jsx(ND,{nested:!0,hasImage:!!p,onPick:f,onRemove:()=>f(null)})]})]})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(Yt,{hint:o("Used for routing and the delegation directory"),children:o("Responsibilities")}),i.jsx(Zt,{value:u.scope,onChange:P=>S({scope:P.target.value})})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(Yt,{action:i.jsx(AD,{value:u,onApply:S}),children:o("Persona")}),i.jsx(ni,{rows:4,value:u.persona,onChange:P=>S({persona:P.target.value})})]}),i.jsxs("div",{className:"col-span-2 rounded-lg border",children:[i.jsxs("button",{type:"button",className:"flex w-full items-center gap-1.5 px-3 py-2 text-left text-sm","aria-expanded":C,onClick:()=>_(P=>!P),children:[i.jsx(un,{className:W("h-4 w-4 transition-transform",C&&"rotate-90")}),i.jsx("span",{className:"font-medium",children:o("Abilities")}),i.jsx("span",{className:"truncate text-muted-foreground text-xs",children:o("Tools, approval, skills, MCP, delegation and memory")})]}),C&&i.jsx("div",{className:"border-t px-3 py-3",children:i.jsx(ID,{value:u,onChange:S,profile:u,zIndex:yn.DROPDOWN_IN_MODAL})})]})]}),g&&i.jsx("p",{className:"text-destructive text-sm",children:g})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),i.jsxs(me,{size:"sm",disabled:b||v&&!!T,onClick:()=>{I()},children:[b&&i.jsx(Xt,{className:"animate-spin"}),o("Create and start chatting")]})]})]})})}function dE({projectId:e,onChange:t}){const{t:n}=ne(),s=we(p=>p.projects),o=we(p=>p.addProject),r=m.useMemo(()=>dh(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:Ns(f),detail:f.path,projectId:f.id})),...a.filter(f=>!p.has(f.path)).map(f=>({path:f.path,label:p_(f.path),detail:`${f.displayPath} · ${f.sourceName}`}))]},[r,a]),h=async p=>{d(p);const f=r.find(g=>g.path===p);if(f)return t(f.id);try{const g=await o(p);if(!g)throw new Error;t(g.id)}catch(g){ze({type:"error",title:n("Failed to add project"),description:g instanceof Error&&g.message||void 0})}};return i.jsxs(Ev,{value:c,onValueChange:(p,f)=>{d(p??""),f.reason==="item-press"&&p?h(p):e&&t("")},items:u,filter:(p,f)=>{if(!f)return!0;const g=f.toLowerCase();return[p.label,p.path,p.detail].some(x=>x.toLowerCase().includes(g))},itemToStringValue:p=>p.path,children:[i.jsxs("div",{className:"mt-2 flex w-full gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(Pv,{placeholder:n("Search Code projects or recent folders..."),showClear:!!c,showTrigger:!0})}),i.jsx(me,{type:"button",variant:"outline",onClick:()=>{window.electronAPI.dialog.selectDirectory().then(p=>{p&&h(p)})},children:n("Browse")})]}),i.jsxs(QD,{zIndex:yn.DROPDOWN_IN_MODAL,children:[i.jsx(Mv,{children:n("No matching projects found")}),i.jsx(Rv,{children:p=>i.jsxs(Av,{value:p,className:"gap-2",children:[i.jsx("span",{className:"shrink-0",children:p.label}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",title:p.path,children:p.detail}),!p.projectId&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:n("Add")})]},p.path)})]})]})}function JQ({open:e,onOpenChange:t}){const{t:n}=ne(),s=ue(I=>I.bots),o=m.useMemo(()=>s.filter(I=>I.archivedAt===void 0),[s]),r=dh(we(I=>I.projects)),[a,l]=m.useState(""),[c,d]=m.useState([]),[u,h]=m.useState(null),[p,f]=m.useState("project"),[g,x]=m.useState(""),[v,y]=m.useState(String(Ar.maxHops)),[b,w]=m.useState(String(Ar.maxTurnsPerBot)),[C,_]=m.useState(!1),[N,k]=m.useState(null);m.useEffect(()=>{e&&(l(""),d([]),h(null),f(r.length>0?"project":"chat-home"),x(r[0]?.id??""),y(String(Ar.maxHops)),w(String(Ar.maxTurnsPerBot)),_(!1),k(null))},[e]);const S=(I,P)=>{const D=P?[...c,I]:c.filter(O=>O!==I);d(D),D.includes(u??"")?!u&&D.length&&h(D[0]):h(D[0]??null)},A=c.length>=2&&u!==null&&(p==="chat-home"||!!g),T=async()=>{if(A){_(!0);try{const I=await window.electronAPI.bots.createChat({kind:"group",title:a.trim(),members:c,bossBotId:u,workspace:p==="project"?{kind:"project",projectId:g}:{kind:"chat-home"},routing:{maxHops:Math.round(Number(v))||Ar.maxHops,maxTurnsPerBot:Math.round(Number(b))||Ar.maxTurnsPerBot}});if(!I.ok){k(Is(I.error,n));return}const P=ue.getState();P.upsertChat(I.chat),P.setView({kind:"chat",chatId:I.chat.id}),P.loadLatest(I.chat.id),t(!1)}finally{_(!1)}}};return i.jsx(xn,{open:e,onOpenChange:t,children:i.jsxs(vn,{className:"max-h-[85vh] max-w-xl",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:n("New group chat")}),i.jsx(Rs,{children:n("One member replies at a time. Without @, the best-fit member is picked to reply.")})]}),i.jsxs(An,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Yt,{children:n("Group name")}),i.jsx(Zt,{value:a,onChange:I=>l(I.target.value)})]}),i.jsxs("div",{children:[i.jsx(Yt,{hint:n("Pick at least two, and one owner"),children:n("Members")}),o.length<2&&i.jsx("p",{className:"text-muted-foreground text-xs",children:n("Create at least two members first.")}),i.jsx("div",{className:"space-y-0.5",children:o.map(I=>{const P=c.includes(I.id);return i.jsxs("div",{className:"flex items-center gap-2.5 rounded-md px-1.5 py-1 hover:bg-muted",children:[i.jsx(gc,{checked:P,onCheckedChange:D=>S(I.id,D===!0)}),i.jsx(tn,{bot:I,size:"sm"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-sm",children:[I.name,I.title&&i.jsx("span",{className:"ml-1.5 text-muted-foreground text-xs",children:I.title})]}),P&&i.jsxs("label",{className:"flex shrink-0 items-center gap-1 text-muted-foreground text-xs",children:[i.jsx("input",{type:"radio",name:"group-owner",checked:u===I.id,onChange:()=>h(I.id),className:"accent-primary"}),n("Owner")]})]},I.id)})})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:n("Shared workspace")}),i.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[i.jsxs("button",{type:"button",onClick:()=>f("project"),className:W("rounded-xl border bg-card p-3 text-left disabled:opacity-50",p==="project"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:n("Based on a Code project")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:n("Members read and write directly in the project folder")})]}),i.jsxs("button",{type:"button",onClick:()=>f("chat-home"),className:W("rounded-xl border bg-card p-3 text-left",p==="chat-home"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:n("Standalone workspace")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:n("A new empty folder for this group, removed with the group")})]})]}),p==="project"&&i.jsx(dE,{projectId:g,onChange:x}),i.jsxs("div",{className:"mt-2 flex gap-2 rounded-lg border border-warning/40 bg-warning/8 px-3 py-2 text-xs",children:[i.jsx(fh,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-warning"}),i.jsx("span",{children:n("All members share this folder: anyone who can talk to a member can reach its contents through them. You can change it later in group info (members start new conversations).")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx(Yt,{children:n("@ relay limit (per message of yours)")}),i.jsx(Zt,{type:"number",min:1,max:20,value:v,onChange:I=>y(I.target.value)})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:n("Max replies per member")}),i.jsx(Zt,{type:"number",min:1,max:10,value:b,onChange:I=>w(I.target.value)})]})]}),N&&i.jsx("p",{className:"text-destructive text-sm",children:N})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsxs(me,{size:"sm",disabled:!A||C,onClick:()=>{T()},children:[C&&i.jsx(Xt,{className:"animate-spin"}),n("Create")]})]})]})})}const nC={skillIds:[],mcpServerIds:[]};function ZQ({open:e,onOpenChange:t,seedTemplateId:n,onCreated:s}){const{t:o,locale:r}=ne(),a=ue(Y=>Y.bots),l=h_(),c=dh(we(Y=>Y.projects)),d=m.useRef(null),[u,h]=m.useState(null),[p,f]=m.useState("chat-home"),[g,x]=m.useState(""),[v,y]=m.useState(!1),[b,w]=m.useState(null),[C,_]=m.useState({}),[N,k]=m.useState(null),[S,A]=m.useState(!1);m.useEffect(()=>{if(!e)return;h(null),x(c[0]?.id??""),y(!1),w(null),_({}),k(null);const Y=l.find(q=>q.id===n);Y&&T({team:L0(Y.data)})},[e]);const T=async Y=>{y(!0),w(null);try{const q=await window.electronAPI.bots.previewTeam(Y);if(!q.ok){w(c5(q.error,o));return}h({team:q.team,renamed:q.renamed,picked:q.team.members.map(ee=>ee.key)}),_({}),k(null),f(q.team.workspace==="project"&&c.length>0?"project":"chat-home")}finally{y(!1)}},I=Y=>h(q=>q&&{...q,team:Y(q.team)}),P=(Y,q)=>I(ee=>({...ee,members:ee.members.map(ge=>ge.key===Y?{...ge,...q}:ge)})),D=m.useMemo(()=>u?d5(u.team,u.picked):null,[u]),O=m.useMemo(()=>{const Y=new Map;if(!D)return Y;const q=[...a,...D.members.map(ee=>({id:`team:${ee.key}`,name:ee.name}))];for(const ee of D.members){const ge=Wg(ee.name,q,o,`team:${ee.key}`);ge&&Y.set(ee.key,ge)}return Y},[D,a,o]),z=D!==null&&O.size===0&&(p==="chat-home"||!!g)&&!v&&!S,R=Y=>C[Y]??nC,$=(Y,q)=>_(ee=>({...ee,[Y]:{...ee[Y]??nC,...q}})),X=async()=>{if(D){A(!0);try{const Y=r==="zh"?"zh":"en",q=await Promise.all(D.members.map(async U=>{try{const oe=await window.electronAPI.bots.suggestAbilities({name:U.name,title:U.title,scope:U.scope,persona:U.persona,language:Y});return{key:U.key,result:oe}}catch{return{key:U.key,result:null}}}));let ee=0,ge=0,Ce;const Re={...C},fe=new Map;for(const{key:U,result:oe}of q){if(!oe?.ok){ge++,oe&&!Ce&&(Ce=qh(oe,o));continue}const{suggestion:Se}=oe,G={};Se.tools&&(G.tools=Se.tools.value),Se.approvalMode&&(G.approvalMode=Se.approvalMode.value),Object.keys(G).length>0&&fe.set(U,G);const Q=Se.skillIds?.value??R(U).skillIds,ae=Se.mcpServerIds?.value??R(U).mcpServerIds;Re[U]={skillIds:[...Q],mcpServerIds:[...ae]},(Q.length+ae.length>0||fe.has(U))&&ee++}_(Re),fe.size>0&&I(U=>({...U,members:U.members.map(oe=>({...oe,...fe.get(oe.key)}))})),ge>0&&ze({type:"error",title:o("Suggestions failed for {{n}} members",{n:ge}),...Ce?{description:Ce}:{}}),ge<q.length&&ze({type:ee>0?"success":"info",title:ee>0?o("Configured abilities for {{n}} members",{n:ee}):o("Current abilities already match the suggestion.")})}finally{A(!1)}}},H=async()=>{if(!(!D||!z)){y(!0),w(null);try{const Y=Object.fromEntries(D.members.map(ge=>[ge.key,R(ge.key)]).filter(([,ge])=>ge.skillIds.length+ge.mcpServerIds.length>0)),q=await window.electronAPI.bots.createTeam({team:{...D,title:D.title.trim()},workspace:p==="project"?{kind:"project",projectId:g}:{kind:"chat-home"},...Object.keys(Y).length>0?{assets:Y}:{}});if(!q.ok){w(dl(q.error,Is(q.error,o),o));return}const ee=ue.getState();for(const ge of q.bots)ee.upsertBot(ge);ee.upsertChat(q.chat),ee.setView({kind:"chat",chatId:q.chat.id}),ee.loadLatest(q.chat.id),t(!1),s?.(q.chat.id)}finally{y(!1)}}},te=r==="zh"?"zh":"en",V=Y=>u?.team.members.find(q=>q.key===Y)?.name??Y;return i.jsx(xn,{open:e,onOpenChange:t,children:i.jsxs(vn,{className:"max-h-[85vh] max-w-2xl",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:o("Create team from template")}),i.jsx(Rs,{children:o("Creates the members and their group chat in one go. Members follow the default model; expand a member to set tools, approval, delegation, skills and MCP, or let AI set them.")})]}),i.jsxs(An,{className:"space-y-4",children:[u?i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx(Yt,{children:o("Group name")}),i.jsx(Zt,{value:u.team.title,onChange:Y=>{const q=Y.target.value;I(ee=>({...ee,title:q}))}})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[i.jsxs("span",{className:"flex items-baseline gap-2",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:o("Members")}),i.jsx("span",{className:"text-[11px] text-muted-foreground/70",children:o("Uncheck members you do not need; the owner stays")})]}),i.jsxs(me,{size:"xs",variant:"outline",disabled:!D||S||v,onClick:()=>{X()},children:[S?i.jsx(Xt,{className:"animate-spin"}):i.jsx(ii,{}),o("AI auto-configure")]})]}),i.jsx("div",{className:"space-y-1.5",children:u.team.members.map(Y=>{const q=u.picked.includes(Y.key),ee=Y.key===u.team.bossKey,ge=u.renamed.find(Se=>Se.key===Y.key),Ce=q?O.get(Y.key):void 0,Re=Y.delegation.canDelegateTo,fe=Re==="any"?[]:Re.filter(Se=>u.picked.includes(Se)),U=R(Y.key),oe=q&&N===Y.key;return i.jsxs("div",{className:W("flex items-start gap-2.5 rounded-lg border px-2.5 py-2",!q&&"opacity-60"),children:[i.jsx(gc,{className:"mt-1.5",checked:q,disabled:ee,onCheckedChange:Se=>h({...u,picked:Se===!0?[...u.picked,Y.key]:u.picked.filter(G=>G!==Y.key)})}),i.jsx(tn,{bot:Y,size:"sm"}),i.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Zt,{className:"h-7 w-36",value:Y.name,disabled:!q,onChange:Se=>{const G=Se.target.value;I(Q=>({...Q,members:Q.members.map(ae=>ae.key===Y.key?{...ae,name:G}:ae)}))}}),i.jsx("span",{className:"truncate text-muted-foreground text-xs",children:Y.title}),ee&&i.jsxs("span",{className:"flex shrink-0 items-center gap-0.5 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:[i.jsx(Zj,{className:"h-3 w-3"}),o("Owner")]})]}),i.jsx("p",{className:"text-muted-foreground text-xs",children:Y.scope}),ge&&ge.to===Y.name&&i.jsx("p",{className:"text-warning text-xs",children:o('"{{from}}" is taken, renamed to "{{to}}"',ge)}),Ce&&i.jsx("p",{className:"text-destructive text-xs",children:Ce}),i.jsxs("button",{type:"button",disabled:!q,onClick:()=>k(oe?null:Y.key),className:"flex items-start gap-1 text-left text-[11px] text-muted-foreground hover:text-foreground disabled:pointer-events-none",children:[oe?i.jsx($n,{className:"mt-px h-3 w-3 shrink-0"}):i.jsx(un,{className:"mt-px h-3 w-3 shrink-0"}),i.jsxs("span",{children:[Y.tools==="readonly"?o("Read-only"):o("All tools")," · ",o(Gl[Y.approvalMode].labelKey),fe.length>0&&` · ${o("Delegates to {{names}}",{names:fe.map(V).join(te==="zh"?"、":", ")})}`," · ",U.skillIds.length+U.mcpServerIds.length===0?o("No skills or MCP"):o("{{n}} skills · {{m}} MCP",{n:U.skillIds.length,m:U.mcpServerIds.length})]})]}),oe&&i.jsxs("div",{className:"space-y-3 rounded-lg bg-muted/40 p-2.5",children:[i.jsxs("div",{children:[i.jsx(Yt,{children:o("Tools")}),i.jsx(Vg,{value:Y.tools,options:[{value:"all",label:o("All tools")},{value:"readonly",label:o("Read-only")}],onChange:Se=>P(Y.key,{tools:Se})})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:o("Approval mode")}),i.jsx(Hj,{value:Y.approvalMode,onChange:Se=>P(Y.key,{approvalMode:Se}),zIndex:yn.DROPDOWN_IN_MODAL})]}),i.jsx(O0,{label:o("Can delegate to"),value:Y.delegation.canDelegateTo,options:u.picked.filter(Se=>Se!==Y.key),nameOf:V,onChange:Se=>P(Y.key,{delegation:{...Y.delegation,canDelegateTo:Se}})}),i.jsx(O0,{label:o("Accepts delegation from"),value:Y.delegation.acceptFrom,options:u.picked.filter(Se=>Se!==Y.key),nameOf:V,onChange:Se=>P(Y.key,{delegation:{...Y.delegation,acceptFrom:Se}})}),i.jsx(DD,{value:U,onChange:Se=>$(Y.key,Se)})]})]})]},Y.key)})}),!D&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:o("Keep the owner and at least one other member.")})]}),i.jsxs("div",{children:[i.jsx(Yt,{children:o("Shared workspace")}),i.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[i.jsxs("button",{type:"button",onClick:()=>f("chat-home"),className:W("rounded-xl border bg-card p-3 text-left",p==="chat-home"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:o("Standalone workspace")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:o("A new empty folder for this group, removed with the group")})]}),i.jsxs("button",{type:"button",onClick:()=>f("project"),className:W("rounded-xl border bg-card p-3 text-left disabled:opacity-50",p==="project"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:o("Based on a Code project")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:o("Members read and write directly in the project folder")})]})]}),p==="project"&&i.jsx(dE,{projectId:g,onChange:x}),i.jsxs("div",{className:"mt-2 flex gap-2 rounded-lg border border-info/40 bg-info/8 px-3 py-2 text-xs",children:[i.jsx(fh,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-info"}),i.jsx("span",{children:o(u.team.routing.mode==="smart"?"Without @, the best-fit member replies; @ relay limit {{n}}.":"Without @, the owner replies; @ relay limit {{n}}.",{n:u.team.routing.maxHops})})]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-3 gap-2.5",children:l.map(({id:Y,data:q})=>i.jsxs("button",{type:"button",disabled:v,onClick:()=>{T({team:L0(q)})},className:"flex flex-col items-start gap-1.5 rounded-xl border bg-card p-3 text-left transition-colors hover:bg-muted disabled:opacity-50",children:[i.jsx("div",{className:"-space-x-1.5 flex",children:q.members.map(ee=>i.jsx(tn,{size:"sm",bot:{name:ee.name,avatar:{color:ee.color}}},ee.key))}),i.jsx("span",{className:"font-medium text-sm",children:q.title}),i.jsx("span",{className:"text-muted-foreground text-xs",children:q.summary})]},Y))}),i.jsxs(me,{size:"sm",variant:"outline",disabled:v,onClick:()=>d.current?.click(),children:[i.jsx(Bg,{}),o("Import team (JSON)")]}),i.jsx("input",{ref:d,type:"file",accept:".json,application/json",hidden:!0,onChange:Y=>{const q=Y.target.files?.[0];Y.target.value="",q&&q.text().then(ee=>T({text:ee}))}})]}),b&&i.jsx("p",{className:"text-destructive text-sm",children:b})]}),i.jsxs(ls,{children:[u&&i.jsxs(me,{variant:"ghost",size:"sm",className:"mr-auto",onClick:()=>{h(null),w(null)},children:[i.jsx(pc,{}),o("Back")]}),i.jsx(me,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),u&&i.jsxs(me,{size:"sm",disabled:!z,onClick:()=>{H()},children:[v&&i.jsx(Xt,{className:"animate-spin"}),o("Create team")]})]})]})})}const Eo="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function QQ({sidebarWidth:e,collapsed:t,onToggleCollapse:n,onResize:s}){const o=gh()==="mobile",{t:r}=ne(),a=ue(D=>D.view),l=ue(D=>D.chats),c=ue(D=>D.bots),d=ue(D=>D.loaded),u=ue(D=>D.setView),[h,p]=m.useState(!1),[f,g]=m.useState(!1),[x,v]=m.useState(!1),[y,b]=m.useState(!1),[w,C]=m.useState(null),_=m.useRef(""),N=Zg(),k=a?.kind==="chat"?l.find(D=>D.id===a.chatId):void 0,S=k?.kind==="group"?s8(l,k):void 0;m.useEffect(()=>{d&&a?.kind==="chat"&&!k&&u(null)},[d,a,k,u]);const A=async D=>{if(D.botId){const O=ue.getState();if(!O.bots.some(R=>R.id===D.botId))throw new Error("Member not found");const z=await O.openDirect(D.botId);if(!z)throw new Error("Could not open chat");z0(z,D.firstMessage.trim()),b(!1);return}b(!1),C(D),_.current=D.firstMessage.trim(),D.templateId?v(!0):p(!0)},T=D=>{_.current&&z0(D,_.current),_.current=""},I=()=>{C(null),_.current="",p(!0)},P=()=>{C(null),_.current="",v(!0)};return i.jsxs(i.Fragment,{children:[t?i.jsxs("aside",{className:"flex w-12 shrink-0 flex-col items-center gap-1 border-r bg-background py-2",children:[i.jsx(cE,{className:Eo}),i.jsx("button",{type:"button",className:Eo,onClick:()=>b(!0),title:r("Start from a goal"),children:i.jsx(Ma,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:Eo,onClick:I,title:r("New member"),children:i.jsx(ql,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:Eo,onClick:()=>g(!0),title:r("New group chat"),children:i.jsx(fa,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:Eo,onClick:P,title:r("Create team from template"),children:i.jsx(Uf,{className:"h-4 w-4"})}),(N>0||a?.kind==="inbox")&&i.jsxs("button",{type:"button",className:W(Eo,a?.kind==="inbox"&&"bg-brand/10 text-foreground hover:bg-brand/10 dark:bg-brand/15 dark:hover:bg-brand/15"),onClick:()=>u({kind:"inbox"}),title:r("Inbox"),children:[i.jsx(Wx,{className:"h-4 w-4"}),N>0&&i.jsx(Xh,{count:N,className:"-top-0.5 -right-1 absolute"})]}),i.jsx("div",{className:"flex-1"}),i.jsx("button",{type:"button",className:Eo,onClick:()=>{window.electronAPI.window.openSettings()},title:r("Settings"),children:i.jsx(mi,{className:"h-4 w-4"})}),o&&i.jsx("button",{type:"button",className:Eo,onClick:n,title:r("Expand sidebar"),children:i.jsx(XN,{className:"h-4 w-4"})})]}):i.jsxs(i.Fragment,{children:[i.jsx(qQ,{width:e,onCollapse:o?n:void 0,onNewMember:I,onNewGroup:()=>g(!0),onNewTeam:P,onStartFromGoal:()=>b(!0)}),i.jsx(Du,{onResize:s})]}),a?.kind==="inbox"?i.jsx(bQ,{}):k?i.jsx(hQ,{chat:S??k,group:k},S?.id??k.id):i.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center justify-center gap-3 bg-background px-6 text-center",children:[i.jsx(Ws,{className:"h-8 w-8 text-muted-foreground"}),i.jsx("p",{className:"font-medium text-lg",children:r("Bot mode")}),i.jsx("p",{className:"max-w-md text-muted-foreground text-sm",children:c.length===0?r("Tell us in one sentence what you want done; we will recommend a member or a team and draft your first message."):r("Pick a member or a group chat on the left.")}),c.length===0&&d&&i.jsx(tC,{onPick:A}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(me,{size:"sm",variant:c.length===0?"outline":"default",onClick:I,children:[i.jsx(ql,{}),r("New member")]}),c.length>=2&&i.jsxs(me,{size:"sm",variant:"outline",onClick:()=>g(!0),children:[i.jsx(fa,{}),r("New group chat")]}),i.jsxs(me,{size:"sm",variant:"outline",onClick:P,children:[i.jsx(Uf,{}),r("Create team from template")]})]})]}),i.jsx(XQ,{open:h,onOpenChange:p,seed:w?.member,onCreated:T}),i.jsx(JQ,{open:f,onOpenChange:g}),i.jsx(UQ,{}),i.jsx(ZQ,{open:x,onOpenChange:v,seedTemplateId:w?.templateId,onCreated:T}),i.jsx(xn,{open:y,onOpenChange:b,children:i.jsxs(vn,{className:"max-w-xl",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:r("Start from a goal")}),i.jsx(Rs,{children:r("Tell us in one sentence what you want done; we will recommend a member or a team and draft your first message.")})]}),i.jsx(An,{className:"flex justify-center pb-4",children:y&&i.jsx(tC,{onPick:A})})]})})]})}const Ua=[{value:"code",label:"Code",Icon:Uo},{value:"bot",label:"Bot",Icon:u5}],eee={ArrowLeft:-1,ArrowUp:-1,ArrowRight:1,ArrowDown:1},tee={duration:.26,ease:[.22,1,.36,1]},nee={duration:.5,ease:[.34,1.36,.64,1]},see={duration:.18,ease:[.4,0,.2,1]};function iee({className:e}){const{t}=ne(),n=fo(h=>h.mode),s=fo(h=>h.setMode),o=Zg(),r=Fi(we(h=>h.keybindings))["toggle-app-mode"],a=r?`${t("Switch between Code and Bot")} (${ti(r)})`:void 0,l=_$()??!1,c=m.useId(),d=m.useRef({}),u=h=>{const p=eee[h.key];if(!p)return;h.preventDefault();const f=Ua.findIndex(x=>x.value===n),g=Ua[(f+p+Ua.length)%Ua.length].value;s(g),d.current[g]?.focus()};return i.jsx("div",{role:"radiogroup","aria-label":t("Switch mode"),onKeyDown:u,className:W("flex h-7 shrink-0 rounded-lg bg-muted/60 p-0.5 text-xs",e),children:Ua.map(({value:h,label:p,Icon:f})=>{const g=n===h,x=h==="bot"&&n==="code"&&o>0;return i.jsxs("button",{ref:v=>{d.current[h]=v},type:"button",role:"radio","aria-checked":g,tabIndex:g?0:-1,title:a,onClick:()=>s(h),className:W("relative flex items-center gap-1.5 rounded-md px-2.5 font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",g?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[g&&i.jsx(Os.span,{layoutId:c,"aria-hidden":!0,className:"absolute inset-0 rounded-md bg-background shadow-xs",transition:l?{duration:0}:ra}),i.jsx(f,{className:"relative h-3.5 w-3.5"}),i.jsx("span",{className:"relative",children:p}),i.jsx(vl,{children:x&&i.jsx(Os.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:tee,children:i.jsx(Os.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:see},transition:nee,children:i.jsx(Xh,{count:o,className:"block"})})})})]},h)})})}const sc="enso:open-chat-find";let cg;function uE(e){cg=e,window.dispatchEvent(new Event(sc))}function sC(){const e=cg;return cg=void 0,e}function oee({query:e,onQueryChange:t,current:n,total:s,onPrev:o,onNext:r,onClose:a}){const{t:l}=ne(),c=m.useRef(null);return m.useEffect(()=>{const d=()=>{c.current?.focus(),c.current?.select()};return d(),window.addEventListener(sc,d),()=>window.removeEventListener(sc,d)},[]),i.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-b px-3 py-1.5",children:[i.jsxs("div",{className:"relative min-w-0 flex-1",children:[i.jsx(si,{className:"pointer-events-none absolute top-1/2 left-2.5 z-10 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Zt,{ref:c,value:e,onChange:d=>t(d.target.value),onKeyDown:d=>{if(d.key==="Escape"){d.preventDefault(),a();return}d.key==="Enter"&&(d.preventDefault(),d.shiftKey?o():r())},placeholder:l("Search messages..."),className:"h-8 text-xs [&_input]:pl-8"})]}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs tabular-nums",children:s===0?l("No results"):`${n}/${s}`}),i.jsx(me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:o,"aria-label":l("Previous match"),children:i.jsx(f_,{className:"h-3.5 w-3.5"})}),i.jsx(me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:r,"aria-label":l("Next match"),children:i.jsx($n,{className:"h-3.5 w-3.5"})}),i.jsx(me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a,children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]})}function ree(e){const{t}=ne(),n=e?.startsWith("bot:")?e.slice(4):void 0,s=ue(a=>n?a.bots.find(l=>l.id===n)?.name:void 0),[o,r]=m.useState();if(m.useEffect(()=>{if(r(void 0),!e||!n||s)return;let a=!0;return window.electronAPI.agentRegistry.list().then(l=>{const c=Rj(l)?.candidates.find(d=>d.typeKey===e);a&&r(c?.displayName)}).catch(()=>{}),()=>{a=!1}},[e,n,s]),!!n)return s??o??t("Member")}function aee(e,t){return e?null:t?"empty":"hydrating"}function lee(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 cee(e){const t=e.activeId?e.conversations[e.activeId]:void 0;if(!t)return null;const n=t.activeTabId?e.conversations[t.activeTabId]??t:t;return{id:n.id,parentId:t.id,projectId:n.projectId,parentProjectId:t.projectId,status:n.status,spawning:n.spawning,started:n.started,sessionFile:n.sessionFile,parentStarted:t.started,parentStatus:t.status,parentSessionFile:t.sessionFile,parentWorktreeMissing:t.worktreeMissing,parentWorktreePath:t.worktree?.path,parentWorktreeBranch:t.worktree?.branch,lastProviderId:n.lastProviderId,lastModelId:n.lastModelId,parentLastProviderId:t.lastProviderId,parentLastModelId:t.lastModelId,reasoningEnabled:n.reasoningEnabled,thinkingLevel:n.thinkingLevel,presetId:n.presetId,approvalMode:n.approvalMode,autoRejectApprovals:n.autoRejectApprovals,draftText:n.draftText,draftImages:n.draftImages,draftAppend:n.draftAppend,commands:n.commands,compactionError:n.compactionError,agentType:n.agentType,parentHasRunningChild:Lg(t,e.conversations),retry:n.retry,pendingApprovals:n.pendingApprovals,pendingAsks:n.pendingAsks,backgroundTasks:n.backgroundTasks,subagents:n.subagents,queuedMessages:n.queuedMessages,goal:n.goal,planState:n.planState,rewinding:n.rewinding,restoringFiles:n.restoringFiles,childLockedProfileId:n.child?.lockedProfileId,displayedParentId:n.parentId,busy:m_(n)}}function dee(){const[e,t]=m.useState([]);return m.useEffect(()=>{let n=!0;const s=window.electronAPI.elevation.onChanged(o=>t(o));return window.electronAPI.elevation.pending().then(o=>{n&&t(o)}),()=>{n=!1,s()}},[]),e}function uee(){const e=dee(),t=e[0];return t?i.jsx(hee,{request:t,total:e.length},t.id):null}function hee({request:e,total:t}){const{t:n}=ne(),[s,o]=m.useState(""),[r,a]=m.useState(!1),l=Jx(e.expiresAt),c=r||l!==void 0&&l<=0,d=u=>{a(!0),o(""),window.electronAPI.elevation.answer(e.id,u)};return i.jsxs("form",{"data-enso":"approval",className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",onSubmit:u=>{u.preventDefault(),s&&!c&&d(s)},children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx(h5,{className:"h-3.5 w-3.5 shrink-0 text-amber-500"}),i.jsx("span",{className:"shrink-0 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:n("Run as administrator")}),i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[i.jsx(Zx,{remainingMs:l,expiredLabel:"Timed out · denied"}),t>1&&i.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["1/",t]})]})]}),i.jsx("pre",{className:"mt-1.5 max-h-24 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted/60 px-2 py-1.5 font-mono text-xs",children:e.command}),i.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[i.jsx("input",{type:"password",autoFocus:!0,autoComplete:"off",value:s,disabled:c,placeholder:n("Login password"),"aria-invalid":e.retry||void 0,onChange:u=>o(u.currentTarget.value),className:W("h-7 min-w-0 flex-1 rounded-md border bg-background px-2 text-xs outline-none focus-visible:border-ring",e.retry?"border-destructive/60":"border-border/60")}),i.jsx("button",{type:"button",disabled:c,onClick:()=>d(null),className:"rounded-md px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50",children:n("Deny")}),i.jsx("button",{type:"submit",disabled:c||!s,className:"rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:n("Allow")})]}),i.jsx("p",{className:W("mt-1 text-[11px]",e.retry?"text-destructive":"text-muted-foreground"),children:e.retry?n("Incorrect password. Try again."):n("Applies to this command only. The password is never shown to the AI.")})]})}function pee(e){const t=new Set;for(const n of e)if(n.kind==="tool"){if(n.name==="apply_patch"){n.fileChanges?.length&&t.add(n.key);continue}n.state==="ok"&&(n.output===null&&n.durationMs===null||n.name!=="edit"&&n.name!=="write"||n.name==="edit"&&!(n.edits&&n.edits.length>0)||n.name==="write"&&!n.writeContent||t.add(n.key))}return t}const fee={conversationId:void 0,historyBaseIndex:0,seen:null};function mee(e,t){const{conversationId:n,historyBaseIndex:s}=t;if(!t.authoritative)return{baseline:{conversationId:n,historyBaseIndex:s,seen:null},added:!1};const r=e.conversationId===n&&e.historyBaseIndex===s?e.seen:null,a=pee(t.timeline),l=r!==null&&[...a].some(c=>!r.has(c));return{baseline:{conversationId:n,historyBaseIndex:s,seen:a},added:l}}function gee(e,t){const n=we(a=>a.openChangesOnFileEdit),s=ie(a=>g_((t?a.conversations[t]?.messages:void 0)??[])),o=ie(a=>(t?a.conversations[t]?.historyBaseIndex:void 0)??0),r=m.useRef(fee);m.useEffect(()=>{const a=mee(r.current,{conversationId:t,historyBaseIndex:o,authoritative:s,timeline:e});r.current=a.baseline,a.added&&n&&Cj()},[s,t,n,o,e])}function Ka(e,t){const n=e.trim().toLowerCase();return n?t.some(s=>s?.toLowerCase().includes(n)):!0}function xee(e,t){const n=t.trim().toLowerCase();if(!n)return[];const s=[];for(const o of e){if(o.kind!=="user"&&o.kind!=="text")continue;const r=o.text.toLowerCase();let a=0,l=0;for(;;){const c=r.indexOf(n,a);if(c===-1)break;s.push({key:o.key,nth:l}),l+=1,a=c+n.length}}return s}const vee=[],bee=[],wee=typeof window<"u"&&!!window.electronAPI?.remote;function hE({conversationId:e,cwd:t,emptyTitle:n,onSuggestion:s,timelineRef:o}){const r=ie(ee=>ee.conversations[e]?.projectId),a=ie(ee=>ee.conversations[e]?.messages??vee),l=ie(ee=>ee.conversations[e]?.customEntries??bee),c=ie(ee=>ee.conversations[e]?.status==="running"),d=ie(ee=>ee.conversations[e]?.compaction),u=ie(ee=>ee.conversations[e]?.compactionNoticeAt),h=ie(ee=>ee.conversations[e]?.occupancy?.compactionTokensAfter),p=ie(ee=>ee.conversations[e]?.historyBaseIndex??0),f=ie(ee=>ee.conversations[e]?.toolOutputs),g=ie(ee=>ee.conversations[e]?.toolStartedAt),x=ie(ee=>ee.conversations[e]?.pendingApprovals),v=ie(ee=>ee.conversations[e]?.runStartedAt),y=ie(ee=>ee.conversations[e]?.lastOutputAt),b=ie(ee=>ee.conversations[e]?.error),w=ie(ee=>ee.conversations[e]?.started===!0),C=ie(ee=>ee.conversations[e]?.sessionFile),_=ie(ee=>ee.conversations[e]?.status),N=ie(ee=>ee.conversations[e]?.spawning===!0),k=ie(ee=>ee.conversations[e]?.historyLoadAttempted),S=ie(ee=>!!ee.conversations[e]?.historyLoading),A=ie(ee=>ee.conversations[e]?.syncStalled===!0),T=m.useRef({conversationId:"",items:[]}),I=m.useMemo(()=>{T.current.conversationId!==e&&(T.current={conversationId:e,items:[]});const ge=p5(T.current.items,a,c,p)??Sr(a,c,l,t,{compaction:d,compactionNoticeAt:u,compactionTokensAfter:h,historyBaseIndex:p,toolOutputs:f,toolStartedAt:g,pendingApprovals:x});return T.current.items=ge,ge},[d,u,h,e,t,l,p,a,x,c,f,g]);gee(I,e);const P=f5({started:w,sessionFile:C,messages:a,spawning:N,status:_,historyLoadAttempted:k,historyLoading:S,syncStalled:A}),[D,O]=m.useState(!1),[z,R]=m.useState(""),[$,X]=m.useState(0),H=m.useMemo(()=>D?xee(I,z):[],[D,z,I]);m.useEffect(()=>{const ee=()=>{const ge=sC();O(!0),ge&&(R(ge),X(0))};return window.addEventListener(sc,ee),()=>window.removeEventListener(sc,ee)},[]),m.useEffect(()=>{const ee=sC();if(X(0),ee){R(ee),O(!0);return}e&&(R(""),O(!1))},[e]),m.useEffect(()=>{if(!D||H.length===0)return;const ee=Math.min($,H.length-1);o.current?.scrollToKey(H[ee].key)},[D,$,H,o]);const te=m.useCallback(ee=>{H.length!==0&&X(ge=>(ge+ee+H.length)%H.length)},[H.length]);m.useEffect(()=>{if(!D)return;const ee=ge=>{if(ge.key==="Escape"){ge.preventDefault(),O(!1);return}const Ce=Ol(ge);Ce==="mod+g"?(ge.preventDefault(),te(1)):Ce==="mod+shift+g"&&(ge.preventDefault(),te(-1))};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[D,te]);const V=m.useMemo(()=>r?{conversationId:e,projectId:r,...t?{cwd:t}:{}}:null,[e,t,r]),Y=m.useRef(null),q=m.useCallback(()=>{const ee=o.current?.getScroller();Y.current=ee?{height:ee.scrollHeight,top:ee.scrollTop}:null,ie.getState().loadOlderHistory(e)},[e,o]);return m.useLayoutEffect(()=>{const ee=o.current?.getScroller(),ge=Y.current;!ee||!ge||(Y.current=null,ee.scrollTop=ge.top+(ee.scrollHeight-ge.height))},[p]),i.jsxs(nh.Provider,{value:V,children:[D&&i.jsx(oee,{query:z,onQueryChange:ee=>{R(ee),X(0)},current:H.length===0?0:Math.min($,H.length-1)+1,total:H.length,onPrev:()=>te(-1),onNext:()=>te(1),onClose:()=>{O(!1),R("")}}),i.jsx(Bh,{virtualize:!wee,ref:o,items:I,busy:P!==null,loading:P==="loading",running:c,runStartedAt:v,lastOutputAt:y,error:m5(a,b),emptyTitle:n,onSuggestion:s,onRetryResume:!w&&C&&_==="failed"?()=>{ie.getState().resumeConversation(e)}:void 0,onRetrySync:A&&!c?()=>ie.getState().retrySessionSync(e):void 0,historyLoading:S,hasOlder:p>0,olderCursor:p,onStartReached:p>0?q:void 0,searchQuery:D?z:"",activeHit:D?H[$]??null:null},e)]})}const yee=/-([0-9a-f]{8})$/i;function iC(e){const t=e.title?.trim();return t||e.name.replace(yee,"").trim()||e.name}function See({parentId:e,coworkerIds:t}){const{t:n,locale:s}=ne(),o=we(y=>y.agentTypes),[r,a]=m.useState([]),[l,c]=m.useState(!1),[d,u]=m.useState(null),h=m.useRef(0),p=t.join("\0"),f=ie(y=>y.pendingChildRun),g=m.useCallback(()=>{const y=++h.current;return window.electronAPI.agent.listChildRuns(e).then(b=>{y===h.current&&a(b.ok?b.items:[])})},[e]);m.useEffect(()=>{g()},[g,p]);const x=m.useCallback(y=>{const b=d?.childId;return b?window.electronAPI.agent.readChildRun(e,b,y):Promise.resolve({ok:!1,code:"not-found",error:"No child run."})},[e,d?.childId]),v=y=>{if(y.available){if(c(!1),y.live&&t.includes(y.childId)){ie.getState().selectTab(e,y.childId);return}u(y)}};return m.useEffect(()=>{if(!f||f.parentId!==e)return;const y=r.find(b=>b.childId===f.childId);if(y&&(ie.setState({pendingChildRun:null}),!!y.available)){if(c(!1),y.live&&t.includes(y.childId)){ie.getState().selectTab(e,y.childId);return}u(y)}},[f,r,e,t]),i.jsxs(i.Fragment,{children:[r.length>0&&i.jsxs(vi,{open:l,onOpenChange:y=>{c(y),y&&g()},children:[i.jsxs(bi,{className:"flex h-6 shrink-0 items-center justify-center gap-1 rounded-full px-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground","aria-label":n("Subagent history"),title:n("Subagent history"),children:[i.jsx(Yo,{className:"size-3.5"}),i.jsx("span",{className:"text-[11px] tabular-nums leading-none",children:r.length})]}),i.jsx(wi,{align:"end",className:"w-96 [&_[data-slot=popover-viewport]]:p-1",children:i.jsx("ul",{className:"flex flex-col",children:r.map(y=>{const b=iC(y);return i.jsx("li",{children:i.jsxs("button",{type:"button",disabled:!y.available,title:b,className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",y.available?"hover:bg-muted":"cursor-default text-muted-foreground opacity-40"),onClick:()=>v(y),children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:b}),y.agentType&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:x_(y.agentType,o)}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:$o(y.startedAt,s)}),y.live&&i.jsx(Tc,{tone:"running",size:"sm",title:n("Running")})]})},y.childId)})})})]}),i.jsx(Iv,{conversationId:d?.childId??null,title:d?iC(d):"",read:x,botSession:!1,onClose:()=>u(null)})]})}const Cee=[{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"}],kee={"/goal":Cee};function jee(e,t){if(!e)return null;const n=t.trimStart();return n?n.search(/\s/)>=0?null:n:""}function _ee(e,t){if(!e)return[];const n=kee[e]??[],s=t.trim().toLowerCase();return s?n.filter(o=>o.name.toLowerCase().startsWith(s)||o.aliases.some(r=>r.toLowerCase().startsWith(s))):n}function Nee(e){return e.filter(t=>t.state==="enabled").flatMap(t=>(t.statusItems??[]).filter(n=>n.visible&&n.text.trim().length>0).map(n=>({...n,pluginId:t.id,pluginName:t.name})))}let pE=[];const dg=new Set;function oC(e){pE=e;for(const t of dg)t()}function Tee(e){return dg.add(e),()=>dg.delete(e)}const rC=()=>pE,Iee={neutral:"text-muted-foreground",accent:"text-primary",success:"text-emerald-600 dark:text-emerald-400",warning:"text-amber-600 dark:text-amber-400",danger:"text-red-600 dark:text-red-400"};function Dee({sessionId:e}){const t=m.useSyncExternalStore(Tee,rC,rC);return t.length===0?null:i.jsx(i.Fragment,{children:t.map(n=>{const s=n.command?v_().find(a=>a.pluginId===n.pluginId&&a.id===n.command):void 0,o=W("shrink-0 truncate px-1 text-[11px]",Iee[n.tone]),r=n.tooltip?`${n.tooltip} · ${n.pluginName}`:n.pluginName;return s?i.jsx("button",{type:"button",title:r,className:W(o,"rounded hover:bg-accent"),onClick:()=>{Qg(s,e).then(a=>{a&&ze({title:a})})},children:n.text},`${n.pluginId}:${n.id}`):i.jsx("span",{title:r,className:o,children:n.text},`${n.pluginId}:${n.id}`)})})}const fE=50,Eee=64,Pee=120,Aee=32*1024,Mee=120,ld=[];function aC(e){return/(?:^|\s)#([^\s#]*)$/.exec(e)?.[1]??null}function Ree(e,t,n){if(!Array.isArray(n))return[];const s=[];for(const o of n){if(s.length>=fE)break;if(typeof o!="object"||o===null)continue;const{id:r,label:a,detail:l}=o;typeof r!="string"||!r||typeof a!="string"||!a||s.push({key:`${e}:${t}:${r}`,pluginId:e,name:t,item:{id:r.slice(0,200),label:a.slice(0,Eee),...typeof l=="string"&&l?{detail:l.slice(0,Pee)}:{}}})}return s}function Lee(e){const t=typeof e=="string"?e:typeof e=="object"&&e!==null?e.text:null;return typeof t=="string"&&t.length<=Aee?t:null}let mE=[];const ug=new Set;function lC(e){mE=e;for(const t of ug)t()}function Oee(e){return ug.add(e),()=>ug.delete(e)}const cC=()=>mE;function zee(e,t){const n=m.useSyncExternalStore(Oee,cC,cC),[s,o]=m.useState(ld);return m.useEffect(()=>{if(e===null||n.length===0){o(ld);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?Ree(l,c,d.value):ld})).then(l=>{r||o(l.flat().slice(0,fE))})},Mee);return()=>{r=!0,clearTimeout(a)}},[e,n,t]),e===null?ld:s}async function Gee(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?Lee(n.value):null}const Qd="composer-drop",gE="pinned-drop",Lv="project-group:__ungrouped__",hg="project:",pg="project-group:",eu="selector-group:",fg="pinned-chat:",xE=e=>`${hg}${e}`,vE=e=>`${pg}${e}`,Ov=e=>`${eu}${e}`,Fee=e=>`chat:${e}`,bE=e=>`${fg}${e}`,Hee=e=>`active-chat:${e}`;function Bee(e){return e.split(`
84
- `)[0].trim()||"Untitled chat"}function dC(e){if(e===Lv||e===`${eu}__ungrouped__`)return null;if(e.startsWith(pg)){const t=e.slice(pg.length);return t==="__all__"?void 0:t}if(e.startsWith(eu)){const t=e.slice(eu.length);return t==="__all__"?void 0:t}}function Vee(e,t,n,s){if(!t)return null;if(e.type==="project-group"){const o=dC(t);return!o||o===e.groupId?null:{kind:"reorder-groups",activeId:e.groupId,overId:o}}if(e.type==="project"){if(t===Qd)return{kind:"insert-file-mention",path:e.path,label:e.name};const o=dC(t);if(o!==void 0)return(s?.projectGroupId?.(e.projectId)??null)===o?null:{kind:"move-project-to-group",projectId:e.projectId,groupId:o};if(t.startsWith(hg)){const r=t.slice(hg.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===Qd?{kind:"insert-file-mention",path:e.relativePath,label:e.name}:null;if(t===Qd)return!e.sessionFile||e.conversationId===n?null:{kind:"insert-chat-mention",conversationId:e.conversationId,label:Bee(e.title),sessionFile:e.sessionFile};if(t===gE)return e.pinned?null:{kind:"pin-conversation",conversationId:e.conversationId};if(t.startsWith(fg)){const o=t.slice(fg.length);return o===e.conversationId?null:e.pinned?{kind:"reorder-pinned",activeId:e.conversationId,overId:o}:{kind:"pin-conversation",conversationId:e.conversationId}}return null}const uC=200,$ee=Array.from({length:Il},(e,t)=>`bar-${t}`),hC=$h([],0);function Wee({active:e,disabled:t,onChange:n}){const{t:s}=ne(),[o,r]=m.useState(!1),[a,l]=m.useState(null),c=m.useRef(null);m.useEffect(()=>{if(!a)return;const h=setTimeout(()=>l(null),4e3);return()=>clearTimeout(h)},[a]);const d=async()=>{if(l(null),!navigator.mediaDevices?.getUserMedia){l(s("Voice input needs a secure (HTTPS) connection."));return}og(),r(!0);try{await hJ(),n(!0)}catch(h){l(s(lD(h)))}finally{r(!1)}},u=s(e?"Switch to keyboard":"Voice input");return i.jsxs("div",{ref:c,className:"flex shrink-0 items-center",children:[i.jsx("button",{type:"button",disabled:t||o,onClick:()=>e?n(!1):void d(),"aria-label":u,title:u,className:rg,children:o?i.jsx(vr,{className:"h-3.5 w-3.5"}):e?i.jsx(g5,{className:"h-3.5 w-3.5"}):i.jsx(Mj,{className:"h-3.5 w-3.5"})}),a&&c.current?i.jsx(uD,{anchor:c.current,status:!0,children:a}):null]})}let pC;function Uee({startSession:e,disabled:t,onText:n}){const{t:s}=ne(),{phase:o,elapsed:r,error:a,setError:l,partial:c,correcting:d,start:u,finish:h,cancel:p}=cD({startSession:e,onText:n}),[f,g]=m.useState(hC),[x,v]=m.useState(!1),[y,b]=m.useState(!1),w=m.useRef(null);m.useEffect(()=>(clearTimeout(pC),()=>{pC=setTimeout(ES,0)}),[]),m.useEffect(()=>{const k=window.visualViewport;if(!x||!k)return;const S=()=>{w.current&&(w.current.shifted=!0)};return k.addEventListener("resize",S),k.addEventListener("scroll",S),()=>{k.removeEventListener("resize",S),k.removeEventListener("scroll",S)}},[x]);const C=k=>{t||w.current||o!=="idle"||k.pointerType==="mouse"&&k.button!==0||(k.preventDefault(),document.activeElement?.blur(),k.currentTarget.setPointerCapture(k.pointerId),w.current={id:k.pointerId,y:k.clientY,at:performance.now(),shifted:!1},v(!0),b(!1),g(hC),u({context:og(),onLevel:S=>g(A=>$h(A,S))}))},_=(k,S)=>{const A=w.current;if(!A||A.id!==k.pointerId)return;w.current=null,v(!1),b(!1);const T=iD({phase:o,heldMs:performance.now()-A.at,cancelZone:S||!A.shifted&&DS(A.y,k.clientY)});T==="finish"?h():T!=="none"&&p(),ES(),og(),T==="too-short"&&l(s("Speech was too short."))},N=x&&(o==="starting"||o==="recording")||o==="transcribing";return i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",disabled:t,onPointerDown:C,onPointerMove:k=>{const S=w.current;S?.id===k.pointerId&&(S.shifted&&(S.y=k.clientY,S.shifted=!1),b(DS(S.y,k.clientY)))},onPointerUp:k=>_(k,!1),onPointerCancel:k=>_(k,!0),onContextMenu:k=>k.preventDefault(),className:W("mt-2 flex h-11 w-full touch-none select-none items-center justify-center rounded-xl border bg-background font-medium text-sm shadow-float transition-[opacity,scale,background-color] duration-200 ease-out [-webkit-touch-callout:none] starting:scale-x-25 starting:opacity-0 disabled:opacity-40",x&&"bg-accent",a&&"text-destructive"),children:a??s(x?"Release to finish":"Hold to talk")}),N?i.jsx(Kee,{phase:o,cancelling:y,elapsed:r,levels:f,partial:c,correcting:d}):null]})}function Kee({phase:e,cancelling:t,elapsed:n,levels:s,partial:o,correcting:r}){const{t:a}=ne(),l=e==="transcribing",c=o.length>uC?`…${o.slice(-uC)}`:o;return qs.createPortal(i.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:[i.jsx("div",{className:"flex flex-1 items-center justify-center px-6",children:i.jsxs("div",{role:"status","aria-live":"polite",className:W("flex min-w-36 max-w-[85vw] flex-col items-center gap-3 rounded-2xl px-5 py-4 shadow-lg transition-colors duration-150",t?"bg-destructive text-white":"bg-brand text-brand-foreground"),children:[c?i.jsx("p",{"data-testid":"voice-partial",className:"text-[15px] leading-relaxed",children:c}):e==="recording"?i.jsx("p",{className:"text-sm",children:a("Speak now")}):null,l||e==="starting"?i.jsxs("span",{className:"flex items-center gap-1.5 text-xs opacity-85",children:[i.jsx(vr,{"aria-hidden":!0,className:"size-3.5"}),a(e==="starting"?"Getting the microphone ready…":r?"Correcting…":"Transcribing…")]}):i.jsx("span",{"aria-hidden":!0,className:"flex h-8 items-center gap-[3px]",children:$ee.map((d,u)=>i.jsx("span",{className:"w-[3px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:4+s[u]*28}},d))})]})}),l?null:i.jsxs("div",{className:"flex flex-col items-center",children:[i.jsx("span",{className:W("mb-3 flex size-14 items-center justify-center rounded-full transition-[scale,background-color,color] duration-150",t?"scale-110 bg-white text-destructive":"bg-white/15 text-white/80"),children:i.jsx(dn,{className:"size-6"})}),i.jsx("p",{className:"mb-5 text-white/80 text-xs",children:a(t?"Release to cancel":"Slide up to cancel")}),i.jsxs("div",{className:W("flex h-[calc(7rem+env(safe-area-inset-bottom))] w-[140%] flex-col items-center rounded-t-[50%] pt-8 transition-colors duration-150",t?"bg-neutral-500 text-white/70":"bg-neutral-100 text-neutral-700"),children:[i.jsx("span",{className:"text-sm",children:a("Release to finish")}),i.jsxs("span",{className:"mt-1 text-xs tabular-nums opacity-60",children:[Math.floor(n/60),":",String(n%60).padStart(2,"0")]})]})]})]}),document.body)}const fC=e=>e.startsWith("/skill:");function qee(e,t){return!fC(t)||!e.every(fC)?[t]:e.includes(t)?[...e]:[...e,t]}function Yee(e){const t=jj(e);if(t.names.length>0)return{slashes:t.names.map(s=>`/skill:${s}`),rest:t.rest};const n=Ru(e);return{slashes:n.slash?[n.slash]:[],rest:n.rest}}function Xee(e,t,n=!1){const s=e.segments.some(r=>r.type!=="text"||r.text.length>0);if(n&&(s||e.slashes.length>0))return{slashes:e.slashes,segments:[...e.segments,...t.text?[{type:"text",text:`${s?`
85
-
86
- `:""}${t.text}`}]:[]],images:[...e.images,...t.images??[]]};const o=Yee(t.text??"");return{slashes:o.slashes,segments:o.rest?[{type:"text",text:o.rest}]:[],images:[...n?e.images:[],...t.images??[]]}}const Jee={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>'},Zee='<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>',Qee={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 mf(e){const t=document.createElement("span");t.contentEditable="false",t.dataset.mentionKind=e.type,e.type==="file"?(t.dataset.path=e.path,e.label&&(t.dataset.label=e.label),t.title=e.path):e.type==="chat"?(t.dataset.label=e.label,t.dataset.sessionFile=e.sessionFile):(t.dataset.id=e.id,t.dataset.label=e.label,t.dataset.path=e.path,t.dataset.text=e.text,t.dataset.imageId=e.imageId,t.title=`${e.path}${e.text?` · ${e.text}`:""}`),t.className=W("mx-0.5 inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium leading-4 select-none",Qee[e.type]);const n=document.createElement("span");n.className="shrink-0 inline-flex",n.innerHTML=e.type==="file"&&/[\\/]$/.test(e.path)?Zee:Jee[e.type],t.appendChild(n);const s=document.createElement("span");return s.className="truncate",s.textContent=e.type==="file"?e.label??Ph(e.path):e.label,t.appendChild(s),t}function wE(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 gf(e){const t=[],n=o=>{if(!o)return;const r=t.at(-1);r?.type==="text"?r.text+=o:t.push({type:"text",text:o})},s=o=>{if(o.nodeType===Node.TEXT_NODE){n(o.textContent??"");return}if(!(o instanceof HTMLElement))return;if(o.dataset.mentionKind){const a=wE(o);a&&t.push(a);return}if(o.tagName==="BR"){n(`
87
- `);return}(o.tagName==="DIV"||o.tagName==="P")&&t.length>0&&n(`
88
- `);for(const a of o.childNodes)s(a)};for(const o of e.childNodes)s(o);return t}function xf(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 ete(e,t){if(t.rangeCount===0||!t.isCollapsed)return null;const{anchorNode:n,anchorOffset:s}=t;if(!n||n.nodeType===Node.TEXT_NODE||n!==e&&!e.contains(n))return null;const o=n.childNodes,r=o[s],a=s>0?o[s-1]:void 0,l=r?.nodeType===Node.TEXT_NODE?{node:r,offset:0}:a?.nodeType===Node.TEXT_NODE?{node:a,offset:a.length}:null;if(!l)return null;const c=document.createRange();return c.setStart(l.node,l.offset),c.collapse(!0),c}function cd(e){return e instanceof HTMLElement&&!!e.dataset.mentionKind}function al(e){return e instanceof Text&&!/[^\s\u00a0]/.test(e.textContent??"")}function tte(e,t){const n=window.getSelection();if(!n||n.rangeCount===0||!n.isCollapsed)return null;const{anchorNode:s,anchorOffset:o}=n;if(!s||!e.contains(s))return null;if(s.nodeType===Node.TEXT_NODE){const c=s.textContent??"";if(t==="before"){if(/[^\s\u00a0]/.test(c.slice(0,o)))return null;let u=s.previousSibling;for(;al(u);)u=u.previousSibling;return cd(u)?u:null}if(/[^\s\u00a0]/.test(c.slice(o)))return null;let d=s.nextSibling;for(;al(d);)d=d.nextSibling;return cd(d)?d:null}const r=s.childNodes;if(t==="before"){let c=o-1;for(;c>=0&&al(r[c]);)c-=1;const d=c>=0?r[c]:null;return cd(d)?d:null}let a=o;for(;a<r.length&&al(r[a]);)a+=1;const l=r[a];return cd(l)?l:null}function nte(e,t){const n=e.nextSibling;al(n)&&n.remove();const s=e.previousSibling;if(e.remove(),s){yE(s);return}const o=window.getSelection();if(!o)return;const r=document.createRange();r.setStart(t,0),r.collapse(!0),o.removeAllRanges(),o.addRange(r)}function yE(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.setStartAfter(e),n.collapse(!0),t.removeAllRanges(),t.addRange(n)}const ste=m.forwardRef(function({placeholder:t,disabled:n,className:s,onStateChange:o,onKeyDown:r,onPaste:a,onPasteText:l,onCompositionStart:c,onCompositionEnd:d,onChipActivate:u,ariaProps:h},p){const f=m.useRef(null),g=m.useRef(null);m.useEffect(()=>{const b=()=>{const w=f.current;if(!w||document.activeElement!==w)return;const C=window.getSelection();if(!C||C.rangeCount===0||!C.isCollapsed)return;const _=C.anchorNode;if(_&&(_===w||w.contains(_))){const S=ete(w,C);S?(C.removeAllRanges(),C.addRange(S)):_.nodeType===Node.TEXT_NODE&&(g.current={node:_,offset:C.anchorOffset});return}const N=g.current,k=document.createRange();N?.node.isConnected&&w.contains(N.node)?(k.setStart(N.node,Math.min(N.offset,N.node.length)),k.collapse(!0)):(k.selectNodeContents(w),k.collapse(!0)),C.removeAllRanges(),C.addRange(k)};return document.addEventListener("selectionchange",b),()=>document.removeEventListener("selectionchange",b)},[]);const x=m.useCallback(()=>{const b=f.current;if(!b)return;const w=gf(b),C=w.map(I=>I.type==="text"?I.text:"").join(""),_=w.some(I=>I.type!=="text");let N=null,k=null,S=null,A=null;const T=xf(b);if(T){const I=T.node.textContent?.slice(0,T.offset)??"";N=Ew(I,I.length),N===null&&(S=ig(I,I.length)),N===null&&S===null&&(A=aC(I)),N===null&&T.node===b.firstChild&&/^\/[^\s]*$/.test(I)&&(k=I.slice(1))}o({plainText:C,hasMentions:_,segments:w,mentionQuery:N,slashQuery:k,skillQuery:S,pluginQuery:A})},[o]),v=m.useCallback(b=>{const w=f.current;if(!w)return null;const C=xf(w);if(!C)return null;const _=C.node.textContent?.slice(0,C.offset)??"";if(b==="#"){const N=aC(_);return N===null?null:{node:C.node,start:_.length-N.length-1,end:C.offset}}if(b==="@"||b==="$"){const N=b==="@"?Ew(_,_.length):ig(_,_.length);return N===null?null:{node:C.node,start:_.length-N.length-1,end:C.offset}}return C.node!==w.firstChild||!/^\/[^\s]*$/.test(_)?null:{node:C.node,start:0,end:C.offset}},[]),y=m.useCallback((b,w)=>{const C=f.current;if(!C)return;C.focus();const _=document.createRange(),N=w?v("@"):null;if(N)_.setStart(N.node,N.start),_.setEnd(N.node,N.end),_.deleteContents();else{const A=xf(C);A?(_.setStart(A.node,A.offset),_.collapse(!0)):(_.selectNodeContents(C),_.collapse(!1))}const k=b();_.insertNode(k);const S=document.createTextNode(" ");k.parentNode?.insertBefore(S,k.nextSibling),yE(S),x()},[v,x]);return m.useImperativeHandle(p,()=>({focus:()=>f.current?.focus(),isEmpty:()=>{const b=f.current;return b?!gf(b).some(C=>C.type!=="text"||C.text.trim().length>0):!0},getSegments:()=>f.current?gf(f.current):[],setSegments:b=>{const w=f.current;if(w){w.textContent="";for(const C of b)C.type==="text"?w.appendChild(document.createTextNode(C.text)):w.appendChild(mf(C));x()}},clear:()=>{const b=f.current;b&&(b.textContent="",x())},insertMention:b=>{const w=b.kind==="file"?{type:"file",path:b.relativePath}:b.kind==="chat"?{type:"chat",label:b.label,sessionFile:b.sessionFile}:{type:"ui-element",id:b.id,label:b.label,path:b.path,text:b.text,imageId:b.imageId};y(()=>mf(w),b.kind!=="ui-element")},consumeToken:b=>{const w=v(b);if(!w)return;const C=document.createRange();C.setStart(w.node,w.start),C.setEnd(w.node,w.end),C.deleteContents(),x()},insertFileChip:(b,w)=>{y(()=>mf({type:"file",path:b,...w?{label:w}:{}}),!1)},insertText:b=>{y(()=>document.createTextNode(b),!1)},getMentionAnchorRect:()=>{const b=v("@");if(!b)return null;const w=document.createRange();return w.setStart(b.node,b.start),w.setEnd(b.node,Math.min(b.start+1,b.node.length)),w.getBoundingClientRect()}}),[v,x,y]),i.jsx("div",{ref:f,contentEditable:!n,role:h?.role??"textbox","aria-placeholder":t,"data-placeholder":t,...h,onInput:x,onKeyDown:b=>{if(!b.nativeEvent.isComposing&&(b.key==="Backspace"||b.key==="Delete")){const w=f.current,C=w&&tte(w,b.key==="Backspace"?"before":"after");if(C&&w){b.preventDefault(),nte(C,w),x();return}}r(b)},onClick:b=>{if(!u)return;const w=b.target;if(!(w instanceof Element))return;const C=w.closest("[data-mention-kind]");if(!(C instanceof HTMLElement)||!f.current?.contains(C))return;const _=wE(C);_&&u(_)},onKeyUp:b=>{b.key!=="Escape"&&x()},onMouseUp:x,onPaste:b=>{if(b.clipboardData.files.length>0){a(b);return}b.preventDefault();const w=b.clipboardData.getData("text/plain");w&&(l?.(w)||document.execCommand("insertText",!1,w))},onCompositionStart:c,onCompositionEnd:()=>{d(),x()},className:W("max-h-40 min-h-10 min-w-0 flex-1 overflow-y-auto pt-0.5 text-sm break-words whitespace-pre-wrap outline-none","empty:before:pointer-events-none empty:before:text-muted-foreground empty:before:content-[attr(data-placeholder)]",n&&"opacity-60",s)})}),ite=/[\\/]/;function ote(e){return e.split(ite).filter(t=>t.length>0)}function rte(e){const t=new Map,n=e.map(ote),s=n.map(o=>o.join("/"));for(let o=0;o<e.length;o++){const r=e[o],a=n[o]??[];let l=Math.max(0,a.length-3);for(;l>0;){const d=a.slice(l).join("/");if(!s.some(h=>h!==s[o]&&(h===d||h.endsWith(`/${d}`))))break;l--}const c=a.slice(l).join("/");t.set(r,l>0?`…/${c}`:c)}return t}function ate({groups:e,query:t,activeIndex:n,onActiveIndexChange:s,openFolderId:o,folderIndex:r,onOpenFolderIdChange:a,onFolderIndexChange:l,onSelect:c,id:d="composer-mention-picker",left:u=0,flyoutSide:h="right"}){const{t:p}=ne(),f=m.useMemo(()=>fD(e,t),[e,t]),g=m.useMemo(()=>rte(e.files.map(k=>k.relativePath)),[e.files]),x=m.useRef(new Map),v=m.useRef(new Map),y=f[0]?.type==="folder";if(m.useEffect(()=>{x.current.get(n)?.scrollIntoView({block:"nearest"})},[n]),m.useEffect(()=>{o&&v.current.get(r)?.scrollIntoView({block:"nearest"})},[o,r]),f.length===0)return null;const b={agents:p("Agents"),members:p("Members"),chats:p("Chats")},w={agents:Ws,members:fa,chats:Yo},C=o?e[o]:[];let _=0;const N=(k,S)=>{const A=e[k];if(A.length===0)return null;const T=k==="files"?p("Files"):b[k];return i.jsxs("div",{role:"group","aria-label":T,children:[i.jsx("p",{className:W("px-2 pb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",S?"pt-2":"pt-1.5"),children:T}),A.map(I=>{const P=_++;return i.jsx(mC,{ref:D=>{D?x.current.set(P,D):x.current.delete(P)},id:`${d}-option-${P}`,candidate:I,active:P===n,pathLabel:I.kind==="file"?g.get(I.relativePath):void 0,onHover:()=>{s(P),y&&a(null)},onSelect:()=>c(I)},`${k}:${I.id}`)})]})};return i.jsxs("div",{"data-slot":"mention-picker",className:"absolute bottom-full z-10 mb-1.5 max-w-full",style:{left:u},children:[i.jsx("div",{id:d,role:"listbox","aria-label":p("Mention suggestions"),className:"max-h-72 w-80 max-w-full overflow-y-auto rounded-lg border bg-popover p-1 shadow-md",children:y?i.jsxs(i.Fragment,{children:[f.filter(k=>k.type==="folder").map(k=>{const S=_++,A=w[k.id];return i.jsxs("button",{ref:T=>{T?x.current.set(S,T):x.current.delete(S)},id:`${d}-option-${S}`,type:"button",role:"option","aria-selected":n===S,onClick:()=>{s(S),a(k.id),l(0)},onMouseMove:()=>{s(S),o!==k.id&&(a(k.id),l(0))},className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",n===S&&"bg-foreground/10"),children:[i.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background",children:i.jsx(A,{className:"h-3.5 w-3.5 text-muted-foreground"})}),i.jsx("span",{className:"min-w-0 flex-1 font-medium",children:b[k.id]}),i.jsx(un,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},`folder:${k.id}`)}),N("files",!0)]}):i.jsxs(i.Fragment,{children:[N("agents",!1),N("members",e.agents.length>0),N("chats",e.agents.length+e.members.length>0),N("files",e.agents.length+e.members.length+e.chats.length>0)]})}),o&&C.length>0&&i.jsx("div",{role:"listbox","aria-label":b[o],"data-slot":"mention-flyout",className:W("absolute top-0 z-20 max-h-72 w-72 overflow-y-auto rounded-lg border bg-popover p-1 shadow-md",h==="right"?"left-full ml-1":"right-full mr-1"),children:C.map((k,S)=>i.jsx(mC,{ref:A=>{A?v.current.set(S,A):v.current.delete(S)},id:`${d}-sub-${S}`,candidate:k,active:S===r,onHover:()=>l(S),onSelect:()=>c(k)},`sub:${k.id}`))})]})}function mC({ref:e,id:t,candidate:n,active:s,pathLabel:o,onHover:r,onSelect:a}){const{t:l}=ne(),c=lte(n),d=n.kind==="agent-type"?n.source==="bot"?fa:Ws:n.kind==="chat"?Yo:c?Nc:jo;return i.jsxs("button",{ref:e,id:t,type:"button",role:"option","aria-selected":s,onClick:a,onMouseMove:r,className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",s&&"bg-foreground/10"),children:[i.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background",children:i.jsx(d,{className:"h-3.5 w-3.5 text-muted-foreground"})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"shrink-0 font-medium",children:n.label}),i.jsx(pa,{variant:"outline",className:"px-1 py-0 text-[9px]",children:n.kind==="agent-type"?l(n.source==="system"?"System":n.source==="builtin"?"Built-in":n.source==="bot"?"Member":"Custom"):n.kind==="chat"?l("Chat"):l(c?"Folder":"File")}),n.kind==="agent-type"&&n.locked&&i.jsx(pa,{variant:"secondary",className:"px-1 py-0 text-[9px]",children:l("Locked")})]}),i.jsx("span",{className:W("block text-muted-foreground",n.kind==="file"?"whitespace-normal break-all":"truncate"),title:n.kind==="file"?n.relativePath:void 0,children:n.kind==="agent-type"?n.source==="bot"?n.description:l(n.description):n.kind==="chat"?n.sessionFile.split("/").at(-1):n.kind==="file"?o??n.relativePath:n.path})]})]})}function lte(e){return e.kind==="file"&&/[\\/]$/.test(e.relativePath)}function cte(e,t){return e.filter(n=>n!==t)}const gC=new Map,dte=()=>!!window.electronAPI?.remote&&window.matchMedia?.("(pointer: coarse)").matches===!0;function zv({cwd:e,commands:t,running:n,busy:s,focusKey:o,pluginPresetId:r=null,autoFocus:a=!window.electronAPI?.remote,enterToSend:l=!dte(),toolbar:c,locked:d=!1,injectedDraft:u,injectedImages:h,injectedDraftAppend:p,onDraftConsumed:f,chatCandidates:g,onActivate:x,onSend:v,onAbort:y,queuedCount:b=0,onSteerQueued:w,isolated:C=!1,placeholder:_,planMode:N=!1,voice:k,requestMicAccess:S,voiceMode:A="click",savePastedText:T}){const{t:I}=ne(),P=_a(),[D,O]=m.useState(!1),z=A==="hold"?k:void 0,R=we(le=>le.keybindings),$=we(le=>le.privacyMasking),X=Fi(R)["send-message"],H=Fi(R)["voice-hold"],te=m.useId(),[V,Y]=m.useState([]),[q,ee]=m.useState([]),[ge,Ce]=m.useState(),Re=m.useRef(o),[fe,U]=m.useState(!1),{setNodeRef:oe,isOver:Se}=Sc({id:C?`isolated-composer:${o??"side"}`:Qd,disabled:C}),[G,Q]=m.useState(null),[ae,Z]=m.useState(null),ce=m.useRef(new Set),De=m.useRef(v);De.current=v;const Oe=m.useRef($);Oe.current=$,m.useEffect(()=>{if(C)return;const le=wW(st=>Ne.current?.insertMention(st)),Pe=SW(st=>Ne.current?.insertText(st)),Ge=yW(()=>Ne.current?.focus()),Ve=jW((st,Xe)=>{Xe&&Y(ke=>[...ke,{...Xe,id:st.imageId}]),Ne.current?.insertMention(st),Ne.current?.focus()}),Ye=_W(st=>{Y(Xe=>[...Xe,{data:st.data,mimeType:st.mimeType}]),Ne.current?.focus()}),at=CW(st=>{if(Et.current)return!1;const Xe=Oe.current,ke=Xe.enabled?fp(st.text,Xe).blocked:[];return ke.length>0?(ze({type:"error",title:I("Message not sent"),description:I("Privacy masking blocks {{kinds}}. Remove it, or change the action or allow list in Settings → Privacy.",{kinds:ke.join(", ")})}),!1):De.current(st)!==!1});return()=>{le(),Pe(),Ge(),Ve(),Ye(),at()}},[C,I]);const Ne=m.useRef(null),Ze=m.useRef(null),bt=m.useRef(null),Ut=m.useRef(!1),Et=m.useRef(d);Et.current=d,m.useEffect(()=>{if(!(C||!o))return x5({key:o,segments:()=>Ne.current?.getSegments()??[],insertText:le=>Ne.current?.insertText(le),setText:le=>Ne.current?.setSegments(le?[{type:"text",text:le}]:[]),busy:()=>Ut.current||Et.current||!Ne.current})},[C,o]);const[_t,B]=m.useState({left:0,flyoutSide:"right"}),[Te,We]=m.useState(""),[kt,Gt]=m.useState(!1),[de,mt]=m.useState(null),Lt=mD(e,de,g),Fe=m.useMemo(()=>fD(Lt,de??""),[Lt,de]),[Nt,Ft]=m.useState(null),[on,re]=m.useState(null),[Ue,dt]=m.useState(null),Dt=zee(Ue,o??null),[it,K]=m.useState(0),[pe,Ie]=m.useState(null),[Ae,He]=m.useState(0),nt=m.useRef(null),be=m.useCallback(le=>{(le.plainText.trim()||le.hasMentions)&&x?.(),We(le.plainText),Gt(le.hasMentions);const Pe=new Set(le.segments.filter(Ve=>Ve.type==="ui-element"&&Ve.imageId).map(Ve=>Ve.type==="ui-element"?Ve.imageId:"")),Ge=[...ce.current].filter(Ve=>!Pe.has(Ve));ce.current=Pe,Ge.length>0&&(Y(Ve=>v5(Ve,Ge)),Q(Ve=>Ve&&Ge.includes(Ve.imageId)?null:Ve)),mt(Ve=>(Ve!==le.mentionQuery&&(K(0),Ie(null),He(0)),le.mentionQuery)),Ft(le.slashQuery),re(le.skillQuery),dt(le.pluginQuery)},[x]);m.useEffect(()=>{const le=Re.current;if(le!==o){le&&gC.set(le,{segments:Ne.current?.getSegments()??[],images:V,slashes:q,recipient:ge});const Pe=o?gC.get(o):void 0,Ge=o?b5(o):void 0;Ne.current?.setSegments(Ge?[{type:"text",text:Ge}]:Pe?.segments??[]),ce.current=new Set((Pe?.segments??[]).filter(Ve=>Ve.type==="ui-element"&&Ve.imageId).map(Ve=>Ve.type==="ui-element"?Ve.imageId:"")),Y(Pe?.images??[]),ee(Pe?.slashes??[]),Ce(Pe?.recipient),Re.current=o,mt(null),Ft(null),re(null),K(0),Ie(null),He(0)}a&&Ne.current?.focus()},[o]),m.useEffect(()=>{if(!u&&!h?.length)return;const le=Xee({segments:Ne.current?.getSegments()??[],images:V,slashes:q},{text:u,images:h},p);ee(le.slashes),Y(le.images),Ne.current?.setSegments(le.segments),f?.(),window.setTimeout(()=>Ne.current?.focus(),0)},[u,h,p]);const et=q.length===1?q[0]:null,tt=jee(et,Te.replaceAll("","")),wt=eJ(t,Nt,on),Jt=Nt===null&&on===null&&tt!==null?_ee(et,tt):[];m.useEffect(()=>{K(0)},[Nt,on,tt,Ue]),m.useEffect(()=>{nt.current?.children[it]?.scrollIntoView({block:"nearest"})},[it]);const E=m.useCallback(le=>{if(le.kind==="agent-type"){Ne.current?.consumeToken("@"),Ce(le),mt(null);return}Ne.current?.insertMention(le),mt(null)},[]),L=m.useCallback(le=>{dt(null),Gee(le,o??null).then(Pe=>{const Ge=Ne.current;Ge&&(Ge.consumeToken("#"),Pe&&Ge.insertText(Pe))})},[o]),M=de!==null&&Fe.length>0?"mention":Ue!==null&&Dt.length>0?"plugin":wt.length>0?"slash":Jt.length>0?"slash-sub":null;m.useLayoutEffect(()=>{if(M!=="mention")return;const le=Ze.current;if(!le)return;const Pe=()=>{const Ge=le.getBoundingClientRect(),Ve=le.querySelector('[data-slot="mention-picker"]'),Ye=Ve?.querySelector('[role="listbox"]'),at=Ve?.querySelector('[data-slot="mention-flyout"]'),st=Ne.current?.getMentionAnchorRect(),Xe=U4({anchorLeft:st?st.left-Ge.left:0,containerWidth:Ge.width,popupWidth:Ye instanceof HTMLElement?Ye.offsetWidth:280,flyoutWidth:at instanceof HTMLElement?at.offsetWidth:252,flyoutGap:4});B(ke=>ke.left===Xe.left&&ke.flyoutSide===Xe.flyoutSide?ke:Xe)};return Pe(),window.addEventListener("resize",Pe),()=>window.removeEventListener("resize",Pe)},[de,Te,pe,M]);const j=M==="mention"?Fe.length:M==="plugin"?Dt.length:M==="slash-sub"?Jt.length:wt.length,F=m.useCallback((le,Pe)=>{const Ge=[{type:"text",text:le}];if(Ne.current?.setSegments(Ge),!Pe)return;const Ve=Mw({segments:Ge,slashes:q,images:V,recipient:ge});v(Ve)!==!1&&(Ne.current?.clear(),Y([]),ee([]),Ce(void 0),mt(null),Ft(null),re(null))},[V,v,ge,q]),he=m.useCallback(le=>{Ne.current?.consumeToken(on!==null?"$":"/"),Ft(null),re(null);const Pe=w5(le);if(!Pe){ee(Ge=>qee(Ge,le));return}Qg(Pe,C?null:o??null).then(Ge=>{Ge&&ze({type:"error",title:I("Plugin command failed"),description:Ge})})},[on,C,o,I]),xe=m.useCallback((le=!1)=>{if(M==="mention"){if(pe){const Ge=Lt[pe][Ae];Ge&&E(Ge);return}const Pe=Fe[it];Pe?.type==="item"&&E(Pe.candidate)}else if(M==="plugin"){const Pe=Dt[it];Pe&&L(Pe)}else if(M==="slash"){const Pe=wt[it];Pe&&he(Pe.name)}else if(M==="slash-sub"){const Pe=Jt[it];if(!Pe)return;F(Pe.name,le)}},[it,Ae,pe,Lt,Fe,E,L,Dt,M,wt,he,Jt,F]),Ee=Te.replaceAll("","").trim(),Ke=!!(Ee||q.length>0||V.length>0||kt),ht=ge!==void 0,ot=s&&!ht,Ht={sessionId:C?null:o??null,draft:Te.replaceAll("",""),busy:d,pluginPresetId:r},ut=n&&b>0&&w!==void 0&&l&&!!X,Tt=ut&&!Ke&&!ht&&!d,yt=m.useMemo(()=>$.enabled&&Ee?fp(Ee,$):null,[Ee,$]),Ot=()=>{if(!Ke)return;const le=Mw({segments:Ne.current?.getSegments()??[],slashes:q,images:V,recipient:ge}),Pe=$.enabled?fp(le.text,$).blocked:[];if(Pe.length>0){ze({type:"error",title:I("Message not sent"),description:I("Privacy masking blocks {{kinds}}. Remove it, or change the action or allow list in Settings → Privacy.",{kinds:Pe.join(", ")})});return}v(le)!==!1&&(Ne.current?.clear(),Y([]),ee([]),Ce(void 0),mt(null),Ft(null),re(null))},jt=m.useCallback(le=>{for(const Pe of le){if(Pe.type.startsWith("image/")){const Ye=new FileReader;Ye.onload=()=>{const at=Ye.result,st=at.slice(at.indexOf(",")+1);Y(Xe=>[...Xe,{data:st,mimeType:Pe.type}])},Ye.readAsDataURL(Pe);continue}const Ge=window.electronAPI.files.pathForFile(Pe),Ve=window.electronAPI.remote;if(!Ge&&Ve){Ve.upload(Pe).then(Ye=>{Ye&&Ne.current?.insertFileChip(Ye)}).catch(()=>{});continue}Ge&&Ne.current?.insertFileChip(Ge)}},[]);m.useEffect(()=>{if(!C)return TW(le=>{jt(le),Ne.current?.focus()})},[C,jt]);const It=le=>{const Pe=le.nativeEvent.isComposing||Ut.current;if(M){const Ve=M==="mention"?Fe[it]:void 0,Ye=K4({key:le.key,shiftKey:le.shiftKey,isComposing:Pe,activeIndex:it,itemCount:j,folderOpen:M==="mention"&&pe!==null,activeIsFolder:M==="mention"&&Ve?.type==="folder",folderIndex:Ae,folderItemCount:pe?Lt[pe].length:0});if(Ye.type==="move"){le.preventDefault(),K(Ye.index),Ie(null);return}if(Ye.type==="move-folder"){le.preventDefault(),He(Ye.index);return}if(Ye.type==="open-folder"){le.preventDefault(),Ve?.type==="folder"&&Ie(Ve.id),He(0);return}if(Ye.type==="close-folder"){le.preventDefault(),Ie(null);return}if(Ye.type==="pick"){le.preventDefault(),xe(M==="slash-sub"&&le.key==="Enter");return}if(Ye.type==="close"){le.preventDefault(),mt(null),Ft(null),re(null),dt(null),Ie(null);return}}if(Pe)return;const Ge=Ol(le);if(!C&&Ge&&Ge===Fi(we.getState().keybindings)["switch-model"]){le.preventDefault(),y5();return}if(le.key==="Backspace"&&q.length>0&&Ee.length===0&&!kt){le.preventDefault(),ee(Ve=>Ve.slice(0,-1));return}if(le.key==="Backspace"&&ge&&Ne.current?.isEmpty()&&q.length===0){le.preventDefault(),Ce(void 0);return}l&&!M&&Ol(le,{allowBare:!0})===X&&(le.preventDefault(),Tt?w?.():Ot())};return i.jsxs("div",{ref:Ze,className:"relative",children:[M==="mention"&&i.jsx(ate,{id:te,groups:Lt,query:de??"",activeIndex:it,onActiveIndexChange:K,openFolderId:pe,folderIndex:Ae,onOpenFolderIdChange:Ie,onFolderIndexChange:He,onSelect:E,left:_t.left,flyoutSide:_t.flyoutSide}),M==="plugin"&&i.jsx("div",{ref:nt,role:"listbox","aria-label":I("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:Dt.map((le,Pe)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Pe===it,onMouseDown:Ge=>Ge.preventDefault(),onClick:()=>L(le),onMouseMove:()=>K(Pe),className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Pe===it&&"bg-foreground/10"),children:[i.jsx("span",{className:"shrink-0 font-mono text-muted-foreground",children:"#"}),i.jsx("span",{className:"shrink-0 font-medium",children:le.item.label}),le.item.detail&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:le.item.detail})]},le.key))}),(M==="slash"||M==="slash-sub")&&i.jsx("div",{ref:nt,role:"listbox","aria-label":I("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"?wt:Jt).map((le,Pe)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Pe===it,onClick:()=>{K(Pe),M==="slash"?he(le.name):F(le.name,!1)},onMouseMove:()=>K(Pe),className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Pe===it&&"bg-foreground/10"),children:[i.jsx(QN,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-mono font-medium",children:on!==null?`$${le.name.slice(7)}`:le.name}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:I(le.description)})]},le.name))}),i.jsxs("div",{ref:oe,"data-slot":"composer","data-enso":"composer",className:W("rounded-[24px] border bg-card shadow-[0_2px_6px_rgb(0_0_0/0.03),0_12px_32px_rgb(0_0_0/0.07)] transition-[border-color,box-shadow] duration-200 focus-within:border-foreground/20 [.dark_&]:shadow-[0_2px_6px_rgb(0_0_0/0.2),0_12px_32px_rgb(0_0_0/0.3)]",(fe||Se)&&"border-brand/50 bg-brand/5",(ht||N)&&"border-primary/35 shadow-primary/5"),onDragOver:le=>{le.dataTransfer.types.includes("Files")&&(le.preventDefault(),U(!0))},onDragLeave:le=>{le.currentTarget.contains(le.relatedTarget)||U(!1)},onDrop:le=>{const Pe=Array.from(le.dataTransfer.files);Pe.length!==0&&(le.preventDefault(),U(!1),jt(Pe))},children:[V.filter(le=>!le.id).length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:V.filter(le=>!le.id).map((le,Pe)=>i.jsxs("div",{className:"group relative",children:[i.jsx("button",{type:"button",onClick:()=>Z(le),className:"block rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none","aria-label":I("Preview"),children:i.jsx("img",{src:`data:${le.mimeType};base64,${le.data}`,alt:"",className:"h-16 w-16 rounded-md border object-cover"})}),i.jsx("button",{type:"button",onClick:()=>Y(Ge=>cte(Ge,le)),className:"absolute -top-1.5 -right-1.5 rounded-full border bg-background p-0.5 text-muted-foreground shadow-sm transition-opacity hover:text-destructive",children:i.jsx(dn,{className:"h-3 w-3"})})]},Pe))}),i.jsxs("div",{className:W("flex items-start gap-1.5 px-4",V.length>0?"pt-1.5":"pt-3.5"),children:[ge&&i.jsx(HK,{recipient:ge,onRemove:()=>Ce(void 0)}),q.map(le=>i.jsx(Lu,{name:le,className:"mt-0.5 shrink-0",trailing:i.jsx("button",{type:"button",onClick:()=>ee(Pe=>Pe.filter(Ge=>Ge!==le)),className:"rounded-sm opacity-70 hover:opacity-100","aria-label":I("Remove"),children:i.jsx(dn,{className:"h-3 w-3"})})},le)),i.jsx(ste,{ref:Ne,placeholder:q.length>0?"":d?I("Resolve the pending approval to continue"):ht?I("Message the selected Agent…"):ut?I("Press {{key}} to steer the next queued message into this round…",{key:ti(X)}):_||I(n?"Message will queue until this round finishes…":"Type @ to choose a file or Agent"),disabled:d,onStateChange:be,onChipActivate:le=>{le.type==="ui-element"&&Q({kind:"ui-element",id:le.id,label:le.label,path:le.path,text:le.text,imageId:le.imageId})},onKeyDown:It,onPasteText:le=>!T||!Lj(le)?!1:(T(le).catch(()=>({ok:!1,error:"unavailable"})).then(Pe=>{const Ge=Ne.current;Pe.ok?Ge?.insertFileChip(Pe.path,`${Qj} · ${I("{{count}} chars",{count:Pe.chars.toLocaleString()})}`):Ge?.insertText(le)}),!0),onPaste:le=>{const Pe=Array.from(le.clipboardData.files);Pe.length!==0&&(le.preventDefault(),jt(Pe))},onCompositionStart:()=>{Ut.current=!0},onCompositionEnd:()=>{Ut.current=!1},ariaProps:{role:"combobox","aria-autocomplete":"list","aria-expanded":M!==null,"aria-controls":M==="mention"?te:void 0,"aria-activedescendant":M==="mention"?pe?`${te}-sub-${Ae}`:`${te}-option-${it}`:void 0}})]}),ht&&i.jsx("p",{className:"sr-only",children:I("Send only to the selected Agent")}),i.jsxs("div",{className:"flex items-center justify-between gap-1.5 px-3 pt-0.5 pb-2.5",children:[i.jsxs("div",{className:W("flex min-w-0 flex-1 items-center gap-1",P?"overflow-x-auto [scrollbar-width:none]":"overflow-hidden"),children:[i.jsx("input",{ref:bt,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:le=>{jt(Array.from(le.target.files??[])),le.target.value=""}}),i.jsx("button",{type:"button",disabled:d,onClick:()=>bt.current?.click(),"aria-label":I("Attach image"),title:I("Attach image"),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40",children:i.jsx(Eh,{className:"h-3.5 w-3.5"})}),i.jsx(G0,{side:"left",...Ht}),z?i.jsx(Wee,{active:D,disabled:d,onChange:le=>{O(le),le?document.activeElement?.blur():Ne.current?.focus()}}):k?i.jsx(hD,{startSession:k,requestMicAccess:S,disabled:d,holdBinding:H||void 0,holdScope:Ze,onText:le=>{Ne.current?.insertText(le),Ne.current?.focus()}}):null,c,!C&&i.jsx(Dee,{sessionId:Ht.sessionId}),i.jsx(G0,{side:"right",...Ht}),yt&&(yt.blocked.length>0||yt.masked>0)&&i.jsxs("span",{className:W("flex shrink-0 items-center gap-1 text-[11px]",yt.blocked.length>0?"text-red-600 dark:text-red-400":"text-sky-600 dark:text-sky-400"),"data-privacy-precheck":!0,children:[yt.blocked.length>0?i.jsx(xj,{className:"size-3.5"}):i.jsx(sh,{className:"size-3.5"}),yt.blocked.length>0?I("Will be blocked: {{kinds}}",{kinds:yt.blocked.join(", ")}):I("{{count}} will be masked",{count:yt.masked})]})]}),ot&&!Ke?i.jsx(me,{variant:"outline",size:"icon",className:"size-8 shrink-0 rounded-full",onClick:y,"aria-label":I("Stop"),children:i.jsx(X$,{className:"h-4 w-4"})}):i.jsx(me,{size:"icon",className:"size-8 shrink-0 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-35",onClick:Ot,disabled:!Ke||d,"aria-label":I(ht?"Send only to the selected Agent":"Send"),title:ht?I("Send only to the selected Agent"):l&&X?`${I("Send")} ${ti(X)}`:I("Send"),children:i.jsx(fc,{className:"h-4 w-4"})})]})]}),z&&D?i.jsx(Uee,{startSession:z,disabled:d,onText:le=>{Ne.current?.insertText(le),document.activeElement?.blur()}}):null,i.jsx(xn,{open:G!==null,onOpenChange:le=>!le&&Q(null),children:i.jsxs(vn,{className:"max-w-md",children:[i.jsx(bn,{children:i.jsx(wn,{children:G?.label??I("Selected UI element")})}),i.jsx(An,{className:"space-y-2 text-xs",children:G&&i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-muted-foreground break-all",children:G.path}),G.text&&i.jsx("p",{children:G.text}),(()=>{const le=V.find(Pe=>Pe.id===G.imageId);return le?i.jsx("img",{src:`data:${le.mimeType};base64,${le.data}`,alt:"",className:"max-h-72 w-full rounded-md border object-contain"}):null})()]})})]})}),i.jsx(xn,{open:ae!==null,onOpenChange:le=>!le&&Z(null),children:i.jsxs(vn,{className:"max-w-3xl",children:[i.jsx(bn,{children:i.jsx(wn,{children:I("Preview")})}),i.jsx(An,{children:ae&&i.jsx("img",{src:`data:${ae.mimeType};base64,${ae.data}`,alt:"",className:"max-h-[80vh] w-full rounded-md object-contain"})})]})})]})}function SE({title:e,className:t,onCommit:n,onCancel:s}){const[o,r]=m.useState(e),a=()=>{const l=o.trim();!l||l===e?s():n(l)};return i.jsx("input",{className:W("min-w-0 flex-1 rounded bg-transparent px-0.5 text-inherit outline-none ring-1 ring-ring",t),value:o,autoFocus:!0,onChange:l=>r(l.target.value),onBlur:a,onClick:l=>l.stopPropagation(),onPointerDown:l=>l.stopPropagation(),onKeyDown:l=>{l.stopPropagation(),!l.nativeEvent.isComposing&&(l.key==="Enter"?(l.preventDefault(),a()):l.key==="Escape"&&(l.preventDefault(),s()))}})}async function CE(e,t){const n=await ie.getState().reloadConversation(e);n&&ze({type:"error",title:t("Failed to reload conversation"),description:n})}async function ute(e,t){const n=await ie.getState().restartConversation(e);n&&ze({type:"error",title:t("Failed to restart conversation"),description:n})}function hte({parentId:e,displayedId:t,trailing:n}){const{t:s}=ne(),o=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=>xW(p.conversations,e)),[d,u]=m.useState(!1),h=p=>W("flex min-w-0 shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",p?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50");return i.jsxs(b_,{"data-enso":"session-tabs",className:"border-b",children:[i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none]",children:[i.jsx(xC,{id:e,label:o||s("New conversation"),className:h(t===e),leading:i.jsx(Cr,{className:"h-3 w-3 shrink-0"}),reloadDisabled:a||l,reloading:a,onSelect:()=>ie.getState().selectTab(e,void 0)}),c.map(p=>{const f=S5({status:p.status,spawning:p.spawning,pendingApprovalCount:p.pendingApprovalCount,pendingAskCount:p.pendingAskCount});return i.jsxs("div",{className:"group/tab relative shrink-0",children:[i.jsx(xC,{id:p.id,label:p.title||p.child?.agentInstanceName||p.coworkerName||p.id,className:W(h(t===p.id),t!==p.id&&"group-hover/tab:bg-muted/50"),leading:p.mode==="task"?i.jsx(ex,{className:"h-3 w-3 shrink-0"}):i.jsx(Ws,{className:"h-3 w-3 shrink-0"}),trailing:i.jsx("span",{className:"inline-flex h-3 w-3 shrink-0 items-center justify-center group-hover/tab:invisible",children:i.jsx(Tc,{tone:f,size:"sm"})}),reloadDisabled:p.reloading||p.spawning,reloading:p.reloading,onSelect:()=>ie.getState().selectTab(e,p.id)}),i.jsx("button",{type:"button",title:s("Dismiss coworker"),className:"absolute top-1/2 right-2 hidden h-3 w-3 -translate-y-1/2 items-center justify-center text-muted-foreground hover:text-destructive group-hover/tab:flex",onClick:()=>{window.confirm(s("Dismiss this coworker? Its session will be closed."))&&ie.getState().dismissCoworkerFromUI(e,p.id)},children:i.jsx(dn,{className:"h-3 w-3"})})]},p.id)}),i.jsx("button",{type:"button",title:s("Hire coworker"),disabled:!r,onClick:()=>u(!0),className:"shrink-0 rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",children:i.jsx(as,{className:"h-3.5 w-3.5"})})]}),n,d&&i.jsx(pte,{parentId:e,onClose:()=>u(!1)})]})}function xC({id:e,label:t,className:n,leading:s,trailing:o,reloadDisabled:r,reloading:a,onSelect:l}){const{t:c}=ne(),[d,u]=m.useState(!1),h=i.jsxs("button",{type:"button",className:n,onClick:()=>{d||l()},onDoubleClick:p=>{p.preventDefault(),p.stopPropagation(),u(!0)},children:[s,d?i.jsx(SE,{title:t,className:"max-w-48 text-xs",onCommit:p=>{ie.getState().renameConversation(e,p),u(!1)},onCancel:()=>u(!1)}):i.jsx("span",{className:"max-w-48 truncate",children:t}),o]});return i.jsxs(go,{children:[i.jsx(xo,{render:h}),i.jsxs(vo,{className:"min-w-36",children:[i.jsxs($t,{onClick:()=>u(!0),children:[i.jsx($s,{}),c("Rename")]}),i.jsxs($t,{disabled:r,onClick:()=>{CE(e,c)},children:[i.jsx(Ko,{className:a?"animate-spin":void 0}),c("Reload conversation")]})]})]})}function pte({parentId:e,onClose:t}){const{t:n}=ne(),s=we(x=>x.agentTypes),o=we(x=>x.disabledBuiltinAgentTypes),[r,a]=m.useState(""),[l,c]=m.useState(""),[d,u]=m.useState(null),h=new Set(s.map(x=>x.name.trim().toLowerCase())),p=[...C5.filter(x=>!o.includes(x.name)&&!h.has(x.name)).map(x=>x.name),...s.map(x=>x.name)],f=[{value:"",label:"general"},...p.map(x=>({value:x,label:x}))],g=async()=>{const x=await ie.getState().hireCoworker(e,r.trim(),l||void 0);x?u(x):t()};return i.jsx(xn,{open:!0,onOpenChange:x=>!x&&t(),children:i.jsxs(vn,{className:"max-w-sm",children:[i.jsx(bn,{children:i.jsx(wn,{children:n("Hire coworker")})}),i.jsxs(An,{className:"space-y-4",children:[i.jsxs(Gs,{children:[i.jsx(Fs,{children:n("Name (slug)")}),i.jsx(Zt,{value:r,onChange:x=>a(x.target.value),placeholder:"reviewer",autoFocus:!0})]}),i.jsxs(Gs,{children:[i.jsx(Fs,{children:n("Agent type")}),i.jsxs(bs,{items:f,value:l,onValueChange:x=>c(x??""),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:f.map(x=>i.jsx(rs,{value:x.value,children:x.label},x.value||"general"))})]})]}),d&&i.jsx("p",{className:"text-destructive text-xs",children:d}),i.jsx("div",{className:"h-1"})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"ghost",onClick:t,children:n("Cancel")}),i.jsx(me,{onClick:()=>{g()},disabled:!r.trim(),children:n("Hire")})]})]})})}function fte(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 mte={active:"bg-green-500 animate-pulse",paused:"bg-amber-500",waiting:"bg-amber-500",blocked:"bg-destructive",completed:"bg-blue-500"};function gte({conversationId:e,goal:t}){const{t:n}=ne(),s={active:n("working"),paused:n("paused"),waiting:n("waiting"),blocked:n("blocked"),completed:n("completed")};return i.jsxs("div",{className:"mb-1 flex items-center gap-2 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-1.5 text-xs",children:[i.jsx(Ma,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",title:t.note?`${t.text} — ${t.note}`:t.text,children:[t.text,t.note&&i.jsxs("span",{className:"text-muted-foreground",children:[" — ",t.note]})]}),i.jsx("span",{className:W("h-1.5 w-1.5 shrink-0 rounded-full",mte[t.status])}),i.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums",children:[s[t.status],t.status==="active"&&t.autoTurns>0?` · ${t.autoTurns}/25`:""]}),t.status==="active"?i.jsx("button",{type:"button",title:n("Pause goal"),onClick:()=>ie.getState().pauseGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(p4,{className:"h-3.5 w-3.5"})}):t.status!=="completed"?i.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:i.jsx($g,{className:"h-3.5 w-3.5"})}):null,i.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:i.jsx(dn,{className:"h-3.5 w-3.5"})})]})}function xte(e,t){return e.trim().length>0||t>0}function vC(e,t){return e>0?`${e} ${t}`:null}function kE({conversationId:e,queued:t}){const{t:n}=ne(),[s,o]=m.useState(null),[r,a]=m.useState("");if(t.length===0)return null;const l=c=>{xte(r,c.images?.length??0)&&ie.getState().updateQueuedMessage(e,c.id,r.trim()),o(null)};return i.jsx("div",{className:"mb-1 flex flex-col gap-0.5",children:t.map(c=>i.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/60 border-dashed bg-muted/20 px-2.5 py-1.5 text-xs",children:[i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground uppercase tracking-wide",children:n("Queued")}),s===c.id?i.jsx("input",{value:r,onChange:d=>a(d.target.value),onKeyDown:d=>{d.nativeEvent.isComposing||(d.key==="Enter"&&l(c),d.key==="Escape"&&o(null))},autoFocus:!0,className:"h-6 min-w-0 flex-1 rounded border bg-transparent px-1.5 outline-none focus:ring-1 focus:ring-ring"}):i.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.text||"[image]"}),vC(c.images?.length??0,n("attachments"))&&i.jsxs("span",{title:vC(c.images?.length??0,n("attachments"))??void 0,className:"flex shrink-0 items-center gap-0.5 text-muted-foreground",children:[i.jsx(W6,{className:"h-3 w-3"}),c.images?.length]}),s===c.id?i.jsx("button",{type:"button",onClick:()=>l(c),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(Yn,{className:"h-3.5 w-3.5"})}):i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:[i.jsx("button",{type:"button",title:n("Withdraw message"),"aria-label":n("Withdraw message"),onClick:()=>ie.getState().withdrawMessage(e,{kind:"queue",id:c.id}),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(va,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Edit"),onClick:()=>{o(c.id),a(c.text)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx($s,{className:"h-3 w-3"})}),i.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:i.jsx(qx,{className:"h-3 w-3"})}),i.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:i.jsx(N4,{className:"h-3 w-3"})}),i.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:i.jsx(dn,{className:"h-3.5 w-3.5"})})]})]},c.id))})}const jE="mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2 text-xs";function _E({doc:e}){return i.jsx("div",{className:"mt-2 max-h-72 overflow-y-auto rounded-md border border-border/60 bg-background/60 px-3 py-2 text-sm",children:i.jsx(Ts,{text:e.text})})}function vte({conversationId:e,planState:t,approvalMode:n}){const s=w_(t);return s==="awaiting_review"&&t?.pending?i.jsx(bte,{conversationId:e,doc:t.pending,approvalMode:n},t.pending.planId):s==="executing"&&t?.executing?i.jsx(wte,{conversationId:e,doc:t.executing},t.executing.planId):null}function bte({conversationId:e,doc:t,approvalMode:n}){const{t:s}=ne(),o=k5(),[r,a]=m.useState(!0),[l,c]=m.useState(!1),[d,u]=m.useState(""),[h,p]=m.useState(!1),[f,g]=m.useState(!1),x=async(v,y)=>{g(!0);const b=ie.getState();y&&y!==n&&b.setApprovalMode(e,y);const w=await b.respondPlan(e,t.planId,v,v==="revise"?d.trim():void 0);w&&(g(!1),ze({type:"error",title:s("Plan response failed"),description:w}))};return i.jsxs("div",{className:jE,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Sa,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),i.jsx("span",{className:"shrink-0 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:s("Plan awaiting approval")}),i.jsxs("button",{type:"button",onClick:()=>a(v=>!v),className:"flex min-w-0 flex-1 items-center gap-1 text-left font-medium",title:t.title,children:[i.jsx("span",{className:"truncate",children:t.title}),i.jsx(un,{className:W("h-3 w-3 shrink-0 transition-transform",r&&"rotate-90")})]})]}),r&&i.jsx(_E,{doc:t}),l&&i.jsx("textarea",{autoFocus:!0,value:d,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&d.trim()&&(v.preventDefault(),x("revise"))},placeholder:s("What should change in this plan?"),className:"mt-2 min-h-16 w-full resize-y rounded-md border border-border/60 bg-background px-2.5 py-1.5 text-sm outline-none focus:border-brand/45"}),i.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[i.jsx("button",{type:"button",disabled:f,onClick:()=>{x("discard")},className:"rounded-md px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50",children:s("Discard and exit plan mode")}),l?i.jsx("button",{type:"button",disabled:f||!d.trim(),onClick:()=>{x("revise")},className:"rounded-md px-2.5 py-1 text-xs text-foreground transition-colors hover:bg-muted disabled:opacity-50",children:s("Send feedback")}):i.jsx("button",{type:"button",disabled:f,onClick:()=>c(!0),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:s("Request changes")}),i.jsxs("div",{className:"flex",children:[i.jsx("button",{type:"button",disabled:f,onClick:()=>{x("approve")},title:s(Gl[n].labelKey),className:"rounded-l-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:s("Approve and execute")}),i.jsxs(vi,{open:h,onOpenChange:p,children:[i.jsx(bi,{disabled:f,"aria-label":s("Choose the approval mode for execution"),className:"flex items-center rounded-r-md border-primary-foreground/20 border-l bg-primary px-1 text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:i.jsx($n,{className:"h-3.5 w-3.5"})}),i.jsxs(wi,{side:"top",align:"end",className:"w-80 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsx("p",{className:"px-2 pt-1 pb-1.5 text-muted-foreground text-xs",children:s("Approve and execute with")}),j5.map(v=>{const y=Gl[v],b=y.icon,w=v==="assistant"&&!o;return i.jsxs("button",{type:"button",disabled:w,onClick:()=>{p(!1),x("approve",v)},className:W("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",v===n?"bg-muted":"hover:bg-muted/60",w&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[i.jsx(b,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block",children:s(y.labelKey)}),i.jsx("span",{className:"block text-xs text-muted-foreground",children:s(y.descKey)})]})]},v)})]})]})]})]})]})}function wte({conversationId:e,doc:t}){const{t:n}=ne(),[s,o]=m.useState(!1);return i.jsxs("div",{className:W(jE,"py-1.5"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(KN,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:n("Executing plan")}),i.jsxs("button",{type:"button",onClick:()=>o(r=>!r),className:"flex min-w-0 flex-1 items-center gap-1 text-left",title:t.title,children:[i.jsx("span",{className:"truncate",children:t.title}),i.jsx(un,{className:W("h-3 w-3 shrink-0 transition-transform",s&&"rotate-90")})]}),i.jsx("button",{type:"button",title:n("Finish plan"),onClick:()=>{ie.getState().respondPlan(e,t.planId,"finish")},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]}),s&&i.jsx(_E,{doc:t})]})}function yte({active:e,onToggle:t}){const{t:n}=ne();return i.jsxs("button",{type:"button","aria-pressed":e,title:n(e?"Plan mode is on: read-only research, then a plan for your approval":"Plan first: research read-only and submit a plan for approval"),onClick:()=>t(!e),className:W("flex h-7 min-w-0 shrink-0 items-center gap-1 rounded-lg px-2 text-xs transition-colors",e?"bg-primary/10 text-primary hover:bg-primary/15":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx(Sa,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"hidden @min-[28rem]:inline",children:n("Plan")})]})}function Ste({presetId:e,onSelect:t,onModel:n,disabled:s}){const{t:o}=ne(),r=we(h=>h.presets),a=_5(),[l,c]=m.useState(!1),d=[{id:N5,name:o("Global")},...r.map(h=>({id:h.id,name:h.name})),...a.map(h=>({id:h.id,name:h.name}))],u=d.find(h=>h.id===e)??{id:e,name:T5(e)?o("Plugin preset unavailable"):d[0]?.name??""};return s?i.jsxs("span",{className:"flex h-7 min-w-0 max-w-40 shrink items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground",title:o("Preset is locked after the conversation starts"),children:[i.jsx(ou,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:u.name})]}):i.jsxs(vi,{open:l,onOpenChange:c,children:[i.jsxs(bi,{className:"flex h-7 min-w-0 max-w-40 shrink items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:u.name,children:[i.jsx(ou,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:u.name}),i.jsx($n,{className:"h-3 w-3 shrink-0"})]}),i.jsx(wi,{side:"top",align:"start",className:"w-52 [&_[data-slot=popover-viewport]]:p-1",children:d.map(h=>{const p=h.id===u.id;return i.jsxs("button",{type:"button",onClick:()=>{t(h.id);const f=r.find(x=>x.id===h.id)?.pluginPresetId,g=I5(f??h.id,a);g&&n?.(g),c(!1)},className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",p?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.name}),p&&i.jsx(Yn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},h.id)})})]})}const Cte=[];function kte({projectId:e,conversationId:t}){const{t:n}=ne(),s=we(p=>p.projects.find(f=>f.id===e)?.trustedProjectCode??Cte),o=we(p=>p.setProjectTrustedCode),[r,a]=m.useState([]),[l,c]=m.useState(!1),[d,u]=m.useState(!1);m.useEffect(()=>{let p=!1;return c(!1),u(!1),window.electronAPI.projects.codeSources({projectId:e,conversationId:t}).then(f=>{p||a(f)}).catch(()=>{p||a([])}),()=>{p=!0}},[e,t]);const h=r.filter(p=>!s.includes(p));return l||h.length===0&&!d?null:h.length===0?i.jsxs("div",{role:"status",className:"mb-1 flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-muted-foreground text-xs",children:[i.jsx(ca,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1",children:n("Project extensions trusted. They load in new sessions and after this one restarts.")}),i.jsx("button",{type:"button",onClick:()=>c(!0),title:n("Dismiss"),children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]}):i.jsxs("div",{role:"alert",className:"mb-1 flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/5 px-2.5 py-2 text-xs",children:[i.jsx(ca,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-warning"}),i.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[i.jsx("p",{children:n("This project ships pi extension code that runs with your permissions. It was not loaded. Trust it only if you trust this repository.")}),i.jsx("p",{className:"truncate font-mono text-muted-foreground",title:h.join(`
89
- `),children:h.join(", ")})]}),i.jsx(me,{size:"xs",variant:"outline",onClick:()=>{o(e,r),u(!0)},children:n("Trust and load")}),i.jsx("button",{type:"button",onClick:()=>c(!0),title:n("Dismiss"),children:i.jsx(dn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}const jte=70,NE=80,TE={system:"bg-brand",memory:"bg-warning",tools:"bg-info",skills:"bg-success",files:"bg-foreground/70",results:"bg-foreground/40",chat:"bg-muted-foreground/70"};function IE({segments:e,highlight:t,className:n}){return i.jsx("span",{"aria-hidden":!0,className:W("flex h-1 w-16 shrink-0 gap-px overflow-hidden rounded-full bg-muted-foreground/15",n),children:e.map(s=>i.jsx("span",{className:W("block h-full transition-opacity",TE[s.kind],t&&t!==s.kind&&"opacity-25"),style:{width:`${s.width}%`}},s.kind))})}function _te({percent:e,critical:t}){return i.jsx("span",{"aria-hidden":!0,className:"h-1 w-7 shrink-0 overflow-hidden rounded-full bg-muted-foreground/20",children:i.jsx("span",{className:W("block h-full rounded-full",t?"bg-destructive":e>=jte?"bg-warning":"bg-muted-foreground/70"),style:{width:`${e}%`}})})}const Nte={system:"System prompt",memory:"Enabled instructions",tools:"Tool definitions",skills:"Enabled skills",files:"Files read",results:"Tool results",chat:"Conversation"};function Tte({conversationId:e}){const{t}=ne(),n=ie(r=>r.conversations[e]?.compaction);if(!ie(r=>r.conversations[e]?.started))return null;const o=t(n==="running"?"Compacting…":n==="queued"?"Compacts after this turn":"Compact context");return i.jsx("button",{type:"button",disabled:!!n,className:"w-full rounded-sm border border-border px-2 py-1 text-[11px] text-foreground/90 hover:bg-muted disabled:cursor-default disabled:text-muted-foreground disabled:hover:bg-transparent",onClick:()=>ie.getState().compact(e),children:o})}function Ite({occupancy:e,conversationId:t,cwd:n,onNavigate:s}){const{t:o}=ne(),[r,a]=m.useState(),[l,c]=m.useState();if(!e)return i.jsx("p",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:o("Context occupancy unavailable until the session starts")});const d=e.contextWindow,u=sI(e),h=(e.percent??0)>=NE,p=[...u].filter(g=>by(e.parts,g.kind).length>0).sort((g,x)=>x.tokens-g.tokens)[0]?.kind,f=l===void 0?p:l;return i.jsxs("div",{className:"flex flex-col gap-2 px-2 py-1.5",children:[i.jsxs("div",{className:"flex items-baseline justify-between gap-2 text-xs",children:[i.jsxs("span",{className:"tabular-nums",children:[Qn(e.used),d?` / ${Qn(d)}`:" · ?",e.percent!==void 0&&i.jsx("span",{className:W(h&&"text-warning"),children:` · ${e.percent}%`})]}),i.jsx("span",{className:"text-muted-foreground",children:o("Estimate")})]}),u.length>0&&i.jsx(IE,{segments:u,highlight:r,className:"h-1.5 w-full"}),h&&d!==void 0&&i.jsx("p",{className:"text-[11px] text-warning",children:o("About {{tokens}} left",{tokens:Qn(Math.max(0,d-e.used))})}),e.compactionModelMismatch&&i.jsx("p",{className:"text-[11px] text-muted-foreground",children:o("Current summary was produced by another model family")}),e.compactedMessageCount>0&&i.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[i.jsx("p",{children:o("{{count}} older messages are folded into the summary",{count:e.compactedMessageCount})}),t&&e.compactionEntryId&&i.jsx("button",{type:"button",className:"shrink-0 text-foreground/80 hover:underline",onClick:()=>{ie.getState().forkFromEntry(t,e.compactionEntryId)},children:o("Conversation branch")})]}),i.jsx("ul",{className:"flex flex-col gap-1",onMouseLeave:()=>a(void 0),children:u.map(({kind:g,tokens:x})=>{const v=e.used>0?Math.round(x/e.used*100):0,y=by(e.parts,g),b=f===g&&y.length>0;return i.jsxs("li",{onMouseEnter:()=>a(g),children:[i.jsxs("button",{type:"button",disabled:y.length===0,"aria-expanded":y.length>0?b:void 0,onClick:()=>c(b?null:g),className:"flex w-full items-center gap-1.5 rounded-sm text-left text-[11px] enabled:hover:bg-muted/60",children:[i.jsx(un,{className:W("h-3 w-3 shrink-0 text-muted-foreground transition-transform",b&&"rotate-90",y.length===0&&"invisible")}),i.jsx("span",{className:"w-24 shrink-0 truncate text-muted-foreground",children:o(Nte[g])}),i.jsx("span",{className:"min-w-0 flex-1",children:i.jsx("span",{className:"block h-1 overflow-hidden rounded-full bg-muted",children:i.jsx("span",{className:W("block h-full",TE[g]),style:{width:`${v}%`}})})}),i.jsx("span",{className:"w-10 shrink-0 text-right tabular-nums",children:Qn(x)}),i.jsxs("span",{className:"w-8 shrink-0 text-right text-muted-foreground tabular-nums",children:[v,"%"]})]}),b&&i.jsx("ul",{className:"mt-0.5 ml-1.5 flex flex-col gap-0.5 border-l border-border pl-2",children:y.map(w=>{const C=m7(w),_=x7(g,w,n),N=k=>{if(k.type==="file"){if(!t)return;D5(t,k.rel)}else window.electronAPI.window.openSettings(k.link);s?.()};return i.jsxs("li",{className:"group/item flex items-center gap-2 rounded-sm text-[11px] text-muted-foreground hover:bg-muted/60 hover:text-foreground",children:["raw"in C?i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono",title:C.raw,children:C.raw}):i.jsx("span",{className:"min-w-0 flex-1 truncate",children:o(C.key,C.vars)}),_&&(_.type==="settings"||t)?i.jsx("button",{type:"button",onClick:()=>N(_),className:"hidden shrink-0 rounded-sm border border-border bg-background px-1.5 text-[10px] leading-4 text-muted-foreground hover:text-foreground group-hover/item:block focus-visible:block",children:o(_.type==="file"?"Open":"Settings")}):null,i.jsx("span",{className:W("shrink-0 tabular-nums",_&&"group-hover/item:hidden"),children:Qn(w.tokens)})]},`${w.tag}-${w.name}`)})})]},g)})}),t&&i.jsx(Tte,{conversationId:t})]})}function Dte(e){return e?e.used:null}const Gv=90;function DE(e,t){const n=Dte(e);if(n===null)return;const s=e?.contextWindow&&e.contextWindow>0?e.contextWindow:t&&t>0?t:0;return s>0?{used:n,window:s}:{used:n}}function Ete(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 Pte(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:`${Qn(a)} · ${l}%`,percent:l,critical:l>=Gv}}else n.context={compact:`${Qn(r)}·?`,full:`${Qn(r)} · ?`}}const s=[],o=[];return t.ttftAvgMs!==void 0&&(s.push(qn(t.ttftAvgMs)),o.push(e("First token avg {{duration}}",{duration:qn(t.ttftAvgMs)}))),t.tokensPerSecond!==void 0&&(s.push(`${t.tokensPerSecond} tok/s`),o.push(e("{{speed}} tok/s",{speed:t.tokensPerSecond}))),s.length>0&&(n.speed={compact:s.join(" · "),full:o.join(" · ")}),(t.inputTokens>0||t.outputTokens>0)&&(n.tokens={compact:`↑${Qn(t.inputTokens)} ↓${Qn(t.outputTokens)}`,full:e("Input {{input}} tok · Output {{output}} tok",{input:Qn(t.inputTokens),output:Qn(t.outputTokens)})}),t.cacheHitPercent!==void 0&&(n.cache={compact:`${t.cacheHitPercent}%`,full:e("Cache hit {{percent}}%",{percent:t.cacheHitPercent})}),n}function Ate(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:vf(t.bytes),full:`${vf(t.bytes)} / ${vf(t.limitBytes)} · ${n}% · ${s}`,critical:t.blocked||n>=Gv}}function vf(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 Mte({className:e,orientation:t="horizontal",...n}){return i.jsx(E5,{className:W("shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px data-[orientation=vertical]:not-[[class^='h-']]:not-[[class*='_h-']]:self-stretch",e),"data-slot":"separator",orientation:t,...n})}const Rte={minimal:"Minimal",default:"Default",full:"Full"};function Lte({icons:e,values:t}){const{t:n}=ne(),s=we(x=>x.statusLineSegments),o=m.useMemo(()=>EE(s),[s]),r=we(x=>x.toggleStatusLineSegment),a=we(x=>x.setStatusLineSegments),[l,c]=m.useState(null),[d,u]=m.useState(null),h=P5(o),p=y_.filter(x=>!o.includes(x)),f=()=>{c(null),u(null)},g=()=>{if(l!==null&&d!==null){const x=d>l?d-1:d,v=L5(o,l,x);v!==o&&a([...v])}f()};return i.jsxs("div",{className:"flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2 border-b p-2",children:[i.jsx("div",{className:"flex gap-1",children:A5.map(x=>i.jsx(me,{variant:h===x?"secondary":"ghost",size:"xs",onClick:()=>a([...M5[x]]),children:n(Rte[x])},x))}),h==="custom"&&i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:n("Custom")})]}),i.jsxs("div",{className:"max-h-80 overflow-y-auto p-2",onDragOver:x=>{l!==null&&x.preventDefault()},onDrop:x=>{l!==null&&(x.preventDefault(),g())},children:[o.map((x,v)=>{const y=e[x],b=t[x];return i.jsxs("div",{children:[l!==null&&d===v&&i.jsx("div",{className:"mx-2 my-0.5 h-0.5 rounded-full bg-primary"}),i.jsxs("div",{onDragOver:w=>{if(l===null)return;w.preventDefault();const C=w.currentTarget.getBoundingClientRect(),_=w.clientY<C.top+C.height/2;u(_?v:v+1)},onDrop:w=>{w.preventDefault(),g()},className:W("flex items-center justify-between gap-3 rounded-md px-2 py-1.5",l===v&&"opacity-40"),children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx("span",{role:"button",tabIndex:0,draggable:!0,onDragStart:w=>{w.dataTransfer.effectAllowed="move",w.dataTransfer.setData("text/plain",x),c(v)},onDragEnd:f,"aria-label":n("Drag to reorder"),className:"shrink-0 cursor-grab text-muted-foreground/50 hover:text-foreground active:cursor-grabbing",children:i.jsx(R5,{className:"h-3.5 w-3.5"})}),i.jsx(y,{className:"h-3.5 w-3.5 shrink-0"}),i.jsxs("div",{className:"flex min-w-0 flex-col",children:[i.jsx("span",{className:"text-sm",children:n(Vu[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:b?.full||n("No data yet")})]})]}),i.jsx(pi,{checked:!0,onCheckedChange:w=>r(x,w)})]})]},x)}),l!==null&&d===o.length&&i.jsx("div",{className:"mx-2 my-0.5 h-0.5 rounded-full bg-primary"}),p.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(Mte,{className:"my-2"}),p.map(x=>{const v=e[x],y=t[x];return i.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md px-2 py-1.5",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx("span",{className:"w-3.5 shrink-0"}),i.jsx(v,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),i.jsxs("div",{className:"flex min-w-0 flex-col",children:[i.jsx("span",{className:"text-sm",children:n(Vu[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:y?.full||n("No data yet")})]})]}),i.jsx(pi,{checked:!1,onCheckedChange:b=>r(x,b)})]},x)})]})]})]})}function EE(e){const t=Array.isArray(e)?e:z5,n=new Set(y_),s=new Set,o=[];for(const r of t)typeof r=="string"&&n.has(r)&&!s.has(r)&&(s.add(r),o.push(r));return o}const Vu={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"},Ote={minimal:"Min",low:"Low",medium:"Med",high:"High",xhigh:"Extra",max:"Max"},zte={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"},Gte={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},Fte={supervised:B5,"auto-edits":sh,full:H5,assistant:ii},Hte={model:h6,context:$5,requestBody:V5,turns:x4,duration:qN,sessionTime:F6,speed:ex,tokens:i6,cache:f6,cwd:oi,sessionName:I4,coworkers:fa,usage:H4};function Bte(e,t,n){if(e.status!=="running")return{llm:0,tool:0};for(let s=t.length-1;s>=0;s--){const o=t[s];if(!(o.role!=="assistant"||!o.timing))return o.timing.completedMs===void 0?{llm:Math.max(0,n-o.timing.stepStartMs),tool:0}:{llm:0,tool:Math.max(0,n-o.timing.completedMs)}}return{llm:0,tool:0}}function Vte(e){return e.split(/[\\/]+/).filter(Boolean).at(-1)??e}function dd(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function bC(e){if(e<=0)return"0m";const t=Math.round(e/6e4),n=Math.floor(t/1440),s=Math.floor(t%1440/60),o=t%60;return n>0?`${n}d${s}h`:s>0?`${s}h${o}m`:`${o}m`}function wC(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 $te(e){return{...Hte,approval:Fte[e.approvalMode??"full"]}}function Wte(e,t){const[n,s]=m.useState(()=>{if(!e)return;const o=F0.get(e);return o?{key:e,data:o.data}:void 0});return m.useEffect(()=>{if(!e)return;let o=!1;const r=F0.get(e);if(r&&Date.now()-r.fetchedAt<G5){s({key:e,data:r.data});return}return F5(e).then(a=>{o||s({key:e,data:a})}).catch(()=>{o||s(a=>a?.key===e?void 0:a)}),()=>{o=!0}},[e,t]),e&&n?.key===e?n.data:void 0}function Ute(e,t,n,s,o,r,a){const l=i7(n),c={model:void 0,requestBody:Ate(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,...Pte(e,Ete(o7(l),DE(t.occupancy,t.contextWindow)))};if(t.lastModelId){const b=s.find(C=>C.id===t.lastProviderId)?.models.find(C=>C.id===t.lastModelId)?.label??t.lastModelId,w=t.reasoningEnabled?t.thinkingLevel:void 0;c.model={compact:w?`${b} · ${e(Ote[w])}`:b,full:w?`${b} · ${e(zte[w])}`:b}}l.steps>0&&(c.turns={compact:`${l.turns}·${l.steps}`,full:e("{{turns}} turns · {{steps}} steps",{turns:l.turns,steps:l.steps})});const d=Bte(t,n,r),u=l.llmMs+d.llm,h=l.toolMs+d.tool,p=[],f=[];u>=1e3&&(p.push(qn(u)),f.push(e("LLM {{duration}}",{duration:qn(u)}))),h>=1e3&&(p.push(qn(h)),f.push(e("Tool calls {{duration}}",{duration:qn(h)}))),p.length>0&&(c.duration={compact:p.join(" · "),full:f.join(" · ")});const g=Math.max(0,r-t.createdAt);c.sessionTime={compact:wC(g),full:wC(g)};const x=o.find(y=>y.id===t.projectId);if(x){const y=Vte(x.path);c.cwd={compact:y,full:x.path}}t.title.trim().length>0&&(c.sessionName={compact:dd(t.title,16),full:dd(t.title,60)}),c.approval={compact:"",full:e(Gte[t.approvalMode??"full"])};const v=t.coworkerIds?.length??0;if(v>0&&(c.coworkers={compact:String(v),full:e("{{count}} coworkers",{count:v})}),a&&!a.error&&a.windows.length>0){const y=a.windows,b=Math.max(...y.map(k=>k.usedPercent)),w=y[0],C=dd(w.label,24),_=w.resetsAt!==void 0?bC(w.resetsAt-r):void 0,N=y.length>1?` +${y.length-1}`:"";c.usage={compact:`${C} ${Math.round(w.usedPercent)}%${_?`·${_}`:""}${N}`,full:y.map(k=>{const S=k.resetsAt!==void 0?` · ${e("resets in {{remaining}}",{remaining:bC(k.resetsAt-r)})}`:"";return`${dd(k.label,24)} ${Math.round(k.usedPercent)}%${S}`}).join(" · "),critical:b>=Gv}}return c}function PE({conversationId:e,cwd:t}){const{t:n}=ne(),s=ie(T=>T.conversations[e]),o=s?.messages??[],r=Na(),a=we(T=>T.virtualModels),l=m.useMemo(()=>a.length===0?r:[...r,{id:S_,models:a.map(T=>({id:T.id,label:T.name}))}],[r,a]),c=we(T=>T.projects),d=we(T=>T.statusLineSegments),u=m.useMemo(()=>EE(d),[d]),[h,p]=m.useState(null),[f,g]=m.useState(!1),x=m.useMemo(()=>{if(u.includes("usage"))return tx(r,s)?.accountKey},[u,r,s]),[v,y]=m.useState(()=>Date.now()),b=s?.status==="running"&&u.includes("duration"),w=u.includes("sessionTime"),C=u.includes("usage")&&x!==void 0;m.useEffect(()=>{if(!b&&!w&&!C)return;const T=setInterval(()=>y(Date.now()),1e3);return()=>clearInterval(T)},[b,w,C]);const _=Wte(x,v),N=m.useMemo(()=>s?$te(s):null,[s]),k=m.useMemo(()=>s?Ute(n,s,o,l,c,v,_):null,[n,s,o,l,c,v,_]);if(!s||!N||!k)return null;const S=s.occupancy?sI(s.occupancy):[],A=u.filter(T=>k[T]);return i.jsxs("div",{"data-slot":"stats-line","data-enso":"status-line",className:"group relative flex h-7 items-center justify-center px-1",children:[A.length>0&&i.jsx("div",{className:"flex min-w-0 flex-nowrap items-center gap-3 overflow-hidden",children:A.map((T,I)=>{const P=k[T];if(!P)return null;const D=N[T],O=i.jsxs("span",{title:`${n(Vu[T])} · ${P.full}`,onMouseEnter:()=>p(T),onMouseLeave:()=>p(z=>z===T?null:z),className:W("relative flex items-center gap-1 text-[11px] tabular-nums",P.critical?"text-destructive":T==="context"&&P.percent!==void 0&&P.percent>=NE?"text-warning":"text-subtle-foreground"),children:[T==="context"&&P.percent!==void 0?S.length>0?i.jsx(IE,{segments:S}):i.jsx(_te,{percent:P.percent,critical:!!P.critical}):i.jsx(D,{className:"h-3 w-3 shrink-0 opacity-75"}),P.compact&&i.jsx("span",{className:"truncate",children:P.compact}),h===T&&T!=="context"&&i.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:[i.jsx("span",{className:"break-words font-medium",children:n(Vu[T])}),i.jsx("span",{className:"ml-1 break-words text-muted-foreground",children:P.full})]})]});return i.jsx("span",{className:W("shrink-0 items-center",f||O5(T,I)?"flex":"hidden group-focus-within:flex group-hover:flex"),children:T==="context"?i.jsxs(vi,{open:f,onOpenChange:g,children:[i.jsx(bi,{className:"rounded-sm outline-none",children:O}),i.jsx(wi,{side:"top",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:i.jsx(Ite,{occupancy:s.occupancy,conversationId:s.id,cwd:t,onNavigate:()=>g(!1)})})]}):O},T)})}),i.jsxs(vi,{children:[i.jsx(bi,{"aria-label":n("Status line settings"),className:"-translate-y-1/2 absolute top-1/2 right-1 flex h-5.5 w-5.5 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100",children:i.jsx(C_,{className:"h-3.5 w-3.5"})}),i.jsx(wi,{side:"top",align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:i.jsx(Lte,{icons:N,values:k})})]})]})}const Kte=["pattern","query","path","file_path"],qte=["path","file_path","query","pattern"],Yte=["command","cmd","script"],Xte=["path","file_path","pattern","query","command","url","description","summary"],yC=120;function qa(e){const t=e.replace(/\s+/g," ").trim();return t.length>yC?`${t.slice(0,yC-1)}…`:t}function Jte(e){const t=e.toLowerCase();return t.includes("search")||t.includes("grep")||t==="find"?Kte:t==="read"||t.endsWith("_read")?qte:t==="bash"||t.includes("shell")||t.includes("terminal")?Yte:Xte}function Zte(e,t){const n=t.trim();if(!n)return"";let s;try{s=JSON.parse(n)}catch{return qa(n)}if(s===null)return"";if(typeof s!="object"||Array.isArray(s))return qa(JSON.stringify(s)??String(s));const o=k_(e,s);if(o.summary!==void 0)return qa(o.summary);if(!o.args||typeof o.args!="object")return"";const r=o.args;for(const l of Jte(o.name)){const c=r[l];if(typeof c=="string"&&c.trim())return qa(c)}const a=JSON.stringify(r);return a==="{}"?"":qa(a)}function Qte(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}const AE=new Map,ene=e=>{const t=AE.get(e);return t?new Set(t):new Set},SC=(e,t)=>(AE.set(e,t),t),mg=new Map,tne=(e,t)=>{const n=mg.get(e)??new Set;mg.set(e,n);for(const s of t)n.add(s);return n};function Fv({sessionId:e,tasks:t,subagents:n,readOnly:s}){const o=we(b=>b.virtualModels),{t:r}=ne(),[a,l]=m.useState(()=>ene(e)),[c,d]=m.useState(null),u=ie(b=>b.pendingAgentOpen);m.useEffect(()=>{!u||u.sessionId!==e||(d(u.agentId),ie.setState({pendingAgentOpen:null}))},[u,e]);const h=tne(e,[...t.filter(b=>b.status==="running").map(b=>b.taskId),...n.filter(b=>b.status==="running").map(b=>b.id)]),p=(b,w)=>!a.has(b)&&(w==="running"||h.has(b)),f=t.filter(b=>p(b.taskId,b.status)),g=n.filter(b=>p(b.id,b.status));if(m.useEffect(()=>{const b=mg.get(e),w=[...t.filter(_=>_.status!=="running").map(_=>_.taskId),...n.filter(_=>_.status!=="running").map(_=>_.id)].filter(_=>b?.has(_)&&!a.has(_)&&_!==c);if(w.length===0)return;const C=setTimeout(()=>{l(_=>{const N=new Set(_);for(const k of w)N.add(k);return SC(e,N)})},5e3);return()=>clearTimeout(C)},[e,t,n,a,c]),f.length===0&&g.length===0)return null;const x=b=>{l(w=>SC(e,new Set(w).add(b))),c===b&&d(null)},v=f.find(b=>b.taskId===c)??null,y=g.find(b=>b.id===c)??null;return i.jsxs("div",{className:"relative mb-1.5",children:[(v||y)&&i.jsxs("div",{className:"absolute bottom-full left-0 right-0 z-30 mb-1.5 rounded-xl border bg-card shadow-float",children:[i.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-1.5 text-xs",children:[i.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:[v?v.command:y?.description,y?.modelId?` · ${Kf(o,y.modelId)}`:""]}),i.jsx("button",{type:"button",onClick:()=>d(null),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(dn,{className:"h-3.5 w-3.5"})})]}),v&&i.jsx(cne,{tail:v.tail}),y&&i.jsx(nne,{agent:y},y.id)]}),i.jsxs("div",{className:"flex flex-col gap-0.5 rounded-xl border bg-card p-1 shadow-xs",children:[f.map(b=>i.jsx(CC,{icon:Uo,status:b.status,meta:i.jsx(lne,{task:b}),open:c===b.taskId,onToggle:()=>d(c===b.taskId?null:b.taskId),stopTitle:r("Stop task"),onStop:s?void 0:()=>{window.electronAPI.agent.stopTask(e,b.taskId)},onDismiss:()=>x(b.taskId),children:i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground",title:b.command,children:b.command})},b.taskId)),g.map(b=>i.jsxs(CC,{icon:Ws,status:b.status,meta:i.jsx(ane,{agent:b}),open:c===b.id,onToggle:()=>d(c===b.id?null:b.id),stopTitle:r("Stop subagent"),onStop:s?void 0:()=>{window.electronAPI.agent.stopSubagent(e,b.id)},onDismiss:()=>x(b.id),children:[b.agentType&&i.jsx("span",{className:"shrink-0 font-medium",children:b.agentType}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:[b.description,b.modelId&&i.jsxs("span",{className:"text-muted-foreground/60",children:[" ","· ",Kf(o,b.modelId)]}),b.status==="running"&&b.currentActivity&&i.jsxs("span",{className:"text-muted-foreground/60",children:[" · ",b.currentActivity]})]})]},b.id))]})]})}function CC({icon:e,status:t,meta:n,open:s,onToggle:o,stopTitle:r,onStop:a,onDismiss:l,children:c}){const{t:d}=ne();return i.jsxs("div",{className:"flex min-h-[30px] min-w-0 items-center gap-2 px-1 text-[13px]",children:[i.jsx(Tq,{icon:e,state:t==="running"?"running":t==="failed"?"error":"ok"}),c,n,i.jsxs("button",{type:"button",onClick:o,"aria-expanded":s,className:"flex h-6 shrink-0 items-center gap-0.5 rounded-md px-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[d("Output"),i.jsx($n,{className:W("h-3 w-3 transition-transform",s&&"rotate-180")})]}),t==="running"?a&&i.jsx("button",{type:"button",onClick:a,title:r,className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",children:i.jsx(mc,{className:"h-3 w-3"})}):i.jsx("button",{type:"button",onClick:l,className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:i.jsx(dn,{className:"h-3 w-3"})})]})}function nne({agent:e}){const{t}=ne(),n=e.activities??[],s=m.useRef(null),o=m.useRef(!0);return m.useEffect(()=>{const r=s.current;r&&o.current&&(r.scrollTop=r.scrollHeight)},[n,e.resultText]),i.jsxs("div",{ref:s,className:"max-h-96 space-y-2 overflow-auto px-3 py-2 text-sm",onScroll:r=>{o.current=Qte(r.currentTarget)},children:[n.map(r=>i.jsx(sne,{activity:r},r.id)),n.length===0&&!e.resultText&&i.jsx("pre",{className:"font-mono text-xs whitespace-pre-wrap text-muted-foreground",children:(e.activityLog??[]).join(`
90
- `)||t("(no output yet)")}),e.detailsPruned&&i.jsx("div",{className:"rounded-md border border-dashed px-2.5 py-2 text-xs text-muted-foreground",children:t("Earlier activity details were cleared; the final report is still available.")}),e.resultText&&e.status!=="running"&&i.jsxs("section",{className:W("rounded-lg border px-3 py-2",e.status==="failed"?"border-destructive/30 bg-destructive/5":"border-blue-500/30 bg-blue-500/5"),children:[i.jsx("div",{className:"mb-1.5 font-medium text-xs text-foreground",children:t("Final report")}),i.jsx(Ts,{text:e.resultText})]})]})}function sne({activity:e}){const{t}=ne(),[n,s]=m.useState(!1);if(e.type==="assistant")return i.jsxs("section",{className:"rounded-md bg-muted/30 px-2.5 py-2",children:[i.jsx("div",{className:"mb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:t("Assistant")}),i.jsx(rne,{text:e.text,markdown:!0})]});const o=Zte(e.toolName,e.argumentsText),r=k_(e.toolName,e.argumentsText).name,a=Sj(r),l=`subagent-tool-${e.id.replace(/[^A-Za-z0-9_-]/g,"-")}`;return i.jsxs("section",{className:"border-b border-border/40 last:border-b-0",children:[i.jsxs("button",{type:"button","aria-controls":l,"aria-expanded":n,onClick:()=>s(c=>!c),className:"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1 text-left text-xs transition-colors hover:bg-muted/50",children:[i.jsx(ine,{toolName:r}),i.jsx("span",{className:"shrink-0 font-medium text-foreground/80",children:a?.tool??r}),o&&i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",title:o,children:o}),!o&&i.jsx("span",{className:"min-w-0 flex-1"}),i.jsx(one,{status:e.status,label:t(e.status)}),i.jsx(un,{"aria-hidden":"true",className:W("h-3 w-3 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")})]}),n&&i.jsxs("div",{id:l,className:"ml-5 border-border/50 border-l pb-2 pl-2.5",children:[a&&i.jsxs("div",{className:"mb-1 truncate font-mono text-[10px] text-muted-foreground/70",children:[a.server,".",a.tool]}),i.jsx("div",{className:"text-[10px] text-muted-foreground/70",children:t("Arguments")}),i.jsx("pre",{className:"max-h-28 overflow-auto font-mono text-[10px] leading-relaxed whitespace-pre-wrap text-muted-foreground/80",children:ki(e.argumentsText)}),e.outputText&&i.jsxs("div",{className:"mt-1.5 border-border/40 border-t pt-1.5",children:[i.jsx("div",{className:"mb-0.5 text-[10px] text-muted-foreground",children:t("Result")}),i.jsx("pre",{className:"overflow-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-foreground/80",children:ki(e.outputText)})]})]})]})}function ine({toolName:e}){const t=e.toLowerCase(),n="h-3.5 w-3.5 shrink-0 text-muted-foreground";return t.includes("search")||t.includes("grep")||t==="find"?i.jsx(si,{"aria-hidden":"true",className:n}):t==="read"||t==="write"||t==="edit"||t==="apply_patch"||t.endsWith("_read")?i.jsx(jo,{"aria-hidden":"true",className:n}):t==="bash"||t==="exec"||t==="codemode"||t.includes("shell")||t.includes("terminal")?i.jsx(zf,{"aria-hidden":"true",className:n}):i.jsx(Kg,{"aria-hidden":"true",className:n})}function one({status:e,label:t}){const n="h-3.5 w-3.5";return i.jsx("span",{role:"status","aria-label":t,title:t,className:W("shrink-0",e==="failed"?"text-destructive":"text-muted-foreground"),children:e==="running"?i.jsx(Xt,{"aria-hidden":"true",className:W(n,"animate-spin")}):e==="done"?i.jsx(Yn,{"aria-hidden":"true",className:n}):e==="failed"?i.jsx(yr,{"aria-hidden":"true",className:n}):i.jsx(L$,{"aria-hidden":"true",className:n})})}function rne({text:e,label:t,markdown:n=!1}){const{t:s}=ne(),o=e.length>800||e.split(`
91
- `).length>16,r=n?i.jsx(Ts,{text:e}):i.jsx("pre",{className:"overflow-x-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:ki(e)});return o?i.jsxs("details",{className:"group/details",children:[i.jsxs("summary",{className:"cursor-pointer text-[10px] text-muted-foreground hover:text-foreground",children:[t?`${t} · `:"",s("{{count}} chars",{count:e.length})]}),i.jsx("div",{className:"mt-1.5",children:r})]}):i.jsxs("div",{children:[t&&i.jsx("div",{className:"mb-0.5 text-[10px] text-muted-foreground",children:t}),r]})}function ane({agent:e}){const[,t]=m.useState(0);return m.useEffect(()=>{if(e.status!=="running")return;const n=setInterval(()=>t(s=>s+1),1e3);return()=>clearInterval(n)},[e.status]),i.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:[e.steps>0?`${e.steps} steps · `:"",e.outputTokens?`${e.outputTokens} tok · `:"",e.status==="running"?qn(Date.now()-e.startedAt):e.status]})}function lne({task:e}){const[,t]=m.useState(0);return m.useEffect(()=>{if(e.status!=="running")return;const n=setInterval(()=>t(s=>s+1),1e3);return()=>clearInterval(n)},[e.status]),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:e.status==="running"?qn(Date.now()-e.startedAt):e.exitCode!==void 0?`exit ${e.exitCode}`:e.status})}function cne({tail:e}){const{t}=ne(),n=m.useRef(null);return m.useEffect(()=>{const s=n.current;s&&(s.scrollTop=s.scrollHeight)},[e]),i.jsx("pre",{ref:n,className:"max-h-56 overflow-auto border-t border-border/60 px-2.5 py-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground",children:ki(e)||t("(no output yet)")})}function Hv(e){return e==="darwin"?"Open in Finder":e==="win32"?"Open in File Explorer":"Open in File Manager"}async function Bv(e,t){try{const n=await window.electronAPI.projects.reveal(e);n.ok||ze({type:"error",title:t("Could not complete the file action."),description:n.error})}catch(n){ze({type:"error",title:t("Could not complete the file action."),description:String(n)})}}const dne="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 une({project:e,conversationId:t,path:n,branch:s,openDisabled:o,children:r}){const{t:a}=ne(),[l,c]=m.useState([]),d=e.kind!=="ssh"&&!window.electronAPI.remote,u=e.kind==="scratch",h=u?a("Temporary chats"):Ns(e),p=m.useCallback(()=>{d&&window.electronAPI.projects.openInApps().then(c).catch(()=>{})},[d]),f=v=>{Bv({projectId:e.id,conversationId:t,...v?{appId:v}:{}},a)},g=l.filter(v=>v.kind==="editor"),x=l.filter(v=>v.kind==="terminal");return i.jsxs($i,{onOpenChange:v=>v&&p(),children:[i.jsxs(Wi,{className:"group ml-1.5 flex h-6 min-w-0 shrink-0 items-center rounded-full border border-border/60 px-2 font-mono text-[11.5px] text-muted-foreground outline-none transition-colors duration-(--duration-quick) hover:border-border focus-visible:border-border data-popup-open:border-border",title:u?h:n,"aria-label":s&&!u?`${h} / ${s}`:h,onPointerEnter:p,children:[i.jsx(Nc,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:`grid grid-cols-[0fr] opacity-0 transition-[grid-template-columns,opacity] duration-(--duration-fast) ease-(--ease-smooth-out) ${dne}`,children:i.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap pl-1.5",children:[i.jsx("span",{className:"max-w-40 truncate",children:h}),s&&!u&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"opacity-40",children:"/"}),i.jsx(zi,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-40 truncate",children:s})]})]})}),i.jsx("span",{className:"ml-1.5 flex shrink-0 items-center",children:r})]}),i.jsxs(Ui,{align:"end",className:"min-w-48",children:[d&&i.jsxs(i.Fragment,{children:[i.jsxs(mn,{disabled:o,onClick:()=>f(),children:[i.jsx(oi,{}),a(Hv(window.electronAPI.env.platform))]}),i.jsx(kC,{label:a("Editors"),apps:g,fallback:i.jsx(_m,{}),disabled:o,onOpen:f}),i.jsx(kC,{label:a("Terminals"),apps:x,fallback:i.jsx(Uo,{}),disabled:o,onOpen:f}),i.jsx(ja,{})]}),i.jsxs(mn,{onClick:()=>{navigator.clipboard.writeText(n)},children:[i.jsx(ih,{}),a("Copy Path")]})]})]})}function kC({label:e,apps:t,fallback:n,disabled:s,onOpen:o}){return t.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx(ja,{}),i.jsxs(Yg,{children:[i.jsx(Xg,{children:e}),t.map(r=>i.jsxs(mn,{disabled:s,onClick:()=>o(r.id),children:[r.icon?i.jsx("img",{src:r.icon,alt:"",className:"-mx-0.5 size-4 shrink-0"}):n,r.name]},r.id))]})]})}function hne({conversationId:e}){const{t}=ne(),n=ie(r=>r.conversations[e]),s=ie(r=>r.rebuildWorktree),o=ie(r=>r.fallbackToMainWorkspace);return!n?.worktreeMissing||!n.worktree?null:i.jsx(j_,{open:!0,children:i.jsxs(__,{className:"sm:max-w-md",children:[i.jsxs(N_,{children:[i.jsx(T_,{className:"text-base",children:t("Isolated worktree is missing")}),i.jsx(I_,{children:t('The worktree of this session was deleted. Rebuild it from branch "{{branch}}" (committed work is preserved), or fall back to the main working tree.',{branch:n.worktree.branch})})]}),i.jsxs(D_,{variant:"bare",children:[i.jsx(me,{variant:"outline",size:"sm",onClick:()=>{o(e)},children:t("Fall back to main working tree")}),i.jsx(me,{size:"sm",onClick:()=>{s(e).then(r=>{r&&ze({type:"error",title:t("Failed to rebuild worktree"),description:r})})},children:t("Rebuild worktree")})]})]})})}function $u(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 pne({initialName:e,data:t,busy:n,disabled:s,error:o,returnFocus:r,onSubmit:a,onClose:l}){const{t:c}=ne(),[d,u]=m.useState(e),h=m.useRef(null),p=m.useId(),f=t?.branches.some(v=>v.name===d.trim()),g=n||s||!t?.headCommit||!!t.blockedReason||!d.trim()||f,x=f?c("A branch with this name already exists."):t?.blockedReason?$u(t.blockedReason,c):t&&!t.headCommit?c("Create a commit before creating a branch from HEAD."):null;return i.jsx(xn,{open:!0,onOpenChange:v=>{!v&&!n&&l()},children:i.jsxs(vn,{className:"max-w-sm",initialFocus:h,finalFocus:r,showCloseButton:!n,children:[i.jsxs(bn,{children:[i.jsx(wn,{children:c("Create branch")}),i.jsx(Rs,{children:c("Creates a branch from the current HEAD and switches every conversation in this workspace to it.")})]}),i.jsxs(An,{children:[i.jsx(Zt,{ref:h,"aria-label":c("Branch name"),"aria-invalid":!!x,"aria-describedby":x||o?p:void 0,value:d,disabled:n,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.nativeEvent.isComposing&&(v.preventDefault(),g||a(d.trim()))}}),(x||o)&&i.jsx("p",{id:p,role:"alert",className:"mt-2 break-words text-xs text-destructive",children:x||o})]}),i.jsxs(ls,{children:[i.jsx(me,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:l,children:c("Cancel")}),i.jsxs(me,{type:"button",size:"sm",disabled:!!g,onClick:()=>{g||a(d.trim())},children:[n&&i.jsx(Xt,{className:"h-3.5 w-3.5 animate-spin"}),c("Create and switch")]})]})]})})}function fne({data:e,loading:t,error:n,disabled:s,query:o,searchRef:r,onQueryChange:a,onSelect:l,onCreate:c,onRetry:d}){const{t:u}=ne(),h=s||t||!!n||!e||!!e.blockedReason,p=e?.branches.filter(f=>f.name.toLowerCase().includes(o.trim().toLowerCase()))??[];return i.jsxs("section",{"aria-label":u("Local branches"),className:"pb-1",onKeyDown:f=>{if(f.nativeEvent.isComposing||!["ArrowDown","ArrowUp"].includes(f.key))return;const g=Array.from(f.currentTarget.querySelectorAll("button[data-branch-row]:not(:disabled)"));if(!g.length)return;f.preventDefault();const x=g.indexOf(f.target),v=x<0?f.key==="ArrowDown"?0:g.length-1:(x+(f.key==="ArrowDown"?1:-1)+g.length)%g.length;g[v]?.focus()},children:[i.jsxs("div",{className:"relative m-1",children:[i.jsx(si,{className:"pointer-events-none absolute left-2 top-1/2 z-10 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Zt,{ref:r,value:o,onChange:f=>a(f.target.value),"aria-label":u("Search local branches"),placeholder:u("Search local branches"),className:"h-8 text-xs [&_input]:pl-7"})]}),i.jsx("p",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:u("Switching branches affects all conversations in this workspace.")}),e?.blockedReason&&i.jsx("p",{role:"status",className:"px-2 py-1 text-xs text-warning",children:$u(e.blockedReason,u)}),t?i.jsxs("div",{role:"status",className:"flex items-center gap-2 px-2 py-3 text-xs text-muted-foreground",children:[i.jsx(Xt,{className:"h-3.5 w-3.5 animate-spin"}),u("Loading...")]}):n?i.jsxs("div",{role:"alert",className:"px-2 py-2 text-xs",children:[i.jsx("p",{className:"break-words text-destructive",children:n}),i.jsx("button",{type:"button",disabled:s,onClick:d,className:"mt-1 rounded px-1 py-1 text-foreground hover:bg-muted disabled:opacity-50",children:u("Retry")})]}):i.jsxs("div",{className:"max-h-48 overflow-y-auto",children:[p.map(f=>{const g=f.name===e?.currentBranch,x=f.occupied&&!!f.worktreeConversationId,v=x?u("New conversation in this worktree"):f.occupied?u("Branch is checked out in another worktree."):null;return i.jsxs("button",{type:"button","data-branch-row":"","aria-current":g||void 0,disabled:h||g||f.occupied&&!x,title:v?`${f.name}
92
- ${v}`:f.name,onClick:()=>l(f),className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",g&&"bg-primary/10"),children:[x?i.jsx(Ho,{className:"h-3.5 w-3.5 shrink-0"}):i.jsx(zi,{className:"h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:f.name}),v&&i.jsx("span",{className:"block text-xs text-muted-foreground",children:v})]}),g&&i.jsx(Yn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},f.name)}),e&&p.length===0&&i.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-3 text-center text-xs text-muted-foreground",children:u("No matching local branches.")})]}),i.jsxs("button",{type:"button",disabled:h||!e?.headCommit,onClick:c,title:e&&!e.headCommit?u("Create a commit before creating a branch from HEAD."):void 0,className:"mt-1 flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",children:[i.jsx(as,{className:"h-3.5 w-3.5 shrink-0"}),u("Create branch from HEAD…")]})]})}function tu(e){return e.name?.trim()||e.branch}function mne(e,t,n){const s=new Set,o=[];for(const[r,a]of Object.entries(e)){const{worktree:l}=a;a.projectId!==t||!l||a.parentId||a.child||a.worktreeMissing||a.ended||a.historyOnly||a.workspaceMigrating||n[r]?.exists===!1||s.has(l.path)||(s.add(l.path),o.push({conversationId:r,worktree:l}))}return o}function gne(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 gg(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[tu(e),e.branch,e.path,s].join(`
93
- `)}function xne({worktree:e,status:t}){const{t:n}=ne();return i.jsx("span",{"data-slot":"worktree-label",title:gg(e,t,n),className:"flex shrink-0 items-center",children:i.jsx(zi,{className:W("size-2.75",t?.exists===!1?"text-destructive":t?.dirty?"text-warning":(t?.ahead??0)>0?"text-info":"text-subtle-foreground")})})}function ME({entity:e,onClose:t}){const{t:n}=ne(),s=ie(d=>d.renameWorktree),[o,r]=m.useState(e?.worktree.name??""),[a,l]=m.useState(!1);m.useEffect(()=>{r(e?.worktree.name??""),l(!1)},[e]);const c=async()=>{if(!(!e||a)){l(!0);try{const d=await s(e.conversationId,o.trim());d?ze({type:"error",title:n("Failed to rename worktree"),description:d}):t()}catch(d){ze({type:"error",title:n("Failed to rename worktree"),description:String(d)})}finally{l(!1)}}};return i.jsx(xn,{open:e!==null,onOpenChange:d=>{!d&&!a&&t()},children:i.jsxs(vn,{className:"max-w-sm",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:n("Rename worktree")}),i.jsx(Rs,{children:n("Only the display name changes, for all sessions in this worktree. Leave empty to use the branch name.")})]}),i.jsx(An,{children:i.jsx(Zt,{"aria-label":n("Worktree name"),maxLength:80,placeholder:e?.worktree.branch,value:o,disabled:a,autoFocus:!0,onChange:d=>r(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.nativeEvent.isComposing&&(d.preventDefault(),c())}})}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",disabled:a,onClick:t,children:n("Cancel")}),i.jsxs(me,{size:"sm",disabled:a,onClick:()=>{c()},children:[a&&i.jsx(Xt,{className:"h-3.5 w-3.5 animate-spin"}),n("Save")]})]})]})})}function vne({conversationId:e,onBranchChange:t}){const{t:n}=ne(),s=ie(Fe=>Fe.conversations[e]),o=ie(Fe=>Fe.moveConversationToWorktree),r=ie(Fe=>Fe.cleanupWorktree),a=ie(Fe=>Fe.refreshWorktreeStatuses),l=ie(Fe=>Fe.conversations),c=ie(Fe=>Fe.worktreeStatuses),d=ie(Fe=>Fe.attachConversationToWorktree),u=ie(Fe=>Fe.newConversation),h=ie(Fe=>Fe.switchWorkspaceBranch),p=ie(Fe=>Fe.workspaceRevisionByConversation[e]??0),[f,g]=m.useState(null),x=m.useMemo(()=>mne(l,s?.projectId??"",c),[l,s?.projectId,c]),[v,y]=m.useState(!1),[b,w]=m.useState(!1),[C,_]=m.useState(!1),[N,k]=m.useState(null),[S,A]=m.useState(!1),T=we(Fe=>s?Fe.projects.find(Nt=>Nt.id===s.projectId):void 0),I=!!(s&&!s.parentId&&!s.child&&T?.kind!=="ssh"&&T?.kind!=="scratch"),P=`${e}\0${s?.worktree?.path??T?.path??""}`,D=m.useRef(P);D.current=P;const O=m.useRef(0),z=m.useRef(!1),R=m.useRef(null),$=m.useRef(null),X=m.useRef(null);m.useEffect(()=>{v&&(b?$:X).current?.focus()},[v,b]);const[H,te]=m.useState(null),V=H?.key===P?H.data:null,Y=V?.currentBranch??void 0;m.useEffect(()=>{t?.(Y)},[t,Y]);const[q,ee]=m.useState(!0),[ge,Ce]=m.useState(null),[Re,fe]=m.useState(""),[U,oe]=m.useState(null),[Se,G]=m.useState(null),Q=U===P;m.useEffect(()=>{y(!1),w(!1),fe(""),oe(null),G(null)},[P]);const ae=m.useCallback(async(Fe=!1)=>{if(!I)return;const Nt=++O.current;ee(!0),Ce(null);try{const Ft=await window.electronAPI.worktree.branches(e);if(Nt!==O.current||D.current!==P)return;if(Ft.ok)te({key:P,data:Ft.value});else{const on=$u(Ft.code,n);Ce(on),Fe&&ze({type:"error",title:n("Failed to load branches"),description:on})}}catch(Ft){if(Nt!==O.current||D.current!==P)return;Ce(n("Failed to load branches")),Fe&&ze({type:"error",title:n("Failed to load branches"),description:String(Ft)})}finally{Nt===O.current&&D.current===P&&ee(!1)}},[e,I,n,P]);if(m.useEffect(()=>{ae();const Fe=()=>{z.current||ae()};return window.addEventListener("focus",Fe),()=>{O.current+=1,window.removeEventListener("focus",Fe)}},[ae,p]),!s||s.parentId||s.child||T?.kind==="ssh")return null;const Z=!!s.worktree,ce=C||s.spawning||s.status==="running"||!!(s.workspaceMigrating||s.reloading),De=s.worktreeMissing||c[e]?.exists===!1,Oe=gne(s),Ne=V?V.currentBranch:s.worktree?.branch,Ze=Ne??(V?.headCommit?n("Detached HEAD"):""),bt=s.worktree?tu(s.worktree):n("Local"),Ut=Ze&&Ze!==bt&&(!V?.defaultBranch||Ne!==V.defaultBranch)?`${bt} · ${Ze}`:bt,Et=ce||De||q||!!ge||!V||!!V.blockedReason,_t=async(Fe,Nt=!1,Ft)=>{if(Et||z.current)return;z.current=!0,O.current+=1,_(!0),G(null);const on=n(Ft?"Failed to create conversation":"Failed to switch branch");try{if(Ft){await u(s.projectId,{worktreeFromConversationId:Ft})?D.current===P&&y(!1):ze({type:"error",title:on});return}const re=await h(e,Fe,Nt);if(D.current!==P)return;if(re.ok)te({key:P,data:re.value}),Ce(null),oe(null),y(!1);else{const Ue=$u(re.code,n);G(Ue),ze({type:"error",title:on,description:re.code==="git-error"?`${Ue}
94
- ${re.error}`:Ue}),ae()}}catch(re){if(D.current!==P)return;G(String(re)),ze({type:"error",title:on,description:String(re)})}finally{z.current=!1,_(!1)}},B=Fe=>{Fe.name===V?.currentBranch||Fe.occupied&&!Fe.worktreeConversationId||_t(Fe.name,!1,Fe.occupied?Fe.worktreeConversationId:void 0)},Te=async Fe=>{if(ce)return;_(!0);const Nt=n(Fe?"Failed to use worktree":"Failed to create conversation");try{if(Fe){const Ft=await d(e,Fe);Ft&&ze({type:"error",title:Nt,description:Ft})}else await u(s.projectId,{worktreeFromConversationId:e})||ze({type:"error",title:Nt})}catch(Ft){ze({type:"error",title:Nt,description:String(Ft)})}finally{_(!1)}},We=async()=>{_(!0);try{const Fe=await r(e);Fe?ze({type:"error",title:n("Failed to clean up worktree"),description:Fe}):a()}catch(Fe){ze({type:"error",title:n("Failed to clean up worktree"),description:String(Fe)})}finally{_(!1)}},kt=async(Fe=!1)=>{_(!0);try{const Nt=await o(e,{allowDirtyMainTree:Fe});Nt===E_?A(!0):Nt?ze({type:"error",title:n("Failed to move to worktree"),description:Nt}):a()}catch(Nt){ze({type:"error",title:n("Failed to move to worktree"),description:String(Nt)})}finally{_(!1)}},Gt=async()=>{_(!0);try{const Fe=await window.electronAPI.worktree.status(e);if(Fe.ok&&Ad(Fe.value)){k(Fe.value);return}await We()}catch(Fe){ze({type:"error",title:n("Failed to clean up worktree"),description:String(Fe)})}finally{_(!1)}},de=[{id:"local",selected:!Z,icon:i.jsx(Tw,{className:"h-3.5 w-3.5 shrink-0"}),name:n("Local workspace"),hint:n("Work directly in the main working tree"),onSelect:()=>{Z&&Gt()}},{id:"worktree",selected:Z,icon:i.jsx(zi,{className:"h-3.5 w-3.5 shrink-0"}),name:s.worktree?tu(s.worktree):n("New isolated worktree"),hint:Z?s.worktree?.branch:n("Run this session on its own git worktree"),onSelect:()=>{Z||kt()}}],mt=i.jsx(gs,{open:S,onOpenChange:A,title:n("Main working tree has uncommitted changes"),description:n("The new worktree branches off HEAD, so those changes stay in the main working tree and will not follow this session."),confirmLabel:n("Move anyway"),onConfirm:()=>{A(!1),kt(!0)}}),Lt=()=>{const Fe=[];return N?.dirty&&Fe.push(n("Uncommitted changes")),N&&N.ahead>0&&Fe.push(n("{{n}} unmerged commits (branch is kept)",{n:N.ahead})),Fe.join("; ")};return i.jsxs(i.Fragment,{children:[i.jsxs(vi,{open:v,onOpenChange:Fe=>{C||(y(Fe),Fe&&(w(!1),fe(""),ae()))},children:[i.jsxs(bi,{ref:R,disabled:ce,className:"flex h-7 min-w-0 max-w-52 shrink items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",title:s.worktree?`${Ut}
95
- ${gg(s.worktree,c[e],n)}`:Ut,children:[C?i.jsx(Xt,{className:"h-3 w-3 shrink-0 animate-spin"}):Z?i.jsx(zi,{className:"h-3 w-3 shrink-0"}):i.jsx(Tw,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:Ut}),i.jsx($n,{className:"h-3 w-3 shrink-0"})]}),i.jsx(wi,{side:"top",align:"start",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",initialFocus:X,finalFocus:Q||f!==null?!1:R,children:b?i.jsxs(i.Fragment,{children:[i.jsxs("button",{type:"button",onClick:()=>w(!1),"aria-label":n("Back to workspaces"),className:"mb-1 flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground",children:[i.jsx(pc,{className:"h-3.5 w-3.5 shrink-0"}),n("Local branches")]}),i.jsx(fne,{data:V,loading:q,error:ge,disabled:ce||De,query:Re,searchRef:$,onQueryChange:fe,onSelect:B,onRetry:()=>{ae(!0)},onCreate:()=>{Et||!V?.headCommit||(G(null),oe(P),y(!1))}})]}):i.jsxs(i.Fragment,{children:[de.map(Fe=>i.jsxs("button",{ref:Fe.id==="local"?X:void 0,type:"button",disabled:ce,onClick:()=>{Fe.onSelect(),y(!1)},className:W("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",Fe.selected?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[Fe.icon,i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:Fe.name}),Fe.hint&&i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:Fe.hint})]}),Fe.selected&&i.jsx(Yn,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},Fe.id)),Oe&&x.length>0&&i.jsxs("div",{className:"mt-1 border-t pt-1",children:[i.jsx("p",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:n("Existing worktrees")}),i.jsx("div",{className:"max-h-56 overflow-y-auto",children:x.map(({conversationId:Fe,worktree:Nt})=>i.jsxs("button",{type:"button",disabled:ce,title:gg(Nt,c[Fe],n),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",onClick:()=>{y(!1),Te(Fe)},children:[i.jsx(zi,{className:"h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:tu(Nt)}),i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:Nt.path})]})]},Nt.path))})]}),s.worktree&&i.jsxs("div",{className:"mt-1 border-t pt-1",children:[i.jsxs("button",{type:"button",disabled:ce||De,className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",onClick:()=>{y(!1),Te()},children:[i.jsx(Ho,{className:"h-3.5 w-3.5"}),n("New conversation in this worktree")]}),i.jsxs("button",{type:"button",disabled:ce||De,className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",onClick:()=>{y(!1),s.worktree&&g({conversationId:e,worktree:s.worktree})},children:[i.jsx($s,{className:"h-3.5 w-3.5"}),n("Rename worktree")]})]}),i.jsx("div",{className:"mt-1 border-t pt-1",children:i.jsxs("button",{type:"button",disabled:ce,onClick:()=>w(!0),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[i.jsx(zi,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"flex-1",children:n("Switch branch")}),i.jsx(un,{className:"h-3.5 w-3.5 shrink-0"})]})})]})})]}),i.jsx(gs,{open:N!==null,onOpenChange:Fe=>{Fe||k(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:Lt()}),confirmLabel:n("Clean up"),onConfirm:()=>{k(null),We()}}),Q&&i.jsx(pne,{initialName:Re.trim(),data:V,busy:C,disabled:Et,error:Se,returnFocus:R,onSubmit:Fe=>{_t(Fe,!0)},onClose:()=>oe(null)},P),mt,i.jsx(ME,{entity:f,onClose:()=>g(null)})]})}function bne(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 wne=e=>{Mh(e)&&_o()};function yne(){const{t:e}=ne(),t=W5(),n=Na(),s=we(B=>B.virtualModels),o=we(B=>B.agentTypes),r=we(B=>B.defaultModel),a=we(B=>B.projects),l=we(B=>B.projectGroups),c=we(B=>B.voiceInputEnabled),d=we(B=>B.voiceModel),u=we(B=>B.presets),{status:h}=t_(c),p=c&&h?.state!=="unsupported"&&h?.models.find(B=>B.id===d)?.state==="ready",f=m.useSyncExternalStore(B=>ie.persist?.onFinishHydration?.(B)??(()=>{}),()=>ie.persist?.hasHydrated?.()??!0),g=ie(qf(cee)),x=ie(B=>B.conversations[g?.parentId??""]?.coworkerIds),v=U5(g?.presetId,B=>u.find(Te=>Te.id===B)).pluginPresetId??null,y=ree(g?.displayedParentId?g.agentType:void 0),b=ko(B=>B.snapshot),w=nx(),C=ie(B=>mW(B.conversations)),_=g?.parentId,N=g?.parentProjectId,k=m.useMemo(()=>_!==void 0&&N!==void 0?kJ(C,N,_):[],[C,_,N]),S=m.useMemo(()=>a.find(B=>B.id===g?.projectId),[g?.projectId,a]),A=m.useMemo(()=>a.find(B=>B.id===g?.parentProjectId),[g?.parentProjectId,a]),T=m.useMemo(()=>ru(S,l),[S,l]),I=m.useMemo(()=>ru(A,l),[A,l]),P=m.useMemo(()=>au({defaultModel:r,...T,lastProviderId:g?.lastProviderId,lastModelId:g?.lastModelId,providers:n,credentials:Fl(b),virtualModels:s}),[g?.lastModelId,g?.lastProviderId,T,r,b,n,s]),D=m.useMemo(()=>au({defaultModel:r,...I,lastProviderId:g?.parentLastProviderId,lastModelId:g?.parentLastModelId,providers:n,credentials:Fl(b),virtualModels:s}),[r,b,g?.parentLastModelId,g?.parentLastProviderId,I,n,s]),O=D.source==="none"?null:{providerId:D.providerId,modelId:D.modelId},z=P.source==="none"?void 0:w.find(B=>B.id===P.providerId),R=P.source==="none"?"":P.modelId,$=P.source==="none"?"":Yf(P)?P.providerId:z?.id??"",X=ie(B=>Yf(P)&&g?.id?bne(B.conversations[g.id]?.messages):void 0),H=ie(qf(B=>tx(n,g?.id?B.conversations[g.id]:void 0))),te=P.source!=="none"?null:P.reason==="oauth-credentials-error"?e("Subscription credentials could not be loaded. Choose an API-key model or retry the credential refresh."):P.reason==="oauth-credentials-loading"||P.reason==="oauth-credentials-unloaded"?e("Subscription credentials are loading. Choose an API-key model or wait, then retry."):w.length>0?e("Choose a model for this conversation or set a project, group, or global default before sending."):e("No usable model is available. Configure provider credentials and enable a model first."),V=a.find(B=>B.id===g?.projectId),Y=g?.id,[q,ee]=m.useState(),ge=m.useCallback(B=>ee(Y&&B?{id:Y,branch:B}:void 0),[Y]),Ce=g?.parentWorktreeBranch??(q?.id===g?.parentId?q?.branch:void 0),Re=we(B=>B.skills),fe=we(B=>B.loadLocalSkills),U=we(B=>K5(B.disabledBuiltinTools,B.projects,g?.projectId,"plan")),[oe,Se]=m.useState([]),G=fe?V?.path??"":"",Q=g?.presetId;m.useEffect(()=>{let B=!1;return window.electronAPI.assets.listProjectSkills(G,Q).then(Te=>{B||Se(Te)}).catch(()=>{B||Se([])}),()=>{B=!0}},[G,Q]);const ae=g?.commands,Z=q5(),ce=m.useMemo(()=>{if(!ae)return[];const B={name:"/goal",description:e("Set a session goal (/goal <objective> · pause · resume · clear)")},Te={name:"/compact",description:e("Compact the context now (/compact [summary focus])")},We={name:"/plan",description:e("Plan mode: research read-only, then approve a plan (/plan [task] · off)")},kt=Re.filter(de=>de.enabled!==!1).map(de=>({name:`/skill:${de.name}`,description:de.description})),Gt=oe.map(de=>({name:`/skill:${de.name}`,description:de.description}));return sD([B,Te,...U?[We]:[],...kt,...Gt,...ae,...Z])},[e,Re,oe,ae,Z,U]),De=m.useRef(null),Oe=!g?.displayedParentId&&["planning","awaiting_review"].includes(w_(g?.planState)),Ne=g?.status==="running",Ze=g?.busy===!0,bt=g?.parentWorktreePath??V?.path,Ut=m.useCallback(()=>{g&&!g.parentStarted&&g.parentSessionFile&&!g.parentWorktreeMissing&&g.parentStatus!=="failed"&&ie.getState().resumeConversation(g.parentId)},[g]);m.useEffect(()=>{const B=g?.compactionError;!B||!g||(ze({type:"error",title:e("Compaction failed"),description:B}),ie.getState().clearCompactionError(g.id))},[g,e]);const Et=aee(g,f);if(!g)return i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",...Et==="hydrating"?{"data-timeline-loading":""}:{},children:[t&&i.jsx(b_,{"data-enso":"title-bar"}),Et==="empty"&&i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-1 text-center",children:[i.jsx("p",{className:"text-lg font-medium",children:"EnsoCode"}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("Create or select a project to start a conversation")})]})]});const _t=i.jsx(Sne,{status:g.spawning?"running":g.status,pendingAskCount:(g.pendingAsks??[]).length,hasRunningChild:g.id===g.parentId&&g.parentHasRunningChild});return i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[i.jsx(hne,{conversationId:g.parentId}),i.jsx(hte,{parentId:g.parentId,displayedId:g.id,trailing:i.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-1",children:[i.jsx(See,{parentId:g.parentId,coworkerIds:x??[]}),V?i.jsx(une,{project:V,conversationId:g.parentId,path:g.parentWorktreePath??V.path,branch:Ce,openDisabled:g.parentWorktreeMissing,children:_t}):i.jsx("div",{className:"flex min-w-0 shrink-0 items-center",children:_t})]})}),i.jsx(hE,{conversationId:g.id,cwd:bt,emptyTitle:V?Ns(V):"EnsoCode",onSuggestion:V?wne:void 0,timelineRef:De}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:Ni,children:[V&&V.kind!=="ssh"&&V.kind!=="scratch"&&!g.displayedParentId&&i.jsx(kte,{projectId:V.id,conversationId:g.id}),g.retry&&i.jsx(Yh,{retry:g.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(g.id)}}),(g.rewinding||g.restoringFiles)&&i.jsxs("div",{role:"status",className:"mb-1 flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-muted-foreground text-xs",children:[i.jsx(Xt,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}),i.jsx("span",{children:g.restoringFiles&&!g.rewinding?e("Restoring files…"):g.restoringFiles?e("Rewinding conversation and files…"):e("Rewinding…")})]}),i.jsx(nh.Provider,{value:{conversationId:g.id,projectId:g.projectId,...bt?{cwd:bt}:{}},children:i.jsx(Fv,{sessionId:g.id,tasks:g.backgroundTasks??[],subagents:g.subagents??[]},g.id)}),i.jsx(Rh,{approvals:g.pendingApprovals??[],allowSession:g.childLockedProfileId===void 0,onRespond:(B,Te)=>{window.electronAPI.agent.respondApproval(g.id,B,Te)}}),i.jsx(uee,{}),i.jsx(Lh,{asks:g.pendingAsks??[],onAnswer:(B,Te)=>{window.electronAPI.agent.respondAsk(g.id,B,Te)}}),!g.displayedParentId&&i.jsx(vte,{conversationId:g.id,planState:g.planState,approvalMode:g.approvalMode??"full"}),i.jsx(kE,{conversationId:g.id,queued:g.queuedMessages??[]}),g.goal&&i.jsx(gte,{conversationId:g.id,goal:g.goal}),i.jsx(Oq,{conversationId:g.id},g.id),!g.displayedParentId&&te&&i.jsx("div",{role:"status",className:"rounded-md border border-dashed px-3 py-2 text-muted-foreground text-xs",children:te}),i.jsx(zv,{cwd:V?.path,chatCandidates:k,commands:ce,running:Ne,busy:Ze,locked:(g.pendingApprovals??[]).length>0||!!(g.rewinding||g.restoringFiles),focusKey:g.id,pluginPresetId:v,planMode:Oe,savePastedText:V?.kind==="ssh"?void 0:B=>window.electronAPI.files.savePastedText({conversationId:g.id,text:B}),voice:p?WI:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,placeholder:Oe?e("Describe the task — a plan comes first"):void 0,injectedDraft:g.draftText,injectedImages:g.draftImages,injectedDraftAppend:g.draftAppend,onDraftConsumed:()=>ie.getState().clearDraft(g.id),queuedCount:g.queuedMessages?.length??0,onSteerQueued:()=>ie.getState().steerQueued(g.id),toolbar:i.jsxs(i.Fragment,{children:[!g.displayedParentId&&i.jsxs(i.Fragment,{children:[i.jsx(Ste,{presetId:g.presetId??"default",disabled:g.started,onSelect:B=>ie.getState().setPreset(g.id,B),onModel:B=>ie.getState().setModel(g.id,B.providerId,B.modelId)}),i.jsx(vne,{conversationId:g.id,onBranchChange:ge}),(U||g.planState?.active)&&i.jsx(yte,{active:g.planState?.active??!1,onToggle:B=>ie.getState().setPlanMode(g.id,B)}),i.jsx(Y5,{mode:g.approvalMode??"full",autoReject:g.autoRejectApprovals===!0,onSelect:B=>ie.getState().setApprovalMode(g.id,B),onToggleAutoReject:B=>ie.getState().setAutoRejectApprovals(g.id,B)}),i.jsx(xh,{listenHotkey:!0,refreshAllModels:!0,providers:w,virtualModels:s,routedModelLabel:X,activeAccount:H,providerId:$,modelId:R,reasoningEnabled:g.reasoningEnabled??!1,thinkingLevel:g.thinkingLevel??"medium",onSelect:(B,Te)=>ie.getState().setModel(g.id,B,Te),onReasoningChange:B=>ie.getState().setReasoning(g.id,B),onThinkingChange:B=>ie.getState().setThinking(g.id,B)})]}),g.displayedParentId&&i.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[y??(g.agentType?x_(g.agentType,o):"coworker"),g.lastModelId?` · ${Kf(s,g.lastModelId)}`:""]})]}),onActivate:Ut,onSend:B=>!B.recipient&&!V||!B.recipient&&!g.displayedParentId&&(!$||!R)?!1:(fte(B,{dispatchAgent:(Te,We)=>{ie.getState().dispatchAgent(Te,We,O)},sendCoding:(Te,We)=>{V&&(De.current?.scrollToBottom(),ie.getState().send(Te,{providerId:$,modelId:R,cwd:V.path},We))}}),!0),onAbort:()=>{ie.getState().abort()}}),i.jsx(PE,{conversationId:g.id,cwd:bt})]})})]})}function Sne({status:e,pendingAskCount:t=0,hasRunningChild:n=!1}){const s=eh({status:e,pendingAskCount:t,hasRunningChild:n});return i.jsx(Tc,{tone:s,title:e})}function RE(e,t,n){const s=e.slice();return s.splice(n<0?s.length+n:n,0,s.splice(t,1)[0]),s}function Cne(e,t){return e.reduce((n,s,o)=>{const r=t.get(s);return r&&(n[o]=r),n},Array(e.length))}function ud(e){return e!==null&&e>=0}function kne(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 jne(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const hd={scaleX:1,scaleY:1},_ne=e=>{var t;let{rects:n,activeNodeRect:s,activeIndex:o,overIndex:r,index:a}=e;const l=(t=n[o])!=null?t:s;if(!l)return null;const c=Nne(n,a,o);if(a===o){const d=n[r];return d?{x:o<r?d.left+d.width-(l.left+l.width):d.left-l.left,y:0,...hd}:null}return a>o&&a<=r?{x:-l.width-c,y:0,...hd}:a<o&&a>=r?{x:l.width+c,y:0,...hd}:{x:0,y:0,...hd}};function Nne(e,t,n){const s=e[t],o=e[t-1],r=e[t+1];return!s||!o&&!r?0:n<t?o?s.left-(o.left+o.width):r.left-(s.left+s.width):r?r.left-(s.left+s.width):s.left-(o.left+o.width)}const LE=e=>{let{rects:t,activeIndex:n,overIndex:s,index:o}=e;const r=RE(t,s,n),a=t[o],l=r[o];return!l||!a?null:{x:l.left-a.left,y:l.top-a.top,scaleX:l.width/a.width,scaleY:l.height/a.height}},pd={scaleX:1,scaleY:1},jC=e=>{var t;let{activeIndex:n,activeNodeRect:s,index:o,rects:r,overIndex:a}=e;const l=(t=r[n])!=null?t:s;if(!l)return null;if(o===n){const d=r[a];return d?{x:0,y:n<a?d.top+d.height-(l.top+l.height):d.top-l.top,...pd}:null}const c=Tne(r,o,n);return o>n&&o<=a?{x:0,y:-l.height-c,...pd}:o<n&&o>=a?{x:0,y:l.height+c,...pd}:{x:0,y:0,...pd}};function Tne(e,t,n){const s=e[t],o=e[t-1],r=e[t+1];return s?n<t?o?s.top-(o.top+o.height):r?r.top-(s.top+s.height):0:r?r.top-(s.top+s.height):o?s.top-(o.top+o.height):0:0}const OE="Sortable",zE=_e.createContext({activeIndex:-1,containerId:OE,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:LE,disabled:{draggable:!1,droppable:!1}});function xg(e){let{children:t,id:n,items:s,strategy:o=LE,disabled:r=!1}=e;const{active:a,dragOverlay:l,droppableRects:c,over:d,measureDroppableContainers:u}=yc(),h=bc(OE,n),p=l.rect!==null,f=m.useMemo(()=>s.map(N=>typeof N=="object"&&"id"in N?N.id:N),[s]),g=a!=null,x=a?f.indexOf(a.id):-1,v=d?f.indexOf(d.id):-1,y=m.useRef(f),b=!kne(f,y.current),w=v!==-1&&x===-1||b,C=jne(r);yi(()=>{b&&g&&u(f)},[b,f,g,u]),m.useEffect(()=>{y.current=f},[f]);const _=m.useMemo(()=>({activeIndex:x,containerId:h,disabled:C,disableTransforms:w,items:f,overIndex:v,useDragOverlay:p,sortedRects:Cne(f,c),strategy:o}),[x,h,C.draggable,C.droppable,w,f,v,c,p,o]);return _e.createElement(zE.Provider,{value:_},t)}const Ine=e=>{let{id:t,items:n,activeIndex:s,overIndex:o}=e;return RE(n,s,o).indexOf(t)},Dne=e=>{let{containerId:t,isSorting:n,wasDragging:s,index:o,items:r,newIndex:a,previousItems:l,previousContainerId:c,transition:d}=e;return!d||!s||l!==r&&o===a?!1:n?!0:a!==o&&t===c},Ene={duration:200,easing:"ease"},GE="transform",Pne=Bi.Transition.toString({property:GE,duration:0,easing:"linear"}),Ane={roleDescription:"sortable"};function Mne(e){let{disabled:t,index:n,node:s,rect:o}=e;const[r,a]=m.useState(null),l=m.useRef(n);return yi(()=>{if(!t&&n!==l.current&&s.current){const c=o.current;if(c){const d=Da(s.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&a(u)}}n!==l.current&&(l.current=n)},[t,n,s,o]),m.useEffect(()=>{r&&a(null)},[r]),r}function Jh(e){let{animateLayoutChanges:t=Dne,attributes:n,disabled:s,data:o,getNewIndex:r=Ine,id:a,strategy:l,resizeObserverConfig:c,transition:d=Ene}=e;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:g,sortedRects:x,overIndex:v,useDragOverlay:y,strategy:b}=m.useContext(zE),w=Rne(s,f),C=u.indexOf(a),_=m.useMemo(()=>({sortable:{containerId:h,index:C,items:u},...o}),[h,o,C,u]),N=m.useMemo(()=>u.slice(u.indexOf(a)),[u,a]),{rect:k,node:S,isOver:A,setNodeRef:T}=Sc({id:a,data:_,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...c}}),{active:I,activatorEvent:P,activeNodeRect:D,attributes:O,setNodeRef:z,listeners:R,isDragging:$,over:X,setActivatorNodeRef:H,transform:te}=px({id:a,data:_,attributes:{...Ane,...n},disabled:w.draggable}),V=Jz(T,z),Y=!!I,q=Y&&!g&&ud(p)&&ud(v),ee=!y&&$,ge=ee&&q?te:null,Re=q?ge??(l??b)({rects:x,activeNodeRect:D,activeIndex:p,overIndex:v,index:C}):null,fe=ud(p)&&ud(v)?r({id:a,items:u,activeIndex:p,overIndex:v}):C,U=I?.id,oe=m.useRef({activeId:U,items:u,newIndex:fe,containerId:h}),Se=u!==oe.current.items,G=t({active:I,containerId:h,isDragging:$,isSorting:Y,id:a,index:C,items:u,newIndex:oe.current.newIndex,previousItems:oe.current.items,previousContainerId:oe.current.containerId,transition:d,wasDragging:oe.current.activeId!=null}),Q=Mne({disabled:!G,index:C,node:S,rect:k});return m.useEffect(()=>{Y&&oe.current.newIndex!==fe&&(oe.current.newIndex=fe),h!==oe.current.containerId&&(oe.current.containerId=h),u!==oe.current.items&&(oe.current.items=u)},[Y,fe,h,u]),m.useEffect(()=>{if(U===oe.current.activeId)return;if(U!=null&&oe.current.activeId==null){oe.current.activeId=U;return}const Z=setTimeout(()=>{oe.current.activeId=U},50);return()=>clearTimeout(Z)},[U]),{active:I,activeIndex:p,attributes:O,data:_,rect:k,index:C,newIndex:fe,items:u,isOver:A,isSorting:Y,isDragging:$,listeners:R,node:S,overIndex:v,over:X,setNodeRef:V,setActivatorNodeRef:H,setDroppableNodeRef:T,setDraggableNodeRef:z,transform:Q??Re,transition:ae()};function ae(){if(Q||Se&&oe.current.newIndex===C)return Pne;if(!(ee&&!yh(P)||!d)&&(Y||G))return Bi.Transition.toString({...d,property:GE})}}function Rne(e,t){var n,s;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(n=e?.draggable)!=null?n:t.draggable,droppable:(s=e?.droppable)!=null?s:t.droppable}}pn.Down,pn.Right,pn.Up,pn.Left;const _C=["idle","running","waiting","error"];function FE(e,t){return e?Vv({...e,hasRunningChild:Lg({...e,status:e.status??"idle"},t)}):"idle"}function Vv(e){const t=eh({status:e.status??"idle",spawning:e.spawning,pendingAskCount:(e.pendingAsks?.length??0)+(e.pendingApprovals?.length??0),hasRunningChild:e.hasRunningChild});return t==="failed"?"error":t==="unread"?"idle":t}function Lne(e){let t=0;for(const n of Object.values(e))!n||n.parentId||n.btwParentId||(t=Math.max(t,_C.indexOf(FE(n,e))));return _C[t]}const One=e=>e==="/"?null:e.replace(/\/[^/]+$/,"")||"/";function zne(e,t){const n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}function vg({list:e,create:t,initialPath:n,reloadKey:s=0,onSelect:o,onClose:r}){const{t:a}=ne(),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,p]=m.useState(""),[f,g]=m.useState(null),[x,v]=m.useState(""),y=m.useRef(0),b=m.useRef(null),w=m.useRef(e);w.current=e;const C=m.useCallback((T,I=!1)=>{const P=++y.current;u(!0),p(""),w.current(T,I).then(D=>{if(!(P!==y.current||!D)){if("error"in D){p(D.error);return}c(D),b.current=D.path}}).catch(()=>{P===y.current&&p(a("Failed to list remote directory."))}).finally(()=>{P===y.current&&u(!1)})},[a]),_=m.useRef(n);m.useEffect(()=>{C(_.current)},[C]),m.useEffect(()=>{s&&C(b.current??_.current,!0)},[s,C]);const N=l?.path??null,k=l?.dirs??[],S=l?.parent??null,A=()=>{if(!t||!N||f===null||!f.trim())return;const T=++y.current;u(!0),v(""),t(N,f).then(I=>{if(T===y.current){if("error"in I){v(a(I.error));return}g(null),p(""),c(I),b.current=I.path}}).catch(()=>{T===y.current&&v(a("Failed to list remote directory."))}).finally(()=>{T===y.current&&u(!1)})};return i.jsxs("div",{className:"w-full space-y-1.5 rounded-md border bg-muted/30 p-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground text-xs",children:N??"…"}),i.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!S||d,onClick:()=>S&&C(S),children:a("Up")}),t&&i.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!N||d||f!==null,onClick:()=>{g(""),v("")},children:a("New Folder")}),i.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:r,children:a("Close")})]}),f!==null&&i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(Zt,{autoFocus:!0,size:"sm",className:"min-w-0 flex-1 font-mono text-xs",placeholder:a("Folder name"),value:f,disabled:d,onChange:T=>g(T.target.value),onKeyDown:T=>{if(T.key==="Enter"){if(T.nativeEvent.isComposing)return;T.preventDefault(),A()}else T.key==="Escape"&&(T.preventDefault(),T.stopPropagation(),g(null))}}),i.jsx(me,{type:"button",size:"sm",className:"h-7 px-2 text-xs",disabled:d||!f.trim(),onClick:A,children:a("Create")}),i.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",disabled:d,onClick:()=>g(null),children:a("Cancel")})]}),x&&i.jsx("p",{className:"px-1 text-destructive text-xs",children:x})]}),i.jsxs("div",{className:"relative min-h-16 max-h-56 overflow-y-auto",children:[h?i.jsx("p",{className:"px-1 py-2 text-destructive text-xs",children:h}):k.length===0&&!d?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:a("No subdirectories")}):i.jsx("div",{className:d?"pointer-events-none space-y-0.5 opacity-40":"space-y-0.5",children:k.map(T=>i.jsxs("button",{type:"button",className:"block w-full truncate rounded px-1.5 py-1 text-left font-mono text-xs hover:bg-muted",disabled:d,onClick:()=>N&&C(zne(N,T)),children:[T,"/"]},T))}),d&&i.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60",children:[i.jsx(Xt,{className:"h-4 w-4 animate-spin text-muted-foreground"}),i.jsx("span",{className:"sr-only",children:a("Loading...")})]})]}),i.jsx(me,{type:"button",variant:"outline",size:"sm",className:"h-7 w-full text-xs",disabled:!N||d,onClick:()=>N&&o(N),children:a("Use this directory")})]})}function Gne({open:e,onOpenChange:t,onAdd:n,groups:s=[],defaultGroupId:o}){const{t:r}=ne(),a=we(Q=>Q.projects),[l,c]=m.useState("local"),[d,u]=m.useState(""),[h,p]=m.useState(""),[f,g]=m.useState(""),[x,v]=m.useState([]),[y,b]=m.useState(o),[w,C]=m.useState(!1),[_,N]=m.useState([]),[k,S]=m.useState(""),[A,T]=m.useState(null),[I,P]=m.useState(null),[D,O]=m.useState(0),[z,R]=m.useState(!1),[$,X]=m.useState(!1),H=m.useRef(0),te=m.useMemo(()=>[{value:"",label:r("Ungrouped")},...s.map(Q=>({value:Q.id,label:Q.name}))],[s,r]);m.useEffect(()=>{H.current+=1,X(!1),e&&(c("local"),u(""),p(""),g(""),b(o),C(!1),S(""),T(null),P(null),O(0),window.electronAPI.sshConnections.list().then(v).catch(()=>v([])),window.electronAPI.projects.getRecent().then(N).catch(()=>N([])))},[e,o]);const V=m.useMemo(()=>new Set(a.map(Q=>Q.path)),[a]),Y=m.useMemo(()=>_.filter(Q=>!V.has(Q.path)),[_,V]),q=m.useCallback((Q,ae)=>{if(!ae)return!0;const Z=ae.toLowerCase();return Q.path.toLowerCase().includes(Z)||Q.displayPath.toLowerCase().includes(Z)||Q.sourceName.toLowerCase().includes(Z)},[]),ee=!!window.electronAPI.remote,ge=async()=>{if(ee){C(ae=>!ae);return}const Q=await window.electronAPI.dialog.selectDirectory();Q&&u(Q)},Ce=m.useCallback(Q=>window.electronAPI.projects.listHostDirs(Q).then(ae=>ae.ok?ae:{error:ae.error}),[]),Re=m.useCallback((Q,ae)=>window.electronAPI.projects.createHostDir(Q,ae).then(Z=>Z.ok?Z:{error:Z.error}),[]),fe=m.useCallback(async(Q,ae)=>{const Z=await window.electronAPI.sshConnections.listDirs(h,Q);if(Z.ok)return{path:Z.path,parent:One(Z.path),dirs:Z.dirs};const ce=H0(Z,x.find(De=>De.id===h));return!ce||ae?{error:Z.error}:(P("browse"),T(ce),null)},[h,x]),U=l==="local"?d.trim().length>0:h.length>0&&f.trim().startsWith("/"),oe=()=>{const Q=x.find(ae=>ae.id===h);n({path:f.trim(),sshConnectionId:h,sshHost:Q?.name,...y?{groupId:y}:{}}),t(!1)},Se=Q=>{if(Q.preventDefault(),!U)return;if(l!=="ssh"){n({path:d.trim(),...y?{groupId:y}:{}}),t(!1);return}if($)return;X(!0),S("");const ae=++H.current,Z=x.find(ce=>ce.id===h);window.electronAPI.sshConnections.test(h).then(ce=>{if(ae===H.current){if(!ce.ok){const De=H0(ce,Z);if(De){P("submit"),T(De);return}S(ce.error);return}oe()}}).finally(()=>{ae===H.current&&X(!1)})},G=async()=>{if(!A)return;R(!0);const Q=await window.electronAPI.sshConnections.trustHost(h);if(R(!1),!Q.ok){S(Q.error||r("Could not save host key.")),T(null),P(null);return}const ae=I;if(T(null),P(null),ae==="browse"){O(Z=>Z+1);return}ae==="submit"&&oe()};return i.jsxs(xn,{open:e,onOpenChange:t,children:[i.jsx(vn,{className:"max-w-lg",children:i.jsxs("form",{onSubmit:Se,className:"flex flex-col",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:r("Add project")}),i.jsx(Rs,{children:r("Add a local directory as the conversation working folder.")})]}),i.jsxs(An,{className:"space-y-4",children:[i.jsx(lh,{value:l,onValueChange:Q=>{c(Q),C(!1)},children:i.jsxs(ch,{children:[i.jsx(Ps,{value:"local",children:r("Local directory")}),i.jsx(Ps,{value:"ssh",children:r("Remote (SSH)")})]})}),l==="ssh"?i.jsxs(i.Fragment,{children:[i.jsxs(Gs,{className:"w-full",children:[i.jsx(Fs,{children:r("SSH connection")}),x.length===0?i.jsx("p",{className:"text-sm text-muted-foreground",children:r("Add an SSH connection in Settings first.")}):i.jsxs(bs,{items:[{value:"",label:r("Select an SSH connection")},...x.map(Q=>({value:Q.id,label:`${Q.name} (${Q.user?`${Q.user}@`:""}${Q.host})`}))],value:h,onValueChange:Q=>p(Q??""),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsxs(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:[i.jsx(rs,{value:"",children:r("Select an SSH connection")}),x.map(Q=>i.jsxs(rs,{value:Q.id,children:[Q.name," (",Q.user?`${Q.user}@`:"",Q.host,")"]},Q.id))]})]})]}),i.jsxs(Gs,{className:"w-full",children:[i.jsx(Fs,{children:r("Remote directory")}),i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx(Zt,{value:f,onChange:Q=>g(Q.target.value),placeholder:"/home/user/project",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,className:"min-w-0 flex-1"}),i.jsx(me,{type:"button",variant:"outline",disabled:!h,onClick:()=>C(Q=>!Q),children:r("Browse")})]})]}),w&&h&&i.jsx(vg,{list:fe,initialPath:f.trim().startsWith("/")?f.trim():void 0,reloadKey:D,onSelect:Q=>{g(Q),C(!1)},onClose:()=>C(!1)},h),i.jsx("p",{className:"text-xs text-muted-foreground",children:r("Tools run on the remote host; chat history stays local.")}),k&&i.jsx("p",{className:"text-destructive text-xs",children:k})]}):i.jsxs(Gs,{className:"w-full",children:[i.jsx(Fs,{children:r("Working directory")}),i.jsxs(Ev,{value:d,onValueChange:Q=>u(Q??""),items:Y,filter:q,itemToStringValue:Q=>Q.path,children:[i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(Pv,{placeholder:r("Type a path or select from recent projects..."),showClear:!!d,showTrigger:!0})}),i.jsx(me,{type:"button",variant:"outline",onClick:()=>{ge()},children:r("Browse")})]}),i.jsxs(QD,{zIndex:yn.DROPDOWN_IN_MODAL,children:[i.jsx(Mv,{children:r("No matching projects found")}),i.jsx(Rv,{children:Q=>i.jsxs(Av,{value:Q,className:"gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",title:Q.path,children:Q.displayPath}),i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:Q.sourceName})]},Q.path)})]})]}),w&&ee&&i.jsx(vg,{list:Ce,create:Re,initialPath:d.trim()||void 0,onSelect:Q=>{u(Q),C(!1)},onClose:()=>C(!1)})]}),s.length>0&&i.jsxs(Gs,{children:[i.jsx(Fs,{children:r("Project group")}),i.jsxs(bs,{items:te,value:y??"",onValueChange:Q=>b(Q||void 0),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:te.map(Q=>i.jsx(rs,{value:Q.value,children:Q.label},Q.value||"ungrouped"))})]})]})]}),i.jsxs(ls,{children:[i.jsx(me,{type:"button",variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(me,{type:"submit",size:"sm",disabled:!U||$,children:r("Add")})]})]})}),i.jsx(X5,{challenge:A,nested:!0,busy:z,onTrust:()=>{G()},onDismiss:()=>{z||(T(null),P(null))}})]})}function Fne(e,t){return{x:e.left-t,width:Math.max(0,e.width)}}const HE="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",BE="flex size-4.5 shrink-0 items-center justify-center rounded-[5px] text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",Hne=24,Ya=20;function Bne({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,query:a,onQueryChange:l,searchOpen:c,onSearchOpenChange:d,onSelect:u,onAddGroup:h,onEditGroup:p}){const{t:f}=ne(),g=e.slice().sort((X,H)=>X.order-H.order),x=g.length>0,v=c||a.length>0,y=m.useRef(null),b=m.useRef(null),w=m.useRef(null),C=m.useRef(null),_=m.useRef(null),[N,k]=m.useState({left:!1,right:!1,overflow:!1}),{active:S}=yc(),A=g.find(X=>X.id===t),T=t===ps?f("Ungrouped"):A?.name??null,I=T?f("Search in {{group}}...",{group:T}):f("Search conversations..."),P=m.useCallback(()=>{const X=w.current,H=b.current,te=C.current,V=_.current,Y=H?.querySelector("[data-selected]");if(!X||!H||!te||!V||!Y||X.offsetParent===null){V&&(V.style.width="0px");return}const q=H.getBoundingClientRect(),ee=X.getBoundingClientRect(),ge=Y.getBoundingClientRect(),Ce=Fne(ge,q.left);te.style.left=`${q.left-ee.left}px`,te.style.width=`${q.width}px`,V.style.transform=`translateX(${Ce.x}px)`,V.style.width=`${Ce.width}px`},[]),D=m.useCallback(()=>{const X=b.current;P(),!(!X||X.clientWidth===0)&&k(H=>{const te=H.overflow?Hne:0,V={left:X.scrollLeft>1,right:X.scrollLeft+X.clientWidth<X.scrollWidth-1,overflow:X.scrollWidth>X.clientWidth+te+1};return H.left===V.left&&H.right===V.right&&H.overflow===V.overflow?H:V})},[P]);m.useLayoutEffect(()=>{const X=b.current;if(!X)return;D();const H=new ResizeObserver(D);return H.observe(X),X.firstElementChild&&H.observe(X.firstElementChild),()=>H.disconnect()},[D]),m.useLayoutEffect(()=>{P()},[P,S,t,v,g.length]),m.useEffect(()=>{const X=b.current;if(!X)return;const H=te=>{Math.abs(te.deltaY)<=Math.abs(te.deltaX)||X.scrollWidth<=X.clientWidth||(X.scrollLeft+=te.deltaY,te.preventDefault())};return X.addEventListener("wheel",H,{passive:!1}),()=>X.removeEventListener("wheel",H)},[]);const O=m.useRef(!1);m.useLayoutEffect(()=>{const X=b.current,H=X?.querySelector("[data-selected]");if(!X||!H||X.clientWidth===0)return;const te=O.current?"smooth":"auto";O.current=!0;const V=H.offsetLeft,Y=V+H.offsetWidth;V<X.scrollLeft+Ya?X.scrollTo({left:V-Ya,behavior:te}):Y>X.scrollLeft+X.clientWidth-Ya&&X.scrollTo({left:Y-X.clientWidth+Ya,behavior:te})},[t,x,c]),m.useEffect(()=>{c&&y.current?.focus()},[c]);const z=()=>{l(""),d(!1)},R=X=>X?`${Ya}px`:"0px",$=N.left||N.right?`linear-gradient(to right, transparent, #000 ${R(N.left)}, #000 calc(100% - ${R(N.right)}), transparent)`:void 0;return i.jsxs("div",{className:"group/bar shrink-0",children:[i.jsxs("div",{className:"relative z-[1] flex h-[35px] items-end gap-1.5 px-3.5",children:[v&&i.jsxs("label",{className:"mb-1 flex h-7 min-w-0 flex-1 cursor-text items-center gap-2 rounded-lg border border-transparent bg-foreground/5 pr-0.5 pl-2.5 text-xs text-muted-foreground transition-colors focus-within:border-brand/45",children:[i.jsx(eT,{className:"size-3.5 shrink-0"}),i.jsx("input",{ref:y,value:a,onChange:X=>l(X.target.value),onKeyDown:X=>{X.key==="Escape"&&(X.stopPropagation(),z())},onBlur:()=>{!a&&document.hasFocus()&&d(!1)},placeholder:I,className:"h-full min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground"}),i.jsx("button",{type:"button",onClick:z,className:"flex size-5 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-foreground/5 hover:text-foreground",title:f("Close"),"aria-label":f("Close"),children:i.jsx(dn,{className:"size-3"})})]}),i.jsxs("div",{ref:w,className:W("relative flex min-w-0 flex-1 items-center gap-1.5",v&&"hidden"),children:[i.jsx("div",{ref:b,onScroll:D,style:{maskImage:$},className:"min-w-0 overflow-x-auto [scrollbar-width:none]",children:i.jsxs("div",{className:"flex w-max gap-3.5",children:[i.jsx("button",{type:"button","data-enso":"group-chip","data-selected":t===In||void 0,"data-active":t===In||void 0,onClick:()=>u(In),className:Wu(t===In,!1),children:i.jsx(Uu,{label:f("All"),count:s})}),i.jsx("button",{type:"button","data-enso":"group-chip","data-selected":t===Oo||void 0,"data-active":t===Oo||void 0,onClick:()=>u(Oo),className:Wu(t===Oo,!1),children:i.jsx(Uu,{label:f("Recent"),count:o})}),i.jsx(xg,{items:g.map(X=>Ov(X.id)),strategy:_ne,children:g.map(X=>i.jsx(Vne,{group:X,count:n[X.id]??0,selected:t===X.id,onSelect:()=>u(X.id)},X.id))}),x&&i.jsx($ne,{label:f("Ungrouped"),count:r,selected:t===ps,onSelect:()=>u(ps)})]})}),i.jsx("span",{ref:C,"aria-hidden":!0,className:"pointer-events-none absolute -bottom-px z-10 h-[1.5px] overflow-hidden",children:i.jsx("span",{ref:_,className:"absolute top-0 left-0 h-full rounded-full bg-foreground"})}),i.jsx("button",{type:"button",onClick:h,className:W(BE,"opacity-0 focus-visible:opacity-100 group-hover/bar:opacity-100 [@media(hover:none)]:opacity-100"),title:f("New group"),"aria-label":f("New group"),children:i.jsx(as,{className:"size-3"})}),N.overflow&&i.jsx(Wne,{groups:g,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,onSelect:u,onAddGroup:h,onEditGroup:p})]})]}),i.jsx("div",{className:"mx-3.5 h-px bg-border"})]})}function Wu(e,t){return W("flex shrink-0 items-center whitespace-nowrap pt-1 pb-[7px] text-[0.8929rem] transition-colors",e?"font-medium text-foreground":"text-subtle-foreground hover:text-foreground",t&&"rounded-t-md bg-foreground/[0.075] text-foreground")}function Uu({label:e,count:t,emoji:n,color:s}){return i.jsxs(i.Fragment,{children:[n&&i.jsx("span",{className:"mr-1 text-[13px] leading-none",children:n}),s&&i.jsx("span",{className:"mr-1.5 size-1.5 shrink-0 rounded-full",style:{backgroundColor:s},"aria-hidden":!0}),i.jsx("span",{className:"max-w-32 truncate",children:e}),i.jsx("span",{className:"ml-1 font-normal text-[0.75rem] text-subtle-foreground/75 tabular-nums",children:t})]})}const VE=e=>e?.type==="project";function Vne({group:e,count:t,selected:n,onSelect:s}){const{attributes:o,listeners:r,setNodeRef:a,transform:l,transition:c,isDragging:d,isOver:u,active:h}=Jh({id:Ov(e.id),data:{type:"project-group",groupId:e.id}});return i.jsx("button",{ref:a,type:"button","data-enso":"group-chip","data-selected":n||void 0,"data-active":n||void 0,onClick:s,style:{transform:l?`translate3d(${Math.round(l.x)}px, 0, 0)`:void 0,transition:c},className:W(Wu(n,u&&VE(h?.data.current)),d&&"z-10 cursor-grabbing text-foreground"),...o,...r,children:i.jsx(Uu,{label:e.name,count:t,emoji:e.emoji,color:e.color})})}function $ne({label:e,count:t,selected:n,onSelect:s}){const{active:o}=yc(),{setNodeRef:r,isOver:a}=Sc({id:Ov(ps),disabled:o?.data.current?.type==="project-group"});return i.jsx("button",{ref:r,type:"button","data-enso":"group-chip","data-selected":n||void 0,"data-active":n||void 0,onClick:s,className:Wu(n,a&&VE(o?.data.current)),children:i.jsx(Uu,{label:e,count:t})})}function Wne({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,onSelect:a,onAddGroup:l,onEditGroup:c}){const{t:d}=ne(),[u,h]=m.useState(!1),p=f=>()=>{h(!1),f()};return i.jsxs(vi,{open:u,onOpenChange:h,children:[i.jsx(bi,{className:W(BE,"ml-auto data-popup-open:bg-foreground/5 data-popup-open:text-foreground"),title:d("All groups"),"aria-label":d("All groups"),children:i.jsx($n,{className:"size-3"})}),i.jsxs(wi,{side:"bottom",align:"end",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsx(fd,{label:d("All"),count:s,selected:t===In,onSelect:p(()=>a(In))}),i.jsx(fd,{label:d("Recent"),count:o,selected:t===Oo,onSelect:p(()=>a(Oo))}),e.map(f=>i.jsx(fd,{label:f.name,emoji:f.emoji,color:f.color,count:n[f.id]??0,selected:t===f.id,onSelect:p(()=>a(f.id)),onEdit:p(()=>c(f.id))},f.id)),e.length>0&&i.jsx(fd,{label:d("Ungrouped"),count:r,selected:t===ps,onSelect:p(()=>a(ps))}),i.jsx("div",{className:"my-1 border-t"}),i.jsxs("button",{type:"button",onClick:p(l),className:W(HE,"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx(as,{className:"size-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:d("New group")})]})]})]})}function fd({label:e,count:t,emoji:n,color:s,selected:o,onSelect:r,onEdit:a}){const{t:l}=ne();return i.jsxs("div",{className:"group/row relative",children:[i.jsxs("button",{type:"button",onClick:r,className:W(HE,o?"bg-brand/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center gap-1",children:n?i.jsx("span",{className:"text-[13px] leading-none",children:n}):s?i.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:s},"aria-hidden":!0}):null}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:e}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs tabular-nums",children:t}),i.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center",children:o&&i.jsx(Yn,{className:W("size-3.5 text-brand",a&&"group-hover/row:opacity-0")})})]}),a&&i.jsx("button",{type:"button",onClick:a,className:"absolute inset-y-0 right-2 my-auto flex size-5 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-background hover:text-foreground focus-visible:opacity-100 group-hover/row:opacity-100",title:l("Edit group"),"aria-label":l("Edit group"),children:i.jsx($s,{className:"size-3.5"})})]})}function $E({value:e,reasoningEnabled:t,thinkingLevel:n,onChange:s,onReasoningChange:o,onThinkingChange:r,description:a,inheritLabel:l}){const{t:c}=ne(),d=we(g=>g.virtualModels),u=nx(),h=e?u.find(g=>g.id===e.providerId):void 0,p=h?.models.find(g=>g.id===e?.modelId),f=r_(d,e);return i.jsxs(Gs,{className:"w-full items-stretch",children:[i.jsx(Fs,{children:c("Default model")}),i.jsx(P_,{children:a}),u.length>0&&i.jsx("div",{className:"w-full min-w-0",children:i.jsx(xh,{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:J5,zIndex:yn.DROPDOWN_IN_MODAL,onSelect:(g,x)=>s({providerId:g,modelId:x}),onReasoningChange:o,onThinkingChange:r})}),e&&!f&&(!h||!p)&&i.jsx("p",{className:"text-muted-foreground text-xs",children:c("Selected model is unavailable — falls back to the default model.")}),e&&i.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"self-start",onClick:()=>s(null),children:c("Follow default model")})]})}const Une=["#3b82f6","#22c55e","#eab308","#f97316","#ef4444","#a855f7","#06b6d4","#64748b"];function Kne({open:e,group:t,projects:n,onOpenChange:s,onSave:o,onDelete:r}){const{t:a}=ne(),l=we(P=>P.defaultReasoningEnabled),c=we(P=>P.defaultThinkingLevel),[d,u]=m.useState(""),[h,p]=m.useState(),[f,g]=m.useState(null),[x,v]=m.useState(!0),[y,b]=m.useState("medium"),[w,C]=m.useState(new Set),[_,N]=m.useState(""),k=t===null,S=k?n??[]:[],A=_.trim().toLowerCase(),T=A?S.filter(P=>[P.alias??"",P.name].some(D=>D.toLowerCase().includes(A))):S;m.useEffect(()=>{if(!e)return;u(t?.name??""),p(t?.color),g(t?.defaultModel??null);const P=lu({defaultReasoningEnabled:l,defaultThinkingLevel:c});v(t?.defaultReasoningEnabled??P.reasoningEnabled),b(t?.defaultThinkingLevel??P.thinkingLevel),C(new Set),N("")},[e,t,l,c]);const I=P=>{C(D=>{const O=new Set(D);return O.has(P)?O.delete(P):O.add(P),O})};return i.jsx(xn,{open:e,onOpenChange:s,children:i.jsx(vn,{className:"max-w-md",children:i.jsxs("form",{className:"flex flex-col",onSubmit:P=>{P.preventDefault();const D=d.trim();D&&(o({name:D,color:h,defaultModel:f,defaultReasoningEnabled:f?x:null,defaultThinkingLevel:f?y:null,...k&&w.size>0?{projectIds:[...w]}:{}}),s(!1))},children:[i.jsxs(bn,{children:[i.jsx(wn,{children:a(t?"Edit group":"New group")}),i.jsx(Rs,{children:a("Groups organize projects in the sidebar.")})]}),i.jsxs(An,{className:"space-y-3",children:[i.jsxs(Gs,{children:[i.jsx(Fs,{children:a("Name")}),i.jsx(Zt,{value:d,onChange:P=>u(P.target.value),autoFocus:!0})]}),i.jsxs("div",{className:"flex flex-wrap gap-2",children:[i.jsx("button",{type:"button",className:"flex h-6 w-6 items-center justify-center rounded-full border border-border bg-background text-muted-foreground",style:{outline:h==null?"2px solid var(--color-ring)":void 0,outlineOffset:2},onClick:()=>p(void 0),"aria-label":a("No color"),children:i.jsx(dn,{className:"h-3 w-3"})}),Une.map(P=>i.jsx("button",{type:"button",className:"h-6 w-6 rounded-full border border-border",style:{backgroundColor:P,outline:h===P?"2px solid var(--color-ring)":void 0,outlineOffset:2},onClick:()=>p(h===P?void 0:P),"aria-label":P},P))]}),i.jsx($E,{value:f,reasoningEnabled:x,thinkingLevel:y,onChange:P=>{if(g(P),P)return;const D=lu({defaultReasoningEnabled:l,defaultThinkingLevel:c});v(D.reasoningEnabled),b(D.thinkingLevel)},onReasoningChange:v,onThinkingChange:b,description:a("Used for new conversations in this group."),inheritLabel:a("Follows the global default")}),S.length>0&&i.jsxs(Gs,{className:"w-full items-stretch",children:[i.jsx(Fs,{children:a("Move projects into this group")}),i.jsx(Zt,{value:_,onChange:P=>N(P.target.value),placeholder:a("Filter projects...")}),i.jsxs("div",{className:"max-h-48 w-full space-y-0.5 overflow-y-auto rounded-md border p-1.5",children:[T.map(P=>i.jsxs("label",{className:"flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 hover:bg-accent/50",children:[i.jsx(gc,{checked:w.has(P.id),onCheckedChange:()=>I(P.id)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:Ns(P)})]},P.id)),T.length===0&&i.jsx("p",{className:"px-2 py-3 text-center text-xs text-muted-foreground",children:a("No matching projects found")})]})]})]}),i.jsxs(ls,{className:t?"sm:justify-between":void 0,children:[t&&r?i.jsx(me,{type:"button",variant:"outline",size:"sm",className:"text-destructive",onClick:()=>{r(),s(!1)},children:a("Delete group")}):i.jsx("span",{}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(me,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),children:a("Cancel")}),i.jsx(me,{type:"submit",size:"sm",disabled:!d.trim(),children:a("Save")})]})]})]})})})}function qne({project:e,onClose:t}){const{t:n}=ne(),[s,o]=m.useState(null),[r,a]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1);m.useEffect(()=>{if(!e)return;let p=!0;return o(null),a(null),c(null),window.electronAPI.sessionImport.scan(e.path).then(f=>{p&&o(f)}).catch(()=>{p&&o([])}),()=>{p=!1}},[e]),m.useEffect(()=>{if(!r){c(null);return}let p=!0;return c(null),window.electronAPI.sessionImport.read(r.sourceId,r.path).then(f=>{p&&c(f)}).catch(()=>{p&&c([])}),()=>{p=!1}},[r]);const h=async()=>{if(!(!e||!r)){u(!0);try{const p=await window.electronAPI.sessionImport.import(r.sourceId,r.path,e.path);p&&(ie.getState().addImportedConversation(e.id,p),t())}finally{u(!1)}}};return i.jsx(xn,{open:e!==null,onOpenChange:p=>!p&&t(),children:i.jsxs(vn,{className:"max-w-3xl",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:n("Import session")}),i.jsx(Rs,{children:n("Pick a conversation from a local AI app under {{name}}.",{name:e?.name??""})})]}),i.jsx(An,{children:s===null?i.jsx("div",{className:"flex flex-col items-center gap-3 py-12",children:i.jsx(vr,{className:"size-5"})}):s.length===0?i.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:n("No sessions found for this project")}):i.jsxs("div",{className:"flex h-96 gap-3",children:[i.jsx("div",{className:"flex w-64 shrink-0 flex-col overflow-y-auto rounded-lg border",children:s.map(p=>i.jsxs("div",{children:[i.jsx("p",{className:"sticky top-0 bg-background px-2.5 pt-2 pb-1 text-[10px] font-semibold tracking-[0.18em] text-muted-foreground uppercase",children:p.sourceName}),p.sessions.map(f=>i.jsxs("button",{type:"button",onClick:()=>a({sourceId:p.sourceId,path:f.path}),className:W("w-full px-2.5 py-1.5 text-left",r?.path===f.path?"bg-muted":"hover:bg-muted/50"),children:[i.jsx("p",{className:"truncate text-xs",children:f.title||n("Untitled")}),i.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[new Date(f.updatedAt).toLocaleString()," ·"," ",n("{{count}} messages",{count:f.messageCount})]})]},f.path))]},p.sourceId))}),i.jsx("div",{className:"min-w-0 flex-1 overflow-y-auto rounded-lg border bg-muted/20 p-3",children:r?l===null?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(vr,{className:"size-4"})}):i.jsx("div",{className:"flex flex-col gap-2.5",children:l.map((p,f)=>i.jsx("div",{className:W("max-w-[90%] rounded-lg px-2.5 py-1.5 text-xs whitespace-pre-wrap",p.role==="user"?"self-end bg-primary/10":"self-start bg-background border"),children:p.text.length>600?`${p.text.slice(0,600)}…`:p.text},f))}):i.jsx("p",{className:"py-12 text-center text-xs text-muted-foreground",children:n("Select a session to preview")})})]})}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",onClick:t,children:n("Cancel")}),i.jsxs(me,{onClick:()=>{h()},disabled:!r||d,children:[d?i.jsx(vr,{className:"mr-1.5 size-3.5"}):i.jsx(cc,{className:"mr-1.5 h-3.5 w-3.5"}),n("Import")]})]})]})})}function Yne({open:e,project:t,onOpenChange:n}){const{t:s}=ne(),o=we(V=>V.projectGroups),r=we(V=>V.defaultReasoningEnabled),a=we(V=>V.defaultThinkingLevel),l=we(V=>V.setProjectDefaultModel),c=we(V=>V.setProjectGroupId),d=we(V=>V.setProjectAlias),u=we(V=>V.setProjectDisabledBuiltinTools),h=we(V=>V.setProjectSubagentAllowedModes),p=we(V=>V.setProjectTrustedCode),f=we(V=>V.disabledBuiltinTools),g=we(V=>V.subagentAllowedModes),[x,v]=m.useState(""),[y,b]=m.useState(null),[w,C]=m.useState(!0),[_,N]=m.useState("medium"),[k,S]=m.useState(""),[A,T]=m.useState(!0),[I,P]=m.useState([]),[D,O]=m.useState(!0),[z,R]=m.useState([]),[$,X]=m.useState(!1);m.useEffect(()=>{if(!e)return;X(!1),b(t?.defaultModel??null),S(t?.groupId??""),v(t?.alias??"");const V=t?.groupId?o.find(ge=>ge.id===t.groupId):void 0,Y=lu({groupReasoningEnabled:V?.defaultReasoningEnabled,groupThinkingLevel:V?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});C(t?.defaultReasoningEnabled??Y.reasoningEnabled),N(t?.defaultThinkingLevel??Y.thinkingLevel);const q=t?.disabledBuiltinTools===void 0;T(q),P(q?[...f]:[...t?.disabledBuiltinTools??[]]);const ee=t?.subagentAllowedModes===void 0;O(ee),R(ee?[...g]:[...t?.subagentAllowedModes??[]])},[e,t,o,r,a,f,g]);const H=m.useMemo(()=>[{value:"",label:s("Ungrouped")},...o.slice().sort((V,Y)=>V.order-Y.order).map(V=>({value:V.id,label:V.name}))],[o,s]),te=t?.kind==="ssh"?`${t.sshConnectionName??t.sshHost}:${t.path}`:t?.path??"";return i.jsx(xn,{open:e,onOpenChange:n,children:i.jsx(vn,{className:"max-w-lg",children:i.jsxs("form",{className:"contents",onSubmit:V=>{V.preventDefault(),t&&(l(t.id,y,y?{reasoningEnabled:w,thinkingLevel:_}:null),c(t.id,k||null),d(t.id,x),u(t.id,A?null:I),h(t.id,D?null:z),$&&p(t.id,null),n(!1))},children:[i.jsxs(bn,{children:[i.jsx(wn,{children:s("Project settings")}),i.jsx(Rs,{children:t?Ns(t):s("Project")})]}),i.jsxs(An,{className:"max-h-[60vh] space-y-4",children:[i.jsxs(Gs,{className:"w-full items-stretch",children:[i.jsx(Fs,{children:s("Alias")}),i.jsx(Zt,{value:x,onChange:V=>v(V.target.value),placeholder:t?Ns({...t,alias:void 0}):""}),i.jsx(P_,{children:s("Shown in the sidebar instead of the folder name. Leave blank to reset.")})]}),i.jsxs(Gs,{className:"w-full items-stretch",children:[i.jsx(Fs,{children:s("Path")}),i.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[i.jsx("p",{className:"min-w-0 flex-1 truncate font-mono text-xs",title:te,children:te}),i.jsx(nj,{text:te,className:"shrink-0"}),t&&t.kind!=="ssh"&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.projects.reveal({projectId:t.id})},className:"shrink-0 transition-colors hover:text-foreground",title:s("Open folder"),children:i.jsx(oi,{className:"h-3 w-3"})})]})]}),o.length>0&&i.jsxs(Gs,{className:"w-full items-stretch",children:[i.jsx(Fs,{children:s("Project group")}),i.jsxs(bs,{items:H,value:k,onValueChange:V=>S(V??""),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:H.map(V=>i.jsx(rs,{value:V.value,children:V.label},V.value||"ungrouped"))})]})]}),i.jsx($E,{value:y,reasoningEnabled:w,thinkingLevel:_,onChange:V=>{if(b(V),V)return;const Y=k?o.find(ee=>ee.id===k):void 0,q=lu({groupReasoningEnabled:Y?.defaultReasoningEnabled,groupThinkingLevel:Y?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});C(q.reasoningEnabled),N(q.thinkingLevel)},onReasoningChange:C,onThinkingChange:N,description:s("Used for new conversations in this project."),inheritLabel:s("Follows group, then global default")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("Session choice overrides the project default.")}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Follow global built-in tools")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("When off, configure built-in tools for this project. They override the global setting on the next session.")})]}),i.jsx(pi,{checked:A,onCheckedChange:T})]}),!A&&i.jsx("div",{className:"space-y-2",children:Z5.map(V=>i.jsxs("div",{className:"flex items-center gap-3 rounded-md border px-3 py-2.5",children:[i.jsx(Kg,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm font-medium",children:s(V.name)}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s(V.description)})]}),i.jsx(pi,{checked:!I.includes(V.id),onCheckedChange:Y=>P(q=>Y?q.filter(ee=>ee!==V.id):[...new Set([...q,V.id])])})]},V.id))}),i.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Follow global unified agent modes")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("When off, this project uses its own explicit Agent mode permission mask.")})]}),i.jsx(pi,{checked:D,onCheckedChange:V=>{O(V),V||R([...g])}})]}),!D&&i.jsxs("div",{className:"space-y-2 rounded-lg border px-3 py-2.5",children:[[["task","One-shot task agents"],["coworker","Persistent coworkers"]].map(([V,Y])=>i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsx("span",{className:"text-sm",children:s(Y)}),i.jsx(pi,{checked:z.includes(V),disabled:(A?f:I).includes("subagent"),onCheckedChange:q=>R(ee=>q?[...new Set([...ee,V])]:ee.filter(ge=>ge!==V))})]},V)),(A?f:I).includes("subagent")&&i.jsx("p",{className:"text-muted-foreground text-xs",children:s("The unified subagent tool is off. Re-enabling it keeps this mode selection.")})]})]}),t?.trustedProjectCode?.length?i.jsxs("div",{className:"flex items-start gap-3 rounded-lg border px-3 py-2.5",children:[i.jsx(ca,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Trusted project extensions")}),i.jsx("p",{className:"truncate font-mono text-muted-foreground text-xs",title:t.trustedProjectCode.join(`
96
- `),children:t.trustedProjectCode.join(", ")}),$&&i.jsx("p",{className:"text-muted-foreground text-xs",children:s("No longer loaded after saving, starting with the next session.")})]}),i.jsx(me,{type:"button",size:"xs",variant:"outline",disabled:$,onClick:()=>X(!0),children:s("Revoke trust")})]}):null]}),i.jsxs(ls,{children:[i.jsx(me,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsx(me,{type:"submit",size:"sm",disabled:!t,children:s("Save")})]})]})})})}const Xne={connecting:"Connecting…","host-offline":"Desktop is offline",unauthorized:"Pairing expired",replaced:"Open in another page",offline:"Reconnecting…"};function Jne(e,t){if(e.state!=="online")return t(Xne[e.state]);const n=e.transport==="direct"?t("Direct link"):t("Via relay"),s=Q5(e.rttMs);return s?`${t("Connected")} · ${n} · ${s}`:`${t("Connected")} · ${n}`}function Zne(){return"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}function Qne(e){const t=e+"=".repeat((4-e.length%4)%4),n=atob(t.replace(/-/g,"+").replace(/_/g,"/"));return Uint8Array.from(n,s=>s.charCodeAt(0))}function ese(e){return e==="AbortError"?"service-unreachable":e==="NotAllowedError"?"permission-denied":"subscribe-failed"}async function tse(e){if(!Zne())return{ok:!1,reason:"unsupported"};if(await Notification.requestPermission()!=="granted")return{ok:!1,reason:"permission-denied"};const n=await navigator.serviceWorker.ready;try{const o=(await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Qne(e)})).toJSON();return!o.endpoint||!o.keys?.p256dh||!o.keys?.auth?{ok:!1,reason:"subscribe-failed"}:{ok:!0,subscription:{endpoint:o.endpoint,keys:{p256dh:o.keys.p256dh,auth:o.keys.auth}}}}catch(s){const o=s instanceof Error?s.name:"";return{ok:!1,reason:ese(o)}}}const nse="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground disabled:opacity-40";function sse(){const e=window.electronAPI.remote,[t,n]=m.useState(null);return m.useEffect(()=>{if(!(!e?.linkStatus||!e.onLinkStatus))return n(e.linkStatus()),e.onLinkStatus(n)},[e]),t}function ise(e,t){return e.pushError?t(WE[e.pushError]):e.pushAvailability==="needs-install"?t("Add this app to the Home Screen before notifications can be turned on."):e.pushAvailability==="unsupported"?t("This browser cannot show notifications."):e.pushReady?e.pushBusy?t("Turning on notifications…"):e.pushEnabled?t("Turn off notifications"):t("Turn on notifications"):t("Notifications need a newer desktop app.")}const WE={unsupported:"This browser cannot show notifications.","permission-denied":"Notification permission was denied. Allow notifications for this site and try again.","service-unreachable":"Cannot reach the push service. Check the network or proxy and try again.","subscribe-failed":"Could not turn on notifications."};function NC(){const{t:e}=ne(),t=sse();if(!t)return null;const n=Jne(t,e),s=ise(t,e),o=t.pushBusy||t.pushAvailability!=="ok"||!t.pushReady||t.state!=="online"&&!t.pushEnabled;return i.jsxs(vi,{children:[i.jsx(bi,{className:nse,title:n,"aria-label":n,children:i.jsx(fh,{className:"h-4 w-4"})}),i.jsxs(wi,{side:"top",align:"end",className:"w-64 [&_[data-slot=popover-viewport]]:px-3 [&_[data-slot=popover-viewport]]:py-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-md bg-background text-muted-foreground shadow-xs ring-1 ring-border",children:i.jsx(eO,{className:"size-3.5"})}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[i.jsx("span",{className:"truncate font-medium text-sm leading-4",children:t.deviceLabel}),i.jsx("span",{className:"truncate text-subtle-foreground text-xs leading-4",children:n})]})]}),i.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 border-t pt-3",children:[i.jsx("span",{className:"text-sm",children:e("Push notifications")}),i.jsx(pi,{checked:t.pushEnabled,disabled:o,title:s,"aria-label":s,onCheckedChange:()=>{ose(t)}})]}),t.pushError&&i.jsx("p",{className:"mt-2 text-destructive text-xs",children:e(WE[t.pushError])})]})]})}async function ose(e){const t=window.electronAPI.remote;if(!t?.setPushSubscription||!t.setPushPending)return;if(e.pushEnabled){t.setPushSubscription(null);return}const n=t.vapidPublicKey?.();if(!n)return;t.setPushPending({busy:!0,enabled:!0,error:null});const s=await tse(n);if(!s.ok){t.setPushPending({busy:!1,enabled:!1,error:s.reason});return}t.setPushSubscription(s.subscription)}const Zh=5,UE=15,TC=9;function Qh(e,t){return e<=0?0:Math.min(e,Zh+Math.max(0,t))}function rse(e,t){return Qh(e,t)>=e?0:Math.min(Math.max(0,e-Zh),t+UE)}function ase(e){return Math.max(0,e-UE)}function lse(e){const{order:t,conversations:n,pinnedOrderIds:s=[],projectIds:o,archivedProjectIds:r=[],collapsedProjects:a={},revealedExtras:l={},searching:c=!1,matches:d=()=>!0,projectMatches:u=()=>!1,leadingIds:h=[]}=e,p=[],f=new Set,g=v=>{f.has(v)||p.length>=TC||(f.add(v),p.push(v))};for(const v of h)g(v);const x=A_(t,n,s,r);for(const v of c?x.filter(d):x)g(v);for(const v of o){if(p.length>=TC)break;if(c?!1:a[v]===!0)continue;const b=Qr(t,n,v),w=!c||u(v)?b:b.filter(d),C=c?w:w.slice(0,Qh(w.length,l[v]??0));for(const _ of C)g(_)}return p}function $v(e,t){const n=new Map(e.map(o=>[o.id,o])),s=[];for(const o of t){const r=n.get(o);r&&(s.push(r),n.delete(o))}for(const o of e)n.has(o.id)&&s.push(o);return s}function md(e,t,n,s){const o=$v(e,t).map(l=>l.id),r=o.indexOf(n),a=o.indexOf(s);return r===-1||a===-1||r===a||(o.splice(r,1),o.splice(a,0,n)),o}function cse(e,t){const n=new Map(e.map(r=>[r.id,r])),s=[],o=new Set;for(const r of t){const a=n.get(r);a&&(s.push(a),o.add(r))}return{pinned:s,rest:e.filter(r=>!o.has(r.id))}}function dse(e,t){return e.includes(t)?e.filter(n=>n!==t):[t,...e]}function use(e,t,n){const s=n.includes(e),o=n.includes(t);return s&&o?"pinned":!s&&!o?"order":null}function bf(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function IC(e){return e==="browser"||typeof e=="string"&&e.startsWith("browser:")}function hse(e){if(typeof e.contentComponent=="string")return e.contentComponent;if(typeof e.component=="string")return e.component}function DC(e){if(!bf(e)||!bf(e.panels))return{browsers:0,terminals:0};let t=0,n=0;for(const[s,o]of Object.entries(e.panels)){if(!bf(o))continue;const r=hse(o);r==="browser"||IC(o.id)||IC(s)?t+=1:r==="terminal"&&(n+=1)}return{browsers:t,terminals:n}}function pse({conversationId:e}){const{t}=ne(),n=fn(o=>DC(o.layouts[e]).browsers),s=fn(o=>DC(o.layouts[e]).terminals);return n===0&&s===0?null:i.jsxs("span",{"data-slot":"session-tab-counts",className:"flex shrink-0 items-center gap-1.5 text-[10px] tabular-nums text-muted-foreground/70",children:[n>0&&i.jsxs("span",{className:"inline-flex items-center gap-0.5",title:t("{{n}} browsers",{n}),children:[i.jsx(bo,{className:"h-3 w-3","aria-hidden":!0}),n]}),s>0&&i.jsxs("span",{className:"inline-flex items-center gap-0.5",title:t("{{n}} terminals",{n:s}),children:[i.jsx(Uo,{className:"h-3 w-3","aria-hidden":!0}),s]})]})}const fse=[7,15,30],EC="h-6.5 rounded-lg px-2 text-xs text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",PC="enso-collapsed-scratch",eo="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",wf="-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 AC({width:e,collapsed:t,onToggleCollapse:n,onOpenSearch:s,onNavigate:o}){const{t:r,locale:a}=ne(),l=we(J=>J.projects),d=gh()==="mobile",u=we(J=>J.scratchSessionsEnabled),h=we(J=>J.projectGroups),p=we(J=>J.createProjectGroup),f=we(J=>J.updateProjectGroup),g=we(J=>J.removeProjectGroup),x=we(J=>J.reorderProjectGroups),v=we(J=>J.setProjectGroupId),y=we(J=>J.keybindings),b=we(J=>J.activeRetentionMinutes),w=we(J=>J.headerRecentMinutes),C=Fi(y)["search-workspace"],_=C?ti(C):"",N=we(J=>J.addProject),k=we(J=>J.removeProject),S=ie(J=>Ah(J.conversations)),A=ie(J=>J.order),T=ie(J=>J.activeId),I=ie(J=>J.newConversation),P=ie(J=>J.selectConversation),D=m.useRef(o);D.current=o;const O=m.useCallback(J=>{D.current?.(),P(J)},[P]),z=ie(J=>J.removeConversation),R=ie(J=>J.togglePinConversation),$=ie(J=>J.toggleArchiveConversation),X=ie(J=>J.moveConversationToWorktree),H=ie(J=>J.cleanupWorktree),te=ie(J=>J.refreshWorktreeStatuses),V=ie(J=>J.worktreeStatuses),[Y,q]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-projects")??"{}")}catch{return{}}}),ee=J=>{q(ye=>{const lt={...ye,[J]:!ye[J]};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(lt)),lt})},[ge,Ce]=m.useState(()=>{try{return localStorage.getItem(PC)==="1"}catch{return!1}}),Re=J=>{try{localStorage.setItem(PC,J?"1":"0")}catch{}},fe=()=>{Ce(J=>{const ye=!J;return Re(ye),ye})},U=()=>{Ce(J=>J&&(Re(!1),!1))},[oe,Se]=m.useState(()=>Mi($d)),G=$v(l.filter(J=>J.kind!=="scratch"),oe),Q=l.find(J=>J.kind==="scratch"),[ae,Z]=m.useState(()=>Mi(co));m.useEffect(()=>BW(()=>q(Em())),[]),m.useEffect(()=>dT(()=>{Z(Mi(co))}),[]);const[ce,De]=m.useState(()=>Mi(zw)),Oe=J=>{De(J),Ao(zw,J)},Ne=J=>{if(Oe(dse(ce,J)),!ce.includes(J)&&ae.includes(J)){const ye=ae.filter(lt=>lt!==J);Z(ye),Ao(co,ye)}},Ze=J=>{const ye=ae.includes(J)?ae.filter(lt=>lt!==J):[...ae,J];Z(ye),Ao(co,ye),!ae.includes(J)&&ce.includes(J)&&Oe(ce.filter(lt=>lt!==J))},[bt,Ut]=m.useState(()=>{try{return localStorage.getItem("enso-selected-project-group")??In}catch{return In}}),[Et,_t]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-project-groups")??"{}")}catch{return{}}}),B=J=>{Ut(J),localStorage.setItem("enso-selected-project-group",J)},Te=J=>{_t(ye=>{const lt={...ye,[J]:!ye[J]};return localStorage.setItem("enso-collapsed-project-groups",JSON.stringify(lt)),lt})},We=bt===In||bt===Oo||bt===ps||h.some(J=>J.id===bt)?bt:In,kt=We===Oo,Gt=h.find(J=>J.id===We)?.id,de=Vr(G,h,ae,We),mt=tO(Vr(G,h,ae,In),A,S,Date.now()),{pinned:Lt,rest:Fe}=kt?{pinned:[],rest:mt}:cse(de,ce),Nt=M_(Fe,h,[]),Ft=[...Lt,...Fe],on=Ft.map(J=>J.id),re=new Set(on),[Ue,dt]=m.useState(()=>Mi(Tm)),{active:Dt}=yc(),it=Dt?.data.current;W_({onDragEnd:J=>{const ye=J.active.data.current;if(!ye)return;const lt=J.over?String(J.over.id):null,vt=Vee(ye,lt,T??void 0,{projectGroupId:Pt=>l.find(ns=>ns.id===Pt)?.groupId});if(vt)switch(vt.kind){case"move-project-to-group":{if(kt&&vt.beforeProjectId)break;if(v(vt.projectId,vt.groupId),vt.beforeProjectId){const Pt=md(l,oe,vt.projectId,vt.beforeProjectId);Se(Pt),Ao($d,Pt)}break}case"reorder-groups":x(vt.activeId,vt.overId);break;case"reorder-projects":{if(kt)break;const Pt=use(vt.activeId,vt.overId,ce);if(Pt==="pinned"){const Qo=md(ce.map(To=>({id:To})),ce,vt.activeId,vt.overId);Oe(Qo);break}if(Pt!=="order")break;const ns=md(l,oe,vt.activeId,vt.overId);Se(ns),Ao($d,ns);break}case"insert-file-mention":Yl({kind:"file",id:vt.path,label:vt.label,relativePath:vt.path});break;case"insert-chat-mention":Yl({kind:"chat",id:vt.conversationId,label:vt.label,sessionFile:vt.sessionFile});break;case"pin-conversation":R(vt.conversationId);break;case"reorder-pinned":{const Pt=md(jt.map(ns=>({id:ns})),Ue,vt.activeId,vt.overId);dt(Pt),Ao(Tm,Pt);break}}}});const[K,pe]=m.useState(null),[Ie,Ae]=m.useState(null),[He,nt]=m.useState(!1),[be,et]=m.useState(!1),[tt,wt]=m.useState(null),Jt=J=>{if(!J.sshConnectionId){mT(J.path,{groupId:J.groupId??Gt,onSelect:O}).catch(lt=>{ze({type:"error",title:r("Failed to add project"),description:lt instanceof Error?lt.message:String(lt)})});return}const ye=new Set(l.map(lt=>lt.id));wt({name:p_(J.path),path:J.path,sshHost:J.sshHost}),N(J.path,{sshConnectionId:J.sshConnectionId},J.groupId??Gt).then(lt=>{if(lt){if(ae.includes(lt.id)){const vt=ae.filter(Pt=>Pt!==lt.id);Z(vt),Ao(co,vt)}if(ye.has(lt.id)){q(Pt=>{if(Pt[lt.id]!==!0)return Pt;const ns={...Pt,[lt.id]:!1};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(ns)),ns});const vt=Qr(A,S,lt.id)[0];if(vt){O(vt);return}}I(lt.id)}}).catch(lt=>{ze({type:"error",title:r("Failed to add project"),description:lt instanceof Error?lt.message:String(lt)})}).finally(()=>wt(null))},[E,L]=m.useState(null),[M,j]=m.useState(null),F=async J=>{const ye=S[J];let lt;if(ye?.worktree){const vt=await zn(J);Ad(vt)&&(lt=c0(vt))}j({kind:"conversation",id:J,worktreeWarning:lt})},[he,xe]=m.useState({}),[Ee,Ke]=m.useState(""),ht=Ai(J=>J.modHeld),ot=m.useCallback(J=>{Ai.setState({modHeld:J})},[]),[Ht,ut]=m.useState(()=>Date.now());m.useEffect(()=>{const J=setInterval(()=>ut(Date.now()),nO);return()=>clearInterval(J)},[]);const Tt={now:Ht,ms:b*6e4},yt=sO(A,S,ae,Tt),Ot=J=>{const ye=OC(l,S[J].projectId),lt=aO(J,S,Tt);if(lt===void 0)return ye;const vt=r("Stays in Active for about {{count}} more min",{count:Math.ceil(lt/6e4)});return ye?`${ye}
97
- ${vt}`:vt},jt=A_(A,S,Ue,ae),It=iO(A,S,G.map(J=>J.id),ae).filter(J=>u||J.projectId!==Q?.id),le=Ee.trim().length>0,Pe=J=>Ka(Ee,[S[J]?.title||r("New conversation")]),Ge=Q?Qr(A,S,Q.id).filter(J=>!le||Pe(J)):[],Ve=le?!1:ge,Ye=J=>{const ye=S[J]?.projectId;return!ye||re.has(ye)},at=(le?yt.filter(Pe):yt).filter(Ye),st=lse({order:A,conversations:S,pinnedOrderIds:Ue,projectIds:on,archivedProjectIds:ae,collapsedProjects:Y,revealedExtras:he,searching:le,matches:Pe,projectMatches:J=>{const ye=G.find(lt=>lt.id===J);return!!(ye&&Ka(Ee,[ye.alias??"",ye.name,ye.path]))},leadingIds:at}),Xe=oO(yt.filter(Ye),A,S,ae,{now:Ht,ms:w*6e4},Ye);T&&S[T]&&!S[T].parentId&&(Xe.includes(T)||Xe.push(T));const je=Ai(J=>J.headerMounted)?Xe.slice(0,9):st,Be=m.useRef(je);Be.current=je,m.useEffect(()=>uW(Xe,je));const Me=(le?jt.filter(Pe):jt).filter(Ye),Le=new Set(Me),qe=new Set(at),Ct=(J,ye)=>{if(t||!ht)return;const lt=je.indexOf(J);if(!(lt<0||(qe.has(J)?"active":Le.has(J)?"pinned":"project")!==ye))return ti(`mod+${lt+1}`)},[Vt,Bt]=m.useState(!1),[Rt,se]=m.useState(""),[qt,rn]=m.useState(null),an=Rt.trim()?It.map(J=>{const ye=l.find(vt=>vt.id===J.projectId);return J.projectArchived===!0&&!!(ye&&Ka(Rt,[ye.alias??"",ye.name,ye.path]))?J:{...J,ids:J.ids.filter(vt=>Ka(Rt,[S[vt]?.title||r("New conversation")]))}}).filter(J=>J.ids.length>0):It,Kt=J=>{if(We===In)return!0;const ye=l.find(lt=>lt.id===J.projectId);return ye?We===ps?!ye.groupId||!h.some(lt=>lt.id===ye.groupId):ye.groupId===We:We===ps},nn=an.filter(Kt),Qt=It.filter(Kt).reduce((J,ye)=>J+ye.ids.length,0),Rn=()=>{se(""),Bt(!0)};m.useEffect(()=>{We!==bt&&(Ut(In),localStorage.setItem("enso-selected-project-group",In))},[We,bt]),m.useEffect(()=>{const J=Pt=>{const Qo=(Xf?Pt.metaKey:Pt.ctrlKey)&&!Pt.shiftKey&&!Pt.altKey;if(ot(Qo),!Qo||Pt.repeat||os.getState().activeNodeId!=="local")return;const To=Number(Pt.key);if(To<1||To>9)return;const er=Be.current[To-1];er&&(Pt.preventDefault(),O(er))},ye=Pt=>{const ns=Xf?Pt.metaKey:Pt.ctrlKey;ot(ns&&!Pt.shiftKey&&!Pt.altKey)},lt=()=>ot(!1),vt=()=>{document.hidden&&lt()};return window.addEventListener("keydown",J),window.addEventListener("keyup",ye),window.addEventListener("blur",lt),document.addEventListener("visibilitychange",vt),()=>{window.removeEventListener("keydown",J),window.removeEventListener("keyup",ye),window.removeEventListener("blur",lt),document.removeEventListener("visibilitychange",vt)}},[O,ot]),m.useEffect(()=>{te();const J=setInterval(()=>{te()},3e4),ye=()=>{te()};return window.addEventListener("focus",ye),()=>{clearInterval(J),window.removeEventListener("focus",ye)}},[te]);const[sn,jn]=m.useState(null),[_n,Nn]=m.useState(null),zn=async J=>{const ye=await window.electronAPI.worktree.status(J);return ye.ok?ye.value:void 0},Wn=async(J,ye)=>{const lt=await H(J);if(lt){ze({type:"error",title:r("Failed to clean up worktree"),description:lt});return}ye&&$(J),te()},Fn=async J=>{const ye=await zn(J);if(Ad(ye)){jn({kind:"cleanup",id:J,status:ye});return}await Wn(J,!1)},Gn=async J=>{const ye=S[J];if(!ye)return;if(ye.archived||!ye.worktree){$(J);return}const lt=await zn(J);if(Ad(lt)){jn({kind:"archive",id:J,status:lt});return}await Wn(J,!0)},jA=async J=>{for(const ye of J)!S[ye]||S[ye].archived||await Gn(ye)},Dr=async(J,ye=!1)=>{const lt=await X(J,{allowDirtyMainTree:ye});if(lt===E_){Nn(J);return}if(lt){ze({type:"error",title:r("Failed to move to worktree"),description:lt});return}te()},c0=J=>{const ye=[];return J?.dirty&&ye.push(r("Uncommitted changes")),J&&J.ahead>0&&ye.push(r("{{n}} unmerged commits (branch is kept)",{n:J.ahead})),ye.join("; ")};return i.jsxs(Os.aside,{initial:!1,animate:{width:t?48:e},transition:ra,"data-enso":"sidebar",className:"flex shrink-0 flex-col overflow-hidden",children:[t&&i.jsxs("div",{className:"flex w-full flex-1 flex-col items-center gap-1 py-2",children:[i.jsx("button",{type:"button",onClick:()=>nt(!0),className:eo,title:r("Add project"),children:i.jsx(Nu,{className:"h-4 w-4"})}),i.jsx("div",{className:"flex-1"}),window.electronAPI.remote?.linkStatus&&i.jsx(NC,{}),Qt>0&&i.jsx("button",{type:"button",onClick:Rn,className:eo,title:`${r("Archived")} (${Qt})`,children:i.jsx(Oi,{className:"h-4 w-4"})}),window.electronAPI.remote&&i.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:eo,title:r("Compact view"),children:i.jsx(B0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"settings-button",onClick:()=>window.electronAPI.window.openSettings(),className:eo,title:r("Settings"),children:i.jsx(mi,{className:"h-4 w-4"})})]}),i.jsxs("div",{className:W("flex h-full min-h-0 flex-col",d&&"pt-3",t&&"hidden"),style:{width:e},children:[i.jsx(Bne,{groups:h,selectedId:We,counts:Object.fromEntries(h.map(J=>[J.id,Vr(G,h,ae,J.id).length])),totalCount:Vr(G,h,ae,In).length,recentCount:mt.length,ungroupedCount:Vr(G,h,ae,ps).length,query:Ee,onQueryChange:Ke,searchOpen:be,onSearchOpenChange:et,onSelect:B,onAddGroup:()=>pe({mode:"create"}),onEditGroup:J=>pe({mode:"edit",id:J})}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pt-0.5 pb-2 pl-1.5 [scrollbar-gutter:stable]",children:[G.length===0&&i.jsx("button",{type:"button",onClick:()=>nt(!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")}),G.length===0&&u&&Q&&i.jsx("button",{type:"button",onClick:()=>{U(),I(Q.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")}),at.length>0&&i.jsxs("div",{"data-slot":"active-section",children:[i.jsx(Ja,{section:"active",children:r("Active")}),i.jsx("div",{className:"flex flex-col",children:at.map(J=>i.jsx(RC,{id:J,dragId:Hee(J),conversation:S[J],children:i.jsx(Xa,{id:J,conversation:S[J],active:T===J,switchHint:Ct(J,"active"),locale:a,nowTick:Ht,hoverTitle:Ot(J),worktreeStatus:S[J].worktree?V[J]:void 0,isolated:!!S[J].worktree,onSelect:O,onTogglePin:R,onToggleArchive:ye=>{Gn(ye)},onCleanupWorktree:ye=>{Fn(ye)},onMoveToWorktree:ye=>{Dr(ye)},onRemove:ye=>{F(ye)}})},J))})]}),jt.length===0&&it?.type==="chat"&&!it.pinned&&i.jsx(LC,{children:i.jsxs("div",{className:"flex items-center justify-center gap-1.5 rounded-lg border border-dashed px-2 py-2 text-xs text-muted-foreground",children:[i.jsx(hi,{className:"h-3.5 w-3.5"}),r("Drop here to pin")]})}),Me.length>0&&i.jsxs(LC,{"data-slot":"pinned-section",children:[i.jsx(Ja,{section:"pinned",children:r("Pinned")}),i.jsx("div",{className:"flex flex-col",children:i.jsx(xg,{items:Me.map(J=>bE(J)),strategy:jC,children:Me.map(J=>i.jsx(bse,{id:J,conversation:S[J],children:i.jsx(Xa,{id:J,conversation:S[J],active:T===J,switchHint:Ct(J,"pinned"),locale:a,nowTick:Ht,hoverTitle:OC(l,S[J].projectId),worktreeStatus:S[J].worktree?V[J]:void 0,isolated:!!S[J].worktree,onSelect:O,onTogglePin:R,onToggleArchive:ye=>{Gn(ye)},onCleanupWorktree:ye=>{Fn(ye)},onMoveToWorktree:ye=>{Dr(ye)},onRemove:ye=>{F(ye)}})},J))})})]}),u&&Q&&i.jsxs("div",{"data-slot":"scratch-section",children:[i.jsxs("div",{"data-enso":"section-header","data-section":"scratch",className:"group flex items-center gap-1 pt-3.5 pr-1 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground",children:[i.jsxs("button",{type:"button",onClick:fe,"aria-expanded":!Ve,className:"flex min-w-0 flex-1 items-center gap-1 text-left transition-colors hover:text-foreground",children:[i.jsx("span",{className:"min-w-0 truncate",children:r("Temporary chats")}),i.jsx(un,{"data-enso":"tree-chevron","data-expanded":!Ve||void 0,className:W("size-3 shrink-0 transition-[opacity,transform] duration-150",!Ve&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:"ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",children:Ge.length})]}),i.jsx("button",{type:"button",className:wf,title:r("Start a temporary chat"),"aria-label":r("Start a temporary chat"),onClick:()=>{U(),I(Q.id)},children:i.jsx(as,{className:"size-3.25"})})]}),i.jsx(vl,{initial:!1,children:!Ve&&i.jsx(Os.div,{initial:"initial",animate:"animate",exit:"exit",variants:ef,className:"overflow-hidden",children:i.jsx("div",{className:"flex flex-col",children:Ge.map(J=>i.jsx(Xa,{id:J,conversation:S[J],active:T===J,switchHint:Ct(J,"project"),locale:a,nowTick:Ht,onSelect:O,onTogglePin:R,onToggleArchive:ye=>{Gn(ye)},onCleanupWorktree:ye=>{Fn(ye)},onMoveToWorktree:ye=>{Dr(ye)},onRemove:ye=>{F(ye)}},J))})},"scratch-conversations")})]}),G.length>0&&i.jsx(Ja,{section:"projects",actions:i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:()=>et(!0),className:W(wf,(be||le)&&"bg-foreground/5 text-foreground opacity-100"),title:r("Search conversations..."),"aria-label":r("Search conversations..."),children:i.jsx(eT,{className:"size-3.25"})}),i.jsx("button",{type:"button",onClick:()=>nt(!0),className:wf,title:r("Add project"),"aria-label":r("Add project"),children:i.jsx(as,{className:"size-3.25"})})]}),children:r("Projects")}),tt&&i.jsxs("div",{className:"flex h-8 w-full items-center gap-2 rounded-lg px-2 text-muted-foreground",children:[i.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:i.jsx(Xt,{className:"size-4 animate-spin"})}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium",title:tt.path,children:[tt.name,tt.sshHost&&i.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal",children:tt.sshHost})]}),i.jsx("span",{className:"shrink-0 text-xs",children:r("Adding...")})]}),i.jsx(xg,{items:[...We===In?Nt.map(J=>J.groupId===ps?Lv:vE(J.groupId)):[],...on.map(J=>xE(J))],strategy:jC,children:(()=>{const J=ye=>{const lt=Qr(A,S,ye.id),vt=Ka(Ee,[ye.alias??"",ye.name,ye.path]),Pt=!le||vt?lt:lt.filter(Pe);if(le&&Pt.length===0)return null;const ns=le?!1:Y[ye.id]===!0,Qo=he[ye.id]??0,To=le?Pt.length:Qh(Pt.length,Qo),er=Pt.slice(To),Er=ce.includes(ye.id),d0=[{kind:"item",key:"pin",label:r(Er?"Unpin project":"Pin project"),icon:Er?i.jsx(Tu,{}):i.jsx(hi,{}),onSelect:()=>Ne(ye.id)},{kind:"item",key:"settings",label:r("Project settings"),icon:i.jsx(mi,{}),onSelect:()=>Ae(ye.id)},...ye.kind!=="ssh"?[{kind:"item",key:"reveal",label:r(Hv(window.electronAPI.env.platform)),icon:i.jsx(oi,{}),onSelect:()=>Bv({projectId:ye.id},r)}]:[],{kind:"item",key:"import",label:r("Import session"),icon:i.jsx(lO,{}),onSelect:()=>L(ye)},{kind:"separator",key:"sep-group"},{kind:"submenu",key:"move-to-group",label:r("Move to group"),icon:i.jsx(yf,{}),items:[{kind:"item",key:"ungrouped",label:r("Ungrouped"),icon:i.jsx(yf,{}),onSelect:()=>v(ye.id,null)},...h.map(Xi=>({kind:"item",key:`group-${Xi.id}`,label:Xi.name,icon:i.jsx(yf,{emoji:Xi.emoji,color:Xi.color}),onSelect:()=>v(ye.id,Xi.id)}))]},{kind:"item",key:"new-group",label:r("New group"),icon:i.jsx(Nu,{}),onSelect:()=>pe({mode:"create"})},{kind:"separator",key:"sep-danger"},{kind:"item",key:"archive",label:r("Archive project"),icon:i.jsx(Oi,{}),onSelect:()=>Ze(ye.id)},{kind:"item",key:"remove",label:r("Remove project"),icon:i.jsx(Vs,{}),destructive:!0,onSelect:()=>j({kind:"project",project:ye,conversationIds:lt})}];return i.jsx(vse,{project:ye,activitySorted:kt,children:Xi=>i.jsxs(go,{children:[i.jsx(xo,{render:i.jsxs("div",{ref:Xi.setNodeRef,style:Xi.style,children:[i.jsxs("div",{"data-enso":"project-row","data-expanded":!ns||void 0,className:"group flex h-8 w-full items-center gap-1 rounded-lg px-2 transition-colors hover:bg-foreground/5",...Xi.handleProps,children:[i.jsxs("button",{type:"button",onClick:()=>ee(ye.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",title:ye.path,children:[i.jsx(KE,{folded:ns}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium text-foreground",title:ye.kind==="ssh"?`${ye.sshHost}:${ye.path}`:ye.path,children:[Ns(ye),ye.kind==="ssh"&&i.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal text-muted-foreground",children:ye.sshConnectionName??ye.sshHost}),kt&&i.jsx("span",{className:"ml-1.5 font-normal text-[0.7857rem] text-subtle-foreground",children:h.find(ss=>ss.id===ye.groupId)?.name??r("Ungrouped")})]})]}),i.jsx("button",{type:"button",onClick:()=>Ne(ye.id),className:"hidden shrink-0 rounded-md p-1 text-muted-foreground group-hover:block hover:bg-muted hover:text-foreground",title:r(Er?"Unpin project":"Pin project"),children:Er?i.jsx(Tu,{className:"h-3.5 w-3.5"}):i.jsx(hi,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",onClick:()=>{I(ye.id)},className:"shrink-0 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted hover:text-foreground focus-visible:opacity-100",title:r("New conversation"),children:i.jsx(Ho,{className:"h-3.5 w-3.5"})}),i.jsx(yse,{actions:d0}),(Er||ns)&&i.jsxs("span",{className:"flex shrink-0 items-center justify-center gap-1 py-1 text-[0.7857rem] text-subtle-foreground tabular-nums group-hover:opacity-0","aria-hidden":!0,children:[Er&&i.jsx(hi,{className:"h-3.5 w-3.5"}),ns&&lt.length]})]}),i.jsx(vl,{initial:!1,children:!ns&&i.jsx(Os.div,{initial:"initial",animate:"animate",exit:"exit",variants:ef,className:"overflow-hidden",children:i.jsxs("div",{className:"flex flex-col",children:[Pt.slice(0,To).map(ss=>i.jsx(Os.div,{layout:it?.type==="project"?!1:"position",transition:ra,children:i.jsx(RC,{id:ss,conversation:S[ss],children:i.jsx(Xa,{id:ss,conversation:S[ss],active:T===ss,switchHint:Ct(ss,"project"),locale:a,nowTick:Ht,worktreeStatus:S[ss].worktree?V[ss]:void 0,isolated:!!S[ss].worktree,onSelect:O,onTogglePin:R,onToggleArchive:tr=>{Gn(tr)},onCleanupWorktree:tr=>{Fn(tr)},onMoveToWorktree:tr=>{Dr(tr)},onRemove:tr=>{F(tr)}})})},ss)),!le&&lt.length>Zh&&i.jsxs("div",{className:"flex items-center gap-1 pl-6",children:[er.length>0&&i.jsxs(go,{children:[i.jsx(xo,{render:i.jsx("button",{type:"button",onClick:()=>xe(ss=>({...ss,[ye.id]:rse(Pt.length,ss[ye.id]??0)})),className:EC,children:r("Show {{n}} more",{n:er.length})})}),i.jsx(vo,{className:"min-w-36",children:i.jsxs($t,{onClick:()=>{jA(er)},children:[i.jsx(Oi,{}),r("Archive {{n}} conversations",{n:er.length})]})})]}),Qo>0&&i.jsx("button",{type:"button",onClick:()=>xe(ss=>({...ss,[ye.id]:ase(ss[ye.id]??0)})),className:EC,children:r("Collapse")})]}),Pt.length===0&&i.jsx("p",{className:"py-1.5 pl-8 text-xs text-subtle-foreground",children:r("No conversations yet")})]})})})]})}),i.jsx(vo,{className:"min-w-40",children:Ku(d0)})]})},ye.id)};return kt&&!le&&Ft.length===0?i.jsx("p",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:r("No projects active in the last {{n}} days",{n:rO})}):!le&&G.length>0&&Ft.length===0?i.jsx("p",{className:"px-2 py-1.5 text-xs text-subtle-foreground",children:r("No projects in this group yet")}):We===In&&h.length>0?i.jsxs("div",{children:[Lt.length>0&&i.jsxs("div",{children:[i.jsx(Ja,{section:"pinned-projects",children:r("Pinned projects")}),i.jsx("div",{children:Lt.map(J)})]}),Nt.map(ye=>{const lt=le?!1:Et[ye.groupId]===!0;return i.jsxs("div",{children:[i.jsx(mse,{groupId:ye.groupId,name:ye.group?.name??r("Ungrouped"),emoji:ye.group?.emoji,color:ye.group?.color,count:ye.projects.length,folded:lt,sortable:ye.groupId!==ps,onToggle:()=>Te(ye.groupId),onEdit:ye.group?()=>pe({mode:"edit",id:ye.groupId}):void 0}),i.jsx(vl,{initial:!1,children:!lt&&i.jsx(Os.div,{initial:"initial",animate:"animate",exit:"exit",variants:ef,className:"overflow-hidden",children:i.jsx("div",{children:ye.projects.map(J)})},`content-${ye.groupId}`)})]},ye.groupId)})]}):Lt.length>0&&Fe.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{children:[i.jsx(Ja,{section:"pinned-projects",children:r("Pinned projects")}),i.jsx("div",{children:Lt.map(J)})]}),i.jsx("div",{children:Fe.map(J)})]}):Ft.map(J)})()})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[window.electronAPI.remote?.linkStatus?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"min-w-0 flex-1"}),i.jsx(NC,{})]}):i.jsx(R_,{}),Qt>0&&i.jsx("button",{type:"button","data-slot":"archived-button",onClick:Rn,className:eo,title:`${r("Archived")} (${Qt})`,children:i.jsx(Oi,{className:"h-4 w-4"})}),window.electronAPI.remote&&i.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:eo,title:r("Compact view"),children:i.jsx(B0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"settings-button",onClick:()=>window.electronAPI.window.openSettings(),className:eo,title:r("Settings"),"aria-label":r("Settings"),children:i.jsx(mi,{className:"h-4 w-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-enso":"search-button",onClick:s,className:eo,title:_?`${r("Search anything")} (${_})`:r("Search anything"),children:i.jsx(si,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"sidebar-toggle",onClick:n,className:eo,title:r("Collapse sidebar"),children:i.jsx(Kx,{className:"h-4 w-4"})})]})]})]}),i.jsx(xn,{open:Vt,onOpenChange:Bt,children:i.jsxs(vn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(bn,{children:[i.jsxs(wn,{className:"flex items-baseline gap-2",children:[r("Archived"),i.jsx("span",{className:"font-sans text-sm text-muted-foreground tabular-nums",children:Qt})]}),i.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[i.jsxs(uh,{"data-size":"sm",children:[i.jsx(hh,{children:i.jsx(si,{})}),i.jsx(ph,{value:Rt,placeholder:r("Search conversations..."),onChange:J=>se(J.target.value)})]}),i.jsx(MC,{open:qt==="*",onOpenChange:J=>rn(J?"*":null),idsForDays:J=>V0(A,S,J,Date.now()),onPick:(J,ye)=>j({kind:"archived",days:J,conversationIds:ye}),className:"h-8 w-8 rounded-md opacity-100 hover:bg-muted"})]})]}),i.jsxs(An,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[nn.length===0&&i.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:Rt.trim()?r("No matching conversations"):r("No conversations")}),nn.map(J=>{const ye=l.find(vt=>vt.id===J.projectId),lt=ye?Ns(ye):r("Other");return i.jsxs("div",{children:[i.jsxs("div",{className:"group flex items-center gap-2 rounded-md pr-0.5 pl-2",children:[J.projectArchived&&i.jsx(N6,{className:"size-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate py-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:lt}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:J.ids.length}),J.projectArchived?i.jsx("button",{type:"button",onClick:()=>Ze(J.projectId),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",title:r("Unarchive project"),children:i.jsx(Kl,{className:"h-3.5 w-3.5"})}):i.jsx(MC,{open:qt===J.projectId,onOpenChange:vt=>rn(vt?J.projectId:null),idsForDays:vt=>V0(A,S,vt,Date.now(),J.projectId),onPick:(vt,Pt)=>j({kind:"archived",days:vt,conversationIds:Pt,projectName:lt})})]}),i.jsx("div",{className:"flex flex-col",children:J.ids.map(vt=>i.jsx(Os.div,{layout:"position",transition:ra,children:i.jsx(Xa,{id:vt,conversation:S[vt],active:T===vt,locale:a,nowTick:Ht,worktreeStatus:S[vt].worktree?V[vt]:void 0,isolated:!!S[vt].worktree,menuZIndex:yn.DROPDOWN_IN_MODAL,onSelect:Pt=>{O(Pt),Bt(!1)},onTogglePin:R,onToggleArchive:Pt=>{Gn(Pt)},onCleanupWorktree:Pt=>{Fn(Pt)},onMoveToWorktree:Pt=>{Dr(Pt)},onRemove:Pt=>{F(Pt)}})},vt))})]},J.projectId)})]})]})}),i.jsx(Gne,{open:He,onOpenChange:nt,onAdd:Jt,groups:h,defaultGroupId:Gt}),i.jsx(Kne,{open:K!==null,group:K?.mode==="edit"?h.find(J=>J.id===K.id)??null:null,projects:G.filter(J=>!ae.includes(J.id)),onOpenChange:J=>{J||pe(null)},onSave:J=>{if(K?.mode==="edit"){f(K.id,J);return}const ye=p(J);for(const lt of J.projectIds??[])v(lt,ye.id)},onDelete:K?.mode==="edit"?()=>{const J=K.id;g(J),bt===J&&B(In)}:void 0}),i.jsx(Yne,{open:Ie!==null,project:l.find(J=>J.id===Ie)??null,onOpenChange:J=>{J||Ae(null)}}),i.jsx(qne,{project:E,onClose:()=>L(null)}),i.jsx(gs,{open:sn!==null,onOpenChange:J=>{J||jn(null)},title:sn?.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:c0(sn?.status)}),confirmLabel:sn?.kind==="archive"?r("Archive"):r("Clean up"),onConfirm:()=>{sn&&Wn(sn.id,sn.kind==="archive")}}),i.jsx(gs,{open:_n!==null,onOpenChange:J=>{J||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(!_n)return;const J=_n;Nn(null),Dr(J,!0)}}),i.jsx(gs,{open:M!==null,onOpenChange:J=>{J||j(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:Ns(M.project),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 J of M.conversationIds)z(J);k(M.project.id)}else if(M.kind==="archived")for(const J of M.conversationIds)z(J);else z(M.id)}}),qs.createPortal(i.jsx(IG,{dropAnimation:null,children:it?.type==="project"?i.jsx(xse,{projectId:it.projectId,name:gse(l,it.projectId,it.name),folded:Y[it.projectId]===!0,revealedExtra:he[it.projectId]??0,width:e}):(it?.type==="chat"||it?.type==="workspace-file")&&i.jsxs("div",{className:"flex w-56 items-center gap-2 rounded-lg border bg-background/95 px-3 py-1.5 text-sm shadow-float",children:[it.type==="workspace-file"?i.jsx(jo,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):i.jsx(hi,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:it.type==="workspace-file"?it.name:it.title.split(`
98
- `)[0].trim()||r("New conversation")})]})}),document.body)]})}function mse({groupId:e,name:t,emoji:n,color:s,count:o,folded:r,sortable:a,onToggle:l,onEdit:c}){const d=e===ps?Lv:vE(e),u=Sc({id:d}),h=Jh({id:d,data:{type:"project-group",groupId:e},disabled:!a}),p=f=>{u.setNodeRef(f),h.setNodeRef(f)};return i.jsxs("div",{ref:p,"data-enso":"section-header","data-section":"group",style:{transform:Bi.Transform.toString(h.transform),transition:h.transition,opacity:h.isDragging?.4:void 0},className:W("group relative flex w-full select-none items-center rounded-md pt-3.5 pr-2.5 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground transition-colors hover:text-foreground",u.isOver&&"bg-foreground/5 text-foreground",a&&"cursor-grab"),...a?h.listeners:{},...a?h.attributes:{},children:[i.jsxs("button",{type:"button",onClick:l,onPointerDown:f=>f.stopPropagation(),className:"flex min-w-0 flex-1 items-center gap-1.5",children:[i.jsx("span",{className:"min-w-0 truncate text-left",children:t}),n&&i.jsx("span",{className:"shrink-0 text-sm leading-none",children:n}),s&&i.jsx("span",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:s}}),i.jsx(un,{"data-enso":"tree-chevron","data-expanded":!r||void 0,className:W("size-3 shrink-0 transition-[opacity,transform] duration-150",!r&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:W("ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",c&&"transition-opacity group-hover:opacity-0"),children:o})]}),c&&i.jsx("button",{type:"button",onClick:f=>{f.stopPropagation(),c()},onPointerDown:f=>f.stopPropagation(),className:"absolute right-1.5 bottom-0.5 flex size-5 items-center justify-center rounded-[5px] opacity-0 transition-opacity hover:bg-foreground/5 hover:text-foreground group-hover:opacity-100 [@media(hover:none)]:opacity-100",children:i.jsx($s,{className:"size-3.25"})})]})}function gse(e,t,n){const s=e.find(o=>o.id===t);return s?Ns(s):n}function xse({projectId:e,name:t,folded:n,revealedExtra:s,width:o}){const{t:r}=ne(),a=ie(h=>Ah(h.conversations)),l=ie(h=>h.order),c=Qr(l,a,e),d=n?[]:c.slice(0,Qh(c.length,s)),u=Math.max(0,c.length-d.length);return i.jsxs("div",{className:"pointer-events-none rounded-lg border bg-background/95 py-0.5 shadow-float",style:{width:o??224},children:[i.jsxs("div",{className:"flex h-8 items-center gap-2 px-2 text-[0.9286rem] font-medium",children:[i.jsx(KE,{folded:n}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:t})]}),!n&&i.jsxs("div",{className:"flex flex-col",children:[d.map(h=>{const p=a[h];return p?i.jsxs("div",{className:"flex h-8 items-center gap-2 px-2 text-[0.9286rem] text-foreground/88",children:[i.jsx(qE,{conversation:p}),i.jsx("span",{className:"min-w-0 truncate",children:p.title||r("New conversation")})]},h):null}),c.length>Zh&&i.jsxs("div",{className:"flex items-center gap-1",children:[u>0&&i.jsx("div",{className:"flex-1 rounded-lg py-1 text-center text-xs text-muted-foreground",children:r("Show {{n}} more",{n:u})}),s>0&&i.jsx("div",{className:"flex-1 rounded-lg py-1 text-center text-xs text-muted-foreground",children:r("Collapse")})]}),c.length===0&&i.jsx("p",{className:"py-1.5 pl-8 text-xs text-muted-foreground",children:r("No conversations yet")})]})]})}function vse({project:e,activitySorted:t=!1,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Jh({id:xE(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:Bi.Transform.toString(o),transition:r,opacity:l?.4:void 0},handleProps:a??{}})}function MC({open:e,onOpenChange:t,idsForDays:n,onPick:s,className:o}){const{t:r}=ne();return i.jsxs($i,{open:e,onOpenChange:t,children:[i.jsx(Wi,{className:W("flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive",e&&"opacity-100",o),title:r("Clean up archived"),"aria-label":r("Clean up archived"),children:i.jsx(sx,{className:"h-3.5 w-3.5"})}),i.jsxs(Ui,{align:"end",className:"min-w-40",zIndex:yn.DROPDOWN_IN_MODAL,children:[fse.map(a=>{const l=n(a);return i.jsx(mn,{variant:"destructive",disabled:l.length===0,onClick:()=>s(a,l),children:r("Older than {{days}} days",{days:a})},a)}),(()=>{const a=n(0);return i.jsx(mn,{variant:"destructive",disabled:a.length===0,onClick:()=>s(0,a),children:r("Delete all archived")})})()]})]})}function bse({id:e,conversation:t,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Jh({id:bE(e),data:{type:"chat",conversationId:e,title:t.title,sessionFile:t.sessionFile,pinned:t.pinned===!0}});return i.jsx("div",{ref:s,...a,style:{transform:Bi.Transform.toString(o),transition:r,opacity:l?.4:void 0},children:n})}function RC({id:e,conversation:t,children:n,dragId:s}){const{setNodeRef:o,listeners:r,isDragging:a}=px({id:s??Fee(e),data:{type:"chat",conversationId:e,title:t.title,sessionFile:t.sessionFile,pinned:t.pinned===!0}});return i.jsx("div",{ref:o,...r,style:{opacity:a?.4:void 0},children:n})}function LC({children:e,...t}){const{setNodeRef:n,isOver:s,active:o}=Sc({id:gE}),r=o?.data.current?.type==="chat";return i.jsx("div",{ref:n,className:W("rounded-lg",s&&r&&"bg-brand/8 ring-1 ring-brand/40"),...t,children:e})}function Xa({id:e,conversation:t,active:n,locale:s,nowTick:o,hoverTitle:r,subtitle:a,isolated:l,worktreeStatus:c,switchHint:d,menuZIndex:u,onSelect:h,onTogglePin:p,onToggleArchive:f,onCleanupWorktree:g,onMoveToWorktree:x,onRemove:v}){const{t:y}=ne(),b=we(V=>V.projects.some(Y=>Y.id===t.projectId&&Y.kind!=="ssh")),w=we(V=>V.projects.some(Y=>Y.id===t.projectId&&Y.kind==="scratch")),[C,_]=m.useState(!1),N=ie(V=>V.conversations[e]?.worktree),k=ie(V=>!!V.conversations[e]?.workspaceMigrating),S=ie(V=>V.conversations[e]?.worktreeMissing),[A,T]=m.useState(!1),[I,P]=m.useState(null),D=A||k||t.spawning||t.status==="running"||t.reloading===!0,O=async()=>{if(!D){T(!0);try{await ie.getState().newConversation(t.projectId,{worktreeFromConversationId:e})||ze({type:"error",title:y("Failed to create conversation")})}catch(V){ze({type:"error",title:y("Failed to create conversation"),description:String(V)})}finally{T(!1)}}},z=t.pinned===!0,R=t.archived===!0,$=z?Tu:hi,X=t.title||y("New conversation"),H=t.forkedFromConversationId?ie.getState().conversations[t.forkedFromConversationId]?.title:void 0,te=i.jsxs("div",{"data-slot":"conversation-row","data-pinned":z?"true":"false","data-enso":"session-row","data-active":n||void 0,"data-status":Vv(t),"data-unread":t.unread||void 0,className:W("group flex h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-[0.9286rem] transition-colors",n?"bg-foreground/[0.075] text-foreground dark:bg-foreground/10":"text-foreground/88 hover:bg-foreground/5 hover:text-foreground"),onClick:()=>{C||h(e)},onDoubleClick:V=>{V.preventDefault(),V.stopPropagation(),_(!0)},onKeyDown:V=>{V.key==="Enter"&&!C&&h(e)},role:"button",tabIndex:0,title:r,children:[i.jsx(qE,{conversation:t}),i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[H&&i.jsx("span",{className:"max-w-1/3 truncate text-[0.7857rem] text-subtle-foreground",children:y("Branched from {{title}}",{title:H})}),C?i.jsx(SE,{title:X,onCommit:V=>{ie.getState().renameConversation(e,V),_(!1)},onCancel:()=>_(!1)}):i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[X,a&&i.jsx("span",{className:"ml-1.5 text-[0.7857rem] text-subtle-foreground",children:a})]})]}),l&&N&&i.jsx(xne,{worktree:N,status:c}),i.jsx(pse,{conversationId:e}),!C&&i.jsx(wse,{pending:t.titleSummaryPending,error:t.titleSummaryError,onRetry:()=>ie.getState().retryTitleSummary(e)}),!C&&(d?i.jsx("span",{className:"shrink-0 text-[0.7857rem] text-subtle-foreground tabular-nums",children:d}):i.jsxs(i.Fragment,{children:[z&&!R&&i.jsx(hi,{className:"h-3 w-3 shrink-0 text-subtle-foreground group-hover:hidden","aria-hidden":!0}),i.jsx("span",{className:"shrink-0 text-[0.7857rem] text-subtle-foreground tabular-nums group-hover:hidden",children:$o(t.lastActiveAt??t.createdAt,s,o)}),!R&&i.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:y(z?"Unpin":"Pin"),children:i.jsx($,{className:"h-3.5 w-3.5"})}),i.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:y(R?"Unarchive":"Archive"),children:R?i.jsx(Kl,{className:"h-3.5 w-3.5"}):i.jsx(Oi,{className:"h-3.5 w-3.5"})}),R&&i.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:y("Delete"),children:i.jsx(Vs,{className:"h-3.5 w-3.5"})})]}))]})]});return i.jsxs(i.Fragment,{children:[i.jsxs(go,{children:[i.jsx(xo,{render:te}),i.jsxs(vo,{className:"min-w-36",zIndex:u,children:[i.jsxs($t,{onClick:()=>_(!0),children:[i.jsx($s,{}),y("Rename")]}),i.jsxs($t,{disabled:t.reloading===!0||t.spawning,onClick:()=>{CE(e,y)},children:[i.jsx(Ko,{className:t.reloading?"animate-spin":void 0}),y("Reload conversation")]}),i.jsxs($t,{disabled:D,onClick:()=>{ute(e,y)},children:[i.jsx(da,{}),y("Restart conversation (reload settings)")]}),b&&i.jsxs($t,{disabled:k||S||c?.exists===!1,onClick:()=>{Bv({projectId:t.projectId,conversationId:e},y)},children:[i.jsx(oi,{}),y(Hv(window.electronAPI.env.platform))]}),!R&&i.jsxs($t,{onClick:()=>p(e),children:[i.jsx($,{}),y(z?"Unpin":"Pin")]}),i.jsxs($t,{onClick:()=>f(e),children:[R?i.jsx(Kl,{}):i.jsx(Oi,{}),y(R?"Unarchive":"Archive")]}),N&&i.jsxs(i.Fragment,{children:[i.jsxs($t,{disabled:D||S||c?.exists===!1,onClick:()=>{O()},children:[A?i.jsx(Xt,{className:"animate-spin"}):i.jsx(Ho,{}),y("New conversation in this worktree")]}),i.jsxs($t,{disabled:D||S||c?.exists===!1,onClick:()=>P({conversationId:e,worktree:N}),children:[i.jsx($s,{}),y("Rename worktree")]})]}),!R&&(l?g&&i.jsxs($t,{disabled:D,onClick:()=>g(e),children:[i.jsx(sx,{}),y("Clean up worktree")]}):x&&b&&!w&&i.jsxs($t,{disabled:D,onClick:()=>x(e),children:[i.jsx(A6,{}),y("Move to worktree")]})),i.jsx(mh,{}),i.jsxs($t,{variant:"destructive",onClick:()=>v(e),children:[i.jsx(Vs,{}),y("Delete")]})]})]}),i.jsx(ME,{entity:I,onClose:()=>P(null)})]})}function wse({pending:e,error:t,onRetry:n}){const{t:s}=ne();return e?i.jsxs(Vf,{children:[i.jsx($f,{render:i.jsx("span",{role:"status",className:"shrink-0 text-muted-foreground/60","aria-label":s("Summarizing title")}),children:i.jsx(Xt,{className:"h-3 w-3 animate-spin"})}),i.jsx(Wf,{side:"right",children:s("Summarizing title")})]}):t?i.jsxs(Vf,{children:[i.jsx($f,{render:i.jsx("button",{type:"button","aria-label":s("Title summary failed"),className:"shrink-0 rounded p-0.5 text-destructive hover:text-destructive/80",onClick:o=>{o.stopPropagation(),n()}}),children:i.jsx(yr,{className:"h-3 w-3"})}),i.jsxs(Wf,{side:"right",className:"max-w-72",children:[i.jsx("p",{className:"font-medium",children:s("Title summary failed")}),i.jsx("p",{className:"mt-0.5 break-all text-muted-foreground",children:t}),i.jsx("p",{className:"mt-1 text-muted-foreground/70",children:s("Click to retry")})]})]}):null}function OC(e,t){const n=e.find(s=>s.id===t);return n?Ns(n):void 0}function yf({emoji:e,color:t}){return e?i.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-sm leading-none",children:e}):i.jsx(E6,{style:t?{color:t}:void 0})}function Ku(e,t="context"){return e.map(n=>n.kind==="separator"?t==="menu"?i.jsx(ja,{},n.key):i.jsx(mh,{},n.key):n.kind==="submenu"?t==="menu"?i.jsxs(qj,{children:[i.jsxs(Yj,{children:[n.icon,n.label]}),i.jsx(Xj,{className:"min-w-40",children:Ku(n.items,"menu")})]},n.key):i.jsxs(c_,{children:[i.jsxs(d_,{children:[n.icon,n.label]}),i.jsx(u_,{className:"min-w-40",children:Ku(n.items)})]},n.key):t==="menu"?i.jsxs(mn,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key):i.jsxs($t,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key))}function yse({actions:e}){const{t}=ne();return i.jsxs($i,{children:[i.jsx(Wi,{"data-enso":"row-menu","aria-label":t("More actions"),className:"shrink-0 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted hover:text-foreground focus-visible:opacity-100 data-popup-open:bg-muted data-popup-open:text-foreground data-popup-open:opacity-100",title:t("More actions"),onPointerDown:n=>n.stopPropagation(),children:i.jsx(Dh,{className:"h-3.5 w-3.5"})}),i.jsx(Ui,{align:"end",className:"min-w-40",children:Ku(e,"menu")})]})}function Ja({section:e,children:t,actions:n}){return i.jsxs("div",{"data-enso":"section-header","data-section":e,className:"group flex items-center gap-1 pt-3.5 pr-1 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:t}),n]})}function KE({folded:e}){return i.jsx("span",{"data-enso":"tree-chevron","data-expanded":!e||void 0,className:"flex size-4 shrink-0 items-center justify-center text-subtle-foreground",children:i.jsx(un,{className:W("size-3.5 transition-transform duration-150",!e&&"rotate-90")})})}function qE({conversation:e}){const t=(e.pendingApprovals?.length??0)>0?"attention":eh({status:e.status,spawning:e.spawning,unread:e.unread,pendingAskCount:e.pendingAsks?.length??0,hasRunningChild:e.hasRunningChild});return i.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:t!=="idle"&&i.jsx(Tc,{tone:t,size:"sm","data-enso":"session-status","data-status":Vv(e)})})}const Sse=15e3,zC={"host-dirs":"host-dirs-result","project-add":"project-add-result"};function Sf(e,t){const n=t.type,s=crypto.randomUUID();return new Promise(o=>{const r=(c,d)=>{clearTimeout(l),a(),o(d??{type:zC[n],requestId:s,error:c})},a=window.electronAPI.nodes.onMessage(c=>{if(c.nodeId!==e)return;const d=c.payload;d.type==="command-rejected"&&d.command===n?r(d.error):d.type===zC[n]&&d.requestId===s&&r(void 0,d)}),l=setTimeout(()=>r("timeout"),Sse);window.electronAPI.nodes.send(e,{...t,requestId:s}).then(c=>{c.ok||r(c.error??"offline")})})}function Cse({nodeId:e,open:t,onOpenChange:n}){const{t:s}=ne(),[o,r]=m.useState(""),[a,l]=m.useState(!0),[c,d]=m.useState(!1),[u,h]=m.useState("");m.useEffect(()=>{t&&(r(""),l(!0),d(!1),h(""))},[t]);const p=m.useCallback(b=>s(b==="timeout"?"The remote desktop did not respond. It may need to be updated.":b),[s]),f=m.useCallback(b=>b.error!==void 0||b.path===void 0?{error:p(b.error??"Failed to list remote directory.")}:{path:b.path,parent:b.parent??null,dirs:b.dirs??[]},[p]),g=m.useCallback(b=>Sf(e,{type:"host-dirs",...b?{path:b}:{}}).then(f),[e,f]),x=m.useCallback((b,w)=>Sf(e,{type:"host-dirs",path:b,create:w}).then(f),[e,f]),v=o.trim(),y=async b=>{if(b.preventDefault(),!v||c)return;d(!0),h("");const w=await Sf(e,{type:"project-add",path:v});if(d(!1),w.error!==void 0){h(p(w.error));return}n(!1)};return i.jsx(xn,{open:t,onOpenChange:n,children:i.jsx(vn,{className:"max-w-lg",children:i.jsxs("form",{onSubmit:b=>{y(b)},className:"flex flex-col",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:s("Add project")}),i.jsx(Rs,{children:s("Add a directory on the remote computer as a project.")})]}),i.jsxs(An,{className:"space-y-4",children:[i.jsxs(Gs,{className:"w-full",children:[i.jsx(Fs,{children:s("Working directory")}),i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx(Zt,{value:o,onChange:b=>r(b.target.value),placeholder:"/home/user/project",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,className:"min-w-0 flex-1"}),i.jsx(me,{type:"button",variant:"outline",onClick:()=>l(b=>!b),children:s("Browse")})]}),a&&i.jsx(vg,{list:g,create:x,initialPath:v||void 0,onSelect:b=>{r(b),l(!1)},onClose:()=>l(!1)})]}),u&&i.jsx("p",{className:"text-destructive text-xs",children:u})]}),i.jsxs(ls,{children:[i.jsx(me,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsx(me,{type:"submit",size:"sm",disabled:!v||c,children:s("Add")})]})]})})})}function kse(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 Cf={exports:{}};const jse={},_se=Object.freeze(Object.defineProperty({__proto__:null,default:jse},Symbol.toStringTag,{value:"Module"})),Nse=cO(_se);var GC;function Tse(){return GC||(GC=1,(function(e){(function(t){var n=function(E){var L,M=new Float64Array(16);if(E)for(L=0;L<E.length;L++)M[L]=E[L];return M},s=function(){throw new Error("no PRNG")},o=new Uint8Array(16),r=new Uint8Array(32);r[0]=9;var a=n(),l=n([1]),c=n([56129,1]),d=n([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),u=n([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),h=n([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),p=n([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=n([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function g(E,L,M,j){E[L]=M>>24&255,E[L+1]=M>>16&255,E[L+2]=M>>8&255,E[L+3]=M&255,E[L+4]=j>>24&255,E[L+5]=j>>16&255,E[L+6]=j>>8&255,E[L+7]=j&255}function x(E,L,M,j,F){var he,xe=0;for(he=0;he<F;he++)xe|=E[L+he]^M[j+he];return(1&xe-1>>>8)-1}function v(E,L,M,j){return x(E,L,M,j,16)}function y(E,L,M,j){return x(E,L,M,j,32)}function b(E,L,M,j){for(var F=j[0]&255|(j[1]&255)<<8|(j[2]&255)<<16|(j[3]&255)<<24,he=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,xe=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,Ee=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,Ke=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,ht=j[4]&255|(j[5]&255)<<8|(j[6]&255)<<16|(j[7]&255)<<24,ot=L[0]&255|(L[1]&255)<<8|(L[2]&255)<<16|(L[3]&255)<<24,Ht=L[4]&255|(L[5]&255)<<8|(L[6]&255)<<16|(L[7]&255)<<24,ut=L[8]&255|(L[9]&255)<<8|(L[10]&255)<<16|(L[11]&255)<<24,Tt=L[12]&255|(L[13]&255)<<8|(L[14]&255)<<16|(L[15]&255)<<24,yt=j[8]&255|(j[9]&255)<<8|(j[10]&255)<<16|(j[11]&255)<<24,Ot=M[16]&255|(M[17]&255)<<8|(M[18]&255)<<16|(M[19]&255)<<24,jt=M[20]&255|(M[21]&255)<<8|(M[22]&255)<<16|(M[23]&255)<<24,It=M[24]&255|(M[25]&255)<<8|(M[26]&255)<<16|(M[27]&255)<<24,le=M[28]&255|(M[29]&255)<<8|(M[30]&255)<<16|(M[31]&255)<<24,Pe=j[12]&255|(j[13]&255)<<8|(j[14]&255)<<16|(j[15]&255)<<24,Ge=F,Ve=he,Ye=xe,at=Ee,st=Ke,Xe=ht,ke=ot,je=Ht,Be=ut,Me=Tt,Le=yt,qe=Ot,Ct=jt,Vt=It,Bt=le,Rt=Pe,se,qt=0;qt<20;qt+=2)se=Ge+Ct|0,st^=se<<7|se>>>25,se=st+Ge|0,Be^=se<<9|se>>>23,se=Be+st|0,Ct^=se<<13|se>>>19,se=Ct+Be|0,Ge^=se<<18|se>>>14,se=Xe+Ve|0,Me^=se<<7|se>>>25,se=Me+Xe|0,Vt^=se<<9|se>>>23,se=Vt+Me|0,Ve^=se<<13|se>>>19,se=Ve+Vt|0,Xe^=se<<18|se>>>14,se=Le+ke|0,Bt^=se<<7|se>>>25,se=Bt+Le|0,Ye^=se<<9|se>>>23,se=Ye+Bt|0,ke^=se<<13|se>>>19,se=ke+Ye|0,Le^=se<<18|se>>>14,se=Rt+qe|0,at^=se<<7|se>>>25,se=at+Rt|0,je^=se<<9|se>>>23,se=je+at|0,qe^=se<<13|se>>>19,se=qe+je|0,Rt^=se<<18|se>>>14,se=Ge+at|0,Ve^=se<<7|se>>>25,se=Ve+Ge|0,Ye^=se<<9|se>>>23,se=Ye+Ve|0,at^=se<<13|se>>>19,se=at+Ye|0,Ge^=se<<18|se>>>14,se=Xe+st|0,ke^=se<<7|se>>>25,se=ke+Xe|0,je^=se<<9|se>>>23,se=je+ke|0,st^=se<<13|se>>>19,se=st+je|0,Xe^=se<<18|se>>>14,se=Le+Me|0,qe^=se<<7|se>>>25,se=qe+Le|0,Be^=se<<9|se>>>23,se=Be+qe|0,Me^=se<<13|se>>>19,se=Me+Be|0,Le^=se<<18|se>>>14,se=Rt+Bt|0,Ct^=se<<7|se>>>25,se=Ct+Rt|0,Vt^=se<<9|se>>>23,se=Vt+Ct|0,Bt^=se<<13|se>>>19,se=Bt+Vt|0,Rt^=se<<18|se>>>14;Ge=Ge+F|0,Ve=Ve+he|0,Ye=Ye+xe|0,at=at+Ee|0,st=st+Ke|0,Xe=Xe+ht|0,ke=ke+ot|0,je=je+Ht|0,Be=Be+ut|0,Me=Me+Tt|0,Le=Le+yt|0,qe=qe+Ot|0,Ct=Ct+jt|0,Vt=Vt+It|0,Bt=Bt+le|0,Rt=Rt+Pe|0,E[0]=Ge>>>0&255,E[1]=Ge>>>8&255,E[2]=Ge>>>16&255,E[3]=Ge>>>24&255,E[4]=Ve>>>0&255,E[5]=Ve>>>8&255,E[6]=Ve>>>16&255,E[7]=Ve>>>24&255,E[8]=Ye>>>0&255,E[9]=Ye>>>8&255,E[10]=Ye>>>16&255,E[11]=Ye>>>24&255,E[12]=at>>>0&255,E[13]=at>>>8&255,E[14]=at>>>16&255,E[15]=at>>>24&255,E[16]=st>>>0&255,E[17]=st>>>8&255,E[18]=st>>>16&255,E[19]=st>>>24&255,E[20]=Xe>>>0&255,E[21]=Xe>>>8&255,E[22]=Xe>>>16&255,E[23]=Xe>>>24&255,E[24]=ke>>>0&255,E[25]=ke>>>8&255,E[26]=ke>>>16&255,E[27]=ke>>>24&255,E[28]=je>>>0&255,E[29]=je>>>8&255,E[30]=je>>>16&255,E[31]=je>>>24&255,E[32]=Be>>>0&255,E[33]=Be>>>8&255,E[34]=Be>>>16&255,E[35]=Be>>>24&255,E[36]=Me>>>0&255,E[37]=Me>>>8&255,E[38]=Me>>>16&255,E[39]=Me>>>24&255,E[40]=Le>>>0&255,E[41]=Le>>>8&255,E[42]=Le>>>16&255,E[43]=Le>>>24&255,E[44]=qe>>>0&255,E[45]=qe>>>8&255,E[46]=qe>>>16&255,E[47]=qe>>>24&255,E[48]=Ct>>>0&255,E[49]=Ct>>>8&255,E[50]=Ct>>>16&255,E[51]=Ct>>>24&255,E[52]=Vt>>>0&255,E[53]=Vt>>>8&255,E[54]=Vt>>>16&255,E[55]=Vt>>>24&255,E[56]=Bt>>>0&255,E[57]=Bt>>>8&255,E[58]=Bt>>>16&255,E[59]=Bt>>>24&255,E[60]=Rt>>>0&255,E[61]=Rt>>>8&255,E[62]=Rt>>>16&255,E[63]=Rt>>>24&255}function w(E,L,M,j){for(var F=j[0]&255|(j[1]&255)<<8|(j[2]&255)<<16|(j[3]&255)<<24,he=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,xe=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,Ee=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,Ke=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,ht=j[4]&255|(j[5]&255)<<8|(j[6]&255)<<16|(j[7]&255)<<24,ot=L[0]&255|(L[1]&255)<<8|(L[2]&255)<<16|(L[3]&255)<<24,Ht=L[4]&255|(L[5]&255)<<8|(L[6]&255)<<16|(L[7]&255)<<24,ut=L[8]&255|(L[9]&255)<<8|(L[10]&255)<<16|(L[11]&255)<<24,Tt=L[12]&255|(L[13]&255)<<8|(L[14]&255)<<16|(L[15]&255)<<24,yt=j[8]&255|(j[9]&255)<<8|(j[10]&255)<<16|(j[11]&255)<<24,Ot=M[16]&255|(M[17]&255)<<8|(M[18]&255)<<16|(M[19]&255)<<24,jt=M[20]&255|(M[21]&255)<<8|(M[22]&255)<<16|(M[23]&255)<<24,It=M[24]&255|(M[25]&255)<<8|(M[26]&255)<<16|(M[27]&255)<<24,le=M[28]&255|(M[29]&255)<<8|(M[30]&255)<<16|(M[31]&255)<<24,Pe=j[12]&255|(j[13]&255)<<8|(j[14]&255)<<16|(j[15]&255)<<24,Ge=F,Ve=he,Ye=xe,at=Ee,st=Ke,Xe=ht,ke=ot,je=Ht,Be=ut,Me=Tt,Le=yt,qe=Ot,Ct=jt,Vt=It,Bt=le,Rt=Pe,se,qt=0;qt<20;qt+=2)se=Ge+Ct|0,st^=se<<7|se>>>25,se=st+Ge|0,Be^=se<<9|se>>>23,se=Be+st|0,Ct^=se<<13|se>>>19,se=Ct+Be|0,Ge^=se<<18|se>>>14,se=Xe+Ve|0,Me^=se<<7|se>>>25,se=Me+Xe|0,Vt^=se<<9|se>>>23,se=Vt+Me|0,Ve^=se<<13|se>>>19,se=Ve+Vt|0,Xe^=se<<18|se>>>14,se=Le+ke|0,Bt^=se<<7|se>>>25,se=Bt+Le|0,Ye^=se<<9|se>>>23,se=Ye+Bt|0,ke^=se<<13|se>>>19,se=ke+Ye|0,Le^=se<<18|se>>>14,se=Rt+qe|0,at^=se<<7|se>>>25,se=at+Rt|0,je^=se<<9|se>>>23,se=je+at|0,qe^=se<<13|se>>>19,se=qe+je|0,Rt^=se<<18|se>>>14,se=Ge+at|0,Ve^=se<<7|se>>>25,se=Ve+Ge|0,Ye^=se<<9|se>>>23,se=Ye+Ve|0,at^=se<<13|se>>>19,se=at+Ye|0,Ge^=se<<18|se>>>14,se=Xe+st|0,ke^=se<<7|se>>>25,se=ke+Xe|0,je^=se<<9|se>>>23,se=je+ke|0,st^=se<<13|se>>>19,se=st+je|0,Xe^=se<<18|se>>>14,se=Le+Me|0,qe^=se<<7|se>>>25,se=qe+Le|0,Be^=se<<9|se>>>23,se=Be+qe|0,Me^=se<<13|se>>>19,se=Me+Be|0,Le^=se<<18|se>>>14,se=Rt+Bt|0,Ct^=se<<7|se>>>25,se=Ct+Rt|0,Vt^=se<<9|se>>>23,se=Vt+Ct|0,Bt^=se<<13|se>>>19,se=Bt+Vt|0,Rt^=se<<18|se>>>14;E[0]=Ge>>>0&255,E[1]=Ge>>>8&255,E[2]=Ge>>>16&255,E[3]=Ge>>>24&255,E[4]=Xe>>>0&255,E[5]=Xe>>>8&255,E[6]=Xe>>>16&255,E[7]=Xe>>>24&255,E[8]=Le>>>0&255,E[9]=Le>>>8&255,E[10]=Le>>>16&255,E[11]=Le>>>24&255,E[12]=Rt>>>0&255,E[13]=Rt>>>8&255,E[14]=Rt>>>16&255,E[15]=Rt>>>24&255,E[16]=ke>>>0&255,E[17]=ke>>>8&255,E[18]=ke>>>16&255,E[19]=ke>>>24&255,E[20]=je>>>0&255,E[21]=je>>>8&255,E[22]=je>>>16&255,E[23]=je>>>24&255,E[24]=Be>>>0&255,E[25]=Be>>>8&255,E[26]=Be>>>16&255,E[27]=Be>>>24&255,E[28]=Me>>>0&255,E[29]=Me>>>8&255,E[30]=Me>>>16&255,E[31]=Me>>>24&255}function C(E,L,M,j){b(E,L,M,j)}function _(E,L,M,j){w(E,L,M,j)}var N=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function k(E,L,M,j,F,he,xe){var Ee=new Uint8Array(16),Ke=new Uint8Array(64),ht,ot;for(ot=0;ot<16;ot++)Ee[ot]=0;for(ot=0;ot<8;ot++)Ee[ot]=he[ot];for(;F>=64;){for(C(Ke,Ee,xe,N),ot=0;ot<64;ot++)E[L+ot]=M[j+ot]^Ke[ot];for(ht=1,ot=8;ot<16;ot++)ht=ht+(Ee[ot]&255)|0,Ee[ot]=ht&255,ht>>>=8;F-=64,L+=64,j+=64}if(F>0)for(C(Ke,Ee,xe,N),ot=0;ot<F;ot++)E[L+ot]=M[j+ot]^Ke[ot];return 0}function S(E,L,M,j,F){var he=new Uint8Array(16),xe=new Uint8Array(64),Ee,Ke;for(Ke=0;Ke<16;Ke++)he[Ke]=0;for(Ke=0;Ke<8;Ke++)he[Ke]=j[Ke];for(;M>=64;){for(C(xe,he,F,N),Ke=0;Ke<64;Ke++)E[L+Ke]=xe[Ke];for(Ee=1,Ke=8;Ke<16;Ke++)Ee=Ee+(he[Ke]&255)|0,he[Ke]=Ee&255,Ee>>>=8;M-=64,L+=64}if(M>0)for(C(xe,he,F,N),Ke=0;Ke<M;Ke++)E[L+Ke]=xe[Ke];return 0}function A(E,L,M,j,F){var he=new Uint8Array(32);_(he,j,F,N);for(var xe=new Uint8Array(8),Ee=0;Ee<8;Ee++)xe[Ee]=j[Ee+16];return S(E,L,M,xe,he)}function T(E,L,M,j,F,he,xe){var Ee=new Uint8Array(32);_(Ee,he,xe,N);for(var Ke=new Uint8Array(8),ht=0;ht<8;ht++)Ke[ht]=he[ht+16];return k(E,L,M,j,F,Ke,Ee)}var I=function(E){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var L,M,j,F,he,xe,Ee,Ke;L=E[0]&255|(E[1]&255)<<8,this.r[0]=L&8191,M=E[2]&255|(E[3]&255)<<8,this.r[1]=(L>>>13|M<<3)&8191,j=E[4]&255|(E[5]&255)<<8,this.r[2]=(M>>>10|j<<6)&7939,F=E[6]&255|(E[7]&255)<<8,this.r[3]=(j>>>7|F<<9)&8191,he=E[8]&255|(E[9]&255)<<8,this.r[4]=(F>>>4|he<<12)&255,this.r[5]=he>>>1&8190,xe=E[10]&255|(E[11]&255)<<8,this.r[6]=(he>>>14|xe<<2)&8191,Ee=E[12]&255|(E[13]&255)<<8,this.r[7]=(xe>>>11|Ee<<5)&8065,Ke=E[14]&255|(E[15]&255)<<8,this.r[8]=(Ee>>>8|Ke<<8)&8191,this.r[9]=Ke>>>5&127,this.pad[0]=E[16]&255|(E[17]&255)<<8,this.pad[1]=E[18]&255|(E[19]&255)<<8,this.pad[2]=E[20]&255|(E[21]&255)<<8,this.pad[3]=E[22]&255|(E[23]&255)<<8,this.pad[4]=E[24]&255|(E[25]&255)<<8,this.pad[5]=E[26]&255|(E[27]&255)<<8,this.pad[6]=E[28]&255|(E[29]&255)<<8,this.pad[7]=E[30]&255|(E[31]&255)<<8};I.prototype.blocks=function(E,L,M){for(var j=this.fin?0:2048,F,he,xe,Ee,Ke,ht,ot,Ht,ut,Tt,yt,Ot,jt,It,le,Pe,Ge,Ve,Ye,at=this.h[0],st=this.h[1],Xe=this.h[2],ke=this.h[3],je=this.h[4],Be=this.h[5],Me=this.h[6],Le=this.h[7],qe=this.h[8],Ct=this.h[9],Vt=this.r[0],Bt=this.r[1],Rt=this.r[2],se=this.r[3],qt=this.r[4],rn=this.r[5],an=this.r[6],Kt=this.r[7],nn=this.r[8],Qt=this.r[9];M>=16;)F=E[L+0]&255|(E[L+1]&255)<<8,at+=F&8191,he=E[L+2]&255|(E[L+3]&255)<<8,st+=(F>>>13|he<<3)&8191,xe=E[L+4]&255|(E[L+5]&255)<<8,Xe+=(he>>>10|xe<<6)&8191,Ee=E[L+6]&255|(E[L+7]&255)<<8,ke+=(xe>>>7|Ee<<9)&8191,Ke=E[L+8]&255|(E[L+9]&255)<<8,je+=(Ee>>>4|Ke<<12)&8191,Be+=Ke>>>1&8191,ht=E[L+10]&255|(E[L+11]&255)<<8,Me+=(Ke>>>14|ht<<2)&8191,ot=E[L+12]&255|(E[L+13]&255)<<8,Le+=(ht>>>11|ot<<5)&8191,Ht=E[L+14]&255|(E[L+15]&255)<<8,qe+=(ot>>>8|Ht<<8)&8191,Ct+=Ht>>>5|j,ut=0,Tt=ut,Tt+=at*Vt,Tt+=st*(5*Qt),Tt+=Xe*(5*nn),Tt+=ke*(5*Kt),Tt+=je*(5*an),ut=Tt>>>13,Tt&=8191,Tt+=Be*(5*rn),Tt+=Me*(5*qt),Tt+=Le*(5*se),Tt+=qe*(5*Rt),Tt+=Ct*(5*Bt),ut+=Tt>>>13,Tt&=8191,yt=ut,yt+=at*Bt,yt+=st*Vt,yt+=Xe*(5*Qt),yt+=ke*(5*nn),yt+=je*(5*Kt),ut=yt>>>13,yt&=8191,yt+=Be*(5*an),yt+=Me*(5*rn),yt+=Le*(5*qt),yt+=qe*(5*se),yt+=Ct*(5*Rt),ut+=yt>>>13,yt&=8191,Ot=ut,Ot+=at*Rt,Ot+=st*Bt,Ot+=Xe*Vt,Ot+=ke*(5*Qt),Ot+=je*(5*nn),ut=Ot>>>13,Ot&=8191,Ot+=Be*(5*Kt),Ot+=Me*(5*an),Ot+=Le*(5*rn),Ot+=qe*(5*qt),Ot+=Ct*(5*se),ut+=Ot>>>13,Ot&=8191,jt=ut,jt+=at*se,jt+=st*Rt,jt+=Xe*Bt,jt+=ke*Vt,jt+=je*(5*Qt),ut=jt>>>13,jt&=8191,jt+=Be*(5*nn),jt+=Me*(5*Kt),jt+=Le*(5*an),jt+=qe*(5*rn),jt+=Ct*(5*qt),ut+=jt>>>13,jt&=8191,It=ut,It+=at*qt,It+=st*se,It+=Xe*Rt,It+=ke*Bt,It+=je*Vt,ut=It>>>13,It&=8191,It+=Be*(5*Qt),It+=Me*(5*nn),It+=Le*(5*Kt),It+=qe*(5*an),It+=Ct*(5*rn),ut+=It>>>13,It&=8191,le=ut,le+=at*rn,le+=st*qt,le+=Xe*se,le+=ke*Rt,le+=je*Bt,ut=le>>>13,le&=8191,le+=Be*Vt,le+=Me*(5*Qt),le+=Le*(5*nn),le+=qe*(5*Kt),le+=Ct*(5*an),ut+=le>>>13,le&=8191,Pe=ut,Pe+=at*an,Pe+=st*rn,Pe+=Xe*qt,Pe+=ke*se,Pe+=je*Rt,ut=Pe>>>13,Pe&=8191,Pe+=Be*Bt,Pe+=Me*Vt,Pe+=Le*(5*Qt),Pe+=qe*(5*nn),Pe+=Ct*(5*Kt),ut+=Pe>>>13,Pe&=8191,Ge=ut,Ge+=at*Kt,Ge+=st*an,Ge+=Xe*rn,Ge+=ke*qt,Ge+=je*se,ut=Ge>>>13,Ge&=8191,Ge+=Be*Rt,Ge+=Me*Bt,Ge+=Le*Vt,Ge+=qe*(5*Qt),Ge+=Ct*(5*nn),ut+=Ge>>>13,Ge&=8191,Ve=ut,Ve+=at*nn,Ve+=st*Kt,Ve+=Xe*an,Ve+=ke*rn,Ve+=je*qt,ut=Ve>>>13,Ve&=8191,Ve+=Be*se,Ve+=Me*Rt,Ve+=Le*Bt,Ve+=qe*Vt,Ve+=Ct*(5*Qt),ut+=Ve>>>13,Ve&=8191,Ye=ut,Ye+=at*Qt,Ye+=st*nn,Ye+=Xe*Kt,Ye+=ke*an,Ye+=je*rn,ut=Ye>>>13,Ye&=8191,Ye+=Be*qt,Ye+=Me*se,Ye+=Le*Rt,Ye+=qe*Bt,Ye+=Ct*Vt,ut+=Ye>>>13,Ye&=8191,ut=(ut<<2)+ut|0,ut=ut+Tt|0,Tt=ut&8191,ut=ut>>>13,yt+=ut,at=Tt,st=yt,Xe=Ot,ke=jt,je=It,Be=le,Me=Pe,Le=Ge,qe=Ve,Ct=Ye,L+=16,M-=16;this.h[0]=at,this.h[1]=st,this.h[2]=Xe,this.h[3]=ke,this.h[4]=je,this.h[5]=Be,this.h[6]=Me,this.h[7]=Le,this.h[8]=qe,this.h[9]=Ct},I.prototype.finish=function(E,L){var M=new Uint16Array(10),j,F,he,xe;if(this.leftover){for(xe=this.leftover,this.buffer[xe++]=1;xe<16;xe++)this.buffer[xe]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(j=this.h[1]>>>13,this.h[1]&=8191,xe=2;xe<10;xe++)this.h[xe]+=j,j=this.h[xe]>>>13,this.h[xe]&=8191;for(this.h[0]+=j*5,j=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=j,j=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=j,M[0]=this.h[0]+5,j=M[0]>>>13,M[0]&=8191,xe=1;xe<10;xe++)M[xe]=this.h[xe]+j,j=M[xe]>>>13,M[xe]&=8191;for(M[9]-=8192,F=(j^1)-1,xe=0;xe<10;xe++)M[xe]&=F;for(F=~F,xe=0;xe<10;xe++)this.h[xe]=this.h[xe]&F|M[xe];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,he=this.h[0]+this.pad[0],this.h[0]=he&65535,xe=1;xe<8;xe++)he=(this.h[xe]+this.pad[xe]|0)+(he>>>16)|0,this.h[xe]=he&65535;E[L+0]=this.h[0]>>>0&255,E[L+1]=this.h[0]>>>8&255,E[L+2]=this.h[1]>>>0&255,E[L+3]=this.h[1]>>>8&255,E[L+4]=this.h[2]>>>0&255,E[L+5]=this.h[2]>>>8&255,E[L+6]=this.h[3]>>>0&255,E[L+7]=this.h[3]>>>8&255,E[L+8]=this.h[4]>>>0&255,E[L+9]=this.h[4]>>>8&255,E[L+10]=this.h[5]>>>0&255,E[L+11]=this.h[5]>>>8&255,E[L+12]=this.h[6]>>>0&255,E[L+13]=this.h[6]>>>8&255,E[L+14]=this.h[7]>>>0&255,E[L+15]=this.h[7]>>>8&255},I.prototype.update=function(E,L,M){var j,F;if(this.leftover){for(F=16-this.leftover,F>M&&(F=M),j=0;j<F;j++)this.buffer[this.leftover+j]=E[L+j];if(M-=F,L+=F,this.leftover+=F,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(M>=16&&(F=M-M%16,this.blocks(E,L,F),L+=F,M-=F),M){for(j=0;j<M;j++)this.buffer[this.leftover+j]=E[L+j];this.leftover+=M}};function P(E,L,M,j,F,he){var xe=new I(he);return xe.update(M,j,F),xe.finish(E,L),0}function D(E,L,M,j,F,he){var xe=new Uint8Array(16);return P(xe,0,M,j,F,he),v(E,L,xe,0)}function O(E,L,M,j,F){var he;if(M<32)return-1;for(T(E,0,L,0,M,j,F),P(E,16,E,32,M-32,E),he=0;he<16;he++)E[he]=0;return 0}function z(E,L,M,j,F){var he,xe=new Uint8Array(32);if(M<32||(A(xe,0,32,j,F),D(L,16,L,32,M-32,xe)!==0))return-1;for(T(E,0,L,0,M,j,F),he=0;he<32;he++)E[he]=0;return 0}function R(E,L){var M;for(M=0;M<16;M++)E[M]=L[M]|0}function $(E){var L,M,j=1;for(L=0;L<16;L++)M=E[L]+j+65535,j=Math.floor(M/65536),E[L]=M-j*65536;E[0]+=j-1+37*(j-1)}function X(E,L,M){for(var j,F=~(M-1),he=0;he<16;he++)j=F&(E[he]^L[he]),E[he]^=j,L[he]^=j}function H(E,L){var M,j,F,he=n(),xe=n();for(M=0;M<16;M++)xe[M]=L[M];for($(xe),$(xe),$(xe),j=0;j<2;j++){for(he[0]=xe[0]-65517,M=1;M<15;M++)he[M]=xe[M]-65535-(he[M-1]>>16&1),he[M-1]&=65535;he[15]=xe[15]-32767-(he[14]>>16&1),F=he[15]>>16&1,he[14]&=65535,X(xe,he,1-F)}for(M=0;M<16;M++)E[2*M]=xe[M]&255,E[2*M+1]=xe[M]>>8}function te(E,L){var M=new Uint8Array(32),j=new Uint8Array(32);return H(M,E),H(j,L),y(M,0,j,0)}function V(E){var L=new Uint8Array(32);return H(L,E),L[0]&1}function Y(E,L){var M;for(M=0;M<16;M++)E[M]=L[2*M]+(L[2*M+1]<<8);E[15]&=32767}function q(E,L,M){for(var j=0;j<16;j++)E[j]=L[j]+M[j]}function ee(E,L,M){for(var j=0;j<16;j++)E[j]=L[j]-M[j]}function ge(E,L,M){var j,F,he=0,xe=0,Ee=0,Ke=0,ht=0,ot=0,Ht=0,ut=0,Tt=0,yt=0,Ot=0,jt=0,It=0,le=0,Pe=0,Ge=0,Ve=0,Ye=0,at=0,st=0,Xe=0,ke=0,je=0,Be=0,Me=0,Le=0,qe=0,Ct=0,Vt=0,Bt=0,Rt=0,se=M[0],qt=M[1],rn=M[2],an=M[3],Kt=M[4],nn=M[5],Qt=M[6],Rn=M[7],sn=M[8],jn=M[9],_n=M[10],Nn=M[11],zn=M[12],Wn=M[13],Fn=M[14],Gn=M[15];j=L[0],he+=j*se,xe+=j*qt,Ee+=j*rn,Ke+=j*an,ht+=j*Kt,ot+=j*nn,Ht+=j*Qt,ut+=j*Rn,Tt+=j*sn,yt+=j*jn,Ot+=j*_n,jt+=j*Nn,It+=j*zn,le+=j*Wn,Pe+=j*Fn,Ge+=j*Gn,j=L[1],xe+=j*se,Ee+=j*qt,Ke+=j*rn,ht+=j*an,ot+=j*Kt,Ht+=j*nn,ut+=j*Qt,Tt+=j*Rn,yt+=j*sn,Ot+=j*jn,jt+=j*_n,It+=j*Nn,le+=j*zn,Pe+=j*Wn,Ge+=j*Fn,Ve+=j*Gn,j=L[2],Ee+=j*se,Ke+=j*qt,ht+=j*rn,ot+=j*an,Ht+=j*Kt,ut+=j*nn,Tt+=j*Qt,yt+=j*Rn,Ot+=j*sn,jt+=j*jn,It+=j*_n,le+=j*Nn,Pe+=j*zn,Ge+=j*Wn,Ve+=j*Fn,Ye+=j*Gn,j=L[3],Ke+=j*se,ht+=j*qt,ot+=j*rn,Ht+=j*an,ut+=j*Kt,Tt+=j*nn,yt+=j*Qt,Ot+=j*Rn,jt+=j*sn,It+=j*jn,le+=j*_n,Pe+=j*Nn,Ge+=j*zn,Ve+=j*Wn,Ye+=j*Fn,at+=j*Gn,j=L[4],ht+=j*se,ot+=j*qt,Ht+=j*rn,ut+=j*an,Tt+=j*Kt,yt+=j*nn,Ot+=j*Qt,jt+=j*Rn,It+=j*sn,le+=j*jn,Pe+=j*_n,Ge+=j*Nn,Ve+=j*zn,Ye+=j*Wn,at+=j*Fn,st+=j*Gn,j=L[5],ot+=j*se,Ht+=j*qt,ut+=j*rn,Tt+=j*an,yt+=j*Kt,Ot+=j*nn,jt+=j*Qt,It+=j*Rn,le+=j*sn,Pe+=j*jn,Ge+=j*_n,Ve+=j*Nn,Ye+=j*zn,at+=j*Wn,st+=j*Fn,Xe+=j*Gn,j=L[6],Ht+=j*se,ut+=j*qt,Tt+=j*rn,yt+=j*an,Ot+=j*Kt,jt+=j*nn,It+=j*Qt,le+=j*Rn,Pe+=j*sn,Ge+=j*jn,Ve+=j*_n,Ye+=j*Nn,at+=j*zn,st+=j*Wn,Xe+=j*Fn,ke+=j*Gn,j=L[7],ut+=j*se,Tt+=j*qt,yt+=j*rn,Ot+=j*an,jt+=j*Kt,It+=j*nn,le+=j*Qt,Pe+=j*Rn,Ge+=j*sn,Ve+=j*jn,Ye+=j*_n,at+=j*Nn,st+=j*zn,Xe+=j*Wn,ke+=j*Fn,je+=j*Gn,j=L[8],Tt+=j*se,yt+=j*qt,Ot+=j*rn,jt+=j*an,It+=j*Kt,le+=j*nn,Pe+=j*Qt,Ge+=j*Rn,Ve+=j*sn,Ye+=j*jn,at+=j*_n,st+=j*Nn,Xe+=j*zn,ke+=j*Wn,je+=j*Fn,Be+=j*Gn,j=L[9],yt+=j*se,Ot+=j*qt,jt+=j*rn,It+=j*an,le+=j*Kt,Pe+=j*nn,Ge+=j*Qt,Ve+=j*Rn,Ye+=j*sn,at+=j*jn,st+=j*_n,Xe+=j*Nn,ke+=j*zn,je+=j*Wn,Be+=j*Fn,Me+=j*Gn,j=L[10],Ot+=j*se,jt+=j*qt,It+=j*rn,le+=j*an,Pe+=j*Kt,Ge+=j*nn,Ve+=j*Qt,Ye+=j*Rn,at+=j*sn,st+=j*jn,Xe+=j*_n,ke+=j*Nn,je+=j*zn,Be+=j*Wn,Me+=j*Fn,Le+=j*Gn,j=L[11],jt+=j*se,It+=j*qt,le+=j*rn,Pe+=j*an,Ge+=j*Kt,Ve+=j*nn,Ye+=j*Qt,at+=j*Rn,st+=j*sn,Xe+=j*jn,ke+=j*_n,je+=j*Nn,Be+=j*zn,Me+=j*Wn,Le+=j*Fn,qe+=j*Gn,j=L[12],It+=j*se,le+=j*qt,Pe+=j*rn,Ge+=j*an,Ve+=j*Kt,Ye+=j*nn,at+=j*Qt,st+=j*Rn,Xe+=j*sn,ke+=j*jn,je+=j*_n,Be+=j*Nn,Me+=j*zn,Le+=j*Wn,qe+=j*Fn,Ct+=j*Gn,j=L[13],le+=j*se,Pe+=j*qt,Ge+=j*rn,Ve+=j*an,Ye+=j*Kt,at+=j*nn,st+=j*Qt,Xe+=j*Rn,ke+=j*sn,je+=j*jn,Be+=j*_n,Me+=j*Nn,Le+=j*zn,qe+=j*Wn,Ct+=j*Fn,Vt+=j*Gn,j=L[14],Pe+=j*se,Ge+=j*qt,Ve+=j*rn,Ye+=j*an,at+=j*Kt,st+=j*nn,Xe+=j*Qt,ke+=j*Rn,je+=j*sn,Be+=j*jn,Me+=j*_n,Le+=j*Nn,qe+=j*zn,Ct+=j*Wn,Vt+=j*Fn,Bt+=j*Gn,j=L[15],Ge+=j*se,Ve+=j*qt,Ye+=j*rn,at+=j*an,st+=j*Kt,Xe+=j*nn,ke+=j*Qt,je+=j*Rn,Be+=j*sn,Me+=j*jn,Le+=j*_n,qe+=j*Nn,Ct+=j*zn,Vt+=j*Wn,Bt+=j*Fn,Rt+=j*Gn,he+=38*Ve,xe+=38*Ye,Ee+=38*at,Ke+=38*st,ht+=38*Xe,ot+=38*ke,Ht+=38*je,ut+=38*Be,Tt+=38*Me,yt+=38*Le,Ot+=38*qe,jt+=38*Ct,It+=38*Vt,le+=38*Bt,Pe+=38*Rt,F=1,j=he+F+65535,F=Math.floor(j/65536),he=j-F*65536,j=xe+F+65535,F=Math.floor(j/65536),xe=j-F*65536,j=Ee+F+65535,F=Math.floor(j/65536),Ee=j-F*65536,j=Ke+F+65535,F=Math.floor(j/65536),Ke=j-F*65536,j=ht+F+65535,F=Math.floor(j/65536),ht=j-F*65536,j=ot+F+65535,F=Math.floor(j/65536),ot=j-F*65536,j=Ht+F+65535,F=Math.floor(j/65536),Ht=j-F*65536,j=ut+F+65535,F=Math.floor(j/65536),ut=j-F*65536,j=Tt+F+65535,F=Math.floor(j/65536),Tt=j-F*65536,j=yt+F+65535,F=Math.floor(j/65536),yt=j-F*65536,j=Ot+F+65535,F=Math.floor(j/65536),Ot=j-F*65536,j=jt+F+65535,F=Math.floor(j/65536),jt=j-F*65536,j=It+F+65535,F=Math.floor(j/65536),It=j-F*65536,j=le+F+65535,F=Math.floor(j/65536),le=j-F*65536,j=Pe+F+65535,F=Math.floor(j/65536),Pe=j-F*65536,j=Ge+F+65535,F=Math.floor(j/65536),Ge=j-F*65536,he+=F-1+37*(F-1),F=1,j=he+F+65535,F=Math.floor(j/65536),he=j-F*65536,j=xe+F+65535,F=Math.floor(j/65536),xe=j-F*65536,j=Ee+F+65535,F=Math.floor(j/65536),Ee=j-F*65536,j=Ke+F+65535,F=Math.floor(j/65536),Ke=j-F*65536,j=ht+F+65535,F=Math.floor(j/65536),ht=j-F*65536,j=ot+F+65535,F=Math.floor(j/65536),ot=j-F*65536,j=Ht+F+65535,F=Math.floor(j/65536),Ht=j-F*65536,j=ut+F+65535,F=Math.floor(j/65536),ut=j-F*65536,j=Tt+F+65535,F=Math.floor(j/65536),Tt=j-F*65536,j=yt+F+65535,F=Math.floor(j/65536),yt=j-F*65536,j=Ot+F+65535,F=Math.floor(j/65536),Ot=j-F*65536,j=jt+F+65535,F=Math.floor(j/65536),jt=j-F*65536,j=It+F+65535,F=Math.floor(j/65536),It=j-F*65536,j=le+F+65535,F=Math.floor(j/65536),le=j-F*65536,j=Pe+F+65535,F=Math.floor(j/65536),Pe=j-F*65536,j=Ge+F+65535,F=Math.floor(j/65536),Ge=j-F*65536,he+=F-1+37*(F-1),E[0]=he,E[1]=xe,E[2]=Ee,E[3]=Ke,E[4]=ht,E[5]=ot,E[6]=Ht,E[7]=ut,E[8]=Tt,E[9]=yt,E[10]=Ot,E[11]=jt,E[12]=It,E[13]=le,E[14]=Pe,E[15]=Ge}function Ce(E,L){ge(E,L,L)}function Re(E,L){var M=n(),j;for(j=0;j<16;j++)M[j]=L[j];for(j=253;j>=0;j--)Ce(M,M),j!==2&&j!==4&&ge(M,M,L);for(j=0;j<16;j++)E[j]=M[j]}function fe(E,L){var M=n(),j;for(j=0;j<16;j++)M[j]=L[j];for(j=250;j>=0;j--)Ce(M,M),j!==1&&ge(M,M,L);for(j=0;j<16;j++)E[j]=M[j]}function U(E,L,M){var j=new Uint8Array(32),F=new Float64Array(80),he,xe,Ee=n(),Ke=n(),ht=n(),ot=n(),Ht=n(),ut=n();for(xe=0;xe<31;xe++)j[xe]=L[xe];for(j[31]=L[31]&127|64,j[0]&=248,Y(F,M),xe=0;xe<16;xe++)Ke[xe]=F[xe],ot[xe]=Ee[xe]=ht[xe]=0;for(Ee[0]=ot[0]=1,xe=254;xe>=0;--xe)he=j[xe>>>3]>>>(xe&7)&1,X(Ee,Ke,he),X(ht,ot,he),q(Ht,Ee,ht),ee(Ee,Ee,ht),q(ht,Ke,ot),ee(Ke,Ke,ot),Ce(ot,Ht),Ce(ut,Ee),ge(Ee,ht,Ee),ge(ht,Ke,Ht),q(Ht,Ee,ht),ee(Ee,Ee,ht),Ce(Ke,Ee),ee(ht,ot,ut),ge(Ee,ht,c),q(Ee,Ee,ot),ge(ht,ht,Ee),ge(Ee,ot,ut),ge(ot,Ke,F),Ce(Ke,Ht),X(Ee,Ke,he),X(ht,ot,he);for(xe=0;xe<16;xe++)F[xe+16]=Ee[xe],F[xe+32]=ht[xe],F[xe+48]=Ke[xe],F[xe+64]=ot[xe];var Tt=F.subarray(32),yt=F.subarray(16);return Re(Tt,Tt),ge(yt,yt,Tt),H(E,yt),0}function oe(E,L){return U(E,L,r)}function Se(E,L){return s(L,32),oe(E,L)}function G(E,L,M){var j=new Uint8Array(32);return U(j,M,L),_(E,o,j,N)}var Q=O,ae=z;function Z(E,L,M,j,F,he){var xe=new Uint8Array(32);return G(xe,F,he),Q(E,L,M,j,xe)}function ce(E,L,M,j,F,he){var xe=new Uint8Array(32);return G(xe,F,he),ae(E,L,M,j,xe)}var De=[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 Oe(E,L,M,j){for(var F=new Int32Array(16),he=new Int32Array(16),xe,Ee,Ke,ht,ot,Ht,ut,Tt,yt,Ot,jt,It,le,Pe,Ge,Ve,Ye,at,st,Xe,ke,je,Be,Me,Le,qe,Ct=E[0],Vt=E[1],Bt=E[2],Rt=E[3],se=E[4],qt=E[5],rn=E[6],an=E[7],Kt=L[0],nn=L[1],Qt=L[2],Rn=L[3],sn=L[4],jn=L[5],_n=L[6],Nn=L[7],zn=0;j>=128;){for(st=0;st<16;st++)Xe=8*st+zn,F[st]=M[Xe+0]<<24|M[Xe+1]<<16|M[Xe+2]<<8|M[Xe+3],he[st]=M[Xe+4]<<24|M[Xe+5]<<16|M[Xe+6]<<8|M[Xe+7];for(st=0;st<80;st++)if(xe=Ct,Ee=Vt,Ke=Bt,ht=Rt,ot=se,Ht=qt,ut=rn,Tt=an,yt=Kt,Ot=nn,jt=Qt,It=Rn,le=sn,Pe=jn,Ge=_n,Ve=Nn,ke=an,je=Nn,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=(se>>>14|sn<<18)^(se>>>18|sn<<14)^(sn>>>9|se<<23),je=(sn>>>14|se<<18)^(sn>>>18|se<<14)^(se>>>9|sn<<23),Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,ke=se&qt^~se&rn,je=sn&jn^~sn&_n,Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,ke=De[st*2],je=De[st*2+1],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,ke=F[st%16],je=he[st%16],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,Ye=Le&65535|qe<<16,at=Be&65535|Me<<16,ke=Ye,je=at,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=(Ct>>>28|Kt<<4)^(Kt>>>2|Ct<<30)^(Kt>>>7|Ct<<25),je=(Kt>>>28|Ct<<4)^(Ct>>>2|Kt<<30)^(Ct>>>7|Kt<<25),Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,ke=Ct&Vt^Ct&Bt^Vt&Bt,je=Kt&nn^Kt&Qt^nn&Qt,Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,Tt=Le&65535|qe<<16,Ve=Be&65535|Me<<16,ke=ht,je=It,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=Ye,je=at,Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,ht=Le&65535|qe<<16,It=Be&65535|Me<<16,Vt=xe,Bt=Ee,Rt=Ke,se=ht,qt=ot,rn=Ht,an=ut,Ct=Tt,nn=yt,Qt=Ot,Rn=jt,sn=It,jn=le,_n=Pe,Nn=Ge,Kt=Ve,st%16===15)for(Xe=0;Xe<16;Xe++)ke=F[Xe],je=he[Xe],Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=F[(Xe+9)%16],je=he[(Xe+9)%16],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Ye=F[(Xe+1)%16],at=he[(Xe+1)%16],ke=(Ye>>>1|at<<31)^(Ye>>>8|at<<24)^Ye>>>7,je=(at>>>1|Ye<<31)^(at>>>8|Ye<<24)^(at>>>7|Ye<<25),Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Ye=F[(Xe+14)%16],at=he[(Xe+14)%16],ke=(Ye>>>19|at<<13)^(at>>>29|Ye<<3)^Ye>>>6,je=(at>>>19|Ye<<13)^(Ye>>>29|at<<3)^(at>>>6|Ye<<26),Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,F[Xe]=Le&65535|qe<<16,he[Xe]=Be&65535|Me<<16;ke=Ct,je=Kt,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[0],je=L[0],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[0]=Ct=Le&65535|qe<<16,L[0]=Kt=Be&65535|Me<<16,ke=Vt,je=nn,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[1],je=L[1],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[1]=Vt=Le&65535|qe<<16,L[1]=nn=Be&65535|Me<<16,ke=Bt,je=Qt,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[2],je=L[2],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[2]=Bt=Le&65535|qe<<16,L[2]=Qt=Be&65535|Me<<16,ke=Rt,je=Rn,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[3],je=L[3],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[3]=Rt=Le&65535|qe<<16,L[3]=Rn=Be&65535|Me<<16,ke=se,je=sn,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[4],je=L[4],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[4]=se=Le&65535|qe<<16,L[4]=sn=Be&65535|Me<<16,ke=qt,je=jn,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[5],je=L[5],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[5]=qt=Le&65535|qe<<16,L[5]=jn=Be&65535|Me<<16,ke=rn,je=_n,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[6],je=L[6],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[6]=rn=Le&65535|qe<<16,L[6]=_n=Be&65535|Me<<16,ke=an,je=Nn,Be=je&65535,Me=je>>>16,Le=ke&65535,qe=ke>>>16,ke=E[7],je=L[7],Be+=je&65535,Me+=je>>>16,Le+=ke&65535,qe+=ke>>>16,Me+=Be>>>16,Le+=Me>>>16,qe+=Le>>>16,E[7]=an=Le&65535|qe<<16,L[7]=Nn=Be&65535|Me<<16,zn+=128,j-=128}return j}function Ne(E,L,M){var j=new Int32Array(8),F=new Int32Array(8),he=new Uint8Array(256),xe,Ee=M;for(j[0]=1779033703,j[1]=3144134277,j[2]=1013904242,j[3]=2773480762,j[4]=1359893119,j[5]=2600822924,j[6]=528734635,j[7]=1541459225,F[0]=4089235720,F[1]=2227873595,F[2]=4271175723,F[3]=1595750129,F[4]=2917565137,F[5]=725511199,F[6]=4215389547,F[7]=327033209,Oe(j,F,L,M),M%=128,xe=0;xe<M;xe++)he[xe]=L[Ee-M+xe];for(he[M]=128,M=256-128*(M<112?1:0),he[M-9]=0,g(he,M-8,Ee/536870912|0,Ee<<3),Oe(j,F,he,M),xe=0;xe<8;xe++)g(E,8*xe,j[xe],F[xe]);return 0}function Ze(E,L){var M=n(),j=n(),F=n(),he=n(),xe=n(),Ee=n(),Ke=n(),ht=n(),ot=n();ee(M,E[1],E[0]),ee(ot,L[1],L[0]),ge(M,M,ot),q(j,E[0],E[1]),q(ot,L[0],L[1]),ge(j,j,ot),ge(F,E[3],L[3]),ge(F,F,u),ge(he,E[2],L[2]),q(he,he,he),ee(xe,j,M),ee(Ee,he,F),q(Ke,he,F),q(ht,j,M),ge(E[0],xe,Ee),ge(E[1],ht,Ke),ge(E[2],Ke,Ee),ge(E[3],xe,ht)}function bt(E,L,M){var j;for(j=0;j<4;j++)X(E[j],L[j],M)}function Ut(E,L){var M=n(),j=n(),F=n();Re(F,L[2]),ge(M,L[0],F),ge(j,L[1],F),H(E,j),E[31]^=V(M)<<7}function Et(E,L,M){var j,F;for(R(E[0],a),R(E[1],l),R(E[2],l),R(E[3],a),F=255;F>=0;--F)j=M[F/8|0]>>(F&7)&1,bt(E,L,j),Ze(L,E),Ze(E,E),bt(E,L,j)}function _t(E,L){var M=[n(),n(),n(),n()];R(M[0],h),R(M[1],p),R(M[2],l),ge(M[3],h,p),Et(E,M,L)}function B(E,L,M){var j=new Uint8Array(64),F=[n(),n(),n(),n()],he;for(M||s(L,32),Ne(j,L,32),j[0]&=248,j[31]&=127,j[31]|=64,_t(F,j),Ut(E,F),he=0;he<32;he++)L[he+32]=E[he];return 0}var Te=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 We(E,L){var M,j,F,he;for(j=63;j>=32;--j){for(M=0,F=j-32,he=j-12;F<he;++F)L[F]+=M-16*L[j]*Te[F-(j-32)],M=Math.floor((L[F]+128)/256),L[F]-=M*256;L[F]+=M,L[j]=0}for(M=0,F=0;F<32;F++)L[F]+=M-(L[31]>>4)*Te[F],M=L[F]>>8,L[F]&=255;for(F=0;F<32;F++)L[F]-=M*Te[F];for(j=0;j<32;j++)L[j+1]+=L[j]>>8,E[j]=L[j]&255}function kt(E){var L=new Float64Array(64),M;for(M=0;M<64;M++)L[M]=E[M];for(M=0;M<64;M++)E[M]=0;We(E,L)}function Gt(E,L,M,j){var F=new Uint8Array(64),he=new Uint8Array(64),xe=new Uint8Array(64),Ee,Ke,ht=new Float64Array(64),ot=[n(),n(),n(),n()];Ne(F,j,32),F[0]&=248,F[31]&=127,F[31]|=64;var Ht=M+64;for(Ee=0;Ee<M;Ee++)E[64+Ee]=L[Ee];for(Ee=0;Ee<32;Ee++)E[32+Ee]=F[32+Ee];for(Ne(xe,E.subarray(32),M+32),kt(xe),_t(ot,xe),Ut(E,ot),Ee=32;Ee<64;Ee++)E[Ee]=j[Ee];for(Ne(he,E,M+64),kt(he),Ee=0;Ee<64;Ee++)ht[Ee]=0;for(Ee=0;Ee<32;Ee++)ht[Ee]=xe[Ee];for(Ee=0;Ee<32;Ee++)for(Ke=0;Ke<32;Ke++)ht[Ee+Ke]+=he[Ee]*F[Ke];return We(E.subarray(32),ht),Ht}function de(E,L){var M=n(),j=n(),F=n(),he=n(),xe=n(),Ee=n(),Ke=n();return R(E[2],l),Y(E[1],L),Ce(F,E[1]),ge(he,F,d),ee(F,F,E[2]),q(he,E[2],he),Ce(xe,he),Ce(Ee,xe),ge(Ke,Ee,xe),ge(M,Ke,F),ge(M,M,he),fe(M,M),ge(M,M,F),ge(M,M,he),ge(M,M,he),ge(E[0],M,he),Ce(j,E[0]),ge(j,j,he),te(j,F)&&ge(E[0],E[0],f),Ce(j,E[0]),ge(j,j,he),te(j,F)?-1:(V(E[0])===L[31]>>7&&ee(E[0],a,E[0]),ge(E[3],E[0],E[1]),0)}function mt(E,L,M,j){var F,he=new Uint8Array(32),xe=new Uint8Array(64),Ee=[n(),n(),n(),n()],Ke=[n(),n(),n(),n()];if(M<64||de(Ke,j))return-1;for(F=0;F<M;F++)E[F]=L[F];for(F=0;F<32;F++)E[F+32]=j[F];if(Ne(xe,E,M),kt(xe),Et(Ee,Ke,xe),_t(Ke,L.subarray(32)),Ze(Ee,Ke),Ut(he,Ee),M-=64,y(L,0,he,0)){for(F=0;F<M;F++)E[F]=0;return-1}for(F=0;F<M;F++)E[F]=L[F+64];return M}var Lt=32,Fe=24,Nt=32,Ft=16,on=32,re=32,Ue=32,dt=32,Dt=32,it=Fe,K=Nt,pe=Ft,Ie=64,Ae=32,He=64,nt=32,be=64;t.lowlevel={crypto_core_hsalsa20:_,crypto_stream_xor:T,crypto_stream:A,crypto_stream_salsa20_xor:k,crypto_stream_salsa20:S,crypto_onetimeauth:P,crypto_onetimeauth_verify:D,crypto_verify_16:v,crypto_verify_32:y,crypto_secretbox:O,crypto_secretbox_open:z,crypto_scalarmult:U,crypto_scalarmult_base:oe,crypto_box_beforenm:G,crypto_box_afternm:Q,crypto_box:Z,crypto_box_open:ce,crypto_box_keypair:Se,crypto_hash:Ne,crypto_sign:Gt,crypto_sign_keypair:B,crypto_sign_open:mt,crypto_secretbox_KEYBYTES:Lt,crypto_secretbox_NONCEBYTES:Fe,crypto_secretbox_ZEROBYTES:Nt,crypto_secretbox_BOXZEROBYTES:Ft,crypto_scalarmult_BYTES:on,crypto_scalarmult_SCALARBYTES:re,crypto_box_PUBLICKEYBYTES:Ue,crypto_box_SECRETKEYBYTES:dt,crypto_box_BEFORENMBYTES:Dt,crypto_box_NONCEBYTES:it,crypto_box_ZEROBYTES:K,crypto_box_BOXZEROBYTES:pe,crypto_sign_BYTES:Ie,crypto_sign_PUBLICKEYBYTES:Ae,crypto_sign_SECRETKEYBYTES:He,crypto_sign_SEEDBYTES:nt,crypto_hash_BYTES:be,gf:n,D:d,L:Te,pack25519:H,unpack25519:Y,M:ge,A:q,S:Ce,Z:ee,pow2523:fe,add:Ze,set25519:R,modL:We,scalarmult:Et,scalarbase:_t};function et(E,L){if(E.length!==Lt)throw new Error("bad key size");if(L.length!==Fe)throw new Error("bad nonce size")}function tt(E,L){if(E.length!==Ue)throw new Error("bad public key size");if(L.length!==dt)throw new Error("bad secret key size")}function wt(){for(var E=0;E<arguments.length;E++)if(!(arguments[E]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function Jt(E){for(var L=0;L<E.length;L++)E[L]=0}t.randomBytes=function(E){var L=new Uint8Array(E);return s(L,E),L},t.secretbox=function(E,L,M){wt(E,L,M),et(M,L);for(var j=new Uint8Array(Nt+E.length),F=new Uint8Array(j.length),he=0;he<E.length;he++)j[he+Nt]=E[he];return O(F,j,j.length,L,M),F.subarray(Ft)},t.secretbox.open=function(E,L,M){wt(E,L,M),et(M,L);for(var j=new Uint8Array(Ft+E.length),F=new Uint8Array(j.length),he=0;he<E.length;he++)j[he+Ft]=E[he];return j.length<32||z(F,j,j.length,L,M)!==0?null:F.subarray(Nt)},t.secretbox.keyLength=Lt,t.secretbox.nonceLength=Fe,t.secretbox.overheadLength=Ft,t.scalarMult=function(E,L){if(wt(E,L),E.length!==re)throw new Error("bad n size");if(L.length!==on)throw new Error("bad p size");var M=new Uint8Array(on);return U(M,E,L),M},t.scalarMult.base=function(E){if(wt(E),E.length!==re)throw new Error("bad n size");var L=new Uint8Array(on);return oe(L,E),L},t.scalarMult.scalarLength=re,t.scalarMult.groupElementLength=on,t.box=function(E,L,M,j){var F=t.box.before(M,j);return t.secretbox(E,L,F)},t.box.before=function(E,L){wt(E,L),tt(E,L);var M=new Uint8Array(Dt);return G(M,E,L),M},t.box.after=t.secretbox,t.box.open=function(E,L,M,j){var F=t.box.before(M,j);return t.secretbox.open(E,L,F)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var E=new Uint8Array(Ue),L=new Uint8Array(dt);return Se(E,L),{publicKey:E,secretKey:L}},t.box.keyPair.fromSecretKey=function(E){if(wt(E),E.length!==dt)throw new Error("bad secret key size");var L=new Uint8Array(Ue);return oe(L,E),{publicKey:L,secretKey:new Uint8Array(E)}},t.box.publicKeyLength=Ue,t.box.secretKeyLength=dt,t.box.sharedKeyLength=Dt,t.box.nonceLength=it,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(E,L){if(wt(E,L),L.length!==He)throw new Error("bad secret key size");var M=new Uint8Array(Ie+E.length);return Gt(M,E,E.length,L),M},t.sign.open=function(E,L){if(wt(E,L),L.length!==Ae)throw new Error("bad public key size");var M=new Uint8Array(E.length),j=mt(M,E,E.length,L);if(j<0)return null;for(var F=new Uint8Array(j),he=0;he<F.length;he++)F[he]=M[he];return F},t.sign.detached=function(E,L){for(var M=t.sign(E,L),j=new Uint8Array(Ie),F=0;F<j.length;F++)j[F]=M[F];return j},t.sign.detached.verify=function(E,L,M){if(wt(E,L,M),L.length!==Ie)throw new Error("bad signature size");if(M.length!==Ae)throw new Error("bad public key size");var j=new Uint8Array(Ie+E.length),F=new Uint8Array(Ie+E.length),he;for(he=0;he<Ie;he++)j[he]=L[he];for(he=0;he<E.length;he++)j[he+Ie]=E[he];return mt(F,j,j.length,M)>=0},t.sign.keyPair=function(){var E=new Uint8Array(Ae),L=new Uint8Array(He);return B(E,L),{publicKey:E,secretKey:L}},t.sign.keyPair.fromSecretKey=function(E){if(wt(E),E.length!==He)throw new Error("bad secret key size");for(var L=new Uint8Array(Ae),M=0;M<L.length;M++)L[M]=E[32+M];return{publicKey:L,secretKey:new Uint8Array(E)}},t.sign.keyPair.fromSeed=function(E){if(wt(E),E.length!==nt)throw new Error("bad seed size");for(var L=new Uint8Array(Ae),M=new Uint8Array(He),j=0;j<32;j++)M[j]=E[j];return B(L,M,!0),{publicKey:L,secretKey:M}},t.sign.publicKeyLength=Ae,t.sign.secretKeyLength=He,t.sign.seedLength=nt,t.sign.signatureLength=Ie,t.hash=function(E){wt(E);var L=new Uint8Array(be);return Ne(L,E,E.length),L},t.hash.hashLength=be,t.verify=function(E,L){return wt(E,L),E.length===0||L.length===0||E.length!==L.length?!1:x(E,0,L,0,E.length)===0},t.setPRNG=function(E){s=E},(function(){var E=typeof self<"u"?self.crypto||self.msCrypto:null;if(E&&E.getRandomValues){var L=65536;t.setPRNG(function(M,j){var F,he=new Uint8Array(j);for(F=0;F<j;F+=L)E.getRandomValues(he.subarray(F,F+Math.min(j-F,L)));for(F=0;F<j;F++)M[F]=he[F];Jt(he)})}else typeof kse<"u"&&(E=Nse,E&&E.randomBytes&&t.setPRNG(function(M,j){var F,he=E.randomBytes(j);for(F=0;F<j;F++)M[F]=he[F];Jt(he)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})(Cf)),Cf.exports}Tse();new TextEncoder;new TextDecoder;function Ise(e){return{id:e.id,name:e.name,path:e.path,...e.alias?.trim()?{alias:e.alias.trim()}:{},...e.groupId?{groupId:e.groupId}:{},...e.kind==="ssh"?{kind:"ssh",...e.sshConnectionName?{sshConnectionName:e.sshConnectionName}:{},...e.sshHost?{sshHost:e.sshHost}:{}}:{}}}function Dse(e){return e.kind!=="ssh"?void 0:e.sshConnectionName?.trim()||e.sshHost}function YE(e){return e.alias?.trim()||e.name}function FC(e){const t=YE(e),n=Dse(e);return n?`${t} (${n})`:t}const gd={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},HC={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"};function Ese({open:e,onOpenChange:t,projects:n,providers:s,onCreate:o}){const{t:r}=ne(),a=we(P=>P.approvalReviewer),l=we(P=>P.lastApprovalMode),c=Na(),d=ko(P=>P.snapshot),u=m.useMemo(()=>dO(a,c,Fl(d),l),[a,l,c,d]),[h,p]=m.useState(null),[f,g]=m.useState(null),[x,v]=m.useState(null),[y,b]=m.useState(u),[w,C]=m.useState(!1),[_,N]=m.useState("medium");m.useEffect(()=>{e&&(p(null),g(null),v(null),b(u))},[e,u]);const k=n.find(P=>P.id===h)?.id??n[0]?.id??"",S=s.find(P=>P.id===f)??s[0]??{id:"",models:[]},A=S.models.find(P=>P.id===x)?.id??S.models[0]?.id??"",T=!!(k&&S.id&&A),I=()=>{T&&(we.getState().setLastApprovalMode(y),o({projectId:k,providerId:S.id,modelId:A,approvalMode:y,...w?{reasoningEnabled:!0,thinkingLevel:_}:{}}),t(!1))};return i.jsx(xn,{open:e,onOpenChange:t,children:i.jsxs(vn,{className:"max-w-md",children:[i.jsxs(bn,{children:[i.jsx(wn,{children:r("New remote conversation")}),i.jsx(Rs,{children:r("The conversation runs on the remote computer with its projects, models and keys.")})]}),i.jsxs(An,{className:"space-y-4",children:[i.jsx(Za,{label:r("Project"),children:i.jsxs(bs,{items:n.map(P=>({value:P.id,label:FC(P)})),value:k,onValueChange:P=>p(P),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:n.map(P=>i.jsx(rs,{value:P.id,children:FC(P)},P.id))})]})}),i.jsx(Za,{label:r("Provider"),children:i.jsxs(bs,{items:s.map(P=>({value:P.id,label:P.name})),value:S.id,onValueChange:P=>{g(P),v(null)},children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:s.map(P=>i.jsx(rs,{value:P.id,children:P.name},P.id))})]})}),i.jsx(Za,{label:r("Model"),children:i.jsxs(bs,{items:S.models.map(P=>({value:P.id,label:P.label??P.id})),value:A,onValueChange:P=>v(P),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:S.models.map(P=>i.jsx(rs,{value:P.id,children:P.label??P.id},P.id))})]})}),i.jsx(Za,{label:r("Approval mode"),children:i.jsxs(bs,{items:Object.keys(gd).map(P=>({value:P,label:r(gd[P])})),value:y,onValueChange:P=>b(P),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:Object.keys(gd).map(P=>i.jsx(rs,{value:P,children:r(gd[P])},P))})]})}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:r("Reasoning")}),i.jsx(pi,{checked:w,onCheckedChange:C})]}),w&&i.jsx(Za,{label:r("Thinking level"),children:i.jsxs(bs,{items:Jf.map(P=>({value:P,label:r(HC[P])})),value:_,onValueChange:P=>N(P),children:[i.jsx(ws,{className:"w-full",children:i.jsx(ys,{})}),i.jsx(Ss,{zIndex:yn.DROPDOWN_IN_MODAL,children:Jf.map(P=>i.jsx(rs,{value:P,children:r(HC[P])},P))})]})})]}),i.jsxs(ls,{children:[i.jsx(me,{variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(me,{size:"sm",disabled:!T,onClick:I,children:r("Create")})]})]})})}function Za({label:e,children:t}){return i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:e}),t]})}function Pse(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 Ase(e){return Jf.includes(e??"")?e:"medium"}function Mse(e){const{t}=ne(),{node:n,sessionId:s,entry:o,view:r,syncing:a}=e,l=m.useRef(null),c=r?.status==="running",d=m.useMemo(()=>r?[...r.messages.entries()].sort((v,y)=>v[0]-y[0]):[],[r]),u=m.useMemo(()=>d.map(([,v])=>v),[d]),h=m.useMemo(()=>Sr(u,c,[],o?.cwd,{pendingApprovals:r?.approvals,compaction:r?.compaction,compactionNoticeAt:uO(d.map(([v])=>v),r?.compactionNoticeAt)}),[u,d,c,o?.cwd,r?.approvals,r?.compaction,r?.compactionNoticeAt]);m.useEffect(()=>{l.current?.isAtBottom()&&l.current.pinToBottom()},[h]);const p=m.useMemo(()=>({sessionId:s,canRewind:!1,canRetry:!1}),[s]),f=m.useMemo(()=>Pse(e.providers),[e.providers]),g=o&&!o.parentId,x=n.hostOnline?a&&s?t("Syncing…"):null:n.connected?t("Remote desktop is offline"):t("Connecting…");return i.jsx(Fh.Provider,{value:p,children:i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[i.jsxs("header",{className:"flex h-9 shrink-0 items-center gap-2 border-b px-3",children:[i.jsx(hO,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:n.label}),i.jsx(pO,{node:n}),o&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-muted-foreground/50",children:"/"}),i.jsx("span",{className:"min-w-0 truncate text-sm",children:o.title||t("New conversation")}),o.projectName&&i.jsx("span",{className:"truncate font-mono text-muted-foreground text-xs",children:o.projectName})]}),i.jsx("div",{className:"flex-1"}),x&&i.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground",children:x})]}),e.tabGroup&&i.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 py-1",children:[i.jsx(BC,{active:s===e.tabGroup.parent.id,label:e.tabGroup.parent.title||t("New conversation"),status:e.tabGroup.parent.status,onClick:()=>e.onSelectTab(e.tabGroup.parent.id),icon:i.jsx(Cr,{className:"h-3 w-3 shrink-0"})}),e.tabGroup.children.map(v=>i.jsx(BC,{active:s===v.id,icon:i.jsx(Ws,{className:"h-3 w-3 shrink-0"}),label:v.title||"coworker",status:v.status,onClick:()=>e.onSelectTab(v.id)},v.id))]}),s===null?i.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-1 px-6 text-center",children:[i.jsx("p",{className:"font-medium text-lg",children:n.label}),i.jsx("p",{className:"text-muted-foreground text-sm",children:n.hostOnline?t("Select a conversation on the left, or create one"):x??""})]}):i.jsx(Bh,{ref:l,items:h,busy:c||r===null,loading:!c&&r===null,running:c,error:void 0,emptyTitle:o?.projectName||n.label,historyLoading:e.historyLoading,hasOlder:e.hasOlder,onStartReached:e.hasOlder?e.onLoadOlder:void 0},s),s!==null&&i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:Ni,children:[r?.retry&&i.jsx(Yh,{retry:r.retry}),i.jsx(Fv,{sessionId:s,tasks:r?.tasks??[],subagents:r?.subagents??[]},s),i.jsx(Rh,{approvals:r?.approvals??[],onRespond:e.onApproval}),i.jsx(Lh,{asks:r?.asks??[],onAnswer:e.onAsk}),i.jsx(zv,{commands:[],running:c,busy:c,locked:(r?.approvals??[]).length>0,focusKey:`${n.nodeId}:${s}`,toolbar:g&&o?i.jsx(xh,{providers:f,providerId:o.providerId??"",modelId:o.modelId??"",reasoningEnabled:o.reasoningEnabled??!1,thinkingLevel:Ase(o.thinkingLevel),onSelect:e.onSetModel,onReasoningChange:e.onSetReasoning,onThinkingChange:e.onSetThinking}):i.jsx("span",{className:"text-[11px] text-muted-foreground",children:o?.modelId??""}),onSend:v=>!v.text.trim()&&v.images.length===0?!1:(e.onSend(v.text,v.images),l.current?.scrollToBottom(),!0),onAbort:e.onAbort})]})})]})})}function BC({active:e,icon:t,label:n,status:s,onClick:o}){return i.jsxs("button",{type:"button",onClick:o,className:W("flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",e?"bg-muted text-foreground":"text-muted-foreground hover:bg-muted/50"),children:[t,i.jsx("span",{className:"max-w-32 truncate",children:n}),i.jsx("span",{className:W("h-1.5 w-1.5 shrink-0 rounded-full",s==="running"?"animate-pulse bg-brand":s==="failed"?"bg-destructive":"bg-muted-foreground/30")})]})}function qu(e){return[...e].sort((t,n)=>(n.updatedAt??0)-(t.updatedAt??0))}function XE(e){const t=n=>(n.pendingAskCount??0)>0||(n.pendingApprovalCount??0)>0;return[...e.filter(t),...e.filter(n=>!t(n))]}function Rse(e,t){const n=qu(e),s=new Map(n.map(r=>[r.id,r])),o=[];for(const r of t){const a=s.get(r);a&&(o.push(a),s.delete(r))}return[...o,...XE([...s.values()])]}function VC(e){return XE([...qu(e.filter(t=>t.pinned)),...qu(e.filter(t=>!t.pinned))])}const kf="flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function Lse({width:e,node:t,catalog:n,pinnedOrder:s,projects:o,groups:r=[],activeId:a,canCreate:l,onSelect:c,onNewConversation:d,onAddProject:u}){const{t:h,locale:p}=ne(),[f,g]=m.useState(In),[x,v]=m.useState(""),[y,b]=m.useState({}),[w,C]=m.useState(!1),[_,N]=m.useState(()=>Date.now());m.useEffect(()=>{const H=setInterval(()=>N(Date.now()),6e4);return()=>clearInterval(H)},[]);const k=f===In||f===ps||r.some(H=>H.id===f)?f:In,S=o.filter(H=>H.archived).map(H=>H.id),A=Vr(o,r,S,k),T=new Set(A.map(H=>H.id)),I=x.trim().toLowerCase(),P=m.useMemo(()=>n.filter(H=>!H.parentId&&(!I||H.title.toLowerCase().includes(I))),[n,I]),D=Rse(P.filter(H=>H.pinned&&!H.archived&&(!H.projectId||T.has(H.projectId))),s),O=qu(P.filter(H=>H.archived?k===In?!0:!!(H.projectId&&T.has(H.projectId)):!1)),z=P.filter(H=>!H.archived),R=new Set(o.map(H=>H.id)),$=VC(z.filter(H=>!R.has(H.projectId))),X=(H,te)=>i.jsxs("button",{type:"button",onClick:()=>c(H.id),className:W("group flex w-full items-center gap-2 rounded-lg py-1.5 pr-2 pl-4 text-left text-sm transition-colors",a===H.id?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted/60"),children:[i.jsx("span",{className:W("h-2 w-2 shrink-0 rounded-full",H.status==="running"&&"animate-pulse bg-brand",H.status==="failed"&&"bg-destructive",H.status==="idle"&&(H.unread?"bg-emerald-500":"bg-muted-foreground/30"))}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[H.title||h("New conversation"),te&&i.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:te})]}),H.updatedAt!==void 0&&i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/80 tabular-nums",children:$o(H.updatedAt,p,_)})]},H.id);return i.jsxs("aside",{className:"flex shrink-0 flex-col overflow-hidden border-r bg-background",style:{width:e},children:[i.jsx("div",{className:W("shrink-0 px-2 py-2",r.length===0&&"border-b"),children:i.jsxs("div",{className:"relative",children:[i.jsx(si,{className:"pointer-events-none absolute top-1/2 left-2.5 z-10 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Zt,{value:x,onChange:H=>v(H.target.value),placeholder:h("Search conversations..."),className:"h-8 border-transparent bg-muted/60 text-xs shadow-none ring-brand/15 before:hidden has-focus-visible:border-brand/45 [&_input]:pl-8"})]})}),r.length>0&&i.jsx("div",{className:"shrink-0 border-b px-2 pb-2",children:i.jsxs(bs,{items:[{value:In,label:h("All")},...r.slice().sort((H,te)=>H.order-te.order).map(H=>({value:H.id,label:H.name})),{value:ps,label:h("Ungrouped")}],value:k,onValueChange:H=>{H&&g(H)},children:[i.jsx(ws,{className:"w-full",size:"sm",children:i.jsx(ys,{})}),i.jsxs(Ss,{children:[i.jsx(rs,{value:In,children:h("All")}),r.slice().sort((H,te)=>H.order-te.order).map(H=>i.jsx(rs,{value:H.id,children:H.name},H.id)),i.jsx(rs,{value:ps,children:h("Ungrouped")})]})]})}),i.jsxs("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto p-2",children:[!t.hostOnline&&n.length===0&&i.jsx("p",{className:"rounded-lg border border-dashed px-3 py-6 text-center text-muted-foreground text-sm",children:t.connected?h("Remote desktop is offline"):h("Connecting…")}),t.hostOnline&&o.length===0&&i.jsx("p",{className:"rounded-lg border border-dashed px-3 py-6 text-center text-muted-foreground text-sm",children:h("The remote desktop has no projects yet")}),D.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-2",children:[i.jsx(hi,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"font-medium text-sm",children:h("Pinned")})]}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:D.map(H=>X(H,H.projectName))})]}),(k===In&&r.length>0?M_(o,r,S).flatMap(H=>{const te=y[`g:${H.groupId}`]===!0;return[{kind:"header",section:H,foldedSection:te},...te?[]:H.projects.map(V=>({kind:"project",project:V}))]}):A.map(H=>({kind:"project",project:H}))).map(H=>{if(H.kind==="header")return i.jsxs("button",{type:"button",onClick:()=>b(q=>({...q,[`g:${H.section.groupId}`]:!q[`g:${H.section.groupId}`]})),className:"flex h-7 w-full items-center gap-1 rounded-md px-2 text-left text-xs font-medium text-muted-foreground",children:[i.jsx(un,{className:W("h-3.5 w-3.5 shrink-0 transition-transform duration-150",!H.foldedSection&&"rotate-90")}),H.section.group?.emoji&&i.jsx("span",{className:"shrink-0 text-sm",children:H.section.group.emoji}),H.section.group?.color&&i.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:H.section.group.color}}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:H.section.group?.name??h("Ungrouped")}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/70",children:H.section.projects.length})]},`hdr-${H.section.groupId}`);const{project:te}=H,V=VC(z.filter(q=>q.projectId===te.id&&!q.pinned));if(I&&V.length===0)return null;const Y=y[te.id]===!0;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>b(q=>({...q,[te.id]:!Y})),className:"flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60",children:[Y?i.jsx(un,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx($n,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:YE(te)}),te.sshHost&&i.jsx("span",{className:"shrink-0 rounded bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"ssh"})]}),!Y&&i.jsxs("div",{className:"flex flex-col gap-y-0.5",children:[V.length===0&&i.jsx("p",{className:"px-4 py-1.5 text-muted-foreground text-xs",children:h("No conversations")}),V.map(q=>X(q))]})]},te.id)}),$.length>0&&i.jsxs("div",{children:[i.jsx("div",{className:"px-2 py-2 font-medium text-sm",children:h("Other")}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:$.map(H=>X(H))})]}),O.length>0&&i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>C(H=>!H),className:"flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60",children:[i.jsx(Oi,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:h("Archived")}),i.jsx("span",{className:"text-[10px] text-muted-foreground",children:O.length})]}),w&&i.jsx("div",{className:"flex flex-col gap-y-0.5",children:O.map(H=>X(H,H.projectName))})]})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[i.jsx(R_,{}),i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.nodes.openSettings(t.nodeId)},disabled:!t.hostOnline,className:W(kf,!t.hostOnline&&"opacity-40"),title:h("Node settings"),children:i.jsx(mi,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:u,disabled:!t.hostOnline,className:W(kf,!t.hostOnline&&"opacity-40"),title:h("Add project"),children:i.jsx(Nu,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:d,disabled:!l,className:W(kf,!l&&"opacity-40"),title:h("New remote conversation"),children:i.jsx(ZN,{className:"h-4 w-4"})})]})]})}function Ose({nodeId:e,sidebarWidth:t}){const n=os(b=>b.nodes.find(w=>w.nodeId===e)),s=os(b=>b.byNode[e])??zse,o=os(b=>b.selectSession),r=os(b=>b.send),a=os(b=>b.requestHistory),l=os(b=>b.spawn),[c,d]=m.useState(!1),[u,h]=m.useState(!1),p=s.activeSessionId,f=m.useMemo(()=>s.catalog.find(b=>b.id===p),[s.catalog,p]),g=m.useMemo(()=>{if(!f)return;const b=f.parentId?s.catalog.find(C=>C.id===f.parentId):f;if(!b)return;const w=s.catalog.filter(C=>C.parentId===b.id);return w.length>0?{parent:b,children:w}:void 0},[s.catalog,f]),x=p?s.sessions[p]??null:null,v=!!(x&&x.messages.size>0&&Math.min(...x.messages.keys())>0);if(!n)return null;const y=b=>r(e,b);return i.jsxs(i.Fragment,{children:[i.jsx(Lse,{width:t,node:n,catalog:s.catalog,pinnedOrder:s.pinnedOrder,projects:s.projects,groups:s.groups,activeId:p,canCreate:n.hostOnline&&s.projects.length>0,onSelect:b=>o(e,b),onNewConversation:()=>d(!0),onAddProject:()=>h(!0)}),i.jsx(Mse,{node:n,sessionId:p,entry:f,tabGroup:g,view:x,syncing:s.sync.state==="syncing",providers:s.providers,hasOlder:v,historyLoading:!!(p&&s.historyPending.has(p)),onLoadOlder:()=>p&&a(e,p),onSelectTab:b=>o(e,b),onSend:(b,w)=>{p&&y({type:x?.status==="running"?"steer":"prompt",sessionId:p,text:b,...w.length?{images:w}:{}})},onAbort:()=>p&&y({type:"abort",sessionId:p}),onApproval:(b,w)=>p&&y({type:"approval-respond",sessionId:p,requestId:b,decision:w}),onAsk:(b,w)=>p&&y({type:"ask-respond",sessionId:p,requestId:b,answer:w}),onSetModel:(b,w)=>p&&y({type:"set-model",sessionId:p,providerId:b,modelId:w}),onSetReasoning:b=>p&&y({type:"set-reasoning",sessionId:p,enabled:b}),onSetThinking:b=>p&&y({type:"set-thinking",sessionId:p,level:b})}),i.jsx(Ese,{open:c,onOpenChange:d,projects:s.projects,providers:s.providers,onCreate:b=>l(e,b)}),i.jsx(Cse,{nodeId:e,open:u,onOpenChange:h})]})}const zse=fO(),jf=["welcome","provider","skill","mcp","instruction","preset","agentType","done"];function Gse(){const{t:e}=ne();Og();const t=we(N=>N.setOnboarded),n=Na(),s=we(N=>N.skills),o=we(N=>N.mcpServers),r=we(N=>N.instructions),a=we(N=>N.presets),[l,c]=m.useState(0),[d,u]=m.useState(null),[h,p]=m.useState(!1),[f,g]=m.useState(!1),[x,v]=m.useState(!1),y=jf[l],b=()=>t(!0),w=()=>c(N=>Math.min(jf.length-1,N+1)),C=()=>c(N=>Math.max(0,N-1)),_={provider:{icon:gO,title:e("Model Providers"),desc:e("Add a provider subscription or API Key, or import providers from local AI apps"),count:n.length,onImport:()=>g(!0),importLabel:e("Add model or provider"),secondary:{label:e("Import from local apps"),onClick:()=>p(!0)}},skill:{icon:ii,title:e("Skills"),desc:e("Import skills from Claude Code, Codex or Cursor"),count:s.length,onImport:()=>u("skill"),importLabel:e("Scan and import")},mcp:{icon:tj,title:e("MCP Servers"),desc:e("Import MCP servers configured in local AI apps"),count:o.length,onImport:()=>u("mcp"),importLabel:e("Scan and import")},instruction:{icon:ou,title:e("Instruction Files"),desc:e("Import global instruction files configured in local AI tools"),count:r.length,onImport:()=>u("instruction"),importLabel:e("Scan and import")}};return i.jsxs("div",{className:"fixed inset-0 z-[45] flex items-center justify-center bg-black/40 backdrop-blur-sm","data-enso-float":"",children:[i.jsxs("div",{className:"relative flex w-[32rem] max-w-[90vw] flex-col rounded-2xl border bg-popover p-6 shadow-xl",children:[i.jsx("button",{type:"button",onClick:b,className:"absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground","aria-label":e("Close"),children:i.jsx(dn,{className:"h-4 w-4"})}),i.jsx("div",{className:"mb-5 flex items-center gap-1.5",children:jf.map((N,k)=>i.jsx("span",{className:W("h-1 flex-1 rounded-full transition-colors",k<=l?"bg-primary":"bg-muted")},N))}),y==="welcome"&&i.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:i.jsx(mO,{className:"h-6 w-6 text-primary"})}),i.jsx("h2",{className:"text-lg font-semibold",children:e("Welcome to EnsoCode")}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("Import your providers and assets from local AI apps to get started. You can skip any step.")})]}),y!=="welcome"&&y!=="done"&&y!=="preset"&&y!=="agentType"&&i.jsx($C,{..._[y],importedLabel:e("{{count}} imported",{count:_[y].count})}),y==="preset"&&i.jsx($C,{icon:ou,title:e("Presets"),desc:e("Bundle skills, MCP servers and an instruction file into a preset (optional)"),count:a.length,onImport:()=>v(!0),importedLabel:e("{{count}} presets",{count:a.length}),importLabel:e("New preset")}),y==="agentType"&&i.jsxs("div",{className:"flex flex-col gap-3 py-2",children:[i.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:i.jsx(Ws,{className:"h-6 w-6 text-muted-foreground"})}),i.jsx("h2",{className:"text-lg font-semibold",children:e("Agent types")}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("Give subagents their own model, skills and MCP servers (optional)")})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto pr-1",children:i.jsx(xO,{})})]}),y==="done"&&i.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:i.jsx(Yn,{className:"h-6 w-6 text-primary"})}),i.jsx("h2",{className:"text-lg font-semibold",children:e("All set")}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("You can always import more from Settings later.")})]}),i.jsxs("div",{className:"mt-6 flex items-center justify-between",children:[i.jsx(me,{variant:"ghost",size:"sm",onClick:C,disabled:l===0,children:e("Back")}),i.jsxs("div",{className:"flex items-center gap-2",children:[y!=="done"&&y!=="welcome"&&i.jsx(me,{variant:"ghost",size:"sm",onClick:w,children:e("Skip")}),y==="done"?i.jsx(me,{size:"sm",onClick:b,children:e("Done")}):i.jsx(me,{size:"sm",onClick:w,children:e(y==="welcome"?"Get started":"Next")})]})]})]}),i.jsx(vO,{open:h,onOpenChange:p}),i.jsx(bO,{open:f,onOpenChange:g}),d&&i.jsx(wO,{kind:d,open:!0,onOpenChange:N=>!N&&u(null)}),x&&i.jsx(yO,{preset:null,onClose:()=>v(!1)})]})}function $C({icon:e,title:t,desc:n,count:s,onImport:o,importedLabel:r,importLabel:a,secondary:l}){return i.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:i.jsx(e,{className:"h-6 w-6 text-muted-foreground"})}),i.jsx("h2",{className:"text-lg font-semibold",children:t}),i.jsx("p",{className:"text-sm text-muted-foreground",children:n}),i.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[i.jsx(me,{variant:"outline",size:"sm",onClick:o,children:a}),l&&i.jsx(me,{variant:"ghost",size:"sm",onClick:l.onClick,children:l.label})]}),s>0&&i.jsx("p",{className:"text-xs text-primary",children:r})]})}const _f=["project","all","all-including-archived"];function WC(e,t=!1){const n=_f.length,s=_f.indexOf(e);return _f[(s+(t?n-1:1))%n]??"all"}const Fse=50,Nf=160,Hse=["title","project","id","body","tool"],Wv=/[\p{Letter}\p{Number}]+/gu,Bse=/[\u3400-\u9fff]/u,Vse=/[^.!?。?!]+[.!?。?!]?/g;function JE(e){return e.toLowerCase().match(Wv)??[]}function Uv(e){return Bse.test(e)}function ZE(e){return JE(e)}function QE(e,t){if(t.length===0)return!1;const n=e.toLowerCase(),s=JE(e);return t.every(o=>Uv(o)?n.includes(o):s.some(r=>r.startsWith(o)))}function eP(e,t){return e.isDraftEmpty?!1:t.scope==="project"?e.projectId===t.currentProjectId&&!e.archived:t.scope==="all"?!e.archived:!0}function $se(e,t){const n=e.toLowerCase(),s=ZE(t);if(s.length===0||n.length!==e.length)return[{text:e,match:!1}];const o=[];for(const l of s){if(Uv(l)){for(let c=n.indexOf(l);c>=0;c=n.indexOf(l,c+1))o.push([c,c+l.length]);continue}for(const c of n.matchAll(Wv))c.index!==void 0&&c[0].startsWith(l)&&o.push([c.index,c.index+l.length])}if(o.length===0)return[{text:e,match:!1}];o.sort((l,c)=>l[0]-c[0]);const r=[];let a=0;for(const[l,c]of o){if(c<=a)continue;const d=Math.max(l,a);d>a&&r.push({text:e.slice(a,d),match:!1});const u=r.at(-1);u?.match&&d===a?u.text+=e.slice(d,c):r.push({text:e.slice(d,c),match:!0}),a=c}return a<e.length&&r.push({text:e.slice(a),match:!1}),r}function Wse(e,t){const n=e.toLowerCase();let s=-1;for(const o of t){if(Uv(o)){const r=n.indexOf(o);r>=0&&(s<0||r<s)&&(s=r);continue}for(const r of e.matchAll(Wv))if(r[0].toLowerCase().startsWith(o)&&r.index!==void 0){(s<0||r.index<s)&&(s=r.index);break}}return s}function Use(e,t){if(e.length<=Nf)return e;const n=Math.max(0,Wse(e,t)),s=Math.min(n,Math.max(0,e.length-Nf));return e.slice(s,s+Nf)}function Kse(e){return(e.match(Vse)??[]).map(t=>t.trim()).filter(Boolean)}function qse(e,t){const n=Kse(e);if(n.length<=1)return;const s=n.findIndex(r=>QE(r,t));if(s<0)return;const o=[...[n[s-1],n[s-2]].filter(r=>!!r),...[n[s+1],n[s+2]].filter(r=>!!r)];return o.length>0?o:void 0}function Yse(e,t,n,s){return e.title.trim().toLowerCase()===n.trim().toLowerCase()?0:t==="title"?1:e.projectId===s?2:3}function Xse(e,t,n){const s=n.trim().toLowerCase(),o=e.fields.filter(r=>r.field==="id"?r.text.toLowerCase().startsWith(s):QE(r.text,t));if(o.length!==0)return Hse.map(r=>o.find(a=>a.field===r)).find(r=>!!r)}function tP(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:Yse(e,t.field,n,s),lastActiveAt:e.lastActiveAt}}function nP(e,t=Fse){return e.sort((n,s)=>n.rank-s.rank||s.lastActiveAt-n.lastActiveAt),e.slice(0,t).map(({rank:n,lastActiveAt:s,...o})=>o)}function Jse(e,t,n){const s=ZE(t);if(s.length===0)return[];const o=[];for(const r of e){if(!eP(r,n))continue;const a=Xse(r,s,t);if(!a)continue;const l=qse(a.text,s);o.push(tP(r,{field:a.field,snippet:Use(a.text,s),nearby:l},t,n.currentProjectId))}return nP(o,n.limit)}function Zse(e,t,n,s,o){const r=new Map(e.map(l=>[l.conversationId,l])),a=new Map;for(const l of[...t,...n]){const c=r.get(l.conversationId);!c||a.has(l.conversationId)||!eP(c,o)||a.set(l.conversationId,tP(c,l,s,o.currentProjectId))}return nP([...a.values()],o.limit)}const Qse=120,eie=8;function sP(e){return!e.started&&!e.sessionFile&&e.messages.length===0}function Pl(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt??e.createdAt}function tie(e,t){return e.filter(n=>n.parentId||sP(n)||n.archived&&t.scope!=="all-including-archived"?!1:t.scope!=="project"||n.projectId===t.currentProjectId).sort((n,s)=>Pl(s)-Pl(n)).slice(0,t.limit??eie)}function nie(e){return e.content.map(t=>t.type==="text"?t.text:"").join(`
99
- `).trim()}function sie(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,Qse);return`${t.join(" ")} ${n}`.trim()}function iie(e){const t=[{field:"title",text:e.title},{field:"project",text:e.projectName},{field:"id",text:e.conversationId},{field:"body",text:e.messages.map(nie).filter(Boolean).join(`
100
- `)}],n=e.messages.map(sie).filter(s=>!!s);return n.length>0&&t.push({field:"tool",text:n.join(`
101
- `)}),{conversationId:e.conversationId,projectId:e.projectId,projectName:e.projectName,title:e.title,lastActiveAt:e.lastActiveAt,fields:t,...e.archived?{archived:!0}:{},...e.isDraftEmpty?{isDraftEmpty:!0}:{},...e.isCurrent?{isCurrent:!0}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.coworkerId?{coworkerId:e.coworkerId}:{}}}const UC=[],oie={project:"This project",all:"All projects","all-including-archived":"Include archived"},rie={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 Qa({text:e,query:t}){let n=0;return $se(e,t).map(s=>{const o=n;return n+=s.text.length,s.match?i.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:s.text},o):i.jsx("span",{children:s.text},o)})}function Gr({icon:e,title:t,badges:n,detail:s,meta:o}){return i.jsxs(i.Fragment,{children:[i.jsx(e,{className:"size-4 shrink-0 text-muted-foreground"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:"truncate",children:t}),n]}),s&&i.jsx("p",{className:"truncate text-muted-foreground text-xs",children:s})]}),o&&i.jsx("span",{className:"max-w-48 shrink-0 truncate text-muted-foreground text-xs",children:o})]})}function aie(e){try{return new URL(e).host||e}catch{return e}}function lie({open:e,onOpenChange:t}){const{t:n,locale:s}=ne(),[o,r]=m.useState(""),[a,l]=m.useState("all"),[c,d]=m.useState(),[u,h]=m.useState([]),[p,f]=m.useState([]),g=ie(U=>U.conversations),x=ie(U=>U.activeId),v=we(U=>U.projects),y=we(U=>U.scratchSessionsEnabled),b=we(U=>U.keybindings),w=(x?g[x]?.projectId:void 0)??v[0]?.id??"",C=o.trim(),_=`${a}
102
- ${w}
103
- ${C}`,N=c?.key===_?c.hits:UC,k=m.useMemo(()=>{if(!e)return[];const oe=(x?g[x]:void 0)?.activeTabId,Se=oe&&g[oe]?oe:x;return Object.values(g).map(G=>{const Q=v.find(ae=>ae.id===G.projectId);return!y&&Q?.kind==="scratch"?null:iie({conversationId:G.id,projectId:G.projectId,projectName:Q?Ns(Q):G.projectId,title:G.title,lastActiveAt:Pl(G),archived:G.archived,isDraftEmpty:sP(G),isCurrent:G.id===Se,parentConversationId:G.parentId,coworkerId:G.parentId?G.id:void 0,messages:G.messages})}).filter(G=>G!==null)},[x,g,e,v,y]),S=m.useMemo(()=>C?Jse(k,o,{currentProjectId:w,scope:a}):UC,[w,k,o,a,C]),A=m.useMemo(()=>e?tie(Object.values(g),{scope:a,currentProjectId:w}):[],[g,w,e,a]),T=SO(p),I=m.useMemo(()=>C?CO(T,o,{translate:U=>n(U)}):[],[o,T,n,C]),P=m.useMemo(()=>o.trim()?kO(u,o):[],[u,o]),D=m.useMemo(()=>jO(u),[u]);m.useEffect(()=>{if(!e)return;const U=oe=>{oe.key==="Escape"&&(oe.preventDefault(),oe.stopPropagation(),t(!1))};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[t,e]),m.useEffect(()=>{if(!e){r(""),l("all"),d(void 0);return}window.electronAPI.browser.listSearchableTabs().then(U=>h(U.filter(oe=>!L_(oe.conversationId)))).catch(()=>{h([])}),window.electronAPI.sshConnections.list().then(U=>{f(U.map(oe=>({id:oe.id,name:oe.name})))}).catch(()=>{f([])})},[e]),m.useEffect(()=>{if(!e||!C||!w)return;let U=!1;const oe=window.setTimeout(()=>{window.electronAPI.workspaceSearch.query({query:C,currentProjectId:w,scope:a}).then(Se=>{U||d({key:_,hits:Se.hits})}).catch(()=>{U||d({key:_,hits:[]})})},80);return()=>{U=!0,window.clearTimeout(oe)}},[_,w,e,a,C]);const O=m.useMemo(()=>Zse(k,S,N,o,{currentProjectId:w,scope:a}),[N,w,k,S,o,a]),z=U=>{const oe=ie.getState(),Se=oe.conversations[U.conversationId],G=U.parentConversationId??Se?.parentId;if(G&&oe.conversations[G]?(oe.selectConversation(G),oe.selectTab(G,U.coworkerId??U.conversationId)):oe.selectConversation(U.conversationId),t(!1),U.field==="body"||U.field==="tool"){const Q=o.trim().split(/\s+/).find(Boolean);Q&&window.setTimeout(()=>uE(Q),0)}},R=U=>{const oe=ie.getState(),G=oe.conversations[U.conversationId]?.parentId;G&&oe.conversations[G]?(oe.selectConversation(G),oe.selectTab(G,U.conversationId)):oe.selectConversation(U.conversationId),ix({conversationId:U.conversationId,tabId:U.tabId,title:U.title||n("Browser")}),t(!1)},$=U=>{window.electronAPI.window.openSettings({category:U.category,rowId:U.id}),t(!1)},X=C.length>0&&O.length===0&&P.length===0&&I.length===0,H=U=>{U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),t(!1))},te=U=>{if(U.key!=="Tab"||U.nativeEvent.isComposing){H(U);return}U.altKey||U.ctrlKey||U.metaKey||(U.preventDefault(),l(oe=>WC(oe,U.shiftKey)))},V=Fi(b),Y=Date.now(),q=U=>{const oe=v.find(Se=>Se.id===U);return oe?Ns(oe):""},ee=(U,oe)=>[q(U),oe?$o(oe,s,Y):""].filter(Boolean).join(" · "),ge=(U,oe)=>i.jsxs(i.Fragment,{children:[U&&i.jsx(pa,{size:"sm",className:"bg-brand/10 text-brand",children:n("Current")}),oe&&i.jsx(pa,{variant:"outline",size:"sm",children:n("Archived")})]}),Ce=U=>{const oe=g[U.conversationId],Se=U.parentConversationId??oe?.parentId;let G=Cr;Se&&(G=oe?.child?.mode==="task"?ex:Ws);const Q=U.title||oe?.child?.agentInstanceName||oe?.coworkerName||n("New conversation"),ae=Se?g[Se]?.title||n("New conversation"):void 0,Z=U.field==="body"||U.field==="tool"||U.field==="id"?U.snippet.replace(/\s+/g," ").trim():"";return i.jsx(Gr,{icon:G,title:i.jsxs(i.Fragment,{children:[ae&&i.jsxs("span",{className:"text-muted-foreground",children:[ae," › "]}),i.jsx(Qa,{text:Q,query:o})]}),badges:ge(U.isCurrent,U.archived),detail:Z&&i.jsx(Qa,{text:Z,query:o}),meta:ee(U.projectId,oe?Pl(oe):void 0)})},Re=(U,oe)=>i.jsx(cr,{value:oe,className:"gap-2.5",onClick:()=>R(U),children:i.jsx(Gr,{icon:bo,title:i.jsx(Qa,{text:U.title||U.url,query:o}),meta:aie(U.url)})},oe),fe=i.jsxs("button",{type:"button",tabIndex:-1,"data-search-scope":a,title:n("Switch scope"),className:"flex h-7 shrink-0 items-center gap-1.5 rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-accent hover:text-foreground",onPointerDown:U=>{U.preventDefault(),U.stopPropagation(),l(oe=>WC(oe,U.shiftKey))},children:[n(oie[a]),i.jsx(di,{className:"h-4 min-w-4 text-[10px]",children:"⇥"})]});return i.jsx(tE,{open:e,onOpenChange:t,children:i.jsx(nE,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:H,children:i.jsxs(sE,{children:[i.jsx(iE,{placeholder:n("Search conversations, browser tabs, settings…"),value:o,onChange:U=>r(U.currentTarget.value),onKeyDown:te,endAddon:fe}),i.jsxs(aE,{children:[X&&i.jsxs(rE,{children:[n("No matching results"),a!=="all-including-archived"&&i.jsxs("span",{className:"mt-2 flex items-center justify-center gap-1.5 text-xs",children:[i.jsx(di,{children:"⇥"}),n(a==="project"?"Search all projects":"Include archived")]})]}),i.jsxs(oE,{children:[!C&&i.jsxs(i.Fragment,{children:[A.length>0&&i.jsxs(Or,{children:[i.jsx(zr,{children:n("Recent")}),A.map(U=>i.jsx(cr,{value:`recent-${U.id}`,className:"gap-2.5",onClick:()=>z({conversationId:U.id,field:"title",snippet:U.title}),children:i.jsx(Gr,{icon:Cr,title:U.title||n("New conversation"),badges:ge(U.id===x,U.archived),meta:ee(U.projectId,Pl(U))})},U.id))]}),D.length>0&&i.jsxs(Or,{children:[i.jsx(zr,{children:n("Browser")}),D.map(U=>Re(U,`recent-browser-${U.tabId}`))]}),i.jsxs(Or,{children:[i.jsx(zr,{children:n("Actions")}),i.jsxs(cr,{value:"new-conversation",className:"gap-2.5",onClick:()=>{w&&ie.getState().newConversation(w),t(!1)},children:[i.jsx(Gr,{icon:as,title:i.jsxs(i.Fragment,{children:[n("New conversation"),q(w)&&i.jsxs("span",{className:"text-muted-foreground",children:[" · ",q(w)]})]})}),i.jsx(JS,{children:ti(V["new-conversation"])})]}),i.jsxs(cr,{value:"open-settings",className:"gap-2.5",onClick:()=>{window.electronAPI.window.openSettings(),t(!1)},children:[i.jsx(Gr,{icon:mi,title:n("Open settings")}),i.jsx(JS,{children:ti(V["open-settings"])})]})]})]}),C.length>0&&O.length>0&&i.jsxs(Or,{children:[i.jsx(zr,{children:n("Conversations")}),O.map(U=>i.jsx(cr,{value:`conv-${U.conversationId}-${U.field}`,className:"gap-2.5",onClick:()=>z(U),children:Ce(U)},`${U.conversationId}-${U.field}`))]}),C.length>0&&P.length>0&&i.jsxs(Or,{children:[i.jsx(zr,{children:n("Browser")}),P.map(U=>Re(U,`browser-${U.tabId}`))]}),C.length>0&&I.length>0&&i.jsxs(Or,{children:[i.jsx(zr,{children:n("Settings")}),I.map(U=>i.jsx(cr,{value:`settings-${U.id}`,className:"gap-2.5",onClick:()=>$(U),children:i.jsx(Gr,{icon:mi,title:i.jsx(Qa,{text:n(U.title),query:o}),detail:U.description&&i.jsx(Qa,{text:n(U.description),query:o}),meta:n(rie[U.category]??U.category)})},U.id))]})]})]}),i.jsxs(lE,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(l_,{children:[i.jsx(di,{children:"↑"}),i.jsx(di,{children:"↓"})]}),n("Navigate")]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(di,{children:"↵"}),n("Open")]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(di,{children:"⇥"}),n("Switch scope")]})]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(di,{children:"esc"}),n("Close")]})]})]})})})}var iP,oP=class{constructor(){}},Zs=class extends oP{constructor(e,t,n,s){super(),this.viewId=e,this.groupId=t,this.panelId=n,this.tabGroupId=s}},Al=class extends oP{constructor(e,t){super(),this.viewId=e,this.paneId=t}},So=class rP{constructor(){}static getInstance(){return rP.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)}};iP=So;So.INSTANCE=new iP;function On(){const e=So.getInstance();if(e.hasData(Zs.prototype))return e.getData(Zs.prototype)[0]}function el(){const e=So.getInstance();if(e.hasData(Al.prototype))return e.getData(Al.prototype)[0]}let cn;(function(e){e.NONE={dispose:()=>{}};function t(n){return{dispose:()=>{n()}}}e.from=t})(cn||(cn={}));var pt=class{get isDisposed(){return this._isDisposed}constructor(...e){this._isDisposed=!1,this._disposables=new Set(e)}addDisposables(...e){e.forEach(t=>this._disposables.add(t))}removeDisposable(e){this._disposables.delete(e)}dispose(){this._isDisposed||(this._isDisposed=!0,this._disposables.forEach(e=>e.dispose()),this._disposables.clear())}},Bn=class{constructor(){this._disposable=cn.NONE}get value(){return this._disposable===cn.NONE?void 0:this._disposable}set value(e){this._disposable&&this._disposable.dispose(),this._disposable=e}dispose(){this._disposable&&(this._disposable.dispose(),this._disposable=cn.NONE)}};let ei;(function(e){e.any=(...t)=>n=>{const s=t.map(o=>o(n));return{dispose:()=>{s.forEach(o=>{o.dispose()})}}}})(ei||(ei={}));var Kv=class{constructor(){this._defaultPrevented=!1}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}},aP=class{constructor(){this._isAccepted=!1}get isAccepted(){return this._isAccepted}accept(){this._isAccepted=!0}},cie=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()}},KC=class lP{static create(){var t;return new lP((t=new Error("listener stacktrace").stack)!==null&&t!==void 0?t:"")}constructor(t){this.value=t}print(){console.warn("dockview: stacktrace",this.value)}},die=class{constructor(e,t){this.callback=e,this.stacktrace=t}},ve=class Ii{static setLeakageMonitorEnabled(t){t!==Ii.ENABLE_TRACKING&&Ii.MEMORY_LEAK_WATCHER.clear(),Ii.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 die(t,Ii.ENABLE_TRACKING?KC.create():void 0);return this._listeners.push(s),{dispose:()=>{const o=this._listeners.indexOf(s);o>-1&&this._listeners.splice(o,1)}}},Ii.ENABLE_TRACKING&&Ii.MEMORY_LEAK_WATCHER.add(this._event,KC.create())),this._event}fire(t){var n;if(this._pauseTokens!==void 0&&this._pauseTokens.size>0)return;!((n=this.options)===null||n===void 0)&&n.replay&&(this._last=t);const s=this._listeners,o=s.length;if(o!==0){if(o===1){s[0].callback(t);return}for(const r of s.slice())r.callback(t)}}pause(){var t;const n={};return(t=this._pauseTokens)!==null&&t!==void 0||(this._pauseTokens=new Set),this._pauseTokens.add(n),cn.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&&(Ii.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=[]),Ii.ENABLE_TRACKING&&this._event&&Ii.MEMORY_LEAK_WATCHER.delete(this._event))}};ve.ENABLE_TRACKING=!1;ve.MEMORY_LEAK_WATCHER=new cie;function ct(e,t,n,s){return e.addEventListener(t,n,s),{dispose:()=>{e.removeEventListener(t,n,s)}}}var qC=class{constructor(){this._onFired=new ve,this._currentFireCount=0,this._queued=!1,this.onEvent=e=>{const t=this._currentFireCount;return this._onFired.event(()=>{this._currentFireCount>t&&e()})}}fire(){this._currentFireCount++,!this._queued&&(this._queued=!0,queueMicrotask(()=>{this._queued=!1,this._onFired.fire()}))}dispose(){this._onFired.dispose()}},uie=class extends pt{constructor(e){super(),this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._value=null,this.addDisposables(this._onDidChange,Ir(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 Ir(e,t){const n=new ResizeObserver(s=>{requestAnimationFrame(()=>{const o=s[0];t(o)})});return n.observe(e),{dispose:()=>{n.unobserve(e),n.disconnect()}}}const ji=(e,...t)=>{for(const n of t)e.classList.contains(n)&&e.classList.remove(n)},_i=(e,...t)=>{for(const n of t)e.classList.contains(n)||e.classList.add(n)},Qe=(e,t,n)=>{const s=e.classList.contains(t);n&&!s&&e.classList.add(t),!n&&s&&e.classList.remove(t)};function bg(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}function cP(e){return new hie(e)}var hie=class extends pt{constructor(e){super(),this._onDidFocus=new ve,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new ve,this.onDidBlur=this._onDidBlur.event,this.addDisposables(this._onDidFocus,this._onDidBlur);let t=bg(document.activeElement,e),n=!1;const s=()=>{n=!1,t||(t=!0,this._onDidFocus.fire())},o=()=>{t&&(n=!0,globalThis.setTimeout(()=>{n&&(n=!1,t=!1,this._onDidBlur.fire())},0))};this._refreshStateHandler=()=>{bg(document.activeElement,e)!==t&&(t?o():s())},this.addDisposables(ct(e,"focus",s,!0)),this.addDisposables(ct(e,"blur",o,!0))}refreshState(){this._refreshStateHandler()}};const dP="dv-quasiPreventDefault";function uP(e){e[dP]=!0}function YC(e){return e[dP]}function pie(e,t,n={}){const s=Array.from(t),{nonce:o}=n,r=typeof o=="function"?o(e):o;for(const a of s){if(a.href){const d=e.createElement("link");d.href=a.href,d.type=a.type,d.rel="stylesheet",e.head.appendChild(d);continue}let l=[];try{a.cssRules&&(l=Array.from(a.cssRules).map(d=>d.cssText))}catch(d){console.warn("dockview: failed to access stylesheet rules due to security restrictions",d)}const c=e.createDocumentFragment();for(const d of l){const u=e.createElement("style");r&&u.setAttribute("nonce",r),u.appendChild(e.createTextNode(d)),c.appendChild(u)}e.head.appendChild(c)}}function wg(e){const{left:t,top:n,width:s,height:o}=e.getBoundingClientRect();return{left:t+window.scrollX,top:n+window.scrollY,width:s,height:o}}function hP(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 fie(e,t){e.dataset.testid=t}function mie(e,t){const n=[];function s(o){if(o.nodeType===Node.ELEMENT_NODE){e.includes(o.tagName)&&n.push(o),o.shadowRoot&&s(o.shadowRoot);for(const r of o.children)s(r)}}return s(t instanceof Document?t.documentElement:t),n}function ic(e=document){const t=mie(["IFRAME","WEBVIEW"],e),n=new WeakMap;for(const s of t)n.set(s,s.style.pointerEvents),s.style.pointerEvents="none";return{release:()=>{for(const o of t){var s;o.style.pointerEvents=(s=n.get(o))!==null&&s!==void 0?s:"auto"}t.splice(0,t.length)}}}function gie(e){function t(o){const r=[];for(let a=0;a<o.classList.length;a++)r.push(o.classList.item(a));return r}let n,s=e;for(;s!==null&&(n=t(s).find(o=>o.startsWith("dockview-theme-")),typeof n!="string");)s=s.parentElement;return n}var ep=class{constructor(e){this.element=e,this._classNames=[]}setClassNames(e){for(const t of this._classNames)Qe(this.element,t,!1);this._classNames=e.split(" ").filter(t=>t.trim().length>0);for(const t of this._classNames)Qe(this.element,t,!0)}};const pP=100;function Tf(e,t){const n=wg(e),s=wg(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 xie(e){const t=new ve;let n=e.screenX,s=e.screenY,o,r=0,a=!1;const l=()=>{if(a||e.closed)return;const d=e.screenX,u=e.screenY;(d!==n||u!==s)&&(clearTimeout(o),o=setTimeout(()=>{t.fire()},pP),n=d,s=u),r=requestAnimationFrame(l)};l();const c=t.dispose.bind(t);return t.dispose=()=>{a||(a=!0,cancelAnimationFrame(r),clearTimeout(o)),c()},t}function vie(e,t){let n;return new pt(ct(e,"resize",()=>{clearTimeout(n),n=setTimeout(()=>{t()},pP)}))}function bie(e,t,n){var s;const o=(s=void 0)!==null&&s!==void 0?s:10,r=e.getBoundingClientRect(),a=t.getBoundingClientRect();let l=0,c=0;const d=r.left-a.left,u=r.top-a.top,h=r.bottom-a.bottom,p=r.right-a.right;d<o?l=o-d:p>o&&(l=-o-p),u<o?c=o-u:h>o&&(c=-h-o),(l!==0||c!==0)&&(e.style.transform=`translate(${l}px, ${c}px)`)}function wie(e){let t=e;for(;t&&(t.style.zIndex==="auto"||t.style.zIndex==="");)t=t.parentElement;return t}function po(e){if(e.length===0)throw new Error("Invalid tail call");return[e.slice(0,e.length-1),e[e.length-1]]}function fP(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 If(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))}function xd(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))}function yie(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(t(s))return n}return-1}function mP(e,t){const n=e.indexOf(t);return n>-1?(e.splice(n,1),!0):!1}const En=(e,t,n)=>t>n?t:Math.min(n,Math.max(e,t)),qv=()=>{let e=1;return{next:()=>(e++).toString()}},ai=(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 Sie=class{set size(e){this._size=e}setContainerGeometry(e,t){this._appliedStyles[e]!==t&&(this._appliedStyles[e]=t,this.container.style[e]=t)}get size(){return this._size}get cachedVisibleSize(){return this._cachedVisibleSize}get visible(){return this._cachedVisibleSize===void 0}get minimumSize(){return this.visible?this.view.minimumSize:0}get viewMinimumSize(){return this.view.minimumSize}get maximumSize(){return this.visible?this.view.maximumSize:0}get viewMaximumSize(){return this.view.maximumSize}get priority(){return this.view.priority}get snap(){return!!this.view.snap}set enabled(e){this.container.style.pointerEvents=e?"":"none"}constructor(e,t,n,s){this.container=e,this.view=t,this.disposable=s,this._cachedVisibleSize=void 0,this._appliedStyles={},typeof n=="number"?(this._size=n,this._cachedVisibleSize=void 0,e.classList.add("visible")):(this._size=0,this._cachedVisibleSize=n.cachedVisibleSize)}setVisible(e,t){if(e!==this.visible){if(e){var n;this.size=En((n=this._cachedVisibleSize)!==null&&n!==void 0?n:0,this.viewMinimumSize,this.viewMaximumSize),this._cachedVisibleSize=void 0}else this._cachedVisibleSize=typeof t=="number"?t:this.size,this.size=0;this.container.classList.toggle("visible",e),this.view.setVisible&&this.view.setVisible(e)}}dispose(){return this.disposable.dispose(),this.view}};function XC(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 _s;(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})(_s||(_s={}));var _r=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,ji(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,Qe(this.element,"dv-splitview-disabled",e)}get margin(){return this._margin}set margin(e){this._margin=e,Qe(this.element,"dv-splitview-has-margin",e!==0)}constructor(e,t){var n,s;this.container=e,this.viewItems=[],this.sashes=[],this._size=0,this._orthogonalSize=0,this._contentSize=0,this._proportions=void 0,this._startSnappingEnabled=!0,this._endSnappingEnabled=!0,this._disabled=!1,this._margin=0,this._onDidSashEnd=new ve,this.onDidSashEnd=this._onDidSashEnd.event,this._onDidAddView=new ve,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new ve,this.onDidRemoveView=this._onDidRemoveView.event,this.resize=(o,r,a=this.viewItems.map(f=>f.size),l,c,d=Number.NEGATIVE_INFINITY,u=Number.POSITIVE_INFINITY,h,p)=>{if(o<0||o>this.viewItems.length)return 0;const f=ai(o,-1),g=ai(o+1,this.viewItems.length);if(c)for(const T of c)If(f,T),If(g,T);if(l)for(const T of l)xd(f,T),xd(g,T);const x=f.reduce((T,I)=>T+this.viewItems[I].minimumSize-a[I],0),v=f.reduce((T,I)=>T+this.viewItems[I].maximumSize-a[I],0),y=g.length===0?Number.POSITIVE_INFINITY:g.reduce((T,I)=>T+a[I]-this.viewItems[I].minimumSize,0),b=g.length===0?Number.NEGATIVE_INFINITY:g.reduce((T,I)=>T+a[I]-this.viewItems[I].maximumSize,0),w=Math.max(x,b),C=Math.min(y,v);let _=!1;if(h){const T=this.viewItems[h.index],I=r>=h.limitDelta;_=I!==T.visible,T.setVisible(I,h.size)}if(!_&&p){const T=this.viewItems[p.index],I=r<p.limitDelta;_=I!==T.visible,T.setVisible(I,p.size)}if(_)return this.resize(o,r,a,l,c,d,u);const N=En(r,w,C);let k=0,S=N;for(const T of f){const I=this.viewItems[T],P=a[T],D=En(P+S,I.minimumSize,I.maximumSize),O=D-P;k+=O,S-=O,I.size=D}let A=k;for(const T of g){const I=this.viewItems[T],P=a[T],D=En(P-A,I.minimumSize,I.maximumSize),O=D-P;A+=O,I.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((o,r)=>{const a=o.visible===void 0||o.visible?o.size:{type:"invisible",cachedVisibleSize:o.size},l=o.view;this.addView(l,a,r,!0)}),this._contentSize=this.viewItems.reduce((o,r)=>o+r.size,0),this.saveProportions())}style(e){e?.separatorBorder==="transparent"?(ji(this.element,"dv-separator-border"),this.element.style.removeProperty("--dv-separator-border")):(_i(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=ai(this.viewItems.length).filter(a=>a!==e),s=[...n.filter(a=>this.viewItems[a].priority==="low"),e],o=n.filter(a=>this.viewItems[a].priority==="high"),r=this.viewItems[e];t=Math.round(t),t=En(t,r.minimumSize,Math.min(r.maximumSize,this._size)),r.size=t,this.relayout(s,o)}getViews(){return this.viewItems.map(e=>e.view)}onDidChange(e,t){const n=this.viewItems.indexOf(e);if(n<0||n>=this.viewItems.length)return;t=typeof t=="number"?t:e.size,t=En(t,e.minimumSize,e.maximumSize),e.size=t;const s=ai(this.viewItems.length).filter(a=>a!==n),o=[...s.filter(a=>this.viewItems[a].priority==="low"),n],r=s.filter(a=>this.viewItems[a].priority==="high");this.relayout([...o,n],r)}addView(e,t=_s.Distribute,n=this.viewItems.length,s){const o=document.createElement("div");o.className="dv-view",o.appendChild(e.element);let r;typeof t=="number"?r=t:t.type==="split"?r=this.getViewSize(t.index)/2:t.type==="invisible"?r={cachedVisibleSize:t.cachedVisibleSize}:r=e.minimumSize;const a=e.onDidChange(c=>this.onDidChange(l,c.size)),l=new Sie(o,e,r,{dispose:()=>{a.dispose(),o.remove()}});if(n===this.viewItems.length?this.viewContainer.appendChild(o):this.viewContainer.insertBefore(o,this.viewContainer.children.item(n)),this.viewItems.splice(n,0,l),this.viewItems.length>1){const c=document.createElement("div");c.className="dv-sash";const d=h=>{var p;for(const R of this.viewItems)R.enabled=!1;const f=(p=c.ownerDocument)!==null&&p!==void 0?p:document,g=ic(f),x=this._orientation==="HORIZONTAL"?h.clientX:h.clientY,v=yie(this.sashes,R=>R.container===c),y=this.viewItems.map(R=>R.size);let b,w;const C=ai(v,-1),_=ai(v+1,this.viewItems.length),N=C.reduce((R,$)=>R+(this.viewItems[$].minimumSize-y[$]),0),k=C.reduce((R,$)=>R+(this.viewItems[$].viewMaximumSize-y[$]),0),S=_.length===0?Number.POSITIVE_INFINITY:_.reduce((R,$)=>R+(y[$]-this.viewItems[$].minimumSize),0),A=_.length===0?Number.NEGATIVE_INFINITY:_.reduce((R,$)=>R+(y[$]-this.viewItems[$].viewMaximumSize),0),T=Math.max(N,A),I=Math.min(S,k),P=this.findFirstSnapIndex(C),D=this.findFirstSnapIndex(_);if(typeof P=="number"){const R=this.viewItems[P],$=Math.floor(R.viewMinimumSize/2);b={index:P,limitDelta:R.visible?T-$:T+$,size:R.size}}if(typeof D=="number"){const R=this.viewItems[D],$=Math.floor(R.viewMinimumSize/2);w={index:D,limitDelta:R.visible?I+$:I-$,size:R.size}}const O=R=>{const $=(this._orientation==="HORIZONTAL"?R.clientX:R.clientY)-x;this.resize(v,$,y,void 0,void 0,T,I,b,w),this.distributeEmptySpace(),this.layoutViews()},z=()=>{for(const R of this.viewItems)R.enabled=!0;g.release(),this.saveProportions(),f.removeEventListener("pointermove",O),f.removeEventListener("pointerup",z),f.removeEventListener("pointercancel",z),f.removeEventListener("contextmenu",z),this._onDidSashEnd.fire(void 0)};f.addEventListener("pointermove",O),f.addEventListener("pointerup",z),f.addEventListener("pointercancel",z),f.addEventListener("contextmenu",z)};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=En(n,a.minimumSize,a.maximumSize);const s=ai(this.viewItems.length),o=s.filter(a=>this.viewItems[a].priority==="low"),r=s.filter(a=>this.viewItems[a].priority==="high");this.relayout(o,r)}removeView(e,t,n=!1){const s=this.viewItems.splice(e,1)[0];if(s.dispose(),this.viewItems.length>=1){const o=Math.max(e-1,0);this.sashes.splice(o,1)[0].disposable()}return n||this.relayout(),t?.type==="distribute"&&this.distributeViewSizes(),this._onDidRemoveView.fire(s.view),s.view}getViewCachedVisibleSize(e){if(e<0||e>=this.viewItems.length)throw new Error("Index out of bounds");return this.viewItems[e].cachedVisibleSize}moveView(e,t){const n=this.getViewCachedVisibleSize(e),s=n===void 0?this.getViewSize(e):_s.Invisible(n),o=this.removeView(e,void 0,!0);this.addView(o,s,t)}layout(e,t){const n=Math.max(this.size,this._contentSize);if(this.size=e,this.orthogonalSize=t,this.proportions){let s=0;for(let o=0;o<this.viewItems.length;o++){const r=this.viewItems[o],a=this.proportions[o];typeof a=="number"?s+=a:e-=r.size}for(let o=0;o<this.viewItems.length;o++){const r=this.viewItems[o],a=this.proportions[o];typeof a=="number"&&s>0&&(r.size=En(Math.round(a*e/s),r.minimumSize,r.maximumSize))}}else{const s=ai(this.viewItems.length),o=s.filter(a=>this.viewItems[a].priority==="low"),r=s.filter(a=>this.viewItems[a].priority==="high");this.resize(this.viewItems.length-1,e-n,void 0,o,r)}this.distributeEmptySpace(),this.layoutViews()}relayout(e,t){const n=this.viewItems.reduce((s,o)=>s+o.size,0);this.resize(this.viewItems.length-1,this._size-n,void 0,e,t),this.distributeEmptySpace(),this.layoutViews(),this.saveProportions()}distributeEmptySpace(e){let t=0;for(const r of this.viewItems)t+=r.size;let n=this.size-t;if(n===0)return;const s=ai(this.viewItems.length-1,-1);let o=!1;for(const r of this.viewItems)if(r.priority==="low"||r.priority==="high"){o=!0;break}if(o){const r=s.filter(l=>this.viewItems[l].priority==="low"),a=s.filter(l=>this.viewItems[l].priority==="high");for(const l of a)If(s,l);for(const l of r)xd(s,l)}typeof e=="number"&&xd(s,e);for(let r=0;n!==0&&r<s.length;r++){const a=this.viewItems[s[r]],l=En(a.size+n,a.minimumSize,a.maximumSize),c=l-a.size;n-=c,a.size=l}}saveProportions(){this.proportionalLayout&&this._contentSize>0&&(this._proportions=this.viewItems.map(e=>e.visible?e.size/this._contentSize:void 0))}layoutViews(){let e=0,t=0;for(const c of this.viewItems)e+=c.size,c.visible&&t++;if(this._contentSize=e,this.updateSashEnablement(),this.viewItems.length===0)return;const n=Math.max(0,t-1),s=this.margin*n/Math.max(1,t);let o=0;const r=[],a=4;let l=0;this.viewItems.forEach((c,d)=>{o+=this.viewItems[d].size,r.push(o),l+=c.visible?1:0;const u=c.visible?c.size-s:0,h=Math.max(0,l-1),p=d===0||h===0?0:r[d-1]+h/n*s;if(d<this.viewItems.length-1){const f=c.visible?p+u-a/2+this.margin/2:p,g=this.sashes[d];this._orientation==="HORIZONTAL"&&XC(g,`${f}px`,"0px"),this._orientation==="VERTICAL"&&XC(g,"0px",`${f}px`)}this._orientation==="HORIZONTAL"&&(c.setContainerGeometry("width",`${u}px`),c.setContainerGeometry("left",`${p}px`),c.setContainerGeometry("top",""),c.setContainerGeometry("height","")),this._orientation==="VERTICAL"&&(c.setContainerGeometry("height",`${u}px`),c.setContainerGeometry("top",`${p}px`),c.setContainerGeometry("width",""),c.setContainerGeometry("left","")),c.view.layout(c.size-s,this._orthogonalSize)})}findFirstSnapIndex(e){for(const t of e){const n=this.viewItems[t];if(n.visible&&n.snap)return t}for(const t of e){const n=this.viewItems[t];if(n.visible&&n.maximumSize-n.minimumSize>0)return;if(!n.visible&&n.snap)return t}}updateSashEnablement(){if(this.sashes.length===0)return;let e=!1;const t=this.viewItems.map(l=>e=l.size-l.minimumSize>0||e);e=!1;const n=this.viewItems.map(l=>e=l.maximumSize-l.size>0||e),s=[...this.viewItems].reverse();e=!1;const o=s.map(l=>e=l.size-l.minimumSize>0||e).reverse();e=!1;const r=s.map(l=>e=l.maximumSize-l.size>0||e).reverse();let a=0;for(let l=0;l<this.sashes.length;l++){const c=this.sashes[l],d=this.viewItems[l];a+=d.size;const u=!(t[l]&&r[l+1]),h=!(n[l]&&o[l+1]);if(u&&h){const p=ai(l,-1),f=ai(l+1,this.viewItems.length),g=this.findFirstSnapIndex(p),x=this.findFirstSnapIndex(f),v=typeof g=="number"&&!this.viewItems[g].visible,y=typeof x=="number"&&!this.viewItems[x].visible;v&&o[l]&&(a>0||this.startSnappingEnabled)?this.updateSash(c,1):y&&t[l]&&(a<this._contentSize||this.endSnappingEnabled)?this.updateSash(c,0):this.updateSash(c,2)}else u&&!h?this.updateSash(c,1):!u&&h?this.updateSash(c,0):this.updateSash(c,3)}}updateSash(e,t){Qe(e.container,"dv-disabled",t===2),Qe(e.container,"dv-enabled",t===3),Qe(e.container,"dv-maximum",t===0),Qe(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 yg=Object.keys({orientation:void 0,descriptor:void 0,proportionalLayout:void 0,styles:void 0,margin:void 0,disableAutoResizing:void 0,className:void 0});var JC=class extends pt{get onDidAddView(){return this.splitview.onDidAddView}get onDidRemoveView(){return this.splitview.onDidRemoveView}get minimumSize(){return this.splitview.minimumSize}get maximumSize(){return this.splitview.maximumSize}get orientation(){return this.splitview.orientation}get size(){return this.splitview.size}get orthogonalSize(){return this.splitview.orthogonalSize}constructor(e,t){var n;super(),this.paneItems=[],this.skipAnimation=!1,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._orientation=(n=t.orientation)!==null&&n!==void 0?n:"VERTICAL",this.element=document.createElement("div"),this.element.className="dv-pane-container",e.appendChild(this.element),this.splitview=new _r(this.element,{orientation:this._orientation,proportionalLayout:!1,descriptor:t.descriptor}),this.getPanes().forEach(s=>{const o=new pt(s.onDidChangeExpansionState(()=>{this.setupAnimation(),this._onDidChange.fire(void 0)})),r={pane:s,disposable:{dispose:()=>{o.dispose()}}};this.paneItems.push(r),s.orthogonalSize=this.splitview.orthogonalSize}),this.addDisposables(this._onDidChange,this.splitview.onDidSashEnd(()=>{this._onDidChange.fire(void 0)}),this.splitview.onDidAddView(()=>{this._onDidChange.fire()}),this.splitview.onDidRemoveView(()=>{this._onDidChange.fire()}))}setViewVisible(e,t){this.splitview.setViewVisible(e,t)}addPane(e,t,n=this.splitview.length,s=!1){const o=e.onDidChangeExpansionState(()=>{this.setupAnimation(),this._onDidChange.fire(void 0)}),r={pane:e,disposable:{dispose:()=>{o.dispose()}}};this.paneItems.splice(n,0,r),e.orthogonalSize=this.splitview.orthogonalSize,this.splitview.addView(e,t,n,s)}getViewSize(e){return this.splitview.getViewSize(e)}getViewCachedVisibleSize(e){return this.splitview.getViewCachedVisibleSize(e)}getPanes(){return this.splitview.getViews()}removePane(e,t){const n=this.paneItems.splice(e,1)[0];return this.splitview.removeView(e),t?.skipDispose||(n.disposable.dispose(),n.pane.dispose()),n}moveView(e,t){if(e===t)return;const n=this.removePane(e,{skipDispose:!0});n.disposable.dispose(),this.skipAnimation=!0;try{this.addPane(n.pane,n.pane.size,t,!1)}finally{this.skipAnimation=!1}}layout(e,t){this.splitview.layout(e,t)}setupAnimation(){this.skipAnimation||(this.animationTimer&&(clearTimeout(this.animationTimer),this.animationTimer=void 0),_i(this.element,"dv-animated"),this.animationTimer=setTimeout(()=>{this.animationTimer=void 0,ji(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()}},ds=class{get minimumWidth(){return this.view.minimumWidth}get maximumWidth(){return this.view.maximumWidth}get minimumHeight(){return this.view.minimumHeight}get maximumHeight(){return this.view.maximumHeight}get priority(){return this.view.priority}get snap(){return this.view.snap}get minimumSize(){return this.orientation==="HORIZONTAL"?this.minimumHeight:this.minimumWidth}get maximumSize(){return this.orientation==="HORIZONTAL"?this.maximumHeight:this.maximumWidth}get minimumOrthogonalSize(){return this.orientation==="HORIZONTAL"?this.minimumWidth:this.minimumHeight}get maximumOrthogonalSize(){return this.orientation==="HORIZONTAL"?this.maximumWidth:this.maximumHeight}get orthogonalSize(){return this._orthogonalSize}get size(){return this._size}get element(){return this.view.element}get width(){return this.orientation==="HORIZONTAL"?this.orthogonalSize:this.size}get height(){return this.orientation==="HORIZONTAL"?this.size:this.orthogonalSize}constructor(e,t,n,s=0){this.view=e,this.orientation=t,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._orthogonalSize=n,this._size=s,this._disposable=this.view.onDidChange(o=>{o?this._onDidChange.fire({size:this.orientation==="VERTICAL"?o.width:o.height,orthogonalSize:this.orientation==="VERTICAL"?o.height:o.width}):this._onDidChange.fire({})})}setVisible(e){this.view.setVisible&&this.view.setVisible(e)}layout(e,t){this._size=e,this._orthogonalSize=t,this.view.layout(this.width,this.height)}dispose(){this._onDidChange.dispose(),this._disposable.dispose()}},Jn=class Sg extends pt{get width(){return this.orientation==="HORIZONTAL"?this.size:this.orthogonalSize}get height(){return this.orientation==="HORIZONTAL"?this.orthogonalSize:this.size}get minimumSize(){if(this._cachedMinimumSize===void 0){let t=0;for(let n=0;n<this.children.length;n++)this.splitview.isViewVisible(n)&&(t=Math.max(t,this.children[n].minimumOrthogonalSize));this._cachedMinimumSize=t}return this._cachedMinimumSize}get maximumSize(){if(this._cachedMaximumSize===void 0){let t=Number.POSITIVE_INFINITY;for(let n=0;n<this.children.length;n++)this.splitview.isViewVisible(n)&&(t=Math.min(t,this.children[n].maximumOrthogonalSize));this._cachedMaximumSize=t}return this._cachedMaximumSize}get minimumOrthogonalSize(){return this.splitview.minimumSize}get maximumOrthogonalSize(){return this.splitview.maximumSize}get orthogonalSize(){return this._orthogonalSize}get size(){return this._size}get minimumWidth(){return this.orientation==="HORIZONTAL"?this.minimumOrthogonalSize:this.minimumSize}get minimumHeight(){return this.orientation==="HORIZONTAL"?this.minimumSize:this.minimumOrthogonalSize}get maximumWidth(){return this.orientation==="HORIZONTAL"?this.maximumOrthogonalSize:this.maximumSize}get maximumHeight(){return this.orientation==="HORIZONTAL"?this.maximumSize:this.maximumOrthogonalSize}get priority(){var t;return(t=this._cachedPriority)!==null&&t!==void 0||(this._cachedPriority=this.computePriority()),this._cachedPriority}computePriority(){if(this.children.length===0)return"normal";let t=!1,n=!1;for(const o of this.children){var s;const r=(s=o.priority)!==null&&s!==void 0?s:"normal";r==="high"?t=!0:r==="low"&&(n=!0)}return t?"high":n?"low":"normal"}invalidateCachedSizes(){this._cachedMinimumSize=void 0,this._cachedMaximumSize=void 0,this._cachedPriority=void 0}get disabled(){return this.splitview.disabled}set disabled(t){this.splitview.disabled=t}get margin(){return this.splitview.margin}set margin(t){this.splitview.margin=t,this.children.forEach(n=>{n instanceof Sg&&(n.margin=t)})}constructor(t,n,s,o,r,a,l,c){if(super(),this.orientation=t,this.proportionalLayout=n,this.styles=s,this._childrenDisposable=cn.NONE,this.children=[],this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidVisibilityChange=new ve,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._orthogonalSize=r,this._size=o,this.element=document.createElement("div"),this.element.className="dv-branch-node",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 _r(this.element,{orientation:this.orientation,descriptor:d,proportionalLayout:n,styles:s,margin:l})}else this.splitview=new _r(this.element,{orientation:this.orientation,proportionalLayout:n,styles:s,margin:l}),this.splitview.layout(this.size,this.orthogonalSize);this.disabled=a,this.addDisposables(this._onDidChange,this._onDidVisibilityChange,this.splitview.onDidSashEnd(()=>{this._onDidChange.fire({})})),this.setupChildrenEvents()}setVisible(t){}isChildVisible(t){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.isViewVisible(t)}setChildVisible(t,n){if(t<0||t>=this.children.length)throw new Error("Invalid index");if(this.splitview.isViewVisible(t)===n)return;const s=this.splitview.contentSize===0;this.splitview.setViewVisible(t,n),this.invalidateCachedSizes();const o=this.splitview.contentSize===0;(n&&s||!n&&o)&&this._onDidVisibilityChange.fire({visible:n})}moveChild(t,n){if(t===n)return;if(t<0||t>=this.children.length)throw new Error("Invalid from index");t<n&&n--,this.splitview.moveView(t,n);const s=this._removeChild(t);this._addChild(s,n)}getChildSize(t){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.getViewSize(t)}resizeChild(t,n){if(t<0||t>=this.children.length)throw new Error("Invalid index");this.splitview.resizeView(t,n)}layout(t,n){this._size=n,this._orthogonalSize=t,this.splitview.layout(n,t)}addChild(t,n,s,o){if(s<0||s>this.children.length)throw new Error("Invalid index");this.splitview.addView(t,n,s,o),this._addChild(t,s)}getChildCachedVisibleSize(t){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.getViewCachedVisibleSize(t)}removeChild(t,n){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.removeView(t,n),this._removeChild(t)}_addChild(t,n){this.children.splice(n,0,t),this.setupChildrenEvents()}_removeChild(t){const[n]=this.children.splice(t,1);return this.setupChildrenEvents(),n}setupChildrenEvents(){this.invalidateCachedSizes(),this._childrenDisposable.dispose(),this._childrenDisposable=new pt(ei.any(...this.children.map(t=>t.onDidChange))(t=>{this.invalidateCachedSizes(),this._onDidChange.fire({size:t.orthogonalSize})}),...this.children.map((t,n)=>t instanceof Sg?t.onDidVisibilityChange(({visible:s})=>{this.setChildVisible(n,s)}):cn.NONE))}dispose(){this._childrenDisposable.dispose(),this.splitview.dispose(),this.children.forEach(t=>t.dispose()),super.dispose()}};function Cg(e,t){if(e instanceof ds)return e;if(e instanceof Jn)return Cg(e.children[t?e.children.length-1:0],t);throw new Error("invalid node")}function gP(e,t,n){if(e instanceof Jn){const s=new Jn(e.orientation,e.proportionalLayout,e.styles,t,n,e.disabled,e.margin);for(let o=e.children.length-1;o>=0;o--){const r=e.children[o];s.addChild(gP(r,r.size,r.orthogonalSize),r.size,0,!0)}return s}else return new ds(e.view,e.orientation,n)}function kg(e,t,n){if(e instanceof Jn){const s=new Jn(Ri(e.orientation),e.proportionalLayout,e.styles,t,n,e.disabled,e.margin);let o=0;for(let r=e.children.length-1;r>=0;r--){const a=e.children[r],l=a instanceof Jn?a.orthogonalSize:a.size;let c=e.size===0?0:Math.round(t*l/e.size);o+=c,r===0&&(c+=t-o),s.addChild(kg(a,n,c),c,0,!0)}return s}else return new ds(e.view,Ri(e.orientation),n)}function Cie(e){const t=e.parentElement;if(!t)throw new Error("Invalid grid element");let n=t.firstElementChild,s=0;for(;n!==e&&n!==t.lastElementChild&&n;)n=n.nextElementSibling,s++;return s}function Tn(e){const t=e.parentElement;if(!t)throw new Error("Invalid grid element");if(/\bdv-grid-view\b/.test(t.className))return[];const n=Cie(t),s=t.parentElement.parentElement.parentElement;return[...Tn(s),n]}function Us(e,t,n){if(jie(e,t)===kie(n)){const[s,o]=po(t);let r=o;return(n==="right"||n==="bottom")&&(r+=1),[...s,r]}else{const s=n==="right"||n==="bottom"?1:0;return[...t,s]}}function kie(e){return e==="top"||e==="bottom"?"VERTICAL":"HORIZONTAL"}function jie(e,t){return t.length%2===0?Ri(e):e}const Ri=e=>e==="HORIZONTAL"?"VERTICAL":"HORIZONTAL";function _ie(e){return!!e.children}const jg=(e,t)=>{const n=t==="VERTICAL"?e.box.width:e.box.height;if(!_ie(e))return typeof e.cachedVisibleSize=="number"?{type:"leaf",data:e.view.toJSON(),size:e.cachedVisibleSize,visible:!1}:{type:"leaf",data:e.view.toJSON(),size:n};const s=e.children.map(o=>jg(o,Ri(t)));return typeof e.cachedVisibleSize=="number"?{type:"branch",data:s,size:e.cachedVisibleSize,visible:!1}:{type:"branch",data:s,size:n}};var xP=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=kg(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 Jn&&(n.disabled=e,t.push(...n.children))}}get margin(){return this._margin}set margin(e){this._margin=e,this.root.margin=e}maximizedView(){var e;return(e=this._maximizedNode)===null||e===void 0?void 0:e.leaf.view}hasMaximizedView(){return this._maximizedNode!==void 0}maximizeView(e){var t;const n=Tn(e.element),[s,o]=this.getNode(n);if(!(o instanceof ds)||((t=this._maximizedNode)===null||t===void 0?void 0:t.leaf)===o)return;this.hasMaximizedView()&&this.exitMaximizedView(),jg(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 ds?u!==c&&(l.isChildVisible(d)?l.setChildVisible(d,!1):r.push(u)):a(u,c)}}a(this.root,o),this._maximizedNode={leaf:o,hiddenOnMaximize:r},this._onDidMaximizedNodeChange.fire({view:o.view,isMaximized:!0})}exitMaximizedView(){if(!this._maximizedNode)return;const e=this._maximizedNode.hiddenOnMaximize;function t(s){for(let o=s.children.length-1;o>=0;o--){const r=s.children[o];r instanceof ds?e.includes(r)||s.setChildVisible(o,!0):t(r)}}t(this.root);const n=this._maximizedNode.leaf;this._maximizedNode=void 0,this._onDidMaximizedNodeChange.fire({view:n.view,isMaximized:!1})}serialize(){const e=this.maximizedView();let t;e&&(t=Tn(e.element));const n=this._onDidMaximizedNodeChange.pause();try{this.hasMaximizedView()&&this.exitMaximizedView();const s={root:jg(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 Jn(e,this.proportionalLayout,this.styles,this.root.size,this.root.orthogonalSize,this.locked,this.margin)}deserialize(e,t){const n=e.orientation,s=n==="VERTICAL"?e.height:e.width;if(this._deserialize(e.root,n,t,s),this.layout(e.width,e.height),e.maximizedNode){const o=e.maximizedNode.location,[r,a]=this.getNode(o);if(!(a instanceof ds))return;this.maximizeView(a.view)}}_deserialize(e,t,n,s){this.root=this._deserializeNode(e,t,n,s)}_deserializeNode(e,t,n,s){let o;if(e.type==="branch"){const a=e.data.map(l=>({node:this._deserializeNode(l,Ri(t),n,e.size),visible:l.visible}));o=new Jn(t,this.proportionalLayout,this.styles,e.size,s,this.locked,this.margin,a)}else{const a=n.fromJSON(e);if(typeof e.visible=="boolean"){var r;(r=a.setVisible)===null||r===void 0||r.call(a,e.visible)}o=new ds(a,t,s,e.size)}return o}get root(){return this._root}set root(e){const t=this._root;t&&(t.dispose(),this._maximizedNode=void 0,t.element.remove()),this._root=e,this.element.appendChild(this._root.element),this.disposable.value=this._root.onDidChange(n=>{this._onDidChange.fire(n)})}normalize(){if(!this._root||this._root.children.length!==1)return;const e=this.root,t=e.children[0];if(t instanceof ds)return;e.element.remove();const n=e.removeChild(0);e.dispose(),n.dispose(),this._root=gP(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 Jn(Ri(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(kg(t,t.orthogonalSize,t.size),_s.Distribute,0)}else this._root.addChild(e,_s.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 ds)return{box:s,view:e.view,cachedVisibleSize:n};const o=[];for(let r=0;r<e.children.length;r++){const a=e.children[r],l=e.getChildCachedVisibleSize(r);o.push(this._getViews(a,Ri(t),l))}return{box:s,children:o,cachedVisibleSize:n}}progmaticSelect(e,t=!1){const[n,s]=this.getNode(e);if(!(s instanceof ds))throw new TypeError("invalid location");for(let o=n.length-1;o>-1;o--){const r=n[o],a=e[o]||0;if(t?a-1>-1:a+1<r.children.length)return Cg(r.children[t?a-1:a+1],t)}return Cg(this.root,t)}constructor(e,t,n,s,o){this.proportionalLayout=e,this.styles=t,this._locked=!1,this._margin=0,this._maximizedNode=void 0,this.disposable=new Bn,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidViewVisibilityChange=new ve,this.onDidViewVisibilityChange=this._onDidViewVisibilityChange.event,this._onDidMaximizedNodeChange=new ve,this.onDidMaximizedNodeChange=this._onDidMaximizedNodeChange.event,this.element=document.createElement("div"),this.element.className="dv-grid-view",this._locked=s??!1,this._margin=o??0,this.root=new Jn(n,e,t,0,0,this.locked,this.margin)}isViewVisible(e){const[t,n]=po(e),[,s]=this.getNode(t);if(!(s instanceof Jn))throw new TypeError("Invalid from location");return s.isChildVisible(n)}setViewVisible(e,t){this.hasMaximizedView()&&this.exitMaximizedView();const[n,s]=po(e),[,o]=this.getNode(n);if(!(o instanceof Jn))throw new TypeError("Invalid from location");this._onDidViewVisibilityChange.fire(),o.setChildVisible(s,t)}moveView(e,t,n){this.hasMaximizedView()&&this.exitMaximizedView();const[,s]=this.getNode(e);if(!(s instanceof Jn))throw new TypeError("Invalid location");s.moveChild(t,n)}addView(e,t,n){this.hasMaximizedView()&&this.exitMaximizedView();const[s,o]=po(n),[r,a]=this.getNode(s);if(a instanceof Jn){const l=new ds(e,Ri(a.orientation),a.orthogonalSize);a.addChild(l,t,o)}else{const[l,...c]=[...r].reverse(),[d,...u]=[...s].reverse();let h=0;const p=l.getChildCachedVisibleSize(d);typeof p=="number"&&(h=_s.Invisible(p)),l.removeChild(d).dispose();const f=new Jn(a.orientation,this.proportionalLayout,this.styles,a.size,a.orthogonalSize,this.locked,this.margin);l.addChild(f,a.size,d);const g=new ds(a.view,l.orientation,a.size);f.addChild(g,h,0),typeof t!="number"&&t.type==="split"&&(t={type:"split",index:0});const x=new ds(e,l.orientation,a.size);f.addChild(x,t,o)}}remove(e,t){const n=Tn(e.element);return this.removeView(n,t)}removeView(e,t){this.hasMaximizedView()&&this.exitMaximizedView();const[n,s]=po(e),[o,r]=this.getNode(n);if(!(r instanceof Jn))throw new TypeError("Invalid location");const a=r.children[s];if(!(a instanceof ds))throw new TypeError("Invalid location");if(r.removeChild(s,t),a.dispose(),r.children.length!==1)return a.view;const l=r.children[0];if(o.length===0)return l instanceof ds||(r.removeChild(0,t),this.root=l),a.view;const[c,...d]=[...o].reverse(),[u,...h]=[...n].reverse(),p=r.isChildVisible(0);r.removeChild(0,t);const f=c.children.map((g,x)=>c.getChildSize(x));if(c.removeChild(u,t).dispose(),l instanceof Jn){f.splice(u,1,...l.children.map(g=>g.size));for(let g=0;g<l.children.length;g++){const x=l.children[g];c.addChild(x,x.size,u+g)}for(;l.children.length>0;)l.removeChild(0)}else{const g=new ds(l.view,Ri(l.orientation),l.size),x=p?l.orthogonalSize:_s.Invisible(l.orthogonalSize);c.addChild(g,x,u)}l.dispose();for(let g=0;g<f.length;g++)c.resizeChild(g,f[g]);return a.view}layout(e,t){const[n,s]=this.root.orientation==="HORIZONTAL"?[t,e]:[e,t];this.root.layout(n,s)}getNode(e,t=this.root,n=[]){if(e.length===0)return[n,t];if(!(t instanceof Jn))throw new TypeError("Invalid location");const[s,...o]=e;if(s<0||s>=t.children.length)throw new Error("Invalid location");const r=t.children[s];return n.push(t),this.getNode(o,r,n)}};const _g=Object.keys({disableAutoResizing:void 0,proportionalLayout:void 0,orientation:void 0,hideBorders:void 0,className:void 0});var Yv=class extends pt{get element(){return this._element}get disableResizing(){return this._disableResizing}set disableResizing(e){this._disableResizing=e}constructor(e,t=!1){super(),this._lastWidth=-1,this._lastHeight=-1,this._disableResizing=t,this._element=e,this.addDisposables(Ir(this._element,n=>{if(this.isDisposed||this.disableResizing||!this._element.offsetParent||!hP(this._element))return;const s=Math.round(n.contentRect.width),o=Math.round(n.contentRect.height);s===this._lastWidth&&o===this._lastHeight||(this._lastWidth=s,this._lastHeight=o,this.layout(s,o))}))}};const Nie=qv();function Yu(e){switch(e){case"left":return"left";case"right":return"right";case"above":return"top";case"below":return"bottom";default:return"center"}}var vP=class extends Yv{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=Nie.next(),this._groups=new Map,this._onDidRemove=new ve,this.onDidRemove=this._onDidRemove.event,this._onDidAdd=new ve,this.onDidAdd=this._onDidAdd.event,this._onDidMaximizedChange=new ve,this.onDidMaximizedChange=this._onDidMaximizedChange.event,this._onDidActiveChange=new ve,this.onDidActiveChange=this._onDidActiveChange.event,this._bufferOnDidLayoutChange=new qC,this.onDidLayoutChange=this._bufferOnDidLayoutChange.onEvent,this._onDidViewVisibilityChangeMicroTaskQueue=new qC,this.onDidViewVisibilityChangeMicroTaskQueue=this._onDidViewVisibilityChangeMicroTaskQueue.onEvent,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new ep(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this.gridview=new xP(!!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()}),cn.from(()=>{this.element.remove()}),this.gridview.onDidChange(()=>{this._bufferOnDidLayoutChange.fire()}),ei.any(this.onDidAdd,this.onDidRemove,this.onDidActiveChange)(()=>{this._bufferOnDidLayoutChange.fire()}),this._onDidMaximizedChange,this._onDidViewVisibilityChangeMicroTaskQueue,this._bufferOnDidLayoutChange)}setVisible(e,t){this.gridview.setViewVisible(Tn(e.element),t),this._bufferOnDidLayoutChange.fire()}isVisible(e){return this.gridview.isViewVisible(Tn(e.element))}updateOptions(e){if(e.proportionalLayout,e.orientation&&(this.gridview.orientation=e.orientation),"disableAutoResizing"in e){var t;this.disableResizing=(t=e.disableAutoResizing)!==null&&t!==void 0?t:!1}if("locked"in e){var n;this.locked=(n=e.locked)!==null&&n!==void 0?n:!1}if("margin"in e){var s;this.gridview.margin=(s=e.margin)!==null&&s!==void 0?s:0}if("className"in e){var o;this._classNames.setClassNames((o=e.className)!==null&&o!==void 0?o:"")}}maximizeGroup(e){this.gridview.maximizeView(e),this.doSetGroupActive(e)}isMaximizedGroup(e){return this.gridview.maximizedView()===e}exitMaximizedGroup(){this.gridview.exitMaximizedView()}hasMaximizedGroup(){return this.gridview.hasMaximizedView()}doAddGroup(e,t=[0],n,s=this.gridview){s.addView(e,n??_s.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,_s.Distribute);if(n&&!t?.skipDispose&&(n.disposable.dispose(),n.value.dispose(),this._groups.delete(e.id),this._onDidRemove.fire(e)),!t?.skipActive&&this._activeGroup===e){const o=Array.from(this._groups.values());this.doSetGroupActive(o.length>0?o[0].value:void 0)}return s}getPanel(e){var t;return(t=this._groups.get(e))===null||t===void 0?void 0:t.value}doSetGroupActive(e){this._activeGroup!==e&&(this._activeGroup&&this._activeGroup.setActive(!1),e&&e.setActive(!0),this._activeGroup=e,this._onDidActiveChange.fire(e))}removeGroup(e){this.doRemoveGroup(e)}activateNext(e){var t,n;if((t=e)!==null&&t!==void 0||(e={}),!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}const s=Tn(e.group.element),o=(n=this.gridview.next(s))===null||n===void 0?void 0:n.view;this.doSetGroupActive(o)}activatePrevious(e){var t,n;if((t=e)!==null&&t!==void 0||(e={}),!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}const s=Tn(e.group.element),o=(n=this.gridview.previous(s))===null||n===void 0?void 0:n.view;this.doSetGroupActive(o)}forceRelayout(){this.layout(this.width,this.height,!0)}layout(e,t,n){(n||e!==this.width||t!==this.height)&&(this.gridview.element.style.height=`${t}px`,this.gridview.element.style.width=`${e}px`,this.gridview.layout(e,t))}dispose(){this._onDidActiveChange.dispose(),this._onDidAdd.dispose(),this._onDidRemove.dispose();for(const e of this.groups)e.dispose();this.gridview.dispose(),super.dispose()}};function oc(e){"@babel/helpers - typeof";return oc=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},oc(e)}function Tie(e,t){if(oc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(oc(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Iie(e){var t=Tie(e,"string");return oc(t)=="symbol"?t:t+""}function Die(e,t,n){return(t=Iie(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ZC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,s)}return n}function gt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ZC(Object(n),!0).forEach(function(s){Die(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ZC(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function Eie(e,t){return e==="center"?`Tab into ${t}`:`Split ${e} of ${t}`}function Pie(e,t){return e==="center"?`docked into ${t}`:`split ${e} of ${t}`}const Xu={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)=>`${Eie(e,t)}. Arrows to change, Enter to confirm, Escape to go back.`,moveCommitted:(e,t,n)=>`${e} ${Pie(n,t)}.`,moveCancelled:()=>"Move cancelled.",moveNotAllowed:()=>"That move is not allowed.",moveFloated:e=>`${e} floated.`};function bP(e){return e?gt(gt({},Xu),e):Xu}var wP=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()}},rc=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()}},yP=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()}},Xv=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 bP(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()}},SP=class extends pt{constructor(e,t){super(),this.element=e,this.callbacks=t,this.target=null,this.registerListeners()}onDragEnter(e){this.target=e.target,this.callbacks.onDragEnter(e)}onDragOver(e){e.preventDefault(),this.callbacks.onDragOver&&this.callbacks.onDragOver(e)}onDragLeave(e){this.target===e.target&&(this.target=null,this.callbacks.onDragLeave(e))}onDragEnd(e){this.target=null,this.callbacks.onDragEnd(e)}onDrop(e){this.callbacks.onDrop(e)}registerListeners(){this.addDisposables(ct(this.element,"dragenter",e=>{this.onDragEnter(e)},!0)),this.addDisposables(ct(this.element,"dragover",e=>{this.onDragOver(e)},!0)),this.addDisposables(ct(this.element,"dragleave",e=>{this.onDragLeave(e)})),this.addDisposables(ct(this.element,"dragend",e=>{this.onDragEnd(e)})),this.addDisposables(ct(this.element,"drop",e=>{this.onDrop(e)}))}};const Aie={value:50,type:"percentage"},Mie=100,Rie=100;function Ng(){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 CP(e,t,n,s){var o,r,a;const l=(o=s?.smallWidthBoundary)!==null&&o!==void 0?o:Mie,c=(r=s?.smallHeightBoundary)!==null&&r!==void 0?r:Rie,d=t<l,u=n<c,h=e==="left",p=e==="right",f=e==="top",g=e==="bottom",x=!d&&p,v=!d&&h,y=!u&&f,b=!u&&g;let w=1;const C=(a=s?.size)!==null&&a!==void 0?a:Aie;return C.type==="percentage"?w=En(C.value,0,100)/100:((x||v)&&(w=En(0,C.value,t)/t),(y||b)&&(w=En(0,C.value,n)/n)),{isSmallX:d,isSmallY:u,isLeft:h,isRight:p,isTop:f,isBottom:g,rightClass:x,leftClass:v,topClass:y,bottomClass:b,size:w}}function kP(e,t,n,s,o){const r=CP(t,n,s,o),{rightClass:a,leftClass:l,topClass:c,bottomClass:d,size:u}=r,h={top:"0px",left:"0px",width:"100%",height:"100%"};a?(h.left=`${100*(1-u)}%`,h.width=`${100*u}%`):l?h.width=`${100*u}%`:c?h.height=`${100*u}%`:d&&(h.top=`${100*(1-u)}%`,h.height=`${100*u}%`),r.isSmallX&&r.isLeft&&(h.width="4px"),r.isSmallX&&r.isRight&&(h.left=`${n-4}px`,h.width="4px"),r.isSmallY&&r.isTop&&(h.height="4px"),r.isSmallY&&r.isBottom&&(h.top=`${s-4}px`,h.height="4px"),e.style.top=h.top,e.style.left=h.left,e.style.width=h.width,e.style.height=h.height,e.style.visibility="visible",(!e.style.transform||e.style.transform==="")&&(e.style.transform="translate3d(0, 0, 0)");const p=r.isSmallX&&(r.isLeft||r.isRight)||r.isSmallY&&(r.isTop||r.isBottom);Qe(e,"dv-drop-target-small-vertical",r.isSmallY),Qe(e,"dv-drop-target-small-horizontal",r.isSmallX),Qe(e,"dv-drop-target-selection-line",p),Qe(e,"dv-drop-target-left",r.isLeft),Qe(e,"dv-drop-target-right",r.isRight),Qe(e,"dv-drop-target-top",r.isTop),Qe(e,"dv-drop-target-bottom",r.isBottom),Qe(e,"dv-drop-target-center",t==="center")}function Lie(e,t){const n=`${Math.round(t.top)}px`,s=`${Math.round(t.left)}px`,o=`${Math.round(t.width)}px`,r=`${Math.round(t.height)}px`;return e.style.top!==n||e.style.left!==s||e.style.width!==o||e.style.height!==r}function Oie(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 jP(e){const t=CP(e.quadrant,e.width,e.height,e.overlayModel),{rightClass:n,leftClass:s,topClass:o,bottomClass:r,size:a}=t,l=e.outlineElement.getBoundingClientRect(),c=e.targetModel.getElements(void 0,e.outlineElement),d=c.root,u=c.overlay,h=d.getBoundingClientRect(),p=l.top-h.top,f=l.left-h.left,g={top:p,left:f,width:e.width,height:e.height};return n?(g.left=f+e.width*(1-a),g.width=e.width*a):s?g.width=e.width*a:o?g.height=e.height*a:r&&(g.top=p+e.height*(1-a),g.height=e.height*a),t.isSmallX&&t.isLeft&&(g.width=4),t.isSmallX&&t.isRight&&(g.left=f+e.width-4,g.width=4),t.isSmallY&&t.isTop&&(g.height=4),t.isSmallY&&t.isBottom&&(g.top=p+e.height-4,g.height=4),Lie(u,g)?(Oie(u,g),u.className=`dv-drop-target-anchor${e.className?` ${e.className}`:""}`,Qe(u,"dv-drop-target-left",t.isLeft),Qe(u,"dv-drop-target-right",t.isRight),Qe(u,"dv-drop-target-top",t.isTop),Qe(u,"dv-drop-target-bottom",t.isBottom),Qe(u,"dv-drop-target-anchor-line",t.isSmallX&&(t.isLeft||t.isRight)||t.isSmallY&&(t.isTop||t.isBottom)),Qe(u,"dv-drop-target-center",e.quadrant==="center"),c.changed&&(Qe(u,"dv-drop-target-anchor-container-changed",!0),setTimeout(()=>{Qe(u,"dv-drop-target-anchor-container-changed",!1)},10)),{boundsChanged:!0,targetChanged:c.changed}):{boundsChanged:!1,targetChanged:c.changed}}var _P=class extends Kv{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 QC(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 zie(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 Gie={value:20,type:"percentage"};var tp=class ll extends pt{get disabled(){return this._disabled}set disabled(t){this._disabled=t}get state(){return this._state}constructor(t,n){super(),this.element=t,this.options=n,this._edge=!1,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._disabled=!1,this._acceptedTargetZonesSet=new Set(this.options.acceptedTargetZones),this.dnd=new SP(this.element,{onDragEnter:()=>{var s,o;(s=(o=this.options).getOverrideTarget)===null||s===void 0||(s=s.call(o))===null||s===void 0||s.getElements()},onDragOver:s=>{var o,r,a,l,c,d,u;if(this._disabled){this.clearOwnOverlay();return}ll.ACTUAL_TARGET=this;const h=(o=(r=this.options).getOverrideTarget)===null||o===void 0?void 0:o.call(r);if(this._acceptedTargetZonesSet.size===0){this.clearOwnOverlay();return}const p=(a=(l=(c=this.options).getOverlayOutline)===null||l===void 0?void 0:l.call(c))!==null&&a!==void 0?a:this.element,f=p.offsetWidth,g=p.offsetHeight;if(f===0||g===0)return;const x=p.getBoundingClientRect(),v=((d=s.clientX)!==null&&d!==void 0?d:0)-x.left,y=((u=s.clientY)!==null&&u!==void 0?u:0)-x.top,b=this.resolvePosition(v,y,f,g,s);if(this.isAlreadyUsed(s)){this.removeDropTarget();return}if(b===null){this.clearOwnOverlay();return}const w=b.position;if(!this.options.canDisplayOverlay(s,w)){this.clearOwnOverlay();return}const C=new _P({nativeEvent:s,position:w,edge:b.edge,edgeGroup:b.edgeGroup});if(this._onWillShowOverlay.fire(C),C.defaultPrevented){this.clearOwnOverlay();return}if(this.markAsUsed(s),b.edge){this.clearOwnOverlay(),this._state=w,this._edge=!0;return}if(this._edge=!1,!h){if(!this.targetElement){const _=Ng();this.targetElement=_.dropzone,this.overlayElement=_.selection,this._state="center",p.classList.add("dv-drop-target"),p.append(this.targetElement)}}this.toggleClasses(w,f,g),this._state=w},onDragLeave:()=>{var s,o;const r=(s=(o=this.options).getOverrideTarget)===null||s===void 0?void 0:s.call(o);if(r){var a;this._state=void 0,this._edge=!1,(a=r.scheduleClear)===null||a===void 0||a.call(r);return}this.removeDropTarget()},onDragEnd:s=>{var o,r;const a=(o=(r=this.options).getOverrideTarget)===null||o===void 0?void 0:o.call(r);a&&ll.ACTUAL_TARGET===this&&this._state&&(s.stopPropagation(),this._onDrop.fire({position:this._state,nativeEvent:s,edge:this._edge})),this.removeDropTarget(),a?.clear()},onDrop:s=>{var o,r;s.preventDefault();const a=this._state,l=this._edge;this.removeDropTarget(),(o=(r=this.options).getOverrideTarget)===null||o===void 0||(o=o.call(r))===null||o===void 0||o.clear(),a&&(s.stopPropagation(),this._onDrop.fire({position:a,nativeEvent:s,edge:l}))}}),this.addDisposables(this._onDrop,this._onWillShowOverlay,this.dnd)}setTargetZones(t){this._acceptedTargetZonesSet=new Set(t)}setOverlayModel(t){this.options.overlayModel=t}dispose(){this.removeDropTarget(),super.dispose()}markAsUsed(t){t[ll.USED_EVENT_ID]=!0}isAlreadyUsed(t){const n=t[ll.USED_EVENT_ID];return typeof n=="boolean"&&n}toggleClasses(t,n,s){var o,r;const a=(o=(r=this.options).getOverrideTarget)===null||o===void 0?void 0:o.call(r);if(a){var l,c,d;jP({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&&kP(this.overlayElement,t,n,s,this.options.overlayModel)}resolvePosition(t,n,s,o,r){var a,l;const c=(a=(l=this.options).getPositionResolver)===null||a===void 0?void 0:a.call(l);if(c){const u=c.resolve({x:t,y:n,width:s,height:o,zones:this._acceptedTargetZonesSet,event:r});return u?{position:u.position,edge:!!u.edge,edgeGroup:!!u.edgeGroup}:null}const d=this.calculateQuadrant(this._acceptedTargetZonesSet,t,n,s,o);return d?{position:d,edge:!1,edgeGroup:!1}:null}calculateQuadrant(t,n,s,o,r){var a,l;const c=(a=(l=this.options.overlayModel)===null||l===void 0?void 0:l.activationSize)!==null&&a!==void 0?a:Gie;return c.type==="percentage"?NP(t,n,s,o,r,c.value):TP(t,n,s,o,r,c.value)}clearOwnOverlay(){const t=this._state!==void 0;if(this.removeDropTarget(),t){var n,s;(n=(s=this.options).getOverrideTarget)===null||n===void 0||(n=n.call(s))===null||n===void 0||n.clear()}}removeDropTarget(){if(this._state=void 0,this._edge=!1,this.targetElement){var t;(t=this.targetElement.parentElement)===null||t===void 0||t.classList.remove("dv-drop-target"),this.targetElement.remove(),this.targetElement=void 0,this.overlayElement=void 0}}showOverlay(t){var n,s,o,r,a;const l=(n=(s=this.options).getOverrideTarget)===null||n===void 0?void 0:n.call(s),c=(o=(r=(a=this.options).getOverlayOutline)===null||r===void 0?void 0:r.call(a))!==null&&o!==void 0?o:this.element,d=c.offsetWidth,u=c.offsetHeight;if(!l&&!this.targetElement){const h=Ng();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}};tp.USED_EVENT_ID="__dockview_droptarget_event_is_used__";function NP(e,t,n,s,o,r){const a=100*t/s,l=100*n/o;return e.has("left")&&a<r?"left":e.has("right")&&a>100-r?"right":e.has("top")&&l<r?"top":e.has("bottom")&&l>100-r?"bottom":e.has("center")?"center":null}function TP(e,t,n,s,o,r){return e.has("left")&&t<r?"left":e.has("right")&&t>s-r?"right":e.has("top")&&n<r?"top":e.has("bottom")&&n>o-r?"bottom":e.has("center")?"center":null}function Fie(e,t,n){var s,o,r;_i(t,"dv-dragged"),t.style.top="-9999px",((s=n?.ownerDocument)!==null&&s!==void 0?s:document).body.appendChild(t),e.setDragImage(t,(o=n?.x)!==null&&o!==void 0?o:0,(r=n?.y)!==null&&r!==void 0?r:0),setTimeout(()=>{ji(t,"dv-dragged"),t.remove()},0)}var Ju=class cl extends pt{static getInstance(){var t;return(t=cl._instance)!==null&&t!==void 0||(cl._instance=new cl),cl._instance}constructor(){super(),this._targets=new Set,this._targetByElement=new Map,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._onDragMove=new ve,this.onDragMove=this._onDragMove.event,this._onDragEnd=new ve,this.onDragEnd=this._onDragEnd.event,this.addDisposables(this._onDragStart,this._onDragMove,this._onDragEnd)}get active(){return this._active}registerTarget(t){return this._targets.add(t),this._targetByElement.set(t.element,t),{dispose:()=>{this._targets.delete(t),this._targetByElement.get(t.element)===t&&this._targetByElement.delete(t.element),this._currentTarget===t&&(this._currentTarget=void 0)}}}beginDrag(t){var n,s,o;this._active&&this.cancel();const{pointerEvent:r,source:a}=t,l=t.getData();this._active={pointerId:r.pointerId,startX:r.clientX,startY:r.clientY,source:a},this._lastPointerEvent=r,this._onDragMoveCallback=t.onDragMove,this._onDragEndCallback=t.onDragEnd,this._dataDisposable=l,this._ghost=t.ghost,this._iframeShield=ic((n=a.ownerDocument)!==null&&n!==void 0?n:document);const c={clientX:r.clientX,clientY:r.clientY,pointerEvent:r};this._onDragStart.fire(c);const d=(s=(o=a.ownerDocument)===null||o===void 0?void 0:o.defaultView)!==null&&s!==void 0?s:globalThis.window;this._moveListener=ct(d,"pointermove",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleMove(u)}),this._upListener=ct(d,"pointerup",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleEnd(u,!0)}),this._cancelListener=ct(d,"pointercancel",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleEnd(u,!1)})}cancel(){var t,n;if(!this._active)return;const s=this._onDragEndCallback,o=this._lastPointerEvent;if((t=this._currentTarget)===null||t===void 0||t.handleDragLeave(),this._teardown(),(n=this._dataDisposable)===null||n===void 0||n.dispose(),this._dataDisposable=void 0,o){const r={clientX:o.clientX,clientY:o.clientY,pointerEvent:o};s?.(r,!1),this._onDragEnd.fire(r)}}_findTargetUnder(t,n){var s,o;const r=((s=(o=this._active)===null||o===void 0?void 0:o.source.ownerDocument)!==null&&s!==void 0?s:document).elementsFromPoint(t,n);for(const a of r){let l=a;for(;l;){const c=this._targetByElement.get(l);if(c)return c;l=l.parentElement}}}_handleMove(t){var n,s;this._lastPointerEvent=t,(n=this._ghost)===null||n===void 0||n.update(t.clientX,t.clientY);const o={clientX:t.clientX,clientY:t.clientY,pointerEvent:t},r=this._findTargetUnder(t.clientX,t.clientY);if(r!==this._currentTarget){var a;(a=this._currentTarget)===null||a===void 0||a.handleDragLeave(),this._currentTarget=r}r&&r.handleDragOver(o),(s=this._onDragMoveCallback)===null||s===void 0||s.call(this,o),this._onDragMove.fire(o)}_handleEnd(t,n){const s={clientX:t.clientX,clientY:t.clientY,pointerEvent:t};if(n&&this._currentTarget)this._currentTarget.handleDrop(s);else{var o;(o=this._currentTarget)===null||o===void 0||o.handleDragLeave()}const r=this._onDragEndCallback,a=this._dataDisposable;this._teardown(),this._dataDisposable=void 0,setTimeout(()=>a?.dispose(),0),r?.(s,n),this._onDragEnd.fire(s)}_teardown(){var t,n,s,o,r;this._currentTarget=void 0,this._active=void 0,this._lastPointerEvent=void 0,this._onDragMoveCallback=void 0,this._onDragEndCallback=void 0,(t=this._ghost)===null||t===void 0||t.dispose(),this._ghost=void 0,(n=this._iframeShield)===null||n===void 0||n.release(),this._iframeShield=void 0,(s=this._moveListener)===null||s===void 0||s.dispose(),(o=this._upListener)===null||o===void 0||o.dispose(),(r=this._cancelListener)===null||r===void 0||r.dispose(),this._moveListener=void 0,this._upListener=void 0,this._cancelListener=void 0}};const Hie={value:20,type:"percentage"};var Bie=class extends pt{get disabled(){return this._disabled}set disabled(e){this._disabled=e,e&&this._removeOverlay()}get state(){return this._state}constructor(e,t){super(),this.element=e,this.options=t,this._edge=!1,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._disabled=!1,this._acceptedTargetZonesSet=new Set(t.acceptedTargetZones);const n={element:this.element,handleDragOver:s=>this._onDragOver(s),handleDragLeave:()=>this._onDragLeave(),handleDrop:s=>this._onDropEvent(s)};this.addDisposables(this._onDrop,this._onWillShowOverlay,Ju.getInstance().registerTarget(n))}setTargetZones(e){this._acceptedTargetZonesSet=new Set(e)}setOverlayModel(e){this.options.overlayModel=e}dispose(){this._removeOverlay(),super.dispose()}_onDragOver(e){var t,n,s,o,r;if(this._disabled){this._clearOwnOverlay();return}const a=(t=(n=this.options).getOverrideTarget)===null||t===void 0?void 0:t.call(n);if(this._acceptedTargetZonesSet.size===0){this._clearOwnOverlay();return}const l=(s=(o=(r=this.options).getOverlayOutline)===null||o===void 0?void 0:o.call(r))!==null&&s!==void 0?s:this.element,c=l.offsetWidth,d=l.offsetHeight;if(c===0||d===0)return;const u=l.getBoundingClientRect(),h=e.clientX-u.left,p=e.clientY-u.top,f=this._resolvePosition(h,p,c,d,e.pointerEvent);if(f===null){this._clearOwnOverlay();return}const g=f.position;if(!this.options.canDisplayOverlay(e.pointerEvent,g)){this._clearOwnOverlay();return}const x=new _P({nativeEvent:e.pointerEvent,position:g,edge:f.edge});if(this._onWillShowOverlay.fire(x),x.defaultPrevented){this._clearOwnOverlay();return}if(f.edge){this._clearOwnOverlay(),this._state=g,this._edge=!0;return}if(this._edge=!1,a){jP({outlineElement:l,targetModel:a,quadrant:g,width:c,height:d,overlayModel:this.options.overlayModel,className:this.options.className}),this._state=g;return}if(!this._targetElement){const v=Ng();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&&kP(this._overlayElement,g,c,d,this.options.overlayModel),this._state=g}_onDragLeave(){var e,t;const n=(e=(t=this.options).getOverrideTarget)===null||e===void 0?void 0:e.call(t);if(n){this._state=void 0,n.clear();return}this._removeOverlay()}_onDropEvent(e){var t,n;const s=this._state,o=this._edge,r=(t=(n=this.options).getOverrideTarget)===null||t===void 0?void 0:t.call(n);this._removeOverlay(),r?.clear(),s&&this._onDrop.fire({position:s,nativeEvent:e.pointerEvent,edge:o})}_resolvePosition(e,t,n,s,o){var r,a;const l=(r=(a=this.options).getPositionResolver)===null||r===void 0?void 0:r.call(a);if(l){const d=l.resolve({x:e,y:t,width:n,height:s,zones:this._acceptedTargetZonesSet,event:o});return d?{position:d.position,edge:!!d.edge}:null}const c=this._calculateQuadrant(e,t,n,s);return c?{position:c,edge:!1}:null}_calculateQuadrant(e,t,n,s){var o,r;const a=(o=(r=this.options.overlayModel)===null||r===void 0?void 0:r.activationSize)!==null&&o!==void 0?o:Hie;return a.type==="percentage"?NP(this._acceptedTargetZonesSet,e,t,n,s,a.value):TP(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 Vie=5,$ie=250,Wie=8;var Uie=class extends pt{constructor(e,t){var n;super(),this.element=e,this.options=t,this._disabled=!1,this._armed=!1,this._startX=0,this._startY=0,this._touchOnly=(n=t.touchOnly)!==null&&n!==void 0?n:!0,this.addDisposables(ct(this.element,"pointerdown",s=>{this._onPointerDown(s)}))}setDisabled(e){this._disabled=e,e&&this._cancelPending()}setTouchOnly(e){this._touchOnly!==e&&(this._touchOnly=e,e&&this._cancelPending())}_shouldHandle(e){var t,n;return!(this._disabled||this._touchOnly&&e.pointerType!=="touch"&&e.pointerType!=="pen"||!((t=(n=this.options).isCancelled)===null||t===void 0)&&t.call(n,e))}_onPointerDown(e){var t,n,s,o,r;if(!this._shouldHandle(e))return;this._cancelPending(),this._pendingPointerId=e.pointerId,this._startX=e.clientX,this._startY=e.clientY,this._startEvent=e;const a=e.pointerType==="touch"||e.pointerType==="pen",l=this.options.touchInitiationDelay,c=(t=typeof l=="function"?l():l)!==null&&t!==void 0?t:$ie;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:Vie,u=this.options.pressTolerance,h=(s=typeof u=="function"?u():u)!==null&&s!==void 0?s:Wie,p=(o=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&o!==void 0?o:globalThis.window;this._pendingMoveListener=ct(p,"pointermove",f=>{if(f.pointerId!==this._pendingPointerId)return;const g=f.clientX-this._startX,x=f.clientY-this._startY,v=Math.hypot(g,x);if(this._armed){v>=d&&this._beginDrag(f);return}v>h&&this._beginDrag(f)}),this._pendingUpListener=ct(p,"pointerup",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()}),this._pendingCancelListener=ct(p,"pointercancel",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()})}cancelPending(){this._cancelPending()}_cancelPending(){var e,t,n;this._pendingPointerId=void 0,this._armTimer!==void 0&&(clearTimeout(this._armTimer),this._armTimer=void 0),this._armed=!1,(e=this._pendingMoveListener)===null||e===void 0||e.dispose(),(t=this._pendingUpListener)===null||t===void 0||t.dispose(),(n=this._pendingCancelListener)===null||n===void 0||n.dispose(),this._pendingMoveListener=void 0,this._pendingUpListener=void 0,this._pendingCancelListener=void 0,this._startEvent=void 0}_beginDrag(e){var t,n,s,o,r;const a=(t=this._startEvent)!==null&&t!==void 0?t:e;this._cancelPending(),(n=(s=this.options).onDragStart)===null||n===void 0||n.call(s,a);const l=(o=(r=this.options).createGhost)===null||o===void 0?void 0:o.call(r,a);Ju.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()}},Kie=class{constructor(e){var t,n,s,o,r;this._disposed=!1,this.element=e.element,this.offsetX=(t=e.offsetX)!==null&&t!==void 0?t:0,this.offsetY=(n=e.offsetY)!==null&&n!==void 0?n:0,this.element.style.position="fixed",this.element.style.left="0px",this.element.style.top="0px",this.element.style.pointerEvents="none",this.element.style.zIndex="99999",this.element.style.opacity=String((s=e.opacity)!==null&&s!==void 0?s:.8),this.element.style.willChange="transform",this.element.style.transform=`translate3d(${e.initialX-this.offsetX}px, ${e.initialY-this.offsetY}px, 0)`,((o=(r=e.owner)===null||r===void 0?void 0:r.ownerDocument)!==null&&o!==void 0?o:document).body.appendChild(this.element)}update(e,t){this._disposed||(this.element.style.transform=`translate3d(${e-this.offsetX}px, ${t-this.offsetY}px, 0)`)}dispose(){this._disposed||(this._disposed=!0,this.element.remove())}},qie=class extends pt{constructor(e,t){super(),this.el=e,this.opts=t,this._dataDisposable=new Bn,this._pointerEventsDisposable=new Bn,this._disabled=!!t.disabled,this.addDisposables(this._dataDisposable,this._pointerEventsDisposable,ct(this.el,"dragstart",n=>{var s,o,r,a,l,c,d;if(n.defaultPrevented||this._disabled||!((s=(o=this.opts).isCancelled)===null||s===void 0)&&s.call(o,n)){n.preventDefault();return}const u=ic((r=this.el.ownerDocument)!==null&&r!==void 0?r:document);this._pointerEventsDisposable.value={dispose:()=>u.release()},this.el.classList.add("dv-dragged"),setTimeout(()=>this.el.classList.remove("dv-dragged"),0),this._dataDisposable.value=this.opts.getData(n);const h=(a=(l=this.opts).createGhost)===null||a===void 0?void 0:a.call(l,n);if(h&&n.dataTransfer){var p,f,g;if(Fie(n.dataTransfer,h.element,{x:(p=h.offsetX)!==null&&p!==void 0?p:0,y:(f=h.offsetY)!==null&&f!==void 0?f:0,ownerDocument:(g=this.el.ownerDocument)!==null&&g!==void 0?g:void 0}),h.dispose){const x=h.dispose;setTimeout(()=>x(),0)}}n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.items.length===0&&n.dataTransfer.setData("text/plain","")),(c=(d=this.opts).onDragStart)===null||c===void 0||c.call(d,n)}),ct(this.el,"dragend",n=>{var s,o;this._pointerEventsDisposable.dispose(),setTimeout(()=>this._dataDisposable.dispose(),0),(s=(o=this.opts).onDragEnd)===null||s===void 0||s.call(o,n)}))}setDisabled(e){this._disabled=e}setTouchOnly(e){}cancelPending(){}},Yie=class{constructor(){this.kind="html5"}createDropTarget(e,t){return new tp(e,t)}createDragSource(e,t){return new qie(e,t)}},Xie=class{constructor(){this.kind="pointer"}createDropTarget(e,t){return new Bie(e,t)}createDragSource(e,t){const n=t.createGhost?o=>{const r=t.createGhost(o);if(!r)return;const a=new Kie({element:r.element,initialX:o.clientX,initialY:o.clientY,offsetX:r.offsetX,offsetY:r.offsetY,owner:e});if(r.dispose){const l=a.dispose.bind(a),c=r.dispose;a.dispose=()=>{l(),c()}}return a}:void 0,s=new Uie(e,{getData:t.getData,isCancelled:t.isCancelled,onDragStart:t.onDragStart,onDragEnd:t.onDragEnd?o=>t.onDragEnd(o.pointerEvent):void 0,createGhost:n,touchOnly:t.touchOnly,touchInitiationDelay:t.touchInitiationDelay,pressTolerance:t.pressTolerance,threshold:t.threshold});return t.disabled&&s.setDisabled(!0),s}};const Wo=new Yie,Co=new Xie,Tg=Object.keys({disableAutoResizing:void 0,disableDnd:void 0,className:void 0});var Jie=class extends aP{constructor(e,t,n,s){super(),this.nativeEvent=e,this.position=t,this.getData=n,this.panel=s}},IP=class extends Kv{constructor(){super()}},DP=class extends pt{get isFocused(){return this._isFocused}get isActive(){return this._isActive}get isVisible(){return this._isVisible}get width(){return this._width}get height(){return this._height}constructor(e,t){super(),this.id=e,this.component=t,this._isFocused=!1,this._isActive=!1,this._isVisible=!0,this._width=0,this._height=0,this._parameters={},this.panelUpdatesDisposable=new Bn,this._onDidDimensionChange=new ve,this.onDidDimensionsChange=this._onDidDimensionChange.event,this._onDidChangeFocus=new ve,this.onDidFocusChange=this._onDidChangeFocus.event,this._onWillFocus=new ve,this.onWillFocus=this._onWillFocus.event,this._onDidVisibilityChange=new ve,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._onWillVisibilityChange=new ve,this.onWillVisibilityChange=this._onWillVisibilityChange.event,this._onDidActiveChange=new ve,this.onDidActiveChange=this._onDidActiveChange.event,this._onActiveChange=new ve,this.onActiveChange=this._onActiveChange.event,this._onDidParametersChange=new ve,this.onDidParametersChange=this._onDidParametersChange.event,this.addDisposables(this.onDidFocusChange(n=>{this._isFocused=n.isFocused}),this.onDidActiveChange(n=>{this._isActive=n.isActive}),this.onDidVisibilityChange(n=>{this._isVisible=n.isVisible}),this.onDidDimensionsChange(n=>{this._width=n.width,this._height=n.height}),this.panelUpdatesDisposable,this._onDidDimensionChange,this._onDidChangeFocus,this._onDidVisibilityChange,this._onDidActiveChange,this._onWillFocus,this._onActiveChange,this._onWillFocus,this._onWillVisibilityChange,this._onDidParametersChange)}getParameters(){return this._parameters}initialize(e){this.panelUpdatesDisposable.value=this._onDidParametersChange.event(t=>{this._parameters=t,e.update({params:t})})}setVisible(e){this._onWillVisibilityChange.fire({isVisible:e})}setActive(){this._onActiveChange.fire()}updateParameters(e){this._onDidParametersChange.fire(e)}},EP=class extends DP{constructor(e,t){super(e,t),this._onDidConstraintsChangeInternal=new ve,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new ve({replay:!0}),this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new ve,this.onDidSizeChange=this._onDidSizeChange.event,this.addDisposables(this._onDidConstraintsChangeInternal,this._onDidConstraintsChange,this._onDidSizeChange)}setConstraints(e){this._onDidConstraintsChangeInternal.fire(e)}setSize(e){this._onDidSizeChange.fire(e)}},Zie=class extends EP{set pane(e){this._pane=e}constructor(e,t){super(e,t),this._onDidExpansionChange=new ve({replay:!0}),this.onDidExpansionChange=this._onDidExpansionChange.event,this._onMouseEnter=new ve({}),this.onMouseEnter=this._onMouseEnter.event,this._onMouseLeave=new ve({}),this.onMouseLeave=this._onMouseLeave.event,this.addDisposables(this._onDidExpansionChange,this._onMouseEnter,this._onMouseLeave)}setExpanded(e){var t;(t=this._pane)===null||t===void 0||t.setExpanded(e)}get isExpanded(){var e;return!!(!((e=this._pane)===null||e===void 0)&&e.isExpanded())}},Jv=class extends pt{get element(){return this._element}get width(){return this._width}get height(){return this._height}get params(){var e;return(e=this._params)===null||e===void 0?void 0:e.params}constructor(e,t,n){super(),this.id=e,this.component=t,this.api=n,this._height=0,this._width=0,this._element=document.createElement("div"),this._element.tabIndex=-1,this._element.style.outline="none",this._element.style.height="100%",this._element.style.width="100%",this._element.style.overflow="hidden";const s=cP(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 IP;this.api._onWillFocus.fire(e),!e.defaultPrevented&&this._element.focus()}layout(e,t){this._width=e,this._height=t,this.api._onDidDimensionChange.fire({width:e,height:t}),this.part&&this._params&&this.part.update(this._params.params)}init(e){this._params=e,this.part=this.getComponent()}update(e){var t,n;this._params=gt(gt({},this._params),{},{params:gt(gt({},(t=this._params)===null||t===void 0?void 0:t.params),e.params)});for(const s of Object.keys(e.params))e.params[s]===void 0&&delete this._params.params[s];(n=this.part)===null||n===void 0||n.update({params:this._params.params})}toJSON(){var e,t;const n=(e=(t=this._params)===null||t===void 0?void 0:t.params)!==null&&e!==void 0?e:{};return{id:this.id,component:this.component,params:Object.keys(n).length>0?n:void 0}}dispose(){var e;this.api.dispose(),(e=this.part)===null||e===void 0||e.dispose(),super.dispose()}},Qie=class extends Jv{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 Zie(e.id,e.component)),this._onDidChangeExpansionState=new ve({replay:!0}),this.onDidChangeExpansionState=this._onDidChangeExpansionState.event,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._orthogonalSize=0,this._size=0,this._isExpanded=!1,this.api.pane=this,this.api.initialize(this),this.headerSize=e.headerSize,this.headerComponent=e.headerComponent,this._minimumBodySize=e.minimumBodySize,this._maximumBodySize=e.maximumBodySize,this._isExpanded=e.isExpanded,this._headerVisible=e.isHeaderVisible,this._onDidChangeExpansionState.fire(this.isExpanded()),this._orientation=e.orientation,this.element.classList.add("dv-pane"),this.addDisposables(this.api.onWillVisibilityChange(t=>{const{isVisible:n}=t,{accessor:s}=this._params;s.setVisible(this,n)}),this.api.onDidSizeChange(t=>{this._onDidChange.fire({size:t.size})}),ct(this.element,"mouseenter",t=>{this.api._onMouseEnter.fire(t)}),ct(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?_i(this.header,"focused"):ji(this.header,"focused"))})),this.renderOnce()}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}isExpanded(){return this._isExpanded}setExpanded(e){var t;this._isExpanded!==e&&(this._isExpanded=e,e?(this.animationTimer&&clearTimeout(this.animationTimer),this.body&&this.element.appendChild(this.body)):(this._expandedSize=this._size,this.animationTimer=setTimeout(()=>{var n;(n=this.body)===null||n===void 0||n.remove()},200)),this._onDidChange.fire(e?{size:(t=this._expandedSize)!==null&&t!==void 0?t:this.width}:{}),this._onDidChangeExpansionState.fire(e))}layout(e,t){this._size=e,this._orthogonalSize=t;const[n,s]=this.orientation==="HORIZONTAL"?[e,t]:[t,e];super.layout(n,s)}init(e){var t,n;super.init(e),typeof e.minimumBodySize=="number"&&(this.minimumBodySize=e.minimumBodySize),typeof e.maximumBodySize=="number"&&(this.maximumBodySize=e.maximumBodySize),this.bodyPart=this.getBodyComponent(),this.headerPart=this.getHeaderComponent(),this.bodyPart.init(gt(gt({},e),{},{api:this.api})),this.headerPart.init(gt(gt({},e),{},{api:this.api})),(t=this.body)===null||t===void 0||t.append(this.bodyPart.element),(n=this.header)===null||n===void 0||n.append(this.headerPart.element),typeof e.isExpanded=="boolean"&&this.setExpanded(e.isExpanded)}toJSON(){const e=this._params;return gt(gt({},super.toJSON()),{},{headerComponent:this.headerComponent,title:e.title})}renderOnce(){this.header=document.createElement("div"),this.header.tabIndex=0,this.header.className="dv-pane-header",this.header.style.height=`${this.headerSize}px`,this.header.style.lineHeight=`${this.headerSize}px`,this.header.style.minHeight=`${this.headerSize}px`,this.header.style.maxHeight=`${this.headerSize}px`,this.element.appendChild(this.header),this.body=document.createElement("div"),this.body.className="dv-pane-body",this.element.appendChild(this.body)}getComponent(){return{update:e=>{var t,n;(t=this.bodyPart)===null||t===void 0||t.update({params:e}),(n=this.headerPart)===null||n===void 0||n.update({params:e})},dispose:()=>{var e,t;(e=this.bodyPart)===null||e===void 0||e.dispose(),(t=this.headerPart)===null||t===void 0||t.dispose()}}}},eoe=class extends Qie{constructor(e){super({id:e.id,component:e.component,headerComponent:e.headerComponent,orientation:e.orientation,isExpanded:e.isExpanded,isHeaderVisible:!0,headerSize:e.headerSize,minimumBodySize:e.minimumBodySize,maximumBodySize:e.maximumBodySize}),this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this.accessor=e.accessor,this.addDisposables(this._onDidDrop,this._onUnhandledDragOver),e.disableDnd||this.initDragFeatures()}initDragFeatures(){if(!this.header)return;const e=this.id,t=this.accessor.id;this.header.draggable=!0;const n={getData:()=>(So.getInstance().setData([new Al(t,e)],Al.prototype),{dispose:()=>{So.getInstance().clearData(Al.prototype)}})};this.html5DragSource=Wo.createDragSource(this.header,n),this.pointerDragSource=Co.createDragSource(this.header,n);const o={acceptedTargetZones:["top","bottom"],overlayModel:{activationSize:{type:"percentage",value:50}},canDisplayOverlay:(r,a)=>{const l=el();if(l&&l.paneId!==this.id&&l.viewId===this.accessor.id)return!0;const c=new Jie(r,a,el,this);return this._onUnhandledDragOver.fire(c),c.isAccepted}};this.target=Wo.createDropTarget(this.element,o),this.pointerTarget=Co.createDropTarget(this.element,o),this.addDisposables(this._onDidDrop,this.html5DragSource,this.pointerDragSource,this.target,this.pointerTarget,this.target.onDrop(r=>{this.onDrop(r)}),this.pointerTarget.onDrop(r=>{this.onDrop(r)}))}onDrop(e){const t=el();if(t?.viewId!==this.accessor.id){this._onDidDrop.fire(gt(gt({},e),{},{panel:this,api:new rc(this.accessor),getData:el}));return}const n=this._params.containerApi,s=t.paneId,o=n.getPanel(s);if(!o){this._onDidDrop.fire(gt(gt({},e),{},{panel:this,getData:el,api:new rc(this.accessor)}));return}const r=n.panels,a=r.indexOf(o);let l=n.panels.indexOf(this);(e.position==="left"||e.position==="top")&&(l=Math.max(0,l-1)),(e.position==="right"||e.position==="bottom")&&(a>l&&l++,l=Math.min(r.length-1,l)),n.movePanel(a,l)}};let toe=0;const noe=()=>`dv-tabpanel-${toe++}`;var soe=class extends pt{get element(){return this._element}constructor(e,t){var n,s,o,r,a,l,c;super(),this.accessor=e,this.group=t,this.disposable=new Bn,this._onDidFocus=new ve,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new ve,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-content-container",this._element.tabIndex=-1,this._element.id=noe(),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 tp(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=Co.createDropTarget(this.element,{acceptedTargetZones:["top","bottom","left","right","center"],canDisplayOverlay:u,getOverlayOutline:()=>{var h;return((h=e.options.theme)===null||h===void 0?void 0:h.dndPanelOverlay)==="group"?this.element.parentElement:null},className:"dv-drop-target-content",getOverrideTarget:d,overlayModel:(o=(r=this.accessor).resolveDropOverlayModel)===null||o===void 0?void 0:o.call(r,"content"),getPositionResolver:()=>{var h;return(h=e.getDropPositionResolver)===null||h===void 0?void 0:h.call(e)}}),this.addDisposables(this.dropTarget,this.pointerDropTarget,(a=(l=(c=this.accessor).onDidOptionsChange)===null||l===void 0?void 0:l.call(c,()=>{var h,p,f;const g=(h=(p=(f=this.accessor).resolveDropOverlayModel)===null||p===void 0?void 0:p.call(f,"content"))!==null&&h!==void 0?h:{};this.dropTarget.setOverlayModel(g),this.pointerDropTarget.setOverlayModel(g)}))!==null&&a!==void 0?a:cn.NONE)}show(){this.element.style.display=""}hide(){this.element.style.display="none"}setLabelledBy(e){e?this._element.setAttribute("aria-labelledby",e):this._element.removeAttribute("aria-labelledby")}renderPanel(e,t){var n,s;const o=((n=t?.asActive)!==null&&n!==void 0?n:!0)||this.panel&&this.group.isPanelActive(this.panel);if(((s=this.panel)===null||s===void 0?void 0:s.view.content.element.parentElement)===this._element){var r,a;this.panel.view.content.element.remove(),(r=(a=this.panel.view.content).onHide)===null||r===void 0||r.call(a)}this.panel=e;let l;switch(e.api.renderer){case"onlyWhenVisible":if(this.group.renderContainer.detatch(e),this.panel&&o){var c,d;this._element.appendChild(this.panel.view.content.element),(c=(d=this.panel.view.content).onShow)===null||c===void 0||c.call(d)}l=this._element;break;case"always":e.view.content.element.parentElement===this._element&&e.view.content.element.remove(),l=this.group.renderContainer.attach({panel:e,referenceContainer:this});break;default:throw new Error(`dockview: invalid renderer type '${e.api.renderer}'`)}if(o){const u=cP(l);this.focusTracker=u;const h=new pt;h.addDisposables(u,u.onDidFocus(()=>this._onDidFocus.fire()),u.onDidBlur(()=>this._onDidBlur.fire())),this.disposable.value=h}}openPanel(e){this.panel!==e&&this.renderPanel(e)}layout(e,t){}closePanel(){if(this.panel&&this.panel.api.renderer==="onlyWhenVisible"){var e,t;this.panel.view.content.element.remove(),(e=(t=this.panel.view.content).onHide)===null||e===void 0||e.call(t)}this.panel=void 0}dispose(){this.disposable.dispose(),super.dispose()}refreshFocusState(){var e;!((e=this.focusTracker)===null||e===void 0)&&e.refreshState&&this.focusTracker.refreshState()}};const np=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},ioe=()=>np({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"}),PP=()=>np({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"}),ooe=()=>np({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"}),AP=()=>np({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"}),roe=500,aoe=8;var Zv=class extends pt{constructor(e,t){super(),this.element=e,this.options=t,this._startX=0,this._startY=0,this.addDisposables(ct(this.element,"pointerdown",n=>{this._onPointerDown(n)}))}_onPointerDown(e){var t,n,s,o,r;if((!((t=this.options.touchOnly)!==null&&t!==void 0)||t)&&e.pointerType!=="touch"&&e.pointerType!=="pen")return;this._cancelPending(),this._pointerId=e.pointerId,this._startX=e.clientX,this._startY=e.clientY;const a=(n=this.options.delay)!==null&&n!==void 0?n:roe,l=(s=this.options.tolerance)!==null&&s!==void 0?s:aoe,c=(o=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&o!==void 0?o:globalThis.window;this._timer=setTimeout(()=>{this._timer=void 0,this._cancelPending(),this._installContextMenuGuard(c),this._installClickGuard(c),this.options.onLongPress(e)},a),this._moveListener=ct(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=ct(c,"pointerup",d=>{d.pointerId===this._pointerId&&this._cancelPending()}),this._cancelListener=ct(c,"pointercancel",d=>{d.pointerId===this._pointerId&&this._cancelPending()})}_installContextMenuGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=ct(e,"contextmenu",s=>{s.preventDefault(),clearTimeout(n),t?.dispose()},{capture:!0})}_installClickGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=ct(e,"click",s=>{const o=s.target;o&&this.element.contains(o)&&(s.preventDefault(),s.stopPropagation()),clearTimeout(n),t?.dispose()},{capture:!0})}_cancelPending(){var e,t,n;this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0),this._pointerId=void 0,(e=this._moveListener)===null||e===void 0||e.dispose(),(t=this._upListener)===null||t===void 0||t.dispose(),(n=this._cancelListener)===null||n===void 0||n.dispose(),this._moveListener=void 0,this._upListener=void 0,this._cancelListener=void 0}dispose(){this._cancelPending(),super.dispose()}};function fi(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 loe()?{html5:!1,pointer:!0,pointerHandlesMouse:!0}:{html5:!0,pointer:!0,pointerHandlesMouse:!1}}}function loe(){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 coe=0;const doe=()=>`dv-tab-${coe++}`;var uoe=class extends pt{get element(){return this._element}constructor(e,t,n){var s,o,r,a,l,c,d,u;super(),this.panel=e,this.accessor=t,this.group=n,this.content=void 0,this.panelTransfer=So.getInstance(),this._direction="horizontal",this._pinIndicator=void 0,this._onPointDown=new ve,this.onPointerDown=this._onPointDown.event,this._onTabClick=new ve,this.onTabClick=this._onTabClick.event,this._onDropped=new ve,this.onDrop=this._onDropped.event,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._onDragEnd=new ve,this.onDragEnd=this._onDragEnd.event;const h=fi(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=doe(),this._element.setAttribute("role","tab"),this._element.setAttribute("aria-selected","false"),this._element.setAttribute("aria-label",(s=this.panel.title)!==null&&s!==void 0?s:this.panel.id),this._element.dataset.tabPanelId=this.panel.id;const p=(o=this.group)===null||o===void 0||(o=o.model)===null||o===void 0?void 0:o.contentContainerId;p&&this._element.setAttribute("aria-controls",p),Qe(this.element,"dv-inactive-tab",!0),this._updatePinnedClasses();const f=(x,v)=>{if(this.group.locked)return!1;const y=On();if(this.accessor.id===y?.viewId){var b;return((b=this.accessor.options.theme)===null||b===void 0?void 0:b.tabAnimation)!=="smooth"}return this.group.model.canDisplayOverlay(x,v,"tab")};this.dropTarget=Wo.createDropTarget(this._element,{acceptedTargetZones:["left","right"],overlayModel:this._buildOverlayModel(),canDisplayOverlay:f,getOverrideTarget:()=>{var x;return(x=n.model.dropTargetContainer)===null||x===void 0?void 0:x.model}}),this.pointerDropTarget=Co.createDropTarget(this._element,{acceptedTargetZones:["left","right"],overlayModel:this._buildOverlayModel(),canDisplayOverlay:f,getOverrideTarget:()=>{var x;return(x=n.model.dropTargetContainer)===null||x===void 0?void 0:x.model}});const g={getData:()=>(this.panelTransfer.setData([new Zs(this.accessor.id,this.group.id,this.panel.id)],Zs.prototype),{dispose:()=>{this.panelTransfer.clearData(Zs.prototype)}}),createGhost:()=>({element:this._buildGhostElement(),offsetX:30,offsetY:-10}),onDragStart:x=>{var v;this._onDragStart.fire(x),!(x instanceof PointerEvent)&&((v=this.accessor.options.theme)===null||v===void 0?void 0:v.tabAnimation)==="smooth"&&requestAnimationFrame(()=>{Qe(this.element,"dv-tab--dragging",!0)})},onDragEnd:x=>{this._onDragEnd.fire(x)}};this.html5DragSource=Wo.createDragSource(this._element,gt(gt({},g),{},{disabled:!h.html5})),this.pointerDragSource=Co.createDragSource(this._element,gt(gt({},g),{},{disabled:!h.pointer,touchOnly:!h.pointerHandlesMouse,isCancelled:()=>!fi(this.accessor.options).pointer})),this.onWillShowOverlay=ei.any(this.dropTarget.onWillShowOverlay,this.pointerDropTarget.onWillShowOverlay),this.addDisposables(this._onPointDown,this._onTabClick,this._onDropped,this._onDragStart,this._onDragEnd,this.accessor.onDidOptionsChange(()=>{const x=this._buildOverlayModel();this.dropTarget.setOverlayModel(x),this.pointerDropTarget.setOverlayModel(x),this._updatePinnedClasses()}),(r=(a=this.panel.api)===null||a===void 0||(l=a.onDidChangePinned)===null||l===void 0?void 0:l.call(a,()=>{this._updatePinnedClasses()}))!==null&&r!==void 0?r:{dispose:()=>{}},(c=(d=this.panel.api)===null||d===void 0||(u=d.onDidTitleChange)===null||u===void 0?void 0:u.call(d,x=>{var v;this._element.setAttribute("aria-label",(v=x.title)!==null&&v!==void 0?v:this.panel.id)}))!==null&&c!==void 0?c:{dispose:()=>{}},ct(this._element,"dragend",()=>{Qe(this.element,"dv-tab--dragging",!1)}),this.html5DragSource,ct(this._element,"pointerdown",x=>{this._onPointDown.fire(x)}),ct(this._element,"click",x=>{this._onTabClick.fire(x)}),ct(this._element,"contextmenu",x=>{var v;(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,x)}),new Zv(this._element,{onLongPress:x=>{var v;this.pointerDragSource.cancelPending(),(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,x)}}),this.dropTarget.onDrop(x=>{this._onDropped.fire(x)}),this.pointerDropTarget.onDrop(x=>{this._onDropped.fire(x)}),this.dropTarget,this.pointerDropTarget,this.pointerDragSource)}_updatePinnedClasses(){var e,t,n,s;const o=(e=(t=this.panel.api)===null||t===void 0?void 0:t.isPinned)!==null&&e!==void 0?e:!1,r=o&&((n=this.accessor.options.pinnedTabs)===null||n===void 0?void 0:n.compact)===!0;Qe(this.element,"dv-tab--pinned",o),Qe(this.element,"dv-tab--pinned-compact",r);const a=o&&!(!((s=this.panel.api)===null||s===void 0)&&s.tabComponent);if(a&&!this._pinIndicator){const l=document.createElement("div");l.className="dv-tab-pin",l.appendChild(PP()),this._element.insertBefore(l,this._element.firstChild),this._pinIndicator=l}else!a&&this._pinIndicator&&(this._pinIndicator.remove(),this._pinIndicator=void 0)}setActive(e){Qe(this.element,"dv-active-tab",e),Qe(this.element,"dv-inactive-tab",!e),this._element.setAttribute("aria-selected",e?"true":"false"),this._element.tabIndex=e?0:-1}setContent(e){this.content&&this.content.element.remove(),this.content=e,this._element.appendChild(this.content.element)}_buildOverlayModel(){var e,t,n;const s=(e=(t=this.accessor).resolveDropOverlayModel)===null||e===void 0?void 0:e.call(t,"tab",this.group);if(s)return s;const o=((n=this.accessor.options.theme)===null||n===void 0?void 0:n.dndTabIndicator)==="line"?Number.POSITIVE_INFINITY:0;return{activationSize:{value:50,type:"percentage"},smallWidthBoundary:o,smallHeightBoundary:o}}setDirection(e){this._direction=e;const t=e==="vertical"?["top","bottom"]:["left","right"];this.dropTarget.setTargetZones(t),this.pointerDropTarget.setTargetZones(t)}updateDragAndDropState(){const e=fi(this.accessor.options);this._element.draggable=e.html5,this.html5DragSource.setDisabled(!e.html5),this.pointerDragSource.setDisabled(!e.pointer),this.pointerDragSource.setTouchOnly(!e.pointerHandlesMouse)}_buildGhostElement(){const e=getComputedStyle(this.element),t=this.element.cloneNode(!0),n=this._direction==="vertical",s=new Set(["writing-mode","inline-size","block-size","min-inline-size","min-block-size","max-inline-size","max-block-size","margin-inline","margin-inline-start","margin-inline-end","margin-block","margin-block-start","margin-block-end","padding-inline","padding-inline-start","padding-inline-end","padding-block","padding-block-start","padding-block-end"]);return Array.from(e).forEach(o=>{n&&s.has(o)||t.style.setProperty(o,e.getPropertyValue(o),e.getPropertyPriority(o))}),n&&(t.style.setProperty("writing-mode","horizontal-tb"),t.style.setProperty("width",e.height),t.style.setProperty("height",e.width)),t.style.position="absolute",t.classList.add("dv-tab-ghost-drag"),t}},ac=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}},MP=class extends pt{get group(){return this.groupAccessor()}constructor(e){var t,n;super(),this.panelTransfer=So.getInstance(),this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._element=e.element,this.accessor=e.accessor;const s=e.group;this.groupAccessor=typeof s=="function"?s:()=>s,this.isFloatingMoveHandle=(t=e.isFloatingMoveHandle)!==null&&t!==void 0?t:(()=>!0);const o=fi(this.accessor.options);this._element.draggable=o.html5,Qe(this._element,"dv-draggable",o.html5||o.pointer),this.addDisposables(this._onDragStart);const r=()=>{const p=document.createElement("div"),f=globalThis.getComputedStyle(this._element),g=f.getPropertyValue("--dv-activegroup-visiblepanel-tab-background-color"),x=f.getPropertyValue("--dv-activegroup-visiblepanel-tab-color");return p.style.backgroundColor=g,p.style.color=x,p.style.padding="2px 8px",p.style.height="24px",p.style.fontSize="11px",p.style.lineHeight="20px",p.style.borderRadius="12px",p.style.whiteSpace="nowrap",p.style.boxSizing="border-box",p.style.display="inline-block",p.textContent=`Multiple Panels (${this.group.size})`,p},l={getData:()=>(this.panelTransfer.setData([new Zs(this.accessor.id,this.group.id,null)],Zs.prototype),{dispose:()=>{this.panelTransfer.clearData(Zs.prototype)}}),createGhost:()=>{var p,f;const g=(p=(f=this.accessor).buildGroupDragGhost)===null||p===void 0?void 0:p.call(f,this.group);return g||{element:r(),offsetX:30,offsetY:-10}},onDragStart:p=>{this._onDragStart.fire(p)}};this.html5DragSource=Wo.createDragSource(this._element,gt(gt({},l),{},{disabled:!o.html5,isCancelled:p=>!!(this.group.api.location.type==="floating"&&this.isFloatingMoveHandle()&&!p.shiftKey||this.group.api.location.type==="edge"&&this.group.size===0)}));const c=()=>{var p;return((p=this.group)===null||p===void 0||(p=p.api)===null||p===void 0||(p=p.location)===null||p===void 0?void 0:p.type)==="floating"&&this.isFloatingMoveHandle()};this.pointerDragSource=Co.createDragSource(this._element,gt(gt({},l),{},{disabled:!o.pointer,touchOnly:!o.pointerHandlesMouse,touchInitiationDelay:()=>c()?500:250,pressTolerance:()=>c()?1/0:8,isCancelled:()=>!fi(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 Bn,u=()=>{const p=this.getFloatingOverlay();d.value=p?p.onDidStartMoving(()=>{this.pointerDragSource.cancelPending()}):cn.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=fi(this.accessor.options);this._element.draggable=e.html5,Qe(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}},hoe=class extends pt{get element(){return this._element}constructor(e,t){var n,s,o,r,a,l,c;super(),this.accessor=e,this.group=t,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._element=document.createElement("div"),this._element.className="dv-void-container",this.addDisposables(this._onDrop,this._onDragStart,ct(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this.group)}),ct(this._element,"pointerdown",u=>{u.shiftKey&&uP(u)},!0)),this.dragSource=new MP({element:this._element,accessor:this.accessor,group:this.group,isFloatingMoveHandle:()=>!this._element.closest(".dv-resize-container-with-titlebar")});const d=(u,h)=>{if(this.group.api.locked)return!1;const p=On();return this.accessor.id===p?.viewId?!0:t.model.canDisplayOverlay(u,h,"header_space")};this.dropTarget=Wo.createDropTarget(this._element,{acceptedTargetZones:["center"],canDisplayOverlay:d,getOverrideTarget:()=>{var u;return(u=t.model.dropTargetContainer)===null||u===void 0?void 0:u.model},overlayModel:(n=(s=this.accessor).resolveDropOverlayModel)===null||n===void 0?void 0:n.call(s,"header_space",this.group)}),this.pointerDropTarget=Co.createDropTarget(this._element,{acceptedTargetZones:["center"],canDisplayOverlay:d,getOverrideTarget:()=>{var u;return(u=t.model.dropTargetContainer)===null||u===void 0?void 0:u.model},overlayModel:(o=(r=this.accessor).resolveDropOverlayModel)===null||o===void 0?void 0:o.call(r,"header_space",this.group)}),this.onWillShowOverlay=ei.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:cn.NONE)}updateDragAndDropState(){this.dragSource.updateDragAndDropState()}},RP=class LP extends pt{get element(){return this._element}get orientation(){return this._orientation}set orientation(t){this._orientation!==t&&(this._scrollOffset=0,this._orientation=t,ji(this._scrollbar,"dv-scrollbar-vertical","dv-scrollbar-horizontal"),t==="vertical"?_i(this._scrollbar,"dv-scrollbar-vertical"):_i(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(ct(this.element,"wheel",n=>{this._scrollOffset+=n.deltaY*LP.MouseWheelSpeed,this.scheduleStyleUpdate()}),ct(this._scrollbar,"pointerdown",n=>{var s;n.preventDefault();const o=(s=this._scrollbar.ownerDocument)!==null&&s!==void 0?s:document;Qe(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=()=>{Qe(this.element,"dv-scrollable-scrolling",!1),o.removeEventListener("pointermove",l),o.removeEventListener("pointerup",c),o.removeEventListener("pointercancel",c)};o.addEventListener("pointermove",l),o.addEventListener("pointerup",c),o.addEventListener("pointercancel",c)}),ct(this.element,"scroll",()=>{this.scheduleStyleUpdate()}),ct(this.scrollableElement,"scroll",()=>{this._scrollOffset=this._orientation==="horizontal"?this.scrollableElement.scrollLeft:this.scrollableElement.scrollTop,this.scheduleStyleUpdate()}),Ir(this.element,()=>{Qe(this.element,"dv-scrollable-resizing",!0),this._animationTimer&&clearTimeout(this._animationTimer),this._animationTimer=setTimeout(()=>{clearTimeout(this._animationTimer),Qe(this.element,"dv-scrollable-resizing",!1)},500),this.scheduleStyleUpdate()}),cn.from(()=>{this._pendingStyleFrame!==void 0&&(cancelAnimationFrame(this._pendingStyleFrame),this._pendingStyleFrame=void 0)}))}scheduleStyleUpdate(){this._pendingStyleFrame===void 0&&(this._pendingStyleFrame=requestAnimationFrame(()=>{this._pendingStyleFrame=void 0,this.calculateScrollbarStyles()}))}calculateScrollbarStyles(){const t=this._orientation==="horizontal"?this.element.clientWidth:this.element.clientHeight,n=this._orientation==="horizontal"?this.scrollableElement.scrollWidth:this.scrollableElement.scrollHeight;if(n>t){const s=t*(t/n);this._orientation==="horizontal"?(this._scrollbar.style.width=`${s}px`,this._scrollbar.style.height=""):(this._scrollbar.style.height=`${s}px`,this._scrollbar.style.width=""),this._scrollOffset=En(this._scrollOffset,0,n-t),this._orientation==="horizontal"?this.scrollableElement.scrollLeft=this._scrollOffset:this.scrollableElement.scrollTop=this._scrollOffset;const o=this._scrollOffset/(n-t);this._orientation==="horizontal"?(this._scrollbar.style.left=`${(t-s)*o}px`,this._scrollbar.style.top=""):(this._scrollbar.style.top=`${(t-s)*o}px`,this._scrollbar.style.left="")}else this._orientation==="horizontal"?(this._scrollbar.style.width="0px",this._scrollbar.style.left="0px"):(this._scrollbar.style.height="0px",this._scrollbar.style.top="0px"),this._scrollOffset=0}};RP.MouseWheelSpeed=1;const OP="dv-tabs-container--wrap";function poe(e,t){return typeof e=="boolean"?e:!!e?.[t]}function Ig(e){return typeof e=="boolean"?e:e?Object.values(e).some(Boolean):!1}var zP=class extends aP{constructor(e,t,n,s,o){super(),this.nativeEvent=e,this.target=t,this.position=n,this.getData=s,this.group=o}};const Dg=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 foe(e){return!!e.referencePanel}function moe(e){return!!e.referenceGroup}function goe(e){return!!e.referencePanel}function xoe(e){return!!e.referenceGroup}const Qv=[{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 GP=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 Df;function FP(){var e;return(e=Df)!==null&&e!==void 0||(Df=new GP(Qv,!0)),Df}function e0(e,t,n){const s=(n??FP()).resolveValue(t);s===void 0?e.style.removeProperty("--dv-tab-group-color"):e.style.setProperty("--dv-tab-group-color",s)}function t0(e,t){return(t??FP()).resolveValue(e)}var ek=class extends pt{get element(){return this._element}constructor(e){super(),this._palette=e,this._onClick=new ve,this.onClick=this._onClick.event,this._onContextMenu=new ve,this.onContextMenu=this._onContextMenu.event,this._element=document.createElement("div"),this._element.className="dv-tab-group-chip",this._element.tabIndex=0,this._label=document.createElement("span"),this._label.className="dv-tab-group-chip-label",this._element.appendChild(this._label),this.addDisposables(this._onClick,this._onContextMenu,new Zv(this._element,{onLongPress:t=>{this._onContextMenu.fire(t)}}),ct(this._element,"click",t=>{this._onClick.fire(t)}),ct(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;e0(this._element,e,this._palette),Qe(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,Qe(this._label,"dv-tab-group-chip-label--empty",!e)}updateCollapsed(e){Qe(this._element,"dv-tab-group-chip--collapsed",e)}};const voe="dv-tab-group-chip-continuation",tk=8;var HP=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=voe,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(OP);s||this._clearContinuationMarkers();const o=n?e.width:e.height,r=this._ctx.getActivePanelId(),a=this._ctx.getTabMap();for(const l of t){const c=this._underlines.get(l.id);if(!c)continue;const d=l.panelIds;if(d.length===0){c.style.display="none";continue}if(c.style.display="",s){this._positionWrappedUnderline(c,l,e,a,n);continue}const u=this._ctx.getChipElement(l.id);let h;if(u){const y=u.getBoundingClientRect(),b=getComputedStyle(u),w=n?Number.parseFloat(b.marginTop)||0:Number.parseFloat(b.marginLeft)||0;h=n?y.top-e.top-w:y.left-e.left-w}else{const y=d[0],b=a.get(y);if(b){const w=b.value.element.getBoundingClientRect();h=n?w.top-e.top:w.left-e.left}else h=0}const p=d[d.length-1],f=a.get(p);if(!f){n?(c.style.top=`${h}px`,c.style.height="0px",c.style.left="",c.style.width=""):(c.style.left=`${h}px`,c.style.width="0px",c.style.top="",c.style.height="");continue}const g=f.value.element.getBoundingClientRect();let x=n?g.bottom-e.top:g.right-e.left,v=x-h;if((l.collapsed||l.panelIds.some(y=>{const b=a.get(y);return b?.value.element.classList.contains("dv-tab--group-expanding")}))&&u){const y=u.getBoundingClientRect(),b=n?y.top+y.height/2-e.top:y.left+y.width/2-e.left;let w=0,C=0;for(const N of l.panelIds){const k=a.get(N);if(!k)continue;const S=k.value.element;n?(w+=S.getBoundingClientRect().height,C+=S.scrollHeight):(w+=S.getBoundingClientRect().width,C+=S.scrollWidth)}const _=C>0?Math.min(1,w/C):0;h=b+(h-b)*_,x=b+(x-b)*_,v=Math.max(0,x-h)}n?(c.style.top=`${h}px`,c.style.height=`${Math.max(0,v)}px`,c.style.left="",c.style.width="",c.style.bottom=""):(c.style.left=`${h}px`,c.style.width=`${Math.max(0,v)}px`,c.style.top="",c.style.height="",c.style.bottom=""),this.applyShape(c,l,h,v,o,r,e,n)}}_positionWrappedUnderline(e,t,n,s,o){const a=t0(t.color,this._ctx.getColorPalette());if(a===void 0){e.style.display="none",this._clearContinuationMarkers(t.id);return}const{runs:l,firstRun:c}=this._computeWrappedRuns(t,n,s,o);if(l.length===0){e.style.display="none",this._clearContinuationMarkers(t.id);return}this._positionContinuationMarkers(t.id,l,c,a,o);const d=Math.min(...l.map(w=>w.left)),u=Math.max(...l.map(w=>w.right)),h=Math.min(...l.map(w=>w.top)),p=Math.max(...l.map(w=>w.bottom)),f=o?Math.max(0,u-d):n.width,g=o?n.height:Math.max(0,p-h);e.style.left=o?`${d}px`:"0px",e.style.top=o?"0px":`${h}px`,e.style.bottom="auto",e.style.width=`${f}px`,e.style.height=`${g}px`,e.style.backgroundColor="";const{svg:x,path:v}=this.ensureSvgPath(e);x.setAttribute("width",String(f)),x.setAttribute("height",String(g)),v.setAttribute("stroke",a),v.setAttribute("stroke-width",String(2));const y=this._ctx.getHeaderPosition(),b=o?y==="right":y==="bottom";v.setAttribute("d",this._wrappedPathData(l,o,b,d,h,2))}_computeWrappedRuns(e,t,n,s){const o=[];let r;for(const l of e.panelIds){var a;const c=n.get(l);if(!c)continue;const d=c.value.element.getBoundingClientRect();if(d.width===0&&d.height===0)continue;const u=d.top-t.top,h=d.bottom-t.top,p=d.left-t.left,f=d.right-t.left,g=s?p:u;let x=o.find(v=>Math.abs((s?v.left:v.top)-g)<=2);x?(x.top=Math.min(x.top,u),x.bottom=Math.max(x.bottom,h),x.left=Math.min(x.left,p),x.right=Math.max(x.right,f)):(x={top:u,bottom:h,left:p,right:f},o.push(x)),(a=r)!==null&&a!==void 0||(r=x)}return{runs:o,firstRun:r}}_wrappedPathData(e,t,n,s,o,r){let a="";for(const l of e)if(t){const c=n?l.right-s-r/2:l.left-s+r/2;a+=`M ${c},${l.top} L ${c},${l.bottom} `}else{const c=n?l.top-o+r/2:l.bottom-o-r/2;a+=`M ${l.left},${c} L ${l.right},${c} `}return a.trim()}_positionContinuationMarkers(e,t,n,s,o){const r=t.filter(l=>l!==n),a=this._syncContinuationMarkers(e,r.length);r.forEach((l,c)=>{const d=a[c];if(d.style.backgroundColor=s,o){const u=(l.left+l.right)/2;d.style.left=`${u-tk/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-tk/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}}},boe=class extends HP{_applyStraightLine(e,t,n,s,o,r,a){const l=a?o:s,c=a?s:o;e.setAttribute("width",String(l)),e.setAttribute("height",String(c)),n.style.width=`${l}px`,n.style.height=`${c}px`,t.setAttribute("d",a?`M ${r},0 L ${r},${s}`:`M 0,${r} L ${s},${r}`)}applyShape(e,t,n,s,o,r,a,l){const d=o,u=s,h=t0(t.color,this._ctx.getColorPalette());if(u<=0||d<=0||h===void 0){e.style.display="none";return}e.style.display="";let p;r&&t.panelIds.includes(r)&&(p=this._ctx.getTabMap().get(r));const{svg:f,path:g}=this.ensureSvgPath(e);g.setAttribute("stroke",h),g.setAttribute("stroke-width",String(2));const x=2,v=this._ctx.getHeaderPosition(),y=!l&&v==="bottom",b=l&&v==="right";let w,C;if(l?(w=b?d-x:x,C=b?x:d-x):(w=y?x:d-x,C=y?d-x:x),!p){this._applyStraightLine(f,g,e,u,d,w,l);return}const _=p.value.element.getBoundingClientRect();let N,k;if(l?(N=Math.max(0,_.top-a.top-n),k=Math.min(u,_.bottom-a.top-n)):(N=Math.max(0,_.left-a.left-n),k=Math.min(u,_.right-a.left-n)),k<=N){this._applyStraightLine(f,g,e,u,d,w,l);return}const S=6,A=C>w?1:-1;if(l){const T=d,I=u;f.setAttribute("width",String(T)),f.setAttribute("height",String(I)),e.style.width=`${T}px`,e.style.height=`${I}px`;const P=[`M ${w},0`,`L ${w},${N-S}`,`Q ${w},${N} ${w+A*S},${N}`,`L ${C-A*S},${N}`,`Q ${C},${N} ${C},${N+S}`,`L ${C},${k-S}`,`Q ${C},${k} ${C-A*S},${k}`,`L ${w+A*S},${k}`,`Q ${w},${k} ${w},${k+S}`,`L ${w},${I}`].join(" ");g.setAttribute("d",P)}else{const T=u,I=d;f.setAttribute("width",String(T)),f.setAttribute("height",String(I)),e.style.width=`${T}px`,e.style.height=`${I}px`;const P=[`M 0,${w}`,`L ${N-S},${w}`,`Q ${N},${w} ${N},${w+A*S}`,`L ${N},${C-A*S}`,`Q ${N},${C} ${N+S},${C}`,`L ${k-S},${C}`,`Q ${k},${C} ${k},${C-A*S}`,`L ${k},${w+A*S}`,`Q ${k},${w} ${k+S},${w}`,`L ${T},${w}`].join(" ");g.setAttribute("d",P)}}},woe=class extends HP{applyShape(e,t,n,s,o,r,a,l){const d=t0(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 yoe=new Map;var Soe=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:yoe}get skipNextCollapseAnimation(){return this._skipNextCollapseAnimation}set skipNextCollapseAnimation(e){this._skipNextCollapseAnimation=e}constructor(e,t){this._ctx=e,this._callbacks=t,this._chipRenderers=new Map,this._indicator=null,this._skipNextCollapseAnimation=!1,this._pendingTransitionCleanups=new Map}update(){const e=this._ctx.group.model.getTabGroups(),t=new Set;for(const s of e)t.add(s.id),this._ensureChipForGroup(s),this._positionChipForGroup(s);for(const[s,o]of this._chipRenderers)if(!t.has(s)){var n;o.chip.element.remove(),o.chip.dispose(),(n=o.dragSourcesDisposable)===null||n===void 0||n.dispose(),o.disposable.dispose(),this._chipRenderers.delete(s)}this._updateTabGroupClasses()}refreshAccents(){for(const n of this._ctx.group.model.getTabGroups()){var e,t;const s=this._chipRenderers.get(n.id);s==null||(t=(e=s.chip).update)===null||t===void 0||t.call(e,{tabGroup:n})}this._updateTabGroupClasses()}positionAllChips(){if(this._chipRenderers.size!==0)for(const e of this._ctx.group.model.getTabGroups())this._positionChipForGroup(e)}updateDirection(){const e=this._ctx.getDirection()==="vertical";for(const[,t]of this._chipRenderers)t.dropTarget.setTargetZones(e?["top"]:["left"])}snapshotChipWidths(){const e=new Map;for(const[t,n]of this._chipRenderers)e.set(t,n.chip.element.getBoundingClientRect().width);return e}positionUnderlines(){var e;(e=this._indicator)===null||e===void 0||e.positionUnderlines()}trackUnderlines(){var e;(e=this._indicator)===null||e===void 0||e.trackUnderlines()}setGroupDragImage(e,t,n){if(!e.dataTransfer)return;const s=this._ctx.getDirection()==="vertical",o=this._ctx.tabsList.cloneNode(!0);s?(o.classList.remove("dv-tabs-container-vertical","dv-vertical"),o.classList.add("dv-horizontal"),o.style.writingMode="horizontal-tb",o.style.height=`${this._ctx.tabsList.offsetWidth}px`):o.style.height=`${this._ctx.tabsList.offsetHeight}px`,o.style.width="auto",o.style.overflow="visible",o.style.pointerEvents="none";const r=Array.from(o.children),a=Array.from(this._ctx.tabsList.children);for(let f=r.length-1;f>=0;f--)a[f]!==n&&r[f].remove();const l=document.createElement("div");l.className="dv-groupview dv-active-group",l.style.position="fixed",l.style.top="-10000px",l.style.left="0px",l.style.height="auto",l.style.width="auto",l.style.pointerEvents="none";const c=document.createElement("div");c.className="dv-tabs-and-actions-container",c.style.height="auto",c.style.width="auto",l.appendChild(c),c.appendChild(o),this._ctx.accessor.element.appendChild(l);const d=o.querySelector(".dv-tab-group-chip"),u=n.getBoundingClientRect(),h=e.clientX-u.left,p=e.clientY-u.top;if(d){const f=d.getBoundingClientRect(),g=l.getBoundingClientRect(),x=f.left-g.left+h,v=f.top-g.top+p;e.dataTransfer.setDragImage(l,x,v)}else e.dataTransfer.setDragImage(l,h,p);requestAnimationFrame(()=>{l.remove()})}cleanupTransition(e){var t;(t=this._pendingTransitionCleanups.get(e))===null||t===void 0||t(),this._pendingTransitionCleanups.delete(e)}updateDragAndDropState(){const e=fi(this._ctx.accessor.options);for(const o of this._chipRenderers.values()){var t,n,s;o.chip.element.draggable=e.html5,(t=o.html5DragSource)===null||t===void 0||t.setDisabled(!e.html5),(n=o.pointerDragSource)===null||n===void 0||n.setDisabled(!e.pointer),(s=o.pointerDragSource)===null||s===void 0||s.setTouchOnly(!e.pointerHandlesMouse)}}disposeChipDrag(e){var t;const n=this._chipRenderers.get(e);n&&((t=n.dragSourcesDisposable)===null||t===void 0||t.dispose(),n.html5DragSource=void 0,n.pointerDragSource=void 0,n.dragSourcesDisposable=void 0)}_buildChipGhostElement(e){const t=getComputedStyle(e),n=e.cloneNode(!0);return Array.from(t).forEach(s=>{n.style.setProperty(s,t.getPropertyValue(s),t.getPropertyPriority(s))}),n.style.position="absolute",n}disposeAll(){var e;(e=this._indicator)===null||e===void 0||e.dispose(),this._indicator=null;for(const[,n]of this._pendingTransitionCleanups)n();this._pendingTransitionCleanups.clear();for(const[,n]of this._chipRenderers){var t;n.chip.element.remove(),n.chip.dispose(),(t=n.dragSourcesDisposable)===null||t===void 0||t.dispose(),n.disposable.dispose()}this._chipRenderers.clear()}_ensureIndicator(){var e,t,n;const s=((e=(t=this._ctx.accessor.options.theme)===null||t===void 0?void 0:t.tabGroupIndicator)!==null&&e!==void 0?e:"wrap")==="none"?woe:boe;this._indicator&&!(this._indicator instanceof s)&&(this._indicator.dispose(),this._indicator=null),(n=this._indicator)!==null&&n!==void 0||(this._indicator=new s({tabsList:this._ctx.tabsList,getTabGroups:()=>this._ctx.group.model.getTabGroups(),getActivePanelId:()=>{var o;return(o=this._ctx.group.activePanel)===null||o===void 0?void 0:o.id},getTabMap:()=>this._ctx.getTabMap(),getChipElement:o=>{var r;return(r=this._chipRenderers.get(o))===null||r===void 0?void 0:r.chip.element},getDirection:()=>this._ctx.getDirection(),getHeaderPosition:()=>this._ctx.group.model.headerPosition,getColorPalette:()=>this._ctx.accessor.tabGroupColorPalette}))}_createChipDragSources(e,t){const n=fi(this._ctx.accessor.options);e.element.draggable=n.html5;const s=So.getInstance(),o=()=>(s.setData([new Zs(this._ctx.accessor.id,this._ctx.group.id,null,t.id)],Zs.prototype),{dispose:()=>{s.clearData(Zs.prototype)}}),r=Wo.createDragSource(e.element,{getData:o,disabled:!n.html5,isCancelled:()=>!fi(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(Zs.prototype)};e.element.addEventListener("dragend",a,{once:!0});const l=Co.createDragSource(e.element,{getData:o,disabled:!n.pointer,touchOnly:!n.pointerHandlesMouse,isCancelled:()=>!fi(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 ek(this._ctx.accessor.tabGroupColorPalette);s.init({tabGroup:e,api:this._ctx.accessor.api});const o=this._createChipDragSources(s,e),r=[e.onDidChange(()=>{var u;(u=s.update)===null||u===void 0||u.call(s,{tabGroup:e}),this._updateTabGroupClasses()}),e.onDidPanelChange(()=>{this._positionChipForGroup(e),this._updateTabGroupClasses()}),e.onDidCollapseChange(()=>{this._updateTabGroupClasses()})],a=u=>{var h;(h=this._chipRenderers.get(e.id))===null||h===void 0||(h=h.pointerDragSource)===null||h===void 0||h.cancelPending(),this._callbacks.onChipContextMenu(e,u)};s instanceof ek?r.push(s.onContextMenu(a)):r.push(new Zv(s.element,{onLongPress:a}),ct(s.element,"contextmenu",a));const l=this._ctx.getDirection()==="vertical",c=new tp(s.element,{acceptedTargetZones:l?["top"]:["left"],overlayModel:{activationSize:{value:100,type:"percentage"}},canDisplayOverlay:(u,h)=>{if(this._ctx.group.locked||this._ctx.accessor.options.disableDnd)return!1;const p=On();if(this._ctx.accessor.id===p?.viewId){var f;return((f=this._ctx.accessor.options.theme)===null||f===void 0?void 0:f.tabAnimation)!=="smooth"}return this._ctx.group.model.canDisplayOverlay(u,h,"tab")}});r.push(c,c.onDrop(u=>{this._callbacks.onChipDrop(e,u)}));const d=new pt(...r);this._chipRenderers.set(e.id,{chip:s,html5DragSource:o.html5DragSource,pointerDragSource:o.pointerDragSource,dragSourcesDisposable:o.disposable,disposable:d,dropTarget:c}),e.collapsed&&(this._skipNextCollapseAnimation=!0)}_positionChipForGroup(e){const t=this._chipRenderers.get(e.id);if(!t)return;const n=t.chip.element,s=e.panelIds;if(s.length===0){n.remove();return}const o=s[0],r=this._ctx.getTabMap().get(o);if(!r){n.remove();return}const a=r.value.element;n.nextSibling!==a&&this._ctx.tabsList.insertBefore(n,a)}_updateTabGroupClasses(){const e=this._ctx.group.model.getTabGroups(),t=this._ctx.getTabs(),n=this._ctx.getTabMap();let s=!1;const o=new Map;for(const l of e)for(const c of l.panelIds)o.set(c,l);for(const l of t){const c=l.value,d=c.panel.id,u=o.get(d),h=!!u;if(Qe(c.element,"dv-tab--grouped",h),u){const p=u.panelIds,f=p[0]===d,g=p[p.length-1]===d;Qe(c.element,"dv-tab--group-first",f),Qe(c.element,"dv-tab--group-last",g),e0(c.element,u.color,this._ctx.accessor.tabGroupColorPalette);const x=c.element.classList.contains("dv-tab--group-collapsed");if(!u.collapsed&&x){var r;s=!0,c.element.classList.remove("dv-tab--group-collapsed"),c.element.classList.add("dv-tab--group-expanding"),(r=this._pendingTransitionCleanups.get(d))===null||r===void 0||r();const v=()=>{c.element.classList.remove("dv-tab--group-expanding"),c.element.style.removeProperty("width"),c.element.removeEventListener("transitionend",v),clearTimeout(y),this._pendingTransitionCleanups.delete(d)},y=setTimeout(v,300);this._pendingTransitionCleanups.set(d,v),c.element.addEventListener("transitionend",v)}}else Qe(c.element,"dv-tab--group-first",!1),Qe(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())}},Coe=class extends pt{get _tabs(){return this.host.tabItems}get _tabMap(){return this.host.tabMap}get _tabsList(){return this.host.tabsList}get _direction(){return this.host.direction}get group(){return this.host.groupPanel}get accessor(){return this.host.component}get _tabGroupManager(){return this.host.tabGroupManager}get _wrapMode(){return this._tabsList.classList.contains(OP)}get animState(){return this._animState}set animState(e){this._animState=e}get pendingCollapse(){return this._pendingCollapse}set pendingCollapse(e){this._pendingCollapse=e}set voidContainerElement(e){this._voidContainer=e}constructor(e){super(),this.host=e,this._animState=null,this._pendingMarginCleanups=new Map,this._pendingCollapse=!1,this._flipTransitionCleanup=null,this._voidContainer=null,this._extendedDropZone=null,this._pointerInsideTabsList=!1,this._wrapIndicatorEl=null,this.addDisposables({dispose:()=>{var t;(t=this._flipTransitionCleanup)===null||t===void 0||t.call(this)}})}setExtendedDropZone(e){this._extendedDropZone=e}setExternalInsertionIndex(e){this._animState&&e!==this._animState.currentInsertionIndex&&(this._animState.currentInsertionIndex=e,this.applyDragOverTransforms())}clearExternalAnimState(){this._animState&&(this.resetTabTransforms(),this._animState.sourceIndex===-1?this._animState=null:this._animState.currentInsertionIndex=null)}snapshotTabPositions(){const e=new Map;for(const t of this._tabs)e.set(t.value.panel.id,t.value.element.getBoundingClientRect());return e}getAverageTabWidth(){if(this._tabs.length===0)return 0;const e=this._direction==="vertical";let t=0;for(const n of this._tabs){const s=n.value.element.getBoundingClientRect();t+=e?s.height:s.width}return t/this._tabs.length}handlePointerDragMove(e,t){var n;const s=((n=this._tabsList.ownerDocument)!==null&&n!==void 0?n:document).elementFromPoint(e,t);if(!(s&&(this._tabsList.contains(s)||this._extendedDropZone&&this._extendedDropZone.contains(s)))){this._pointerInsideTabsList&&(this._pointerInsideTabsList=!1,this.processDragLeave(s));return}this._pointerInsideTabsList=!0,this.processDragOver(e,t)}handlePointerDragEnd(e){e&&this._animState&&this._animState.sourceIndex!==-1&&!this._animState.sourceTabGroupId&&this._animState.currentInsertionIndex!==null&&this.isPointInsideTabsList(e.clientX,e.clientY)&&this.commitPointerReorder(e.pointerEvent),this._pointerInsideTabsList=!1,this.resetDragAnimation()}isPointInsideTabsList(e,t){var n;const s=((n=this._tabsList.ownerDocument)!==null&&n!==void 0?n:document).elementFromPoint(e,t);return!!s&&this._tabsList.contains(s)}commitPointerReorder(e){const t=this._animState;if(t?.currentInsertionIndex==null)return;const n=t.currentInsertionIndex,s=t.sourceIndex,o=n-(s!==-1&&s<n?1:0);this._animState=null,this.clearWrapDropIndicator(),this.uncollapseSourceTab(t.sourceTabId),o!==s&&this.host.fireDrop({event:e,index:o,targetTabGroupId:null})}processDragOver(e,t){if(this.accessor.options.disableDnd||(this._dropStaleAnimState(),!this._animState&&!this._initAnimStateForExternalDrag()))return!1;if(this._animState.sourceIndex!==-1){var n;(n=this.group.model.dropTargetContainer)===null||n===void 0||(n=n.model)===null||n===void 0||n.clear()}return this.handleDragOver({clientX:e,clientY:t}),!0}_dropStaleAnimState(){if(!this._animState)return;const e=On();e?.tabGroupId&&e.groupId!==this.group.id&&this._animState.sourceTabGroupId!==e.tabGroupId&&(this._animState=null)}_initAnimStateForExternalDrag(){var e;const t=On();if(((e=this.accessor.options.theme)===null||e===void 0?void 0:e.tabAnimation)==="default"&&!t?.tabGroupId||!t||!(t.panelId||t.tabGroupId)||t.groupId===this.group.id)return!1;const n=this.getAverageTabWidth();return this._animState=t.tabGroupId?this._makeGroupDragAnimState(t,n):this._makeTabDragAnimState(t,n),!0}_makeGroupDragAnimState(e,t){var n;const s=this.accessor.getPanel(e.groupId),o=s?.model.getTabGroups().find(a=>a.id===e.tabGroupId),r=t*((n=o?.panelIds.length)!==null&&n!==void 0?n:1)+t;return{sourceTabId:"",sourceIndex:-1,tabPositions:this.snapshotTabPositions(),chipPositions:this._tabGroupManager.snapshotChipWidths(),currentInsertionIndex:null,targetTabGroupId:null,sourceTabGroupId:e.tabGroupId,sourceGroupPanelIds:o?new Set(o.panelIds):new Set,sourceChipWidth:t,cursorOffsetFromDragLeft:r/2,sourceGapWidth:r,containerLeft:this._tabsList.getBoundingClientRect().left}}_makeTabDragAnimState(e,t){return{sourceTabId:e.panelId,sourceIndex:-1,tabPositions:this.snapshotTabPositions(),chipPositions:this._tabGroupManager.snapshotChipWidths(),currentInsertionIndex:null,targetTabGroupId:null,sourceTabGroupId:null,sourceGroupPanelIds:null,sourceChipWidth:0,cursorOffsetFromDragLeft:t/2,sourceGapWidth:t,containerLeft:this._tabsList.getBoundingClientRect().left}}processDragLeave(e){var t;if(this._animState&&!(e&&this._tabsList.contains(e))){if(e&&(!((t=this._extendedDropZone)===null||t===void 0)&&t.contains(e))){this.resetTabTransforms(),this._animState.currentInsertionIndex=null;return}if(!(this._voidContainer&&e&&(e===this._voidContainer||this._voidContainer.contains(e))))if(this.resetTabTransforms(),this._animState.sourceIndex===-1){var n;(n=this.group.model.dropTargetContainer)===null||n===void 0||(n=n.model)===null||n===void 0||n.clear(),this._animState=null}else this._animState.currentInsertionIndex=null}}handleDragOver(e){var t;if(!this._animState)return;if(this._wrapMode&&!this._animState.sourceTabGroupId){var n;this.handleWrappedDragOver(e.clientX,(n=e.clientY)!==null&&n!==void 0?n:0);return}const s=e.clientX,o=this._buildFirstPanelToGroupMap();let r=this._computeDragOverInsertionIndex(s,o),a=null;if(r!==null&&this._tabGroupManager.chipRenderers.size>0){const l=this._resolveInsertionAgainstTabGroups(s,r,o);r=l.insertionIndex,a=l.targetTabGroupId}r===this._animState.currentInsertionIndex&&a===this._animState.targetTabGroupId||(this._animState.currentInsertionIndex=r,this._animState.targetTabGroupId=a,((t=this.accessor.options.theme)===null||t===void 0?void 0:t.tabAnimation)==="smooth"&&this.applyDragOverTransforms())}_buildFirstPanelToGroupMap(){const e=new Map;if(this._tabGroupManager.chipRenderers.size===0)return e;for(const t of this.group.model.getTabGroups())t.id!==this._animState.sourceTabGroupId&&t.panelIds.length>0&&e.set(t.panelIds[0],t.id);return e}_computeDragOverInsertionIndex(e,t){const n=this._animState,s=n.sourceGroupPanelIds,o=e-n.cursorOffsetFromDragLeft-n.containerLeft;let r=0,a=null;for(let u=0;u<this._tabs.length;u++){const h=this._tabs[u].value;if(h.panel.id===n.sourceTabId||s?.has(h.panel.id))continue;const p=t.get(h.panel.id);if(p){var l;const x=(l=n.chipPositions.get(p))!==null&&l!==void 0?l:0;if(r+x>o){var c;(c=a)!==null&&c!==void 0||(a=u);break}r+=x}const f=n.tabPositions.get(h.panel.id),g=f?f.width:h.element.getBoundingClientRect().width;if(r+g/2<=o)r+=g,a=u+1;else{var d;(d=a)!==null&&d!==void 0||(a=u);break}}return a}_accumulatedWidthUpTo(e,t){const n=this._animState,s=n.sourceGroupPanelIds;let o=0;for(let a=0;a<this._tabs.length;a++){const l=this._tabs[a].value;if(l.panel.id===n.sourceTabId||s?.has(l.panel.id))continue;if(a>=e)break;const c=t.get(l.panel.id);if(c){var r;o+=(r=n.chipPositions.get(c))!==null&&r!==void 0?r:0}const d=n.tabPositions.get(l.panel.id);o+=d?d.width:l.element.getBoundingClientRect().width}return o}_resolveInsertionAgainstTabGroups(e,t,n){const s=!!this._animState.sourceTabGroupId,o=this._accumulatedWidthUpTo(t,n);for(const r of this.group.model.getTabGroups()){const a=this._evaluateTabGroupForInsertion(r,e,t,o,s);if(a)return a}return{insertionIndex:t,targetTabGroupId:null}}_evaluateTabGroupForInsertion(e,t,n,s,o){const r=this._resolveGroupRange(e);if(!r)return null;const{firstIdx:a,lastIdx:l}=r,c=n>=a&&n<=l,d=!c&&n===a-1;return!c&&!d?null:o?this._resolveGroupDragTarget(n,a,l,c):this._resolveTabDragTarget(e,t,n,s,a,d)}_resolveGroupRange(e){const t=this._animState,n=t.sourceGroupPanelIds,s=e.panelIds.filter(a=>a!==t.sourceTabId&&!n?.has(a));if(s.length===0)return null;const o=this._tabs.findIndex(a=>a.value.panel.id===s[0]),r=this._tabs.findIndex(a=>a.value.panel.id===s[s.length-1]);return o===-1||r===-1?null:{firstIdx:o,lastIdx:r}}_resolveGroupDragTarget(e,t,n,s){return s?{insertionIndex:e<(t+n+1)/2?t:n+1,targetTabGroupId:null}:{insertionIndex:e,targetTabGroupId:null}}_resolveTabDragTarget(e,t,n,s,o,r){var a;const l=this._animState,c=(a=l.chipPositions.get(e.id))!==null&&a!==void 0?a:0;if(r)return this._onlySourceBetween(n,o)?t>=(e.collapsed?l.containerLeft+s+c/2:l.containerLeft+s+c)?{insertionIndex:o,targetTabGroupId:e.id}:{insertionIndex:n,targetTabGroupId:null}:null;const d=l.containerLeft+s+c;return n===o?{insertionIndex:n,targetTabGroupId:t>=d?e.id:null}:{insertionIndex:n,targetTabGroupId:e.id}}_onlySourceBetween(e,t){const n=this._animState;for(let o=e;o<t;o++){var s;const r=this._tabs[o].value.panel.id;if(r!==n.sourceTabId&&!(!((s=n.sourceGroupPanelIds)===null||s===void 0)&&s.has(r)))return!1}return!0}handleWrappedDragOver(e,t){if(!this._animState)return;const n=this.computeWrappedInsertionIndex(e,t);n===this._animState.currentInsertionIndex&&this._animState.targetTabGroupId===null||(this._animState.currentInsertionIndex=n,this._animState.targetTabGroupId=null,this.updateWrapDropIndicator(n))}computeWrappedInsertionIndex(e,t){var n;const s=this._direction==="vertical",o=this._wrappedDragEntries();if(o.length===0)return this._tabs.length;const r=s?e:t,a=s?t:e,l=f=>s?f.left:f.top,c=f=>s?f.right:f.bottom,d=f=>s?f.top:f.left,u=f=>s?f.height:f.width,h=this._bucketWrappedLines(o,l,c),p=[...((n=h.find(f=>r>=f.start&&r<=f.end))!==null&&n!==void 0?n:this._nearestWrappedLine(h,r)).items].sort((f,g)=>d(f.rect)-d(g.rect));for(const f of p)if(a<d(f.rect)+u(f.rect)/2)return f.index;return p[p.length-1].index+1}_wrappedDragEntries(){var e,t;const n=(e=this._animState)===null||e===void 0?void 0:e.sourceTabId,s=(t=this._animState)===null||t===void 0?void 0:t.sourceGroupPanelIds,o=[];for(let r=0;r<this._tabs.length;r++){const a=this._tabs[r].value;a.panel.id!==n&&(s?.has(a.panel.id)||o.push({index:r,rect:a.element.getBoundingClientRect()}))}return o}_bucketWrappedLines(e,t,n){const s=[];for(const o of e){const r=t(o.rect),a=s.find(l=>Math.abs(l.start-r)<=2);a?(a.items.push(o),a.end=Math.max(a.end,n(o.rect))):s.push({start:r,end:n(o.rect),items:[o]})}return s.sort((o,r)=>o.start-r.start),s}_nearestWrappedLine(e,t){const n=s=>t<s.start?s.start-t:t-s.end;return e.reduce((s,o)=>n(o)<n(s)?o:s,e[0])}updateWrapDropIndicator(e){var t;this.clearWrapDropIndicator();const n=this._tabs.length;if(n===0)return;const s=(t=this._animState)===null||t===void 0?void 0:t.sourceTabId;if(e<n){const o=this._tabs[e].value.element;if(this._tabs[e].value.panel.id===s)return;o.classList.add("dv-tab--reorder-before"),this._wrapIndicatorEl=o}else{const o=this._tabs[n-1].value.element;o.classList.add("dv-tab--reorder-after"),this._wrapIndicatorEl=o}}clearWrapDropIndicator(){var e;(e=this._wrapIndicatorEl)===null||e===void 0||e.classList.remove("dv-tab--reorder-before","dv-tab--reorder-after"),this._wrapIndicatorEl=null}_removeClassInstantlyBatch(e,t){const n=[];for(const s of e)s.classList.contains(t)&&(s.style.transition="none",Qe(s,t,!1),n.push(s));if(n.length>0){n[0].getBoundingClientRect();for(const s of n)s.style.removeProperty("transition")}}uncollapseSourceTab(e){const t=this._tabMap.get(e);t&&this._removeClassInstantlyBatch([t.value.element],"dv-tab--dragging")}applyDragOverTransforms(e=!1){var t;if(this._wrapMode)return;if(((t=this._animState)===null||t===void 0?void 0:t.currentInsertionIndex)==null){this.resetTabTransforms();return}if(this._pendingCollapse)return;const n=this._animState.currentInsertionIndex,s=this._computeGapWidth(),o=this._computeChipToShift(n);this._applyGapMargins(n,s,o,e)}_computeGapWidth(){const e=this._animState;if(e.sourceTabGroupId&&e.sourceGroupPanelIds)return e.sourceGapWidth;const t=e.tabPositions.get(e.sourceTabId);return t?t.width:this.getAverageTabWidth()}_computeChipToShift(e){if(this._tabGroupManager.chipRenderers.size===0)return null;for(const t of this.group.model.getTabGroups()){const n=this._chipToShiftForGroup(t,e);if(n!==void 0)return n}return null}_chipToShiftForGroup(e,t){const n=this._animState;if(e.id===n.sourceTabGroupId||e.panelIds.includes(n.sourceTabId))return;const s=e.panelIds.filter(r=>{var a;return r!==n.sourceTabId&&!(!((a=n.sourceGroupPanelIds)===null||a===void 0)&&a.has(r))});if(s.length===0)return;const o=this._tabs.findIndex(r=>r.value.panel.id===s[0]);if((!n.targetTabGroupId||n.targetTabGroupId===e.id&&e.collapsed)&&!(o<t)){if(this._onlySourceBetween(t,o)){const r=this._tabGroupManager.chipRenderers.get(e.id);if(r)return r.chip.element}return null}}_applyGapMargins(e,t,n,s){const o=this._animState,r=o.sourceGroupPanelIds;let a=!1;for(const[l,c]of this._tabGroupManager.chipRenderers)l!==o.sourceTabGroupId&&this._clearMargin(c.chip.element,s);n&&(this._setMargin(n,`${t}px`,s),a=!0);for(let l=0;l<this._tabs.length;l++){const c=this._tabs[l].value;c.panel.id!==o.sourceTabId&&(r?.has(c.panel.id)||(!a&&l>=e?(this._setMargin(c.element,`${t}px`,s),a=!0):this._clearMargin(c.element,s)))}this._tabGroupManager.trackUnderlines()}_shiftingClass(e){return e.classList.contains("dv-tab-group-chip")?"dv-tab-group-chip--shifting":"dv-tab--shifting"}_setMargin(e,t,n){n?(e.style.transition="none",e.style.marginLeft=t,e.getBoundingClientRect(),e.style.removeProperty("transition")):e.style.marginLeft=t,Qe(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"),Qe(e,n,!1);else{e.style.marginLeft="0px",Qe(e,n,!0);const o=()=>{e.style.removeProperty("margin-left"),Qe(e,n,!1),e.removeEventListener("transitionend",o),clearTimeout(r),this._pendingMarginCleanups.delete(e)},r=setTimeout(o,300);this._pendingMarginCleanups.set(e,o),e.addEventListener("transitionend",o)}}resetTabTransforms(){this.clearWrapDropIndicator();for(const[,e]of this._pendingMarginCleanups)e();this._pendingMarginCleanups.clear();for(const e of this._tabs)e.value.element.style.removeProperty("margin-left"),e.value.element.style.removeProperty("margin-right"),e.value.element.style.removeProperty("margin-top"),e.value.element.style.removeProperty("margin-bottom"),e.value.element.style.removeProperty("transform"),Qe(e.value.element,"dv-tab--shifting",!1);for(const[,e]of this._tabGroupManager.chipRenderers)e.chip.element.style.removeProperty("margin-left"),Qe(e.chip.element,"dv-tab-group-chip--shifting",!1);this._tabGroupManager.positionUnderlines()}commitGroupMove(e,t){const n=On();if(this._tabGroupManager.disposeChipDrag(e),this.group.model.getTabGroups().some(r=>r.id===e)){var s;if(((s=this.accessor.options.theme)===null||s===void 0?void 0:s.tabAnimation)==="smooth"){this._clearGroupDragClasses(e);const r=this.snapshotTabPositions();this.resetTabTransforms(),this.group.model.moveTabGroup(e,t),this.runFlipAnimation(r,"",!1)}else this._tabGroupManager.skipNextCollapseAnimation=!0,this.group.model.moveTabGroup(e,t)}else if(n){var o;this.resetTabTransforms(),this.accessor.moveGroupOrPanel({from:{groupId:n.groupId,tabGroupId:(o=n.tabGroupId)!==null&&o!==void 0?o:e},to:{group:this.group,position:"center",index:t}})}}_clearGroupDragClasses(e){const t=this._tabGroupManager.chipRenderers.get(e);t&&this._removeClassInstantlyBatch([t.chip.element],"dv-tab-group-chip--dragging"),this._removeClassInstantlyBatch(this._tabs.map(s=>s.value.element),"dv-tab--dragging");const n=this._tabGroupManager.groupUnderlines.get(e);n&&n.style.removeProperty("display"),this._tabGroupManager.skipNextCollapseAnimation=!0}resetDragAnimation(){if(this._pendingCollapse=!1,this._animState){this.resetTabTransforms(),this._animState.sourceTabGroupId?this._clearGroupDragClasses(this._animState.sourceTabGroupId):this._removeClassInstantlyBatch(this._tabs.map(e=>e.value.element),"dv-tab--dragging"),this._animState=null;for(const[,e]of this._tabGroupManager.groupUnderlines)e.style.removeProperty("display")}}runFlipAnimation(e,t,n=!1,s){if(this._wrapMode)return;let o=!1;for(let r=0;r<this._tabs.length;r++)this._applyFlipTransform(this._tabs[r],r,t,n,e,s)&&(o=!0);o&&this._scheduleFlipReset()}_applyFlipTransform(e,t,n,s,o,r){const a=this._direction==="vertical",l=e.value.panel.id;if(l===n){if(!s)return!1;const h=e.value.element.getBoundingClientRect();return e.value.element.style.transform=a?`translateY(${h.height}px)`:`translateX(${h.width}px)`,Qe(e.value.element,"dv-tab--shifting",!0),!0}if(r!==void 0&&(t<r.from||t>r.to))return!1;const c=o.get(l);if(!c)return!1;const d=e.value.element.getBoundingClientRect(),u=a?c.top-d.top:c.left-d.left;return Math.abs(u)<1?!1:(e.value.element.style.transform=a?`translateY(${u}px)`:`translateX(${u}px)`,Qe(e.value.element,"dv-tab--shifting",!0),!0)}_scheduleFlipReset(){requestAnimationFrame(()=>{var e;for(const s of this._tabs)s.value.element.style.transform&&(s.value.element.style.transform="");this._tabGroupManager.trackUnderlines(),(e=this._flipTransitionCleanup)===null||e===void 0||e.call(this);const t=s=>{if(s.propertyName==="transform"){n();for(const o of this._tabs)Qe(o.value.element,"dv-tab--shifting",!1);this._tabGroupManager.positionUnderlines()}},n=()=>{this._tabsList.removeEventListener("transitionend",t),this._flipTransitionCleanup=null};this._flipTransitionCleanup=n,this._tabsList.addEventListener("transitionend",t)})}},koe=class extends pt{get _animState(){return this._reorder.animState}set _animState(e){this._reorder.animState=e}get _pendingCollapse(){return this._reorder.pendingCollapse}set _pendingCollapse(e){this._reorder.pendingCollapse=e}get tabItems(){return this._tabs}get tabMap(){return this._tabMap}get tabsList(){return this._tabsList}get groupPanel(){return this.group}get component(){return this.accessor}get tabGroupManager(){return this._tabGroupManager}fireDrop(e){this._onDrop.fire(e)}setOverflowExclude(e){this._overflowExclude=e,this.refreshOverflow()}setForcedOverflow(e){this._forcedOverflow=e,this.refreshOverflow()}refreshOverflow(){this._showTabsOverflowControl&&this.toggleDropdown({reset:!1}),this._applyPinnedSticky()}setPinnedSticky(e){this._pinnedSticky!==e&&(this._pinnedSticky=e,this._applyPinnedSticky())}_applyPinnedSticky(){const e=this._pinnedSticky?this._tabs.filter(n=>this._overflowExclude(n.value.panel.id)):[];if(e.length===0&&!this._hasPinnedStickyStyling)return;for(const n of this._tabs){const s=n.value.element;s.classList.contains("dv-tab--pinned-sticky")&&(s.classList.remove("dv-tab--pinned-sticky"),s.style.removeProperty("--dv-pinned-sticky-left"))}if(e.length===0){this._hasPinnedStickyStyling=!1;return}const t=e.map(n=>n.value.element.offsetLeft);e.forEach((n,s)=>{const o=n.value.element;o.classList.add("dv-tab--pinned-sticky"),o.style.setProperty("--dv-pinned-sticky-left",`${t[s]}px`)}),this._hasPinnedStickyStyling=!0}get showTabsOverflowControl(){return this._showTabsOverflowControl}set showTabsOverflowControl(e){if(this._showTabsOverflowControl!=e)if(this._showTabsOverflowControl=e,e){const t=new uie(this._tabsList);this._observerDisposable.value=new pt(t,t.onDidChange(n=>{const s=n.hasScrollX||n.hasScrollY;this.toggleDropdown({reset:!s}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}),ct(this._tabsList,"scroll",()=>{this.toggleDropdown({reset:!1}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}))}else this._observerDisposable.value=cn.NONE}get element(){return this._element}get tabsListElement(){return this._tabsList}set voidContainer(e){var t;(t=this._voidContainerListeners)===null||t===void 0||t.dispose(),this._voidContainerListeners=null,this._reorder.voidContainerElement=e,e&&(this._voidContainerListeners=new pt(ct(e,"dragover",n=>{this._animState&&n.preventDefault()}),ct(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),ji(this._tabsList,"dv-horizontal","dv-vertical"),e==="vertical"?_i(this._tabsList,"dv-tabs-container-vertical","dv-vertical"):(ji(this._tabsList,"dv-tabs-container-vertical"),_i(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 Bn,this._pointerActivation=new Bn,this._scrollbar=null,this._tabs=[],this._tabMap=new Map,this.selectedIndex=-1,this._showTabsOverflowControl=!1,this._overflowExclude=()=>!1,this._forcedOverflow=()=>!1,this._pinnedSticky=!1,this._hasPinnedStickyStyling=!1,this._direction="horizontal",this._voidContainerListeners=null,this._onTabDragStart=new ve,this.onTabDragStart=this._onTabDragStart.event,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onOverflowTabsChange=new ve,this.onOverflowTabsChange=this._onOverflowTabsChange.event,this._tabsList=document.createElement("div"),this._tabsList.className="dv-tabs-container",this._tabsList.setAttribute("role","tablist"),this._tabsList.setAttribute("aria-orientation",this._direction==="vertical"?"vertical":"horizontal"),this.showTabsOverflowControl=n.showTabsOverflowControl,t.options.scrollbars==="native"?this._element=this._tabsList:(this._scrollbar=new RP(this._tabsList),this._scrollbar.orientation=this.direction,this._element=this._scrollbar.element,this.addDisposables(this._scrollbar)),this._tabGroupManager=new Soe({group:this.group,accessor:this.accessor,tabsList:this._tabsList,getTabs:()=>this._tabs,getTabMap:()=>this._tabMap,getDirection:()=>this._direction},{onChipContextMenu:(s,o)=>{var r;(r=this.accessor.contextMenuService)===null||r===void 0||r.showForChip(s,this.group,o)},onChipDragStart:(s,o,r)=>{this._handleChipDragStart(s,o,r)},onChipDragEnd:()=>{this._reorder.resetDragAnimation()},onChipDrop:(s,o)=>{this._handleChipDrop(s,o)}}),this._reorder=new Coe(this),this.addDisposables(this._onOverflowTabsChange,this._observerDisposable,this._pointerActivation,this._onWillShowOverlay,this._onDrop,this._onTabDragStart,this._reorder,Ju.getInstance().onDragEnd(s=>{this._reorder.handlePointerDragEnd(s)}),Ju.getInstance().onDragMove(s=>{this._reorder.handlePointerDragMove(s.clientX,s.clientY)}),ct(this.element,"pointerdown",s=>{s.defaultPrevented||s.button===0&&this.accessor.doSetGroupActive(this.group)}),ct(this._tabsList,"wheel",s=>{const o=this._direction==="vertical",r=o?s.deltaY||s.deltaX:s.deltaX||s.deltaY;if(r===0)return;const a=o?this._tabsList.scrollHeight-this._tabsList.clientHeight:this._tabsList.scrollWidth-this._tabsList.clientWidth;if(a<=0)return;const l=o?this._tabsList.scrollTop:this._tabsList.scrollLeft;r<0&&l<=0||r>0&&l>=a||(s.preventDefault(),s.stopPropagation(),o?this._tabsList.scrollTop=l+r:this._tabsList.scrollLeft=l+r)},{passive:!1}),ct(this._tabsList,"keydown",s=>{this._onKeyDown(s)}),ct(this._tabsList,"dragover",s=>{this._reorder.processDragOver(s.clientX,s.clientY)&&s.preventDefault()},!0),ct(this._tabsList,"dragleave",s=>{this._reorder.processDragLeave(s.relatedTarget)},!0),ct(this._tabsList,"dragend",()=>{this._reorder.resetDragAnimation()}),ct(this._tabsList,"drop",s=>{var o,r,a;if(((o=this._animState)===null||o===void 0?void 0:o.currentInsertionIndex)==null||((r=this.accessor.options.theme)===null||r===void 0?void 0:r.tabAnimation)!=="smooth"&&!this._animState.sourceTabGroupId)return;s.stopPropagation(),s.preventDefault(),(a=this.group.model.dropTargetContainer)===null||a===void 0||(a=a.model)===null||a===void 0||a.clear();const l=this._animState;if(this._animState=null,this._pendingCollapse=!1,l.sourceTabGroupId){this._commitGroupMove(l.sourceTabGroupId,l.currentInsertionIndex);return}const c=l.currentInsertionIndex,d=l.sourceIndex,u=c-(d!==-1&&d<c?1:0),h=this.group.model.getTabGroupForPanel(l.sourceTabId);if(u===d&&!l.targetTabGroupId&&!h){this._reorder.uncollapseSourceTab(l.sourceTabId),this.resetTabTransforms();return}this._reorder.uncollapseSourceTab(l.sourceTabId);const p=this.snapshotTabPositions();this.resetTabTransforms(),this._onDrop.fire({event:s,index:u,targetTabGroupId:l.targetTabGroupId}),this.runFlipAnimation(p,l.sourceTabId,l.sourceIndex===-1,{from:Math.min(d,u),to:Math.max(d,u)})},!0),cn.from(()=>{var s;(s=this._voidContainerListeners)===null||s===void 0||s.dispose(),this._reorder.resetDragAnimation(),this._tabGroupManager.disposeAll();for(const{value:o,disposable:r}of this._tabs)r.dispose(),o.dispose();this._tabs=[],this._tabMap.clear()}))}indexOf(e){return this._tabs.findIndex(t=>t.value.panel.id===e)}getTabId(e){var t;return(t=this._tabMap.get(e))===null||t===void 0?void 0:t.value.element.id}getPanelForTab(e){for(const{value:t}of this._tabs)if(t.element===e||t.element.contains(e))return t.panel}isActive(e){return this.selectedIndex>-1&&this._tabs[this.selectedIndex].value===e}_onKeyDown(e){const t=this._tabs.findIndex(a=>a.value.element===e.target);if(t===-1)return;const n=this._direction==="vertical",s=n?"ArrowDown":"ArrowRight",o=n?"ArrowUp":"ArrowLeft",r=this._tabs.length-1;switch(e.key){case s:e.preventDefault(),this._focusTab(Math.min(t+1,r));break;case o:e.preventDefault(),this._focusTab(Math.max(t-1,0));break;case"Home":e.preventDefault(),this._focusTab(0);break;case"End":e.preventDefault(),this._focusTab(r);break;case"Enter":case" ":e.preventDefault(),this.accessor.withOrigin("user",()=>this._tabs[t].value.panel.api.setActive());break;case"Delete":case"Backspace":e.preventDefault(),this._closeTab(t);break}}_closeTab(e){var t,n,s,o,r;const a=(t=this._tabs[e])===null||t===void 0?void 0:t.value;if(!a)return;const l=(n=(s=(o=this._tabs[e+1])===null||o===void 0?void 0:o.value)!==null&&s!==void 0?s:(r=this._tabs[e-1])===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n.panel.id;if(a.panel.api.close(),l!==void 0){const c=this._tabs.findIndex(d=>d.value.panel.id===l);c>-1&&this._focusTab(c)}}_focusTab(e){for(let t=0;t<this._tabs.length;t++)this._tabs[t].value.element.tabIndex=t===e?0:-1;this._tabs[e].value.element.focus()}focusActiveTab(){var e;if(this._tabs.length===0)return;const t=(e=this.group.activePanel)===null||e===void 0?void 0:e.id,n=t?this._tabs.findIndex(s=>s.value.panel.id===t):-1;this._focusTab(n>-1?n:0)}setActivePanel(e){const t=this._direction==="vertical";for(const n of this._tabs){const s=e.id===n.value.panel.id;n.value.setActive(s),s&&this._scrollTabIntoView(n.value.element,t)}this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}_scrollTabIntoView(e,t){const n=e.parentElement;if(!n)return;const s=t?e.offsetTop:e.offsetLeft,o=t?e.offsetHeight:e.offsetWidth,r=t?n.scrollTop:n.scrollLeft,a=t?n.clientHeight:n.clientWidth;(s<r||s+o>r+a)&&(t?n.scrollTop=s:n.scrollLeft=s)}_activateOnPointerDown(e){if(!fi(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 uoe(e,this.accessor,this.group);n.setContent(e.view.tab),this._direction!=="horizontal"&&n.setDirection(this._direction);const s={value:n,disposable:new pt(n.onDragStart(o=>{var r;if(this._onTabDragStart.fire({nativeEvent:o,panel:e}),((r=this.accessor.options.theme)===null||r===void 0?void 0:r.tabAnimation)==="smooth"){const a=n.element.getBoundingClientRect().width,l=this._tabs.findIndex(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",Qe(n.element,"dv-tab--dragging",!0),n.element.offsetHeight),(d=(c=this._animState).currentInsertionIndex)!==null&&d!==void 0||(c.currentInsertionIndex=l),this.applyDragOverTransforms(!0),n.element.style.removeProperty("transition"))})}}),n.onTabClick(o=>{o.defaultPrevented||this.group.api.location.type==="edge"&&(this.group.activePanel===e?this.group.api.isCollapsed()?this.group.api.expand():this.group.api.collapse():(this.group.model.openPanel(e),this.group.api.isCollapsed()&&this.group.api.expand()))}),n.onPointerDown(o=>{if(o.defaultPrevented)return;const r=!this.accessor.options.disableFloatingGroups,a=this.group.api.location.type==="floating"&&this.size===1;if(r&&!a&&o.shiftKey){o.preventDefault();const l=this.accessor.getGroupPanel(n.panel.id),{top:c,left:d}=n.element.getBoundingClientRect(),{top:u,left:h}=this.accessor.element.getBoundingClientRect();this.accessor.addFloatingGroup(l,{x:d-h,y:c-u,inDragMode:!0});return}o.button===0&&this.group.api.location.type!=="edge"&&this.group.activePanel!==e&&this._activateOnPointerDown(e)}),n.onDrop(o=>{const r=this._animState;this._animState=null,this._pendingCollapse=!1;const a=this._tabs.findIndex(h=>h.value===n);if(r){var l;const h=o.position==="right"?a+1:a;if(r.sourceTabGroupId){var c;this._commitGroupMove(r.sourceTabGroupId,(c=r.currentInsertionIndex)!==null&&c!==void 0?c:h);return}this._reorder.uncollapseSourceTab(r.sourceTabId);const p=this.snapshotTabPositions();this.resetTabTransforms(),this._onDrop.fire({event:o.nativeEvent,index:h,targetTabGroupId:r.targetTabGroupId}),((l=this.accessor.options.theme)===null||l===void 0?void 0:l.tabAnimation)==="smooth"&&this.runFlipAnimation(p,r.sourceTabId,r.sourceIndex===-1,r.sourceIndex===-1?void 0:{from:Math.min(r.sourceIndex,h),to:Math.max(r.sourceIndex,h)})}else{var d,u;const h=this._direction==="vertical"?"bottom":"right",p=o.position===h?a+1:a,f=On(),g=f?this._tabs.findIndex(y=>y.value.panel.id===f.panelId):-1,x=p-(g!==-1&&g<p?1:0),v=(d=(u=this.group.model.getTabGroupForPanel(n.panel.id))===null||u===void 0?void 0:u.id)!==null&&d!==void 0?d:null;this._onDrop.fire({event:o.nativeEvent,index:x,targetTabGroupId:v})}}),n.onWillShowOverlay(o=>{this._onWillShowOverlay.fire(new ac(o,{kind:"tab",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:On}))}))};this.addTab(s,t),this._tabGroupManager.positionAllChips(),this._animState&&(this._animState.tabPositions=this.snapshotTabPositions(),this._animState.chipPositions=this._tabGroupManager.snapshotChipWidths(),this.applyDragOverTransforms())}delete(e){var t;((t=this._animState)===null||t===void 0?void 0:t.sourceTabId)===e&&(this.resetTabTransforms(),this._animState=null),this._tabGroupManager.cleanupTransition(e);const n=this.indexOf(e),s=this._tabs.splice(n,1)[0];if(this._tabMap.delete(e),s){const{value:o,disposable:r}=s;r.dispose(),o.dispose(),o.element.remove()}this._animState&&(this._animState.tabPositions=this.snapshotTabPositions(),this._animState.chipPositions=this._tabGroupManager.snapshotChipWidths(),this.applyDragOverTransforms())}addTab(e,t=this._tabs.length){if(t<0||t>this._tabs.length)throw new Error("invalid location");const n=t<this._tabs.length?this._tabs[t].value.element:null;this._tabsList.insertBefore(e.value.element,n),this._tabs=[...this._tabs.slice(0,t),e,...this._tabs.slice(t)],this._tabMap.set(e.value.panel.id,e),this.selectedIndex<0&&(this.selectedIndex=t)}toggleDropdown(e){const t=this._tabs.some(a=>!this._overflowExclude(a.value.panel.id)&&this._forcedOverflow(a.value.panel.id));if(e.reset&&!t){this._onOverflowTabsChange.fire({tabs:[],tabGroups:[],pinnedTabs:[],reset:!0});return}const n=this._tabs.filter(a=>!this._overflowExclude(a.value.panel.id)&&(this._forcedOverflow(a.value.panel.id)||!e.reset&&!Tf(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&&!Tf(a.value.element,this._tabsList)).map(a=>a.value.panel.id),o=new Set(n),r=[];for(const a of this.group.model.getTabGroups()){const l=this._tabGroupManager.chipRenderers.get(a.id),c=l&&!Tf(l.chip.element,this._tabsList),d=a.panelIds.length>0&&a.panelIds.every(u=>o.has(u));if((c||d)&&(r.push(a.id),a.collapsed))for(const u of a.panelIds)o.has(u)||(o.add(u),n.push(u))}this._onOverflowTabsChange.fire({tabs:n,tabGroups:r,pinnedTabs:s,reset:!1})}updateDragAndDropState(){for(const e of this._tabs)e.value.updateDragAndDropState();this._tabGroupManager.updateDragAndDropState()}updateTabGroups(){this._tabGroupManager.update()}refreshTabGroupAccent(){this._tabGroupManager.refreshAccents()}_handleChipDragStart(e,t,n){var s;const o=e.panelIds[0],r=o?this._tabs.findIndex(d=>d.value.panel.id===o):-1,a=t.element.getBoundingClientRect();let l=a.width;for(const d of e.panelIds){const u=this._tabMap.get(d);u&&(l+=u.value.element.getBoundingClientRect().width)}if(this._animState={sourceTabId:"",sourceIndex:r,tabPositions:this.snapshotTabPositions(),chipPositions:this._tabGroupManager.snapshotChipWidths(),currentInsertionIndex:null,targetTabGroupId:null,sourceTabGroupId:e.id,sourceGroupPanelIds:new Set(e.panelIds),sourceChipWidth:a.width,cursorOffsetFromDragLeft:n.clientX-a.left,sourceGapWidth:l,containerLeft:this._tabsList.getBoundingClientRect().left},((s=this.accessor.options.theme)===null||s===void 0?void 0:s.tabAnimation)!=="smooth")return;const c=new Set(e.panelIds);this._pendingCollapse=!0,requestAnimationFrame(()=>{var d,u;if(this._pendingCollapse=!1,!this._animState)return;for(const f of this._tabs)c.has(f.value.panel.id)&&(f.value.element.style.transition="none",Qe(f.value.element,"dv-tab--dragging",!0));const h=this._tabGroupManager.chipRenderers.get(e.id);h&&(h.chip.element.style.transition="none",Qe(h.chip.element,"dv-tab-group-chip--dragging",!0)),this._tabsList.offsetHeight;const p=this._tabGroupManager.groupUnderlines.get(e.id);p&&(p.style.display="none"),(u=(d=this._animState).currentInsertionIndex)!==null&&u!==void 0||(d.currentInsertionIndex=r),this.applyDragOverTransforms(!0);for(const f of this._tabs)c.has(f.value.panel.id)&&f.value.element.style.removeProperty("transition");h&&h.chip.element.style.removeProperty("transition")})}_handleChipDrop(e,t){const n=e.panelIds[0];if(!n)return;const s=this._tabs.findIndex(l=>l.value.panel.id===n);if(s===-1)return;const o=On(),r=o?.groupId===this.group.id&&o?.panelId?this._tabs.findIndex(l=>l.value.panel.id===o.panelId):-1,a=s-(r!==-1&&r<s?1:0);this._onDrop.fire({event:t.nativeEvent,index:a,targetTabGroupId:null})}setExtendedDropZone(e){this._reorder.setExtendedDropZone(e)}setExternalInsertionIndex(e){this._reorder.setExternalInsertionIndex(e)}clearExternalAnimState(){this._reorder.clearExternalAnimState()}snapshotTabPositions(){return this._reorder.snapshotTabPositions()}handleDragOver(e){this._reorder.handleDragOver(e)}applyDragOverTransforms(e=!1){this._reorder.applyDragOverTransforms(e)}resetTabTransforms(){this._reorder.resetTabTransforms()}_commitGroupMove(e,t){this._reorder.commitGroupMove(e,t)}runFlipAnimation(e,t,n=!1,s){this._reorder.runFlipAnimation(e,t,n,s)}};function joe(){const e=document.createElement("div");e.className="dv-tabs-overflow-dropdown-default";const t=document.createElement("span");t.textContent="";const n=AP();return e.appendChild(n),e.appendChild(t),{element:e,update:s=>{t.textContent=`${s.tabs}`}}}var _oe=class extends pt{get onTabDragStart(){return this.tabs.onTabDragStart}get panels(){return this.tabs.panels}get size(){return this.tabs.size}get hidden(){return this._hidden}set hidden(e){this._hidden=e,this.element.style.display=e?"none":""}get direction(){return this._direction}set direction(e){this._direction=e,e==="vertical"?(_i(this._element,"dv-groupview-header-vertical"),_i(this.rightActionsContainer,"dv-right-actions-container-vertical"),this.tabs.direction=e):(ji(this._element,"dv-groupview-header-vertical"),ji(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 Bn,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onGroupDragStart=new ve,this.onGroupDragStart=this._onGroupDragStart.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._element=document.createElement("div"),this._element.className="dv-tabs-and-actions-container",Qe(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 koe(t,e,{showTabsOverflowControl:!e.options.disableTabsOverflowList}),this.voidContainer=new hoe(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 ac(n,{kind:"header_space",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:On}))}),ct(this.leftActionsContainer,"dragleave",n=>{const s=n.relatedTarget;!this.leftActionsContainer.contains(s)&&!this._element.contains(s)&&this.tabs.clearExternalAnimState()}),ct(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())}),ct(this.voidContainer.element,"pointerdown",n=>{if(!n.defaultPrevented&&!this.accessor.options.disableFloatingGroups&&n.shiftKey&&this.group.api.location.type!=="floating"&&this.group.api.location.type!=="edge"){n.preventDefault();const{top:s,left:o}=this.element.getBoundingClientRect(),{top:r,left:a}=this.accessor.element.getBoundingClientRect();this.accessor.addFloatingGroup(this.group,{x:o-a+20,y:s-r+20,inDragMode:!0})}}))}show(){this.hidden||(this.element.style.display="")}hide(){this._element.style.display="none"}setRightActionsElement(e){this.rightActions!==e&&(this.rightActions&&(this.rightActions.remove(),this.rightActions=void 0),e&&(this.rightActionsContainer.appendChild(e),this.rightActions=e))}setLeftActionsElement(e){this.leftActions!==e&&(this.leftActions&&(this.leftActions.remove(),this.leftActions=void 0),e&&(this.leftActionsContainer.appendChild(e),this.leftActions=e))}setPrefixActionsElement(e){this.preActions!==e&&(this.preActions&&(this.preActions.remove(),this.preActions=void 0),e&&(this.preActionsContainer.appendChild(e),this.preActions=e))}isActive(e){return this.tabs.isActive(e)}indexOf(e){return this.tabs.indexOf(e)}getTabId(e){return this.tabs.getTabId(e)}getPanelForTab(e){return this.tabs.getPanelForTab(e)}setActive(e){}delete(e){this.tabs.delete(e),this.updateClassnames()}setActivePanel(e){this.tabs.setActivePanel(e)}focusActiveTab(){this.tabs.focusActiveTab()}openPanel(e,t=this.tabs.size){this.tabs.openPanel(e,t),this.updateClassnames()}closePanel(e){this.delete(e.id)}setOverflowExclude(e){this.tabs.setOverflowExclude(e)}setForcedOverflow(e){this.tabs.setForcedOverflow(e)}setPinnedSticky(e){this.tabs.setPinnedSticky(e)}refreshOverflow(){this.tabs.refreshOverflow()}setPinnedRow(e){this._pinnedRow!==e&&(this._pinnedRow&&this._pinnedRow.remove(),this._pinnedRow=e,e&&(e.classList.add("dv-pinned-row"),this._element.insertBefore(e,this._element.firstChild)),Qe(this._element,"dv-tabs-and-actions-container--pinned-row",!!e))}setDropIndexResolver(e){this._dropIndexResolver=e}resolveDropIndex(e,t){return this._dropIndexResolver(e,t)}updateClassnames(){Qe(this._element,"dv-single-tab",this.size===1)}toggleDropdown(e){const t=e.reset?[]:e.tabs,n=e.reset?[]:e.tabGroups,s=e.reset?[]:e.pinnedTabs;this._overflowTabs=t,this._overflowTabGroups=n,this._overflowPinnedTabs=s;const o=this._overflowTabs.length+this._overflowPinnedTabs.length;if(o>0&&this.dropdownPart){this.dropdownPart.update({tabs:o});return}if(o===0){this._dropdownDisposable.dispose();return}const r=document.createElement("div");r.className="dv-tabs-overflow-dropdown-root";const a=joe();a.update({tabs:o}),this.dropdownPart=a,r.appendChild(a.element),this.rightActionsContainer.prepend(r),this._dropdownDisposable.value=new pt(cn.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}),ct(r,"pointerdown",l=>{l.preventDefault()},{capture:!0}),ct(r,"click",l=>{const c=wie(r),d={x:l.clientX,y:l.clientY,zIndex:c?.style.zIndex?`calc(${c.style.zIndex} * 2)`:void 0},u=this.createOverflowRenderContext(r,d),h=this.accessor.advancedOverflowService;h?h.renderOverflow({group:this.group,overflowTabs:[...this._overflowTabs],overflowTabGroups:[...this._overflowTabGroups],pinnedOverflowTabs:[...this._overflowPinnedTabs],context:u}):u.open(this.renderFreeOverflowList(u))}))}createOverflowRenderContext(e,t){const n=new Set(this._overflowTabGroups),s=this.group.model.getTabGroups(),o=new Map,r=new Map;for(const c of s)if(r.set(c.id,c),n.has(c.id))for(const d of c.panelIds)o.set(d,c);const a=()=>this.accessor.getPopupServiceForGroup(this.group),l=c=>{const d=document.createElement("div");d.className="dv-tabs-overflow-group-header";const u=document.createElement("span");u.className="dv-tabs-overflow-group-color",e0(u,c.color,this.accessor.tabGroupColorPalette),d.appendChild(u);const h=document.createElement("span");if(h.className="dv-tabs-overflow-group-label",h.textContent=c.label||c.id,d.appendChild(h),c.collapsed){const p=document.createElement("span");p.className="dv-tabs-overflow-group-collapsed-badge",p.textContent=`${c.panelIds.length}`,d.appendChild(p)}return d.addEventListener("click",()=>{a().close(),c.collapsed&&c.expand();const p=c.panelIds[0];if(p){const f=this.group.panels.find(g=>g.id===p);this.accessor.withOrigin("user",()=>f?.api.setActive())}}),d};return{overflowGroupIdForPanel:c=>{var d;return(d=o.get(c))===null||d===void 0?void 0:d.id},buildGroupHeader:c=>{const d=r.get(c);if(!(!d||!n.has(d.id)))return l(d)},buildPinnedHeader:()=>{const c=document.createElement("div");c.className="dv-tabs-overflow-group-header dv-tabs-overflow-pinned-header";const d=PP();d.classList.add("dv-tabs-overflow-pinned-icon"),c.appendChild(d);const u=document.createElement("span");return u.className="dv-tabs-overflow-group-label",u.textContent="Pinned",c.appendChild(u),c},buildRow:c=>{const d=this.group.panels.find(x=>x.id===c);if(!d)return;const u=this.tabs.tabs.find(x=>x.panel.id===c),h=o.get(c),p=d.view.createTabRenderer("headerOverflow").element,f=document.createElement("div");Qe(f,"dv-tab",!0),Qe(f,"dv-active-tab",d.api.isActive),Qe(f,"dv-inactive-tab",!d.api.isActive),h&&Qe(f,"dv-tab--grouped",!0);const g=()=>{h?.collapsed&&h.expand(),u?.element.scrollIntoView({block:"nearest",inline:"nearest"}),this.accessor.withOrigin("user",()=>d.api.setActive())};return f.addEventListener("click",x=>{a().close(),!x.defaultPrevented&&g()}),f.appendChild(p),{element:f,panel:d,activate:()=>{a().close(),g()}}},open:c=>{a().openPopover(c,t)},close:()=>a().close(),focusTrigger:()=>{e.tabIndex=-1,e.focus()}}}renderFreeOverflowList(e){const t=document.createElement("div");t.style.overflow="auto",t.className="dv-tabs-overflow-container";const n=this._overflowPinnedTabs.map(o=>e.buildRow(o)).filter(o=>o!=null);if(n.length>0){t.appendChild(e.buildPinnedHeader());for(const o of n)t.appendChild(o.element)}const s=new Set;for(const o of this.tabs.tabs.filter(r=>this._overflowTabs.includes(r.panel.id))){const r=e.overflowGroupIdForPanel(o.panel.id);if(r&&!s.has(r)){s.add(r);const l=e.buildGroupHeader(r);l&&t.appendChild(l)}const a=e.buildRow(o.panel.id);a&&t.appendChild(a.element)}return t}updateDragAndDropState(){this.tabs.updateDragAndDropState(),this.voidContainer.updateDragAndDropState()}updateTabGroups(){this.tabs.updateTabGroups()}refreshTabGroupAccent(){this.tabs.refreshTabGroupAccent()}},Noe=class extends pt{get label(){return this._label}get color(){return this._color}get componentParams(){return this._componentParams}setLabel(e){this.isDisposed||this._label===e||(this._label=e,this._onDidChange.fire())}setColor(e){if(this.isDisposed)return;const t=e===""?void 0:e;this._color!==t&&(this._color=t,this._onDidChange.fire())}setComponentParams(e){this.isDisposed||(this._componentParams=e,this._onDidChange.fire())}get collapsed(){return this._collapsed}get panelIds(){return this._panelIds}get size(){return this._panelIds.length}get isEmpty(){return this._panelIds.length===0}constructor(e,t){var n,s;super(),this.id=e,this._collapsed=!1,this._panelIds=[],this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidPanelChange=new ve,this.onDidPanelChange=this._onDidPanelChange.event,this._onDidCollapseChange=new ve,this.onDidCollapseChange=this._onDidCollapseChange.event,this._onDidDestroy=new ve,this.onDidDestroy=this._onDidDestroy.event,this._label=(n=t?.label)!==null&&n!==void 0?n:"",this._color=t?.color===""?void 0:t?.color,this._collapsed=(s=t?.collapsed)!==null&&s!==void 0?s:!1,this._componentParams=t?.componentParams,this.addDisposables(this._onDidChange,this._onDidPanelChange,this._onDidCollapseChange,this._onDidDestroy)}addPanel(e,t){if(this.isDisposed||this._panelIds.includes(e))return;const n=t===void 0?this._panelIds.length:Math.max(0,Math.min(t,this._panelIds.length));this._panelIds.splice(n,0,e),this._onDidPanelChange.fire({panelId:e,type:"add"})}removePanel(e){if(this.isDisposed)return!1;const t=this._panelIds.indexOf(e);return t===-1?!1:(this._panelIds.splice(t,1),this._onDidPanelChange.fire({panelId:e,type:"remove"}),!0)}indexOfPanel(e){return this._panelIds.indexOf(e)}containsPanel(e){return this._panelIds.includes(e)}collapse(){this.isDisposed||this._collapsed||(this._collapsed=!0,this._onDidCollapseChange.fire(!0))}expand(){this.isDisposed||!this._collapsed||(this._collapsed=!1,this._onDidCollapseChange.fire(!1))}toggle(){this._collapsed?this.expand():this.collapse()}toJSON(){const e={id:this.id,collapsed:this._collapsed,panelIds:[...this._panelIds]};return this._label&&(e.label=this._label),this._color!==void 0&&(e.color=this._color),this._componentParams!==void 0&&(e.componentParams=this._componentParams),e}dispose(){this._onDidDestroy.fire(),super.dispose()}},n0=class extends Kv{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()}},BP=class extends n0{get kind(){return this._kind}constructor(e){super(e),this._kind=e.kind}},Toe=class extends pt{get tabGroups(){return this._tabGroups}get element(){throw new Error("dockview: not supported")}get activePanel(){return this._activePanel}get contentContainerId(){return this.contentContainer.element.id}get contentDropTarget(){return this.contentContainer.dropTarget}get locked(){return this._locked}set locked(e){this._locked=e,Qe(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?bg(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(),ji(this.container,"dv-groupview-header-top","dv-groupview-header-bottom","dv-groupview-header-left","dv-groupview-header-right"),_i(this.container,`dv-groupview-header-${e}`);const n=e==="top"||e==="bottom"?"horizontal":"vertical",s=this._headerDirection;if(this._headerDirection=n,this.tabsContainer.direction=n,this.header.direction=n,!((t=this._activePanel)===null||t===void 0)&&t.layout){const{width:r,height:a}=this.contentDimensions();this._activePanel.layout(r,a)}if(this.updateHeaderActions(),s!==void 0&&s!==n){var o;(o=this.groupPanel)===null||o===void 0||o.api._onDidHeaderDirectionChange.fire({direction:n,position:e})}}get location(){return this._location}set location(e){this._location=e,Qe(this.container,"dv-groupview-floating",!1),Qe(this.container,"dv-groupview-popout",!1),Qe(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"]),Qe(this.container,"dv-groupview-floating",!0);break;case"popout":t(["top","bottom","left","right","center"]),Qe(this.container,"dv-groupview-popout",!0);break;case"edge":t(["center"]),Qe(this.container,"dv-groupview-edge",!0);break}this.groupPanel.api._onDidLocationChange.fire({location:this.location})}constructor(e,t,n,s,o){var r,a;super(),this.container=e,this.accessor=t,this.id=n,this.options=s,this.groupPanel=o,this._isGroupActive=!1,this._locked=!1,this._location={type:"grid"},this.mostRecentlyUsed=[],this._overwriteRenderContainer=null,this._overwriteDropTargetContainer=null,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._width=0,this._height=0,this._panels=[],this._panelDisposables=new Map,this._tabGroupDisposables=new Map,this._pendingMicrotaskDisposables=new Set,this._onMove=new ve,this.onMove=this._onMove.event,this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new ve,this.onWillDrop=this._onWillDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onTabDragStart=new ve,this.onTabDragStart=this._onTabDragStart.event,this._onGroupDragStart=new ve,this.onGroupDragStart=this._onGroupDragStart.event,this._onDidAddPanel=new ve,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPanelTitleChange=new ve,this.onDidPanelTitleChange=this._onDidPanelTitleChange.event,this._onDidPanelParametersChange=new ve,this.onDidPanelParametersChange=this._onDidPanelParametersChange.event,this._onDidRemovePanel=new ve,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidActivePanelChange=new ve,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._tabGroups=[],this._tabGroupMap=new Map,this._panelToTabGroup=new Map,this._tabGroupIdCounter=0,this._pendingTabGroupUpdate=!1,this._onDidCreateTabGroup=new ve,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new ve,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new ve,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new ve,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new ve,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new ve,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,Qe(this.container,"dv-groupview",!0),this.container.setAttribute("role","region"),this._api=new Xv(this.accessor),this.tabsContainer=new _oe(this.accessor,this.groupPanel),this.contentContainer=new soe(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(Ir(this.tabsContainer.element,()=>{if(this.isDisposed)return;const l=this.measureHeaderSize();l!==this._cachedHeaderSize&&(this._cachedHeaderSize=l,this.layout(this._width,this._height))}),this._onDidPanelTitleChange.event(()=>this.updateAccessibleLabel()),this._onTabDragStart,this._onGroupDragStart,this._onWillShowOverlay,this.tabsContainer.onTabDragStart(l=>{this._onTabDragStart.fire(l)}),this.tabsContainer.onGroupDragStart(l=>{this._onGroupDragStart.fire(l)}),this.tabsContainer.onDrop(l=>{var c;const d=On(),u=(c=d?.panelId)!==null&&c!==void 0?c:null,h=u?this.tabsContainer.resolveDropIndex(u,l.index):l.index;if(this.handleDropEvent("header",l.event,"center",h),u&&l.targetTabGroupId){const p=this._tabGroupMap.get(l.targetTabGroupId);let f;if(p){const g=this._panels.findIndex(x=>x.id===u);if(g!==-1){f=0;for(const x of p.panelIds)this._panels.findIndex(v=>v.id===x)<g&&f++}}this.addPanelToTabGroup(l.targetTabGroupId,u,f)}else u&&l.targetTabGroupId===null&&this.removePanelFromTabGroup(u)}),this.contentContainer.onDidFocus(()=>{this.accessor.doSetGroupActive(this.groupPanel)}),this.contentContainer.onDidBlur(()=>{}),this.contentContainer.dropTarget.onDrop(l=>{this.handleDropEvent("content",l.nativeEvent,l.position,void 0,l.edge)}),this.contentContainer.pointerDropTarget.onDrop(l=>{this.handleDropEvent("content",l.nativeEvent,l.position,void 0,l.edge)}),this.tabsContainer.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(l)}),this.contentContainer.dropTarget.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(new ac(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:On}))}),this.contentContainer.pointerDropTarget.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(new ac(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:On}))}),this._onMove,this._onDidChange,this._onDidDrop,this._onWillDrop,this._onDidAddPanel,this._onDidRemovePanel,this._onDidActivePanelChange,this._onUnhandledDragOver,this._onDidPanelTitleChange,this._onDidPanelParametersChange,this._onDidCreateTabGroup,this._onDidDestroyTabGroup,this._onDidAddPanelToTabGroup,this._onDidRemovePanelFromTabGroup,this._onDidTabGroupChange,this._onDidTabGroupCollapsedChange,this._onDidCreateTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidDestroyTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidAddPanelToTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidRemovePanelFromTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidTabGroupChange.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidTabGroupCollapsedChange.event(()=>{this._scheduleTabGroupUpdate()}))}_scheduleTabGroupUpdate(){this._pendingTabGroupUpdate||(this._pendingTabGroupUpdate=!0,queueMicrotask(()=>{this._pendingTabGroupUpdate=!1,this.isDisposed||this.tabsContainer.updateTabGroups()}))}_bracketTabGroupMutation(e){return this.accessor.mutation?this.accessor.mutation("tab-group",e):e()}createTabGroup(e){return this._bracketTabGroupMutation(()=>this._doCreateTabGroup(e))}_doCreateTabGroup(e){var t;const n=(t=e?.id)!==null&&t!==void 0?t:`tg-${this.id}-${this._tabGroupIdCounter++}`,s=new Noe(n,{label:e?.label,color:e?.color,collapsed:e?.collapsed,componentParams:e?.componentParams});return this._tabGroups.push(s),this._tabGroupMap.set(n,s),this._tabGroupDisposables.set(n,new pt(s.onDidChange(()=>{this._onDidTabGroupChange.fire({tabGroup:s})}),s.onDidCollapseChange(o=>{o?this._handleGroupCollapse(s):this._handleGroupExpand(s),this._onDidTabGroupCollapsedChange.fire({tabGroup:s})}),s.onDidDestroy(()=>{this._removeTabGroupInternal(s)}))),this._onDidCreateTabGroup.fire({tabGroup:s}),s}dissolveTabGroup(e){const t=this._tabGroupMap.get(e);t&&this._bracketTabGroupMutation(()=>{const n=[...t.panelIds];for(const s of n)t.removePanel(s),this._panelToTabGroup.delete(s),this._onDidRemovePanelFromTabGroup.fire({tabGroup:t,panelId:s});t.dispose()})}addPanelToTabGroup(e,t,n){const s=this._tabGroupMap.get(e);if(!s||!this._panels.some(r=>r.id===t))return;const o=this.getTabGroupForPanel(t);o?.id!==e&&this._bracketTabGroupMutation(()=>{o&&this.removePanelFromTabGroup(t),s.addPanel(t,n),this._panelToTabGroup.set(t,s),this._enforceContiguity(s,t),this._onDidAddPanelToTabGroup.fire({tabGroup:s,panelId:t})})}movePanelWithinGroup(e,t,n){const s=this._tabGroupMap.get(e);s?.containsPanel(t)&&(s.removePanel(t),s.addPanel(t,n),this._enforceContiguity(s,t),this.tabsContainer.updateTabGroups())}movePanelBetweenGroups(e,t,n){const s=this._findTabGroupForPanel(e),o=this._tabGroupMap.get(t);o&&(s&&(s.removePanel(e),this._panelToTabGroup.delete(e),this._onDidRemovePanelFromTabGroup.fire({tabGroup:s,panelId:e}),s.isEmpty&&s.dispose()),o.addPanel(e,n),this._panelToTabGroup.set(e,o),this._enforceContiguity(o,e),this._onDidAddPanelToTabGroup.fire({tabGroup:o,panelId:e}))}moveTabGroup(e,t){const n=this._tabGroupMap.get(e);if(!n||n.panelIds.length===0)return;const s=new Set(n.panelIds),o=n.panelIds.map(c=>this._panels.find(d=>d.id===c)).filter(c=>c!==void 0);if(o.length===0)return;let r=0;for(let c=0;c<Math.min(t,this._panels.length);c++)s.has(this._panels[c].id)&&r++;for(const c of o){const d=this._panels.indexOf(c);d!==-1&&this._panels.splice(d,1)}const a=t-r,l=Math.max(0,Math.min(a,this._panels.length));this._panels.splice(l,0,...o);for(const c of this._panels)this.tabsContainer.delete(c.id);for(let c=0;c<this._panels.length;c++)this.tabsContainer.openPanel(this._panels[c],c);this.tabsContainer.updateTabGroups()}_enforceContiguity(e,t){const n=this._panels.find(l=>l.id===t);if(!n)return;const s=e.indexOfPanel(t),o=this._computeGlobalIndex(e,s),r=this._panels.indexOf(n);if(r===o)return;this._panels.splice(r,1);const a=o>r?o-1:o;this._panels.splice(a,0,n),this.tabsContainer.delete(t),this.tabsContainer.openPanel(n,a)}_computeGlobalIndex(e,t){const n=e.panelIds;if(n.length<=1){const s=this._panels.find(o=>o.id===n[0]);return s?this._panels.indexOf(s):this._panels.length}for(let s=0;s<n.length;s++){if(s===t)continue;const o=this._panels.find(r=>r.id===n[s]);if(o){const r=this._panels.indexOf(o);return Math.max(0,r+(t-s))}}return this._panels.length}removePanelFromTabGroup(e){const t=this._findTabGroupForPanel(e);t&&this._bracketTabGroupMutation(()=>{t.removePanel(e),this._panelToTabGroup.delete(e),this._onDidRemovePanelFromTabGroup.fire({tabGroup:t,panelId:e}),t.isEmpty&&t.dispose()})}getTabGroups(){return this._tabGroups}updateTabGroups(){this.tabsContainer.updateTabGroups()}refreshTabGroupAccent(){this.tabsContainer.refreshTabGroupAccent()}refreshWatermark(){if(this.watermark){var e,t;this.watermark.element.remove(),(e=(t=this.watermark).dispose)===null||e===void 0||e.call(t),this.watermark=void 0}this.updateContainer()}getTabGroupForPanel(e){return this._findTabGroupForPanel(e)}_findTabGroupForPanel(e){return this._panelToTabGroup.get(e)}_removeTabGroupInternal(e){const t=this._tabGroups.indexOf(e);if(t!==-1){this._tabGroups.splice(t,1),this._tabGroupMap.delete(e.id);for(const s of e.panelIds)this._panelToTabGroup.delete(s);this._onDidDestroyTabGroup.fire({tabGroup:e});const n=this._tabGroupDisposables.get(e.id);this._tabGroupDisposables.delete(e.id),n&&(this._pendingMicrotaskDisposables.add(n),queueMicrotask(()=>{this._pendingMicrotaskDisposables.delete(n),n.dispose()}))}}_handleGroupCollapse(e){if(!this._activePanel||!e.containsPanel(this._activePanel.id))return;const t=this._panels.indexOf(this._activePanel);for(let n=t+1;n<this._panels.length;n++){const s=this._panels[n],o=this._findTabGroupForPanel(s.id);if(!o?.collapsed){this.doSetActivePanel(s),this.updateContainer();return}}for(let n=t-1;n>=0;n--){const s=this._panels[n],o=this._findTabGroupForPanel(s.id);if(!o?.collapsed){this.doSetActivePanel(s),this.updateContainer();return}}this.contentContainer.closePanel(),this.doSetActivePanel(void 0),this.updateContainer()}_handleGroupExpand(e){if(this._activePanel)return;const t=e.panelIds[0];if(t){const n=this._panels.find(s=>s.id===t);n&&(this.doSetActivePanel(n),this.updateContainer())}}restoreTabGroups(e){for(const t of e){const n=/-(\d+)$/.exec(t.id);if(n){const s=Number.parseInt(n[1],10)+1;s>this._tabGroupIdCounter&&(this._tabGroupIdCounter=s)}}for(const t of e){const n=this.createTabGroup({id:t.id,label:t.label,color:t.color,componentParams:t.componentParams}),s=this._tabGroupMap.get(n.id);for(const o of t.panelIds)this._panels.some(r=>r.id===o)&&(n.addPanel(o),this._panelToTabGroup.set(o,s),this._enforceContiguity(s,o));t.collapsed&&n.collapse(),n.isEmpty&&n.dispose()}}focusContent(){this.contentContainer.element.focus()}focusActiveTab(){this.tabsContainer.focusActiveTab()}set renderContainer(e){if(this.panels.forEach(t=>{this.renderContainer.detatch(t)}),this._overwriteRenderContainer=e,this.panels.forEach(t=>{this.rerender(t)}),this._activePanel){this.contentContainer.renderPanel(this._activePanel,{asActive:!0});const{width:t,height:n}=this.contentDimensions();this._activePanel.layout(t,n)}}get renderContainer(){var e;return(e=this._overwriteRenderContainer)!==null&&e!==void 0?e:this.accessor.overlayRenderContainer}set dropTargetContainer(e){this._overwriteDropTargetContainer=e}get dropTargetContainer(){var e;return this._location.type==="floating"&&this.accessor.rootDropTargetContainer.disabled?this.accessor.floatingDropTargetContainer:(e=this._overwriteDropTargetContainer)!==null&&e!==void 0?e:this.accessor.rootDropTargetContainer}initialize(){this.options.panels&&this.options.panels.forEach(e=>{this.doAddPanel(e)}),this.options.activePanel&&this.openPanel(this.options.activePanel),this.setActive(this.isActive,!0),this.updateContainer(),this.updateHeaderActions()}updateHeaderActions(){var e;(e=this.accessor.headerActionsService)===null||e===void 0||e.refresh(this.groupPanel)}attachHeaderAction(e,t){switch(e){case"left":this.tabsContainer.setLeftActionsElement(t);break;case"right":this.tabsContainer.setRightActionsElement(t);break;case"prefix":this.tabsContainer.setPrefixActionsElement(t);break}}rerender(e){this.contentContainer.renderPanel(e,{asActive:!1})}indexOf(e){return this.tabsContainer.indexOf(e.id)}toJSON(){var e;const t={views:this.tabsContainer.panels,activeView:(e=this._activePanel)===null||e===void 0?void 0:e.id,id:this.id};return this.locked!==!1&&(t.locked=this.locked),this.header.hidden&&(t.hideHeader=!0),this.headerPosition!=="top"&&(t.headerPosition=this.headerPosition),this._tabGroups.length>0&&(t.tabGroups=this._tabGroups.map(n=>n.toJSON())),t}moveToNext(e){var t,n,s;(t=e)!==null&&t!==void 0||(e={}),(s=(n=e).panel)!==null&&s!==void 0||(n.panel=this.activePanel);const o=e.panel?this.panels.indexOf(e.panel):-1;let r;if(o<this.panels.length-1)r=o+1;else{if(e.suppressRoll)return;r=0}this.openPanel(this.panels[r])}moveToPrevious(e){var t,n,s;if((t=e)!==null&&t!==void 0||(e={}),(s=(n=e).panel)!==null&&s!==void 0||(n.panel=this.activePanel),!e.panel)return;const o=this.panels.indexOf(e.panel);let r;if(o>0)r=o-1;else{if(e.suppressRoll)return;r=this.panels.length-1}this.openPanel(this.panels[r])}containsPanel(e){return this.panels.includes(e)}init(e){}update(e){}focus(){var e;(e=this._activePanel)===null||e===void 0||e.focus()}openPanel(e,t={}){(typeof t.index!="number"||t.index>this.panels.length)&&(t.index=this.panels.length);const n=!!t.skipSetActive;if(e.updateParentGroup(this.groupPanel,{skipSetActive:t.skipSetActive}),this.doAddPanel(e,t.index,{skipSetActive:n}),this.invalidateHeaderSize(),this._activePanel===e){this.contentContainer.renderPanel(e,{asActive:!0});return}n||this.doSetActivePanel(e),t.skipSetGroupActive||this.accessor.doSetGroupActive(this.groupPanel),t.skipSetActive||this.updateContainer()}removePanel(e,t){const n=typeof e=="string"?e:e.id,s=this._panels.find(o=>o.id===n);if(!s)throw new Error("invalid operation");return this._removePanel(s,t)}closeAllPanels(){if(this.panels.length>0){const e=[...this.panels];for(const t of e)this.doClose(t)}else this.accessor.removeGroup(this.groupPanel)}closePanel(e){this.doClose(e)}doClose(e){const t=this.panels.length===1&&this.accessor.groups.length===1;this.accessor.removePanel(e,t&&this.accessor.options.noPanelsOverlay==="emptyGroup"?{removeEmptyGroup:!1}:void 0)}isPanelActive(e){return this._activePanel===e}updateActions(e){this.tabsContainer.setRightActionsElement(e)}setActive(e,t=!1){if(!(!t&&this.isActive===e)){if(this._isGroupActive=e,Qe(this.container,"dv-active-group",e),Qe(this.container,"dv-inactive-group",!e),this.tabsContainer.setActive(this.isActive),!this._activePanel&&this.panels.length>0){const n=this._panels.find(s=>{const o=this._findTabGroupForPanel(s.id);return!o?.collapsed});n&&this.doSetActivePanel(n)}this.updateContainer()}}layout(e,t){var n;this._width=e,this._height=t;const{width:s,height:o}=this.contentDimensions();this.contentContainer.layout(s,o),!((n=this._activePanel)===null||n===void 0)&&n.layout&&this._activePanel.layout(s,o)}relayout(){this.invalidateHeaderSize(),this.layout(this._width,this._height)}measureHeaderSize(){const e=this.tabsContainer.element;return this.headerPosition==="top"||this.headerPosition==="bottom"?e.offsetHeight:e.offsetWidth}invalidateHeaderSize(){this._cachedHeaderSize=void 0}contentDimensions(){var e;const t=this.headerPosition==="top"||this.headerPosition==="bottom",n=(e=this._cachedHeaderSize)!==null&&e!==void 0?e:this._cachedHeaderSize=this.measureHeaderSize();return{width:t?this._width:Math.max(0,this._width-n),height:t?Math.max(0,this._height-n):this._height}}_removePanel(e,t){const n=this._activePanel===e;if(this.doRemovePanel(e),this.invalidateHeaderSize(),n&&this.panels.length>0){const s=this.mostRecentlyUsed[0];this.openPanel(s,{skipSetActive:t?.skipSetActive,skipSetGroupActive:t?.skipSetActiveGroup})}return this._activePanel&&this.panels.length===0&&this.doSetActivePanel(void 0),t?.skipSetActive||this.updateContainer(),e}doRemovePanel(e){const t=this.panels.indexOf(e);if(this._activePanel===e&&this.contentContainer.closePanel(),this.tabsContainer.delete(e.id),this._panels.splice(t,1),this.mostRecentlyUsed.includes(e)){const s=this.mostRecentlyUsed.indexOf(e);this.mostRecentlyUsed.splice(s,1)}const n=this._panelDisposables.get(e.id);n&&(n.dispose(),this._panelDisposables.delete(e.id)),this.removePanelFromTabGroup(e.id),this._onDidRemovePanel.fire({panel:e})}doAddPanel(e,t=this.panels.length,n){const s=this._panels.indexOf(e)>-1;this.tabsContainer.show(),this.contentContainer.show(),this.tabsContainer.openPanel(e,t),n?.skipSetActive?e.api.renderer==="always"&&this.contentContainer.renderPanel(e,{asActive:!1}):this.contentContainer.openPanel(e),!s&&(this.updateMru(e),this.panels.splice(t,0,e),this._panelDisposables.set(e.id,new pt(e.api.onDidTitleChange(o=>this._onDidPanelTitleChange.fire(o)),e.api.onDidParametersChange(o=>this._onDidPanelParametersChange.fire(o)))),this._onDidAddPanel.fire({panel:e}))}doSetActivePanel(e){if(this._activePanel!==e){if(this._activePanel=e,e){var t,n,s;this.tabsContainer.setActivePanel(e),this.contentContainer.setLabelledBy(this.tabsContainer.getTabId(e.id)),this.contentContainer.openPanel(e);const{width:o,height:r}=this.contentDimensions();e.layout(o,r),this.updateMru(e),this.contentContainer.refreshFocusState(),this._onDidActivePanelChange.fire({panel:e,origin:(t=(n=(s=this.accessor).currentOrigin)===null||n===void 0?void 0:n.call(s))!==null&&t!==void 0?t:"user"})}this.updateAccessibleLabel()}}updateAccessibleLabel(){var e;const t=(e=this._activePanel)===null||e===void 0?void 0:e.title;t?this.container.setAttribute("aria-label",t):this.container.removeAttribute("aria-label")}updateMru(e){this.mostRecentlyUsed.includes(e)&&this.mostRecentlyUsed.splice(this.mostRecentlyUsed.indexOf(e),1),this.mostRecentlyUsed=[e,...this.mostRecentlyUsed]}updateContainer(){this.panels.forEach(s=>s.runEvents());const e=this.isEmpty||!this._activePanel;if(e&&!this.watermark){const s=this.accessor.createWatermarkComponent();s.init({containerApi:this._api,group:this.groupPanel}),this.watermark=s,ct(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 zP(e,n,t,On,this.accessor.getPanel(this.id));return this._onUnhandledDragOver.fire(s),s.isAccepted}canDisplayContentOverlay(e,t){if(this.locked==="no-drop-target"||this.locked&&t==="center")return!1;const n=On();return!n&&e.shiftKey&&this.location.type!=="floating"?!1:n?.viewId===this.accessor.id?!0:this.canDisplayOverlay(e,t,"content")}handleDropEvent(e,t,n,s,o){if(this.locked==="no-drop-target")return;if(e==="content"&&o){this.accessor.dockToLayoutEdge(t,n);return}function r(){switch(e){case"header":return typeof s=="number"?"tab":"header_space";case"content":return"content"}}const a=typeof s=="number"?this.panels[s]:void 0,l=new BP({nativeEvent:t,position:n,panel:a,getData:()=>On(),kind:r(),group:this.groupPanel,api:this._api});if(this._onWillDrop.fire(l),l.defaultPrevented)return;const c=On();if(c?.viewId===this.accessor.id){if(e==="content"&&c.groupId===this.id&&(n==="center"||c.panelId===null&&!c.tabGroupId)||e==="header"&&c.groupId===this.id&&c.panelId===null&&!c.tabGroupId)return;if(c.panelId===null){const{groupId:h}=c;this._onMove.fire({target:n,groupId:h,index:s,tabGroupId:c.tabGroupId});return}if(this.tabsContainer.indexOf(c.panelId)!==-1&&this.tabsContainer.size===1)return;const{groupId:d,panelId:u}=c;if(this.id===d&&!n&&this.tabsContainer.indexOf(u)===s)return;this._onMove.fire({target:n,groupId:c.groupId,itemId:c.panelId,index:s})}else this._onDidDrop.fire(new n0({nativeEvent:t,position:n,panel:a,getData:()=>On(),group:this.groupPanel,api:this._api}))}updateDragAndDropState(){this.tabsContainer.updateDragAndDropState()}dispose(){var e,t,n;super.dispose(),(e=this.watermark)===null||e===void 0||e.element.remove(),(t=this.watermark)===null||t===void 0||(n=t.dispose)===null||n===void 0||n.call(t),this.watermark=void 0;for(const s of[...this._tabGroups])s.dispose();for(const s of this._tabGroupDisposables.values())s.dispose();this._tabGroupDisposables.clear();for(const s of this._pendingMicrotaskDisposables)s.dispose();this._pendingMicrotaskDisposables.clear();for(const s of this.panels)s.dispose();this.tabsContainer.dispose(),this.contentContainer.dispose()}},s0=class extends DP{constructor(e,t,n){super(e,t),this._onDidConstraintsChangeInternal=new ve,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new ve,this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new ve,this.onDidSizeChange=this._onDidSizeChange.event,this.addDisposables(this._onDidConstraintsChangeInternal,this._onDidConstraintsChange,this._onDidSizeChange),n&&this.initialize(n)}setConstraints(e){this._onDidConstraintsChangeInternal.fire(e)}setSize(e){this._onDidSizeChange.fire(e)}},VP=class extends Jv{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 s0(e,t)),this._evaluatedMinimumWidth=0,this._evaluatedMaximumWidth=Number.MAX_SAFE_INTEGER,this._evaluatedMinimumHeight=0,this._evaluatedMaximumHeight=Number.MAX_SAFE_INTEGER,this._minimumWidth=0,this._minimumHeight=0,this._maximumWidth=Number.MAX_SAFE_INTEGER,this._maximumHeight=Number.MAX_SAFE_INTEGER,this._snap=!1,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,typeof n?.minimumWidth=="number"&&(this._minimumWidth=n.minimumWidth),typeof n?.maximumWidth=="number"&&(this._maximumWidth=n.maximumWidth),typeof n?.minimumHeight=="number"&&(this._minimumHeight=n.minimumHeight),typeof n?.maximumHeight=="number"&&(this._maximumHeight=n.maximumHeight),this.api.initialize(this),this.addDisposables(this.api.onWillVisibilityChange(o=>{const{isVisible:r}=o,{accessor:a}=this._params;a.setVisible(this,r)}),this.api.onActiveChange(()=>{const{accessor:o}=this._params;o.doSetGroupActive(this)}),this.api.onDidConstraintsChangeInternal(o=>{(typeof o.minimumWidth=="number"||typeof o.minimumWidth=="function")&&(this._minimumWidth=o.minimumWidth),(typeof o.minimumHeight=="number"||typeof o.minimumHeight=="function")&&(this._minimumHeight=o.minimumHeight),(typeof o.maximumWidth=="number"||typeof o.maximumWidth=="function")&&(this._maximumWidth=o.maximumWidth),(typeof o.maximumHeight=="number"||typeof o.maximumHeight=="function")&&(this._maximumHeight=o.maximumHeight),this._onDidChange.fire(void 0)}),this.api.onDidSizeChange(o=>{this._onDidChange.fire({height:o.height,width:o.width})}),this._onDidChange)}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}init(e){e.maximumHeight&&(this._maximumHeight=e.maximumHeight),e.minimumHeight&&(this._minimumHeight=e.minimumHeight),e.maximumWidth&&(this._maximumWidth=e.maximumWidth),e.minimumWidth&&(this._minimumWidth=e.minimumWidth),this._priority=e.priority,this._snap=!!e.snap,super.init(e),typeof e.isVisible=="boolean"&&this.setVisible(e.isVisible)}updateConstraints(){this.api._onDidConstraintsChange.fire({minimumWidth:this._evaluatedMinimumWidth,maximumWidth:this._evaluatedMaximumWidth,minimumHeight:this._evaluatedMinimumHeight,maximumHeight:this._evaluatedMaximumHeight})}toJSON(){const e=super.toJSON(),t=s=>s===Number.MAX_SAFE_INTEGER?void 0:s,n=s=>s<=0?void 0:s;return gt(gt({},e),{},{minimumHeight:n(this.minimumHeight),maximumHeight:t(this.maximumHeight),minimumWidth:n(this.minimumWidth),maximumWidth:t(this.maximumWidth),snap:this.snap,priority:this.priority})}};const to="dockview: DockviewGroupPanelApiImpl not initialized";var Ioe=class extends s0{get location(){if(!this._group)throw new Error(to);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(to);return this._group.locked}set locked(e){if(!this._group)throw new Error(to);this._group.locked=e}constructor(e,t){super(e,"__dockviewgroup__"),this.accessor=t,this._onDidLocationChange=new ve,this.onDidLocationChange=this._onDidLocationChange.event,this._onDidActivePanelChange=new ve,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidCollapsedChange=new ve,this.onDidCollapsedChange=this._onDidCollapsedChange.event,this._onDidPeekChange=new ve,this.onDidPeekChange=this._onDidPeekChange.event,this._onDidHeaderDirectionChange=new ve,this.onDidHeaderDirectionChange=this._onDidHeaderDirectionChange.event,this.addDisposables(this._onDidLocationChange,this._onDidActivePanelChange,this._onDidCollapsedChange,this._onDidPeekChange,this._onDidHeaderDirectionChange,this._onDidVisibilityChange.event(n=>{n.isVisible&&this._pendingSize&&(super.setSize(this._pendingSize),this._pendingSize=void 0)}))}setSize(e){this._pendingSize=gt({},e),super.setSize(e)}close(){if(this._group)return this.accessor.removeGroup(this._group)}getWindow(){return this.location.type==="popout"?this.location.getWindow():globalThis.window}setHeaderPosition(e){if(!this._group)throw new Error(to);this._group.model.headerPosition=e}getHeaderPosition(){if(!this._group)throw new Error(to);return this._group.model.headerPosition}moveTo(e){if(!this._group)throw new Error(to);this.accessor.withOrigin("api",()=>{var t,n,s,o;const r=(t=e.group)!==null&&t!==void 0?t:this.accessor.addGroup({direction:zie((n=e.position)!==null&&n!==void 0?n:"right"),skipSetActive:(s=e.skipSetActive)!==null&&s!==void 0?s:!1});this.accessor.moveGroupOrPanel({from:{groupId:this._group.id},to:{group:r,position:e.group&&(o=e.position)!==null&&o!==void 0?o:"center",index:e.index},skipSetActive:e.skipSetActive})})}maximize(){if(!this._group)throw new Error(to);this.location.type==="grid"&&this.accessor.maximizeGroup(this._group)}isMaximized(){if(!this._group)throw new Error(to);return this.accessor.isMaximizedGroup(this._group)}exitMaximized(){if(!this._group)throw new Error(to);this.isMaximized()&&this.accessor.exitMaximizedGroup()}collapse(){this._group&&this.accessor.setEdgeGroupCollapsed(this._group,!0)}expand(){this._group&&this.accessor.setEdgeGroupCollapsed(this._group,!1)}isCollapsed(){return this._group?this.accessor.isEdgeGroupCollapsed(this._group):!1}isPeeking(){return this._group?this.accessor.isEdgeGroupPeeking(this._group):!1}setAutoHide(e){this._group&&this.accessor.setEdgeGroupAutoHide(this._group,e)}isAutoHide(){return this._group?this.accessor.isEdgeGroupAutoHide(this._group):!1}initialize(e){this._group=e}};const Doe=100,Eoe=100;var vd=class extends VP{get minimumWidth(){var e;if(typeof this._explicitConstraints.minimumWidth=="number")return this._explicitConstraints.minimumWidth;const t=(e=this.activePanel)===null||e===void 0?void 0:e.minimumWidth;return typeof t=="number"?t:super.__minimumWidth()}get minimumHeight(){var e;if(typeof this._explicitConstraints.minimumHeight=="number")return this._explicitConstraints.minimumHeight;const t=(e=this.activePanel)===null||e===void 0?void 0:e.minimumHeight;return typeof t=="number"?t:super.__minimumHeight()}get maximumWidth(){var e;if(typeof this._explicitConstraints.maximumWidth=="number")return this._explicitConstraints.maximumWidth;const t=(e=this.activePanel)===null||e===void 0?void 0:e.maximumWidth;return typeof t=="number"?t:super.__maximumWidth()}get maximumHeight(){var e;if(typeof this._explicitConstraints.maximumHeight=="number")return this._explicitConstraints.maximumHeight;const t=(e=this.activePanel)===null||e===void 0?void 0:e.maximumHeight;return typeof t=="number"?t:super.__maximumHeight()}get panels(){return this._model.panels}get activePanel(){return this._model.activePanel}get size(){return this._model.size}get model(){return this._model}get locked(){return this._model.locked}set locked(e){this._model.locked=e}get header(){return this._model.header}constructor(e,t,n){var s,o,r,a,l,c;super(t,"groupview_default",{minimumHeight:(s=(o=n.constraints)===null||o===void 0?void 0:o.minimumHeight)!==null&&s!==void 0?s:Eoe,minimumWidth:(r=(a=n.constraints)===null||a===void 0?void 0:a.minimumWidth)!==null&&r!==void 0?r:Doe,maximumHeight:(l=n.constraints)===null||l===void 0?void 0:l.maximumHeight,maximumWidth:(c=n.constraints)===null||c===void 0?void 0:c.maximumWidth},new Ioe(t,e)),this._explicitConstraints={},this.api.initialize(this),this._model=new Toe(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 Poe={name:"dark",className:"dockview-theme-dark",colorScheme:"dark"},Aoe={name:"light",className:"dockview-theme-light",colorScheme:"light"},Moe={className:"dockview-theme-abyss",tabGroupIndicator:"none"};var Roe=class extends s0{get location(){return this.group.api.location}get title(){return this.panel.title}get isPinned(){return this.panel.isPinned}get isGroupActive(){return this.group.isActive}get renderer(){return this.panel.renderer}set group(e){const t=this._group;this._group!==e&&(this._group=e,this._onDidGroupChange.fire({}),this.setupGroupEventListeners(t),this.fireLocationChange())}get group(){return this._group}get tabComponent(){return this._tabComponent}constructor(e,t,n,s,o){super(e.id,s),this.panel=e,this.accessor=n,this._onDidTitleChange=new ve,this.onDidTitleChange=this._onDidTitleChange.event,this._onDidChangePinned=new ve,this.onDidChangePinned=this._onDidChangePinned.event,this._onDidActiveGroupChange=new ve,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._onDidGroupChange=new ve,this.onDidGroupChange=this._onDidGroupChange.event,this._onDidRendererChange=new ve,this.onDidRendererChange=this._onDidRendererChange.event,this._onDidLocationChange=new ve,this.onDidLocationChange=this._onDidLocationChange.event,this.groupEventsDisposable=new Bn,this._tabComponent=o,this.initialize(e),this._group=t,this.setupGroupEventListeners(),this.addDisposables(this.groupEventsDisposable,this._onDidRendererChange,this._onDidTitleChange,this._onDidChangePinned,this._onDidGroupChange,this._onDidActiveGroupChange,this._onDidLocationChange)}getWindow(){return this.group.api.getWindow()}setActive(){this.accessor.withOrigin("api",()=>super.setActive())}moveTo(e){this.accessor.withOrigin("api",()=>{var t,n;return this.accessor.moveGroupOrPanel({from:{groupId:this._group.id,panelId:this.panel.id},to:{group:(t=e.group)!==null&&t!==void 0?t:this._group,position:e.group&&(n=e.position)!==null&&n!==void 0?n:"center",index:e.index},skipSetActive:e.skipSetActive})})}setTitle(e){this.panel.setTitle(e)}setPinned(e){this.accessor.setPanelPinned(this.panel,e)}setRenderer(e){this.panel.setRenderer(e)}close(){this.group.model.closePanel(this.panel)}maximize(){this.group.api.maximize()}isMaximized(){return this.group.api.isMaximized()}exitMaximized(){this.group.api.exitMaximized()}fireLocationChange(){this.accessor.deferLocationChange(this,()=>{this.isDisposed||this._onDidLocationChange.fire({location:this.location})})}setupGroupEventListeners(e){var t;let n=(t=e?.isActive)!==null&&t!==void 0?t:!1;this.groupEventsDisposable.value=new pt(this.group.api.onDidVisibilityChange(s=>{const o=!s.isVisible&&this.isVisible,r=s.isVisible&&!this.isVisible,a=this.group.model.isPanelActive(this.panel);(o||r&&a)&&this._onDidVisibilityChange.fire(s)}),this.group.api.onDidLocationChange(()=>{this.group===this.panel.group&&this.fireLocationChange()}),this.group.api.onDidActiveChange(()=>{this.group===this.panel.group&&n!==this.isGroupActive&&(n=this.isGroupActive,this._onDidActiveGroupChange.fire({isActive:this.isGroupActive}))}))}},Wr=class extends pt{get params(){return this._params}get title(){return this._title}get isPinned(){return this._pinned}get group(){return this._group}get renderer(){var e;return(e=this._renderer)!==null&&e!==void 0?e:this.accessor.renderer}get minimumWidth(){return this._minimumWidth}get minimumHeight(){return this._minimumHeight}get maximumWidth(){return this._maximumWidth}get maximumHeight(){return this._maximumHeight}constructor(e,t,n,s,o,r,a,l){super(),this.id=e,this.accessor=s,this.containerApi=o,this.view=a,this._pinned=!1,this._renderer=l.renderer,this._group=r,this._minimumWidth=l.minimumWidth,this._minimumHeight=l.minimumHeight,this._maximumWidth=l.maximumWidth,this._maximumHeight=l.maximumHeight,this.api=new Roe(this,this._group,s,t,n),this.addDisposables(this.api.onActiveChange(()=>{s.setActivePanel(this)}),this.api.onDidSizeChange(c=>{this.group.api.setSize(c)}),this.api.onDidRendererChange(()=>{this.group.model.rerender(this)}))}init(e){this._params=e.params,this.view.init(gt(gt({},e),{},{api:this.api,containerApi:this.containerApi})),this.setTitle(e.title)}focus(){const e=new IP;this.api._onWillFocus.fire(e),!e.defaultPrevented&&(this.api.isActive||this.api.setActive())}toJSON(){return{id:this.id,contentComponent:this.view.contentComponent,tabComponent:this.view.tabComponent,params:Object.keys(this._params||{}).length>0?this._params:void 0,title:this.title,renderer:this._renderer,minimumHeight:this._minimumHeight,maximumHeight:this._maximumHeight,minimumWidth:this._minimumWidth,maximumWidth:this._maximumWidth,pinned:this._pinned?!0:void 0}}setTitle(e){e!==this.title&&(this._title=e,this.view.setTitle(e),this.api._onDidTitleChange.fire({title:e}))}setPinned(e){this._pinned!==e&&(this._pinned=e,this.api._onDidChangePinned.fire({isPinned:e}))}setRenderer(e){e!==this.renderer&&(this._renderer=e,this.api._onDidRendererChange.fire({renderer:e}))}update(e){this._params=gt(gt({},this._params),e.params);for(const t of Object.keys(e.params))e.params[t]===void 0&&delete this._params[t];this.view.update({params:this._params})}updateFromStateModel(e){var t,n,s,o,r;this._maximumHeight=e.maximumHeight,this._minimumHeight=e.minimumHeight,this._maximumWidth=e.maximumWidth,this._minimumWidth=e.minimumWidth,this._params=(t=e.params)!==null&&t!==void 0?t:{},this.view.update({params:this._params}),this.setTitle((n=e.title)!==null&&n!==void 0?n:this.id),this.setRenderer((s=e.renderer)!==null&&s!==void 0?s:this.accessor.renderer),this.setPinned(((o=e.pinned)!==null&&o!==void 0?o:!1)&&!!(!((r=this.accessor.options.pinnedTabs)===null||r===void 0)&&r.enabled))}updateParentGroup(e,t){this._group=e,this.api.group=this._group;const n=this._group.model.isPanelActive(this),s=this.group.api.isActive&&n;t?.skipSetActive||this.api.isActive!==s&&this.api._onDidActiveChange.fire({isActive:this.group.api.isActive&&n}),this.api.isVisible!==n&&this.api._onDidVisibilityChange.fire({isVisible:n})}runEvents(){const e=this._group.model.isPanelActive(this),t=this.group.api.isActive&&e;this.api.isActive!==t&&this.api._onDidActiveChange.fire({isActive:this.group.api.isActive&&e}),this.api.isVisible!==e&&this.api._onDidVisibilityChange.fire({isVisible:e})}layout(e,t){this.api._onDidDimensionChange.fire({width:e,height:t}),this.view.layout(e,t)}dispose(){this.api.dispose(),this.view.dispose()}},nk=class extends pt{get element(){return this._element}constructor(){super(),this._messages=Xu,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=ioe();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:Xu,this.addDisposables(e.api.onDidTitleChange(n=>{this._title=n.title,this.render()}),ct(this.action,"pointerdown",n=>{n.preventDefault()}),ct(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())}},$P=class{get content(){return this._content}get tab(){return this._tab}constructor(e,t,n,s){this.accessor=e,this.id=t,this.contentComponent=n,this.tabComponent=s,this._content=this.createContentComponent(this.id,n),this._tab=this.createTabComponent(this.id,s)}createTabRenderer(e){const t=this.createTabComponent(this.id,this.tabComponent);if(this._params&&t.init(gt(gt({},this._params),{},{tabLocation:e})),this._updateEvent){var n;(n=t.update)===null||n===void 0||n.call(t,this._updateEvent)}return t}init(e){this._params=e,this.content.init(e),this.tab.init(gt(gt({},e),{},{tabLocation:"header"}))}setTitle(e){this._params&&(this._params.title=e)}layout(e,t){var n,s;(n=(s=this.content).layout)===null||n===void 0||n.call(s,e,t)}update(e){var t,n,s,o;this._updateEvent=e,(t=(n=this.content).update)===null||t===void 0||t.call(n,e),(s=(o=this.tab).update)===null||s===void 0||s.call(o,e)}dispose(){var e,t,n,s;(e=(t=this.content).dispose)===null||e===void 0||e.call(t),(n=(s=this.tab).dispose)===null||n===void 0||n.call(s)}createContentComponent(e,t){return this.accessor.options.createComponent({id:e,name:t})}createTabComponent(e,t){const n=t??this.accessor.options.defaultTabComponent;if(n){if(this.accessor.options.createTabComponent){const s=this.accessor.options.createTabComponent({id:e,name:n});return s||new nk}console.warn(`dockview: tabComponent '${t}' was not found. falling back to the default tab.`)}return new nk}},Loe=class{constructor(e){this.accessor=e}fromJSON(e,t){var n,s,o;const r=e.id,a=e.params,l=e.title,c=e.view,d=c?c.content.id:(n=e.contentComponent)!==null&&n!==void 0?n:"unknown",u=c?(s=c.tab)===null||s===void 0?void 0:s.id:e.tabComponent,h=new $P(this.accessor,r,d,u),p=new Wr(r,d,u,this.accessor,new Xv(this.accessor),t,h,{renderer:e.renderer,minimumWidth:e.minimumWidth,minimumHeight:e.minimumHeight,maximumWidth:e.maximumWidth,maximumHeight:e.maximumHeight});return p.init({title:l??r,params:a??{}}),e.pinned&&(!((o=this.accessor.options.pinnedTabs)===null||o===void 0)&&o.enabled)&&p.setPinned(!0),p}},Ooe=class extends pt{get element(){return this._element}constructor(){super(),this._element=document.createElement("div"),this._element.className="dv-watermark"}init(t){}},zoe=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 bd=new zoe;var i0=class dr extends pt{set minimumInViewportWidth(t){this.options.minimumInViewportWidth=t}set minimumInViewportHeight(t){this.options.minimumInViewportHeight=t}get element(){return this._element}get isVisible(){return this._isVisible}get headerHeight(){var t,n;return(t=(n=this.options.header)===null||n===void 0?void 0:n.offsetHeight)!==null&&t!==void 0?t:0}constructor(t){super(),this.options=t,this._element=document.createElement("div"),this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidChangeEnd=new ve,this.onDidChangeEnd=this._onDidChangeEnd.event,this._onDidStartMoving=new ve,this.onDidStartMoving=this._onDidStartMoving.event,this._dragMove=new Bn,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&&(Qe(this._element,"dv-resize-container-with-titlebar",!0),this._element.appendChild(this.options.header)),this._element.appendChild(this.options.content),this.options.container.appendChild(this._element),this.setBounds(gt(gt(gt(gt({height:this.options.height,width:this.options.width},"top"in this.options&&{top:this.options.top}),"bottom"in this.options&&{bottom:this.options.bottom}),"left"in this.options&&{left:this.options.left}),"right"in this.options&&{right:this.options.right})),bd.push(this._element)}setVisible(t){t!==this.isVisible&&(this._isVisible=t,Qe(this.element,"dv-hidden",!this.isVisible))}bringToFront(){bd.push(this._element)}setBounds(t={}){typeof t.height=="number"&&(this._element.style.height=`${t.height}px`),typeof t.width=="number"&&(this._element.style.width=`${t.width}px`),"top"in t&&typeof t.top=="number"&&(this._element.style.top=`${t.top}px`,this._element.style.bottom="auto",this.verticalAlignment="top"),"bottom"in t&&typeof t.bottom=="number"&&(this._element.style.bottom=`${t.bottom}px`,this._element.style.top="auto",this.verticalAlignment="bottom"),"left"in t&&typeof t.left=="number"&&(this._element.style.left=`${t.left}px`,this._element.style.right="auto",this.horiziontalAlignment="left"),"right"in t&&typeof t.right=="number"&&(this._element.style.right=`${t.right}px`,this._element.style.left="auto",this.horiziontalAlignment="right");const n=this.options.container.getBoundingClientRect(),s=this._element.getBoundingClientRect(),o=Math.max(0,this.getMinimumWidth(s.width)),r=Math.max(0,this.getMinimumHeight(s.height));if(this.verticalAlignment==="top"){const a=En(s.top-n.top,-r,Math.max(0,n.height-s.height+r));this._element.style.top=`${a}px`,this._element.style.bottom="auto"}if(this.verticalAlignment==="bottom"){const a=En(n.bottom-s.bottom,-r,Math.max(0,n.height-s.height+r));this._element.style.bottom=`${a}px`,this._element.style.top="auto"}if(this.horiziontalAlignment==="left"){const a=En(s.left-n.left,-o,Math.max(0,n.width-s.width+o));this._element.style.left=`${a}px`,this._element.style.right="auto"}if(this.horiziontalAlignment==="right"){const a=En(n.right-s.right,-o,Math.max(0,n.width-s.width+o));this._element.style.right=`${a}px`,this._element.style.left="auto"}this._onDidChange.fire()}toJSON(){const t=this.options.container.getBoundingClientRect(),n=this._element.getBoundingClientRect(),s={};return this.verticalAlignment==="top"?s.top=Number.parseFloat(this._element.style.top):this.verticalAlignment==="bottom"?s.bottom=Number.parseFloat(this._element.style.bottom):s.top=n.top-t.top,this.horiziontalAlignment==="left"?s.left=Number.parseFloat(this._element.style.left):this.horiziontalAlignment==="right"?s.right=Number.parseFloat(this._element.style.right):s.left=n.left-t.left,s.width=n.width,s.height=n.height,s}cancelPendingDrag(){this._dragMove.value&&(this._dragCancelled=!0,Qe(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=cn.NONE)}setupDrag(t,n){const s=(o,r)=>{var a,l,c;let d=null,u=!1;this._dragCancelled=!1;const h=this.options.transformDragPosition?(a=(l=(c=this.options).getSiblingBoxes)===null||l===void 0?void 0:l.call(c))!==null&&a!==void 0?a:[]:[],p=ic();if(o&&typeof r=="number"&&typeof o.setPointerCapture=="function")try{o.setPointerCapture(r)}catch{}const f=()=>{Qe(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=cn.NONE,this._onDidChangeEnd.fire()};this._dragMove.value=new pt({dispose:()=>{if(p.release(),o&&typeof r=="number"&&typeof o.releasePointerCapture=="function")try{o.releasePointerCapture(r)}catch{}}},ct(globalThis.window,"pointermove",g=>{var x;if(this._dragCancelled)return;const v=this.options.container.getBoundingClientRect(),y=g.clientX-v.left,b=g.clientY-v.top;Qe(this._element,"dv-resize-container-dragging",!0);const w=this._element.getBoundingClientRect();(x=d)!==null&&x!==void 0||(d={x:g.clientX-w.left,y:g.clientY-w.top});const C=Math.max(0,this.getMinimumWidth(w.width)),_=Math.max(0,this.getMinimumHeight(w.height));let N=b-d.y,k=y-d.x;if(this.options.transformDragPosition){const z=this.options.transformDragPosition({proposed:{top:N,left:k,width:w.width,height:w.height},container:{width:v.width,height:v.height},others:h,modifiers:{altKey:g.altKey,ctrlKey:g.ctrlKey,metaKey:g.metaKey,shiftKey:g.shiftKey}});z&&(N=z.top,k=z.left)}const S=Math.max(0,v.height-w.height+_),A=Math.max(0,v.width-w.width+C),T=En(N,-_,S),I=En(v.height-w.height-N,-_,S),P=En(k,-C,A),D=En(v.width-w.width-k,-C,A),O={};T<=I?O.top=T:O.bottom=I,P<=D?O.left=P:O.right=D,this.setBounds(O),u||(u=!0,this._onDidStartMoving.fire())}),ct(globalThis.window,"pointerup",f),ct(globalThis.window,"pointercancel",f))};this.addDisposables(ct(t,"pointerdown",o=>{if(o.defaultPrevented){o.preventDefault();return}YC(o)||s(t,o.pointerId)}),ct(this.options.content,"pointerdown",o=>{o.defaultPrevented||YC(o)||o.shiftKey&&s(this.options.content,o.pointerId)}),ct(this.options.content,"pointerdown",()=>{bd.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 Bn;this.addDisposables(s,ct(n,"pointerdown",o=>{o.preventDefault();let r=null;const a=ic(),l=o.pointerId;if(typeof n.setPointerCapture=="function")try{n.setPointerCapture(l)}catch{}const c=()=>{s.dispose(),this._onDidChangeEnd.fire()};s.value=new pt(ct(globalThis.window,"pointermove",d=>{var u;const h=this.options.container.getBoundingClientRect(),p=this._element.getBoundingClientRect(),f=d.clientY-h.top,g=d.clientX-h.left;(u=r)!==null&&u!==void 0||(r={originalY:f,originalHeight:p.height,originalX:g,originalWidth:p.width});let x,v,y,b,w,C;const _=()=>{const T=r.originalY+r.originalHeight>h.height?Math.max(0,h.height-dr.MINIMUM_HEIGHT):Math.max(0,r.originalY+r.originalHeight-dr.MINIMUM_HEIGHT);x=En(f,0,T),y=r.originalY+r.originalHeight-x,v=h.height-x-y},N=()=>{x=r.originalY-r.originalHeight;const T=x<0&&typeof this.options.minimumInViewportHeight=="number"?-x+this.options.minimumInViewportHeight:dr.MINIMUM_HEIGHT,I=h.height-Math.max(0,x);y=En(f-x,T,I),v=h.height-x-y},k=()=>{const T=r.originalX+r.originalWidth>h.width?Math.max(0,h.width-dr.MINIMUM_WIDTH):Math.max(0,r.originalX+r.originalWidth-dr.MINIMUM_WIDTH);b=En(g,0,T),C=r.originalX+r.originalWidth-b,w=h.width-b-C},S=()=>{b=r.originalX-r.originalWidth;const T=b<0&&typeof this.options.minimumInViewportWidth=="number"?-b+this.options.minimumInViewportWidth:dr.MINIMUM_WIDTH,I=h.width-Math.max(0,b);C=En(g-b,T,I),w=h.width-b-C};switch(t){case"top":_();break;case"bottom":N();break;case"left":k();break;case"right":S();break;case"topleft":_(),k();break;case"topright":_(),S();break;case"bottomleft":N(),k();break;case"bottomright":N(),S();break}const A={};x<=v?A.top=x:A.bottom=v,b<=w?A.left=b:A.right=w,A.height=y,A.width=C,this.setBounds(A)}),{dispose:()=>{if(a.release(),typeof n.releasePointerCapture=="function")try{n.releasePointerCapture(l)}catch{}}},ct(globalThis.window,"pointerup",c),ct(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(){bd.destroy(this._element),this._element.remove(),super.dispose()}};i0.MINIMUM_HEIGHT=20;i0.MINIMUM_WIDTH=20;var Goe=class extends pt{get element(){return this._element}get group(){return this._group}setGroup(e){this._group=e}constructor(e,t){super(),this.accessor=e,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._group=t,this._element=document.createElement("div"),this._element.className="dv-floating-titlebar",this.addDisposables(this._onDragStart,ct(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this._group)}),ct(this._element,"pointerdown",n=>{n.shiftKey&&uP(n)},!0)),this.dragSource=new MP({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 No(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 Foe=new Set(["AdvancedOverflow","AutoEdgeGroup","AutoHideEdgeGroup","ContextMenu","DndCompass","KeyboardDocking","KeyboardNavigation","LayoutHistory","License","MultiRowTabs","PinnedTabs","SmartGuides"]),sk=new Set;function WP(e,t){const n=t===void 0?[]:[].concat(t),s=n.map(a=>`\`${a}\``).join(", "),o=n.length>1?"require":"requires",r=n.length?`${s} ${o} the "${e}" module`:`The "${e}" module is required`;return Foe.has(e)?`dockview: ${r}, which ships in dockview-enterprise.
104
-
105
- npm install dockview-enterprise
106
- import 'dockview-enterprise'; // self-registers every enterprise module
107
- `:`dockview: ${r}, but it is not registered.`}function UP(e,t){const n=`${e}|${(t===void 0?[]:[].concat(t)).join("|")}`;sk.has(n)||(sk.add(n),console.error(WP(e,t)))}function Ls(e,t,n){if(e!==void 0)return e;UP(t,n)}var Hoe=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 Boe=[];function Voe(){return[...Boe]}const $oe=[{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=>Ig(e.autoHideEdgeGroups)},{optionKey:"dockToEdgeGroups",reason:"dockToEdgeGroups",moduleName:"AutoEdgeGroup",when:e=>Ig(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 Woe(e,t){const n=new Map;for(const s of $oe){if(!s.when(e)||t(s.moduleName))continue;const o=n.get(s.moduleName);o?o.push(s.reason):n.set(s.moduleName,[s.reason])}for(const[s,o]of n)UP(s,o)}const Po={left:100,top:100,width:300,height:300};var Uoe=class extends pt{get group(){return this._group}setTitleBar(e){this._titleBar=e}setAnchorGroup(e){var t;this._group=e,(t=this._titleBar)===null||t===void 0||t.setGroup(e)}constructor(e,t,n){super(),this.overlay=t,this.gridview=n,this._group=e,this.addDisposables(t,{dispose:()=>this.gridview.dispose()})}position(e){this.overlay.setBounds(e)}},Koe=class{get floatingGroups(){return this._floatingGroups}constructor(e){this._floatingGroups=[],this._host=e}add(e,t,n){const s=new Uoe(e,t,n),o=new pt(e.api.onDidActiveChange(a=>{a.isActive&&t.bringToFront()}),(()=>{let a=-1,l=-1;return Ir(n.element,c=>{const d=Math.round(c.contentRect.width),u=Math.round(c.contentRect.height);d===a&&u===l||(a=d,l=u,n.layout(d,u))})})()),r=()=>{var a;const l=(a=e.activePanel)===null||a===void 0?void 0:a.title;l?t.element.setAttribute("aria-label",l):t.element.removeAttribute("aria-label")};return r(),s.addDisposables(e.api.onDidActivePanelChange(()=>r()),t.onDidChange(()=>{n.layout(n.width,n.height)}),t.onDidChangeEnd(()=>{this._host.fireLayoutChange()}),e.onDidChange(a=>{t.setBounds({height:typeof a?.height=="number"?a.height+t.headerHeight:a?.height,width:a?.width})}),{dispose:()=>{o.dispose(),mP(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 qoe=No({name:"FloatingGroup",serviceKey:"floatingGroupService",create:e=>new Koe(e)});var Yoe=class{constructor(e){this._entries=[],this._restorationCleanups=new Set,this._restorationPromise=Promise.resolve(),this._onDidRemove=new ve,this.onDidRemove=this._onDidRemove.event,this._host=e}get entries(){return this._entries}get restorationPromise(){return this._restorationPromise}add(e){this._entries.push(e)}remove(e){mP(this._entries,e)&&!this._host.isDisposed&&this._onDidRemove.fire(e)}findByGroup(e){return this._entries.find(t=>t.popoutGroup===e||t.gridview.element.contains(e.element))}findReferenceGroupId(e){var t;return(t=this._entries.find(n=>n.popoutGroup===e))===null||t===void 0?void 0:t.referenceGroup}observeGridviewSize(e,t,n){var s;const o=(s=e.window)===null||s===void 0?void 0:s.ResizeObserver;if(!o)return;let r=-1,a=-1;const l=()=>{const d=e.window;if(this._host.isDisposed||!d||d.closed)return;const u=Math.round(t.element.clientWidth),h=Math.round(t.element.clientHeight);u===r&&h===a||(r=u,a=h,u>0&&h>0&&t.layout(u,h),n.updateAllPositions())},c=new o(()=>{var d;const u=(d=e.window)===null||d===void 0?void 0:d.requestAnimationFrame;u?u.call(e.window,l):l()});return c.observe(t.element),{dispose:()=>c.disconnect()}}scheduleRestoration(e,t,n){return new Promise(s=>{const o=()=>{this._restorationCleanups.delete(o),clearTimeout(r),n?.(),s()},r=setTimeout(()=>{if(this._restorationCleanups.delete(o),this._host.isDisposed){s();return}t(),s()},e);this._restorationCleanups.add(o)})}finishRestoration(e){this._restorationPromise=Promise.all(e).then(()=>{})}cancelPendingRestorations(){for(const e of[...this._restorationCleanups])e();this._restorationCleanups.clear()}serialize(){return this._entries.map(e=>{const t=e.gridview.serialize(),n=t.root,s=e.popoutGroup.api.location.type==="popout"?e.popoutGroup.api.location.popoutUrl:void 0,o={gridReferenceGroup:e.referenceGroup,position:e.window.dimensions(),url:s};return n.type==="branch"&&n.data.length===1&&n.data[0].type==="leaf"?gt(gt({},o),{},{data:n.data[0].data}):gt(gt({},o),{},{grid:t})})}disposeAll(){for(const e of[...this._entries])e.disposable.dispose()}dispose(){this.cancelPendingRestorations(),this.disposeAll(),this._onDidRemove.dispose()}};const Xoe=No({name:"PopoutWindow",serviceKey:"popoutWindowService",create:e=>new Yoe(e)});var Joe=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",fie(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 Zoe=No({name:"Watermark",serviceKey:"watermarkService",create:e=>new Joe(e),init:(e,t)=>(t.update(),new pt(ei.any(e.onDidAdd,e.onDidRemove)(()=>{t.update()}),e.onDidViewVisibilityChangeMicroTaskQueue(()=>{t.update()})))});var Qoe=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 ere=No({name:"EdgeGroup",serviceKey:"edgeGroupService",create:()=>new Qoe}),tre={activationSize:{type:"pixels",value:10},size:{type:"pixels",value:20}},nre={activationSize:{type:"pixels",value:32},size:{type:"pixels",value:20}};function ik(e,t){return typeof e.dndEdges=="object"&&e.dndEdges!==null?e.dndEdges:t&&Ig(e.dockToEdgeGroups)?nre:tre}var sre=class{constructor(e){this._host=e;const t=(s,o)=>{const r=On();return r?r.viewId!==e.id?!1:o==="center"?e.isGridEmpty():!0:o==="center"&&!e.isGridEmpty()?!1:e.dispatchUnhandledDragOver(s,o)},n=ik(e.options,!1);this._html5Target=Wo.createDropTarget(e.element,{className:"dv-drop-target-edge",canDisplayOverlay:t,acceptedTargetZones:["top","bottom","left","right","center"],overlayModel:n,getOverrideTarget:()=>e.rootDropTargetOverrideTarget(),getPositionResolver:()=>e.options.dropPositionResolver}),this._pointerTarget=Co.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=ei.any(this._html5Target.onWillShowOverlay,this._pointerTarget.onWillShowOverlay),this.onDrop=ei.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=ik({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 ire=No({name:"RootDropTarget",serviceKey:"rootDropTargetService",create:e=>new sre(e),init:(e,t)=>(t.setOptions(e.options),cn.NONE)}),ore={left:"createLeftHeaderActionComponent",right:"createRightHeaderActionComponent",prefix:"createPrefixHeaderActionComponent"};var rre=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 Bn,right:new Bn,prefix:new Bn},this._perGroup.set(e,t)),t}_refreshSlot(e,t,n){const s=this._host.options[ore[e]];if(s){const o=s(t);n.value=o,o.init({containerApi:this._host.api,api:t.api,group:t}),t.model.attachHeaderAction(e,o.element)}else n.dispose(),t.model.attachHeaderAction(e,void 0)}};const are=No({name:"HeaderActions",serviceKey:"headerActionsService",create:e=>new rre(e),init:(e,t)=>new pt(e.onDidRemoveGroup(n=>{t.disposeGroup(n)}))}),ok=e=>e==="load"||e==="clear";function wd(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 lre=class extends pt{constructor(e){var t;super(),this._regions=new Map,this._suppressDepth=0,this._locationSubs=new Map,this._host=e;const n=e.element.ownerDocument;this._mainWindow=(t=n.defaultView)!==null&&t!==void 0?t:window;const s={polite:wd(n,"polite"),assertive:wd(n,"assertive")};e.element.appendChild(s.polite),e.element.appendChild(s.assertive),this._regions.set(this._mainWindow,s),this._syncPopoutRegions(),this.addDisposables({dispose:()=>this._disposeRegions()},e.onDidChangePopouts(()=>this._syncPopoutRegions()),e.onDidAddPanel(o=>this._announce(o,"open")),e.onDidRemovePanel(o=>this._announce(o,"close")),e.onWillMutateLayout(o=>{ok(o.kind)&&this._suppressDepth++}),e.onDidMutateLayout(o=>{ok(o.kind)&&(this._suppressDepth=Math.max(0,this._suppressDepth-1))}),e.onDidMaximizedGroupChange(o=>{const r=o.group.activePanel;r&&this._announce(r,o.isMaximized?"maximize":"restore")}),e.onDidAddGroup(o=>this._trackLocation(o)),e.onDidRemoveGroup(o=>{var r;(r=this._locationSubs.get(o.id))===null||r===void 0||r.dispose(),this._locationSubs.delete(o.id)}),{dispose:()=>{this._locationSubs.forEach(o=>o.dispose()),this._locationSubs.clear()}})}_syncPopoutRegions(){const e=this._host.element.ownerDocument,t=new Set([this._mainWindow]);for(const s of this._host.getPopoutWindows()){var n;if(s.document===e||(t.add(s),this._regions.has(s)))continue;const o=s.document,r=(n=o.body)!==null&&n!==void 0?n:o.documentElement,a={polite:wd(o,"polite"),assertive:wd(o,"assertive")};r.appendChild(a.polite),r.appendChild(a.assertive),this._regions.set(s,a)}for(const[s,o]of this._regions)t.has(s)||(o.polite.remove(),o.assertive.remove(),this._regions.delete(s))}_disposeRegions(){for(const e of this._regions.values())e.polite.remove(),e.assertive.remove();this._regions.clear()}_focusedRegions(){for(const[e,t]of this._regions)if(e!==this._mainWindow)try{if(e.document.hasFocus())return t}catch{}return this._regions.get(this._mainWindow)}_trackLocation(e){let t=e.api.location.type;const n=e.api.onDidLocationChange(s=>{const o=s.location.type;if(o===t)return;t=o;const r=e.activePanel;if(!r)return;let a;switch(o){case"floating":a="float";break;case"popout":a="popout";break;default:a="dock";break}this._announce(r,a)});this._locationSubs.set(e.id,n)}announce(e,t="polite"){if(this._host.options.announcements===!1||this._suppressDepth>0||!e)return;const n=this._host.options.announcer;if(n){n({message:e,politeness:t});return}const s=this._focusedRegions(),o=t==="assertive"?s.assertive:s.polite;o.textContent="",o.textContent=e}_announce(e,t){var n,s;const o=(n=(s=this._host.options).getAnnouncement)===null||n===void 0?void 0:n.call(s,{kind:t,panel:e});o===null||o===""||this.announce(o??this._defaultMessage(e,t))}_defaultMessage(e,t){var n;const s=bP(this._host.options.messages),o=(n=e.title)!==null&&n!==void 0?n:e.id;switch(t){case"open":return s.panelOpened(o);case"close":return s.panelClosed(o);case"maximize":return s.groupMaximized(o);case"restore":return s.groupRestored(o);case"float":return s.groupFloated(o);case"dock":return s.groupDocked(o);case"popout":return s.groupPoppedOut(o)}}};const cre=No({name:"LiveRegion",serviceKey:"liveRegionService",create:e=>new lre(e)}),dre=30,ure=-10;var hre=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:dre,offsetY:ure,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),cn.from(()=>n.clearOverlay())}dispose(){}};const pre=No({name:"AdvancedDnD",serviceKey:"advancedDnDService",create:e=>new hre(e)});var fre=class{constructor(e){this._host=e}attachToGroup(e){return new pt(e.model.onDidCreateTabGroup(t=>{this._host.fireDidCreateTabGroup(t)}),e.model.onDidDestroyTabGroup(t=>{this._host.fireDidDestroyTabGroup(t)}),e.model.onDidAddPanelToTabGroup(t=>{this._host.fireDidAddPanelToTabGroup(t)}),e.model.onDidRemovePanelFromTabGroup(t=>{this._host.fireDidRemovePanelFromTabGroup(t)}),e.model.onDidTabGroupChange(t=>{this._host.fireDidTabGroupChange(t)}),e.model.onDidTabGroupCollapsedChange(t=>{this._host.fireDidTabGroupCollapsedChange(t)}))}dispose(){}};const mre=No({name:"TabGroupChips",serviceKey:"tabGroupChipsService",create:e=>new fre(e),init:(e,t)=>{const n=new Map;return new pt(e.onDidAddGroup(s=>{n.set(s,t.attachToGroup(s))}),e.onDidRemoveGroup(s=>{var o;(o=n.get(s))===null||o===void 0||o.dispose(),n.delete(s)}),{dispose:()=>{for(const s of n.values())s.dispose();n.clear()}})}}),gre=[qoe,Xoe,Zoe,ere,ire,are,cre,pre,mre];var xre=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=wg(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 rk=-1;function vre(){const e=document.createElement("div");return e.tabIndex=-1,e}var ak=class extends pt{constructor(e,t){super(),this.element=e,this.accessor=t,this.map={},this._disposed=!1,this._generation=0,this.positionCache=new xre,this.addDisposables(cn.from(()=>{for(const n of Object.values(this.map))n.disposable.dispose(),n.destroy.dispose(),this.cancelPendingUpdate(n);this._disposed=!0}))}updateAllPositions(){if(!this._disposed){this.positionCache.invalidate();for(const e of Object.values(this.map))e.panel.api.isVisible&&e.resize&&e.resize()}}repositionPanelOverlay(e,t=!1,n){var s;if(this._disposed)return;const o=this.map[e];o&&(o.forceVisible=t,o.clip=n,this.positionCache.invalidate(),(s=o.resize)===null||s===void 0||s.call(o))}cancelPendingUpdate(e){e.pendingUpdate!==void 0&&(cancelAnimationFrame(e.pendingUpdate),e.pendingUpdate=void 0)}detatch(e){if(this.map[e.api.id]){const t=this.map[e.api.id];return t.disposable.dispose(),t.destroy.dispose(),this.cancelPendingUpdate(t),delete this.map[e.api.id],!0}return!1}attach(e){const{panel:t,referenceContainer:n}=e;if(!this.map[t.api.id]){const p=vre();p.className="dv-render-overlay",p.style.visibility="hidden",this.map[t.api.id]={panel:t,disposable:cn.NONE,destroy:cn.NONE,element:p,retainPreviousGeometry:!1,positioned:!1,generation:++this._generation}}const s=this.map[t.api.id];s.referenceContainer!==n&&(s.generation=++this._generation,this.cancelPendingUpdate(s),s.referenceContainer=n,s.retainPreviousGeometry=s.positioned);const o=s.generation,r=s.element,a=t.view.content.element;a.parentElement!==r&&r.appendChild(a),r.parentElement!==this.element&&this.element.appendChild(r);const l=()=>{const p=t.api.id,f=this.map[p];if(f?.generation!==o||f.pendingUpdate!==void 0)return;f.pendingUpdate=rk;const g=requestAnimationFrame(()=>{var x;const v=this.map[p];if(v&&(v.pendingUpdate=void 0),this.isDisposed||v?.generation!==o)return;const y=(x=v.forceVisible)!==null&&x!==void 0?x:!1,b=v.clip,w=this.positionCache.getPosition(n.element),C=this.positionCache.getPosition(this.element),_=w.left-C.left,N=w.top-C.top,k=w.width,S=w.height;if(v.retainPreviousGeometry&&(k===0||S===0)){!t.api.isVisible&&!y&&(r.style.visibility="hidden",r.style.pointerEvents="none");return}if(v.retainPreviousGeometry=!1,v.positioned=!0,r.style.left=`${_}px`,r.style.top=`${N}px`,r.style.width=`${k}px`,r.style.height=`${S}px`,t.api.isVisible||y?(r.style.visibility="",r.style.pointerEvents=""):(r.style.visibility="hidden",r.style.pointerEvents="none"),y?r.style.zIndex="1000":t.api.location.type!=="floating"&&(r.style.zIndex=""),b){var A,T;const I=this.element.ownerDocument.defaultView,P=(A=I?.scrollX)!==null&&A!==void 0?A:0,D=(T=I?.scrollY)!==null&&T!==void 0?T:0,O=b.top+D,z=b.left+P,R=Math.max(0,O-w.top),$=Math.max(0,z-w.left),X=Math.max(0,w.left+k-(b.right+P)),H=Math.max(0,w.top+S-(b.bottom+D));r.style.clipPath=`inset(${R}px ${X}px ${H}px ${$}px)`}else r.style.clipPath="";Qe(r,"dv-render-overlay-float",t.group.api.location.type==="floating")});f.pendingUpdate===rk&&(f.pendingUpdate=g)},c=()=>{if(t.api.isVisible){var p;this.positionCache.invalidate(),l(),!((p=this.map[t.api.id])===null||p===void 0)&&p.retainPreviousGeometry&&(r.style.visibility=""),r.style.pointerEvents=""}else r.style.visibility="hidden",r.style.pointerEvents="none"},d=new Bn,u=()=>{t.api.location.type==="floating"?queueMicrotask(()=>{const p=this.accessor.getFloatingWindowForGroup(t.api.group);if(!p)return;const f=p.overlay.element,g=()=>{const v=Number(f.getAttribute("aria-level"));r.style.zIndex=`calc(var(--dv-overlay-z-index, 999) + ${v*2+1})`},x=new MutationObserver(()=>{g()});d.value=cn.from(()=>x.disconnect()),x.observe(f,{attributeFilter:["aria-level"],attributes:!0}),g()}):r.style.zIndex=""},h=new pt(d,new SP(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=cn.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 lk(e,t,n,s,o,r,a){try{var l=e[r](a),c=l.value}catch(d){n(d);return}l.done?t(c):Promise.resolve(c).then(s,o)}function KP(e){return function(){var t=this,n=arguments;return new Promise(function(s,o){var r=e.apply(t,n);function a(c){lk(r,s,o,a,l,"next",c)}function l(c){lk(r,s,o,a,l,"throw",c)}a(void 0)})}}function bre(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 wre=class extends pt{get window(){var e,t;return(e=(t=this._window)===null||t===void 0?void 0:t.value)!==null&&e!==void 0?e:null}constructor(e,t,n){super(),this.target=e,this.className=t,this.options=n,this._onWillClose=new ve,this.onWillClose=this._onWillClose.event,this._onDidClose=new ve,this.onDidClose=this._onDidClose.event,this._window=null,this.addDisposables(this._onWillClose,this._onDidClose,{dispose:()=>{this.close()}})}dimensions(){if(!this._window)return null;const e=this._window.value.screenX;return{top:this._window.value.screenY,left:e,width:this._window.value.innerWidth,height:this._window.value.innerHeight}}close(){if(this._window){var e,t;this._onWillClose.fire(),(e=(t=this.options).onWillClose)===null||e===void 0||e.call(t,{id:this.target,window:this._window.value}),this._window.disposable.dispose(),this._window=null,this._onDidClose.fire()}}open(){var e=this;return KP(function*(){var t,n;if(e._window)throw new Error("instance of popout window is already open");const s=`${e.options.url}`;bre(s);const o=Object.entries({top:e.options.top,left:e.options.left,width:e.options.width,height:e.options.height}).map(([c,d])=>`${c}=${d}`).join(","),r=window.open(s,e.target,o);if(!r)return null;const a=new pt;e._window={value:r,disposable:a},a.addDisposables(cn.from(()=>{r.close()}),ct(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),pie(u,globalThis.document.styleSheets,{nonce:e.options.nonce}),ct(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}},yre=class extends pt{constructor(e){super(),this.accessor=e,this.init()}init(){const e=new Set,t=new Set;this.addDisposables(this.accessor.onDidAddPanel(n=>{if(e.has(n.api.id))throw new Error(`dockview: Invalid event sequence. [onDidAddPanel] called for panel ${n.api.id} but panel already exists`);e.add(n.api.id)}),this.accessor.onDidRemovePanel(n=>{if(e.has(n.api.id))e.delete(n.api.id);else throw new Error(`dockview: Invalid event sequence. [onDidRemovePanel] called for panel ${n.api.id} but panel does not exists`)}),this.accessor.onDidAddGroup(n=>{if(t.has(n.api.id))throw new Error(`dockview: Invalid event sequence. [onDidAddGroup] called for group ${n.api.id} but group already exists`);t.add(n.api.id)}),this.accessor.onDidRemoveGroup(n=>{if(t.has(n.api.id))t.delete(n.api.id);else throw new Error(`dockview: Invalid event sequence. [onDidRemoveGroup] called for group ${n.api.id} but group does not exists`)}))}};function Sre(e){if(!e.matchMedia)return!1;const t=e.matchMedia("(pointer: coarse)").matches,n=e.matchMedia("(pointer: fine)").matches;return t&&!n}function Cre(e){var t,n,s,o,r,a,l;const c=(t=e.window)!==null&&t!==void 0?t:window,d=(n=e.capture)!==null&&n!==void 0?n:!1,u=(s=e.escape)!==null&&s!==void 0?s:!0,h=(o=e.keys)!==null&&o!==void 0?o:[],p=(r=e.outsidePointerDown)!==null&&r!==void 0?r:!0,f=(a=e.pointerDownGraceMs)!==null&&a!==void 0?a:0,g=(l=e.now)!==null&&l!==void 0?l:Date.now,x=g(),v=new pt,y=b=>{var w,C;if(e.isInside)return e.isInside(b);const _=b.target;return _ instanceof Node?((w=(C=e.elements)===null||C===void 0?void 0:C.call(e))!==null&&w!==void 0?w:[]).some(N=>N.contains(_)):!1};if((u||h.length>0)&&v.addDisposables(ct(c,"keydown",b=>{(u&&b.key==="Escape"||h.includes(b.key))&&e.onDismiss()},d)),(p||e.onInsidePointerDown)&&v.addDisposables(ct(c,"pointerdown",b=>{if(y(b)){var w;(w=e.onInsidePointerDown)===null||w===void 0||w.call(e,b);return}!p||g()-x<f||e.onDismiss()},d)),e.resize&&v.addDisposables(ct(c,"resize",()=>{Sre(c)||e.onDismiss()})),e.focusOut){const b=C=>{var _,N;return e.isFocusInside?e.isFocusInside(C):((_=(N=e.elements)===null||N===void 0?void 0:N.call(e))!==null&&_!==void 0?_:[]).some(k=>k.contains(C))},w=C=>{const _=C.target;_ instanceof Element&&!b(_)&&e.onDismiss()};c.addEventListener("focusin",w,d),v.addDisposables({dispose:()=>c.removeEventListener("focusin",w,d)})}return v}var ck=class extends pt{constructor(e,t=globalThis.window){super(),this._active=null,this._activeDisposable=new Bn,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(cn.from(()=>{this.close()}),this._activeDisposable)}updateRoot(e){e.prepend(this._element),this._root=e}openPopover(e,t){var n;this.close();const s=this._window.document.createElement("div");s.style.position="absolute",s.style.zIndex=(n=t.zIndex)!==null&&n!==void 0?n:"var(--dv-overlay-z-index)",s.appendChild(e);const o=this._element.getBoundingClientRect(),r=o.left,a=o.top;s.style.top=`${t.y-a}px`,s.style.left=`${t.x-r}px`,this._element.appendChild(s),this._active=s;const l=200;this._activeDisposable.value=Cre({window:this._window,onDismiss:()=>this.close(),elements:()=>this._active?[this._active]:[],keys:["Enter"],pointerDownGraceMs:l,resize:!0}),this._window.requestAnimationFrame(()=>{bie(s,this._root)})}close(){this._active&&(this._active.remove(),this._activeDisposable.dispose(),this._active=null)}},Ef=class extends pt{get disabled(){return this._disabled}set disabled(e){this.disabled!==e&&(this._disabled=e,e&&this._clearNow())}_cancelPendingClear(){this._pendingClear!==void 0&&(clearTimeout(this._pendingClear),this._pendingClear=void 0)}_clearNow(){this._cancelPendingClear(),this._model&&this._model.root.remove(),this._model=void 0}get model(){if(!this.disabled)return{clear:()=>{this._clearNow()},scheduleClear:()=>{this._pendingClear!==void 0||!this._model||(this._pendingClear=setTimeout(()=>{this._pendingClear=void 0,this._clearNow()},0))},exists:()=>!!this._model,getElements:(e,t)=>{this._cancelPendingClear();const n=this._outline!==t;if(this._outline=t,this._model)return this._model.changed=n,this._model;const s=this.createContainer(),o=this.createAnchor();if(this._model={root:s,overlay:o,changed:n},s.appendChild(o),this.element.appendChild(s),e?.target instanceof HTMLElement){const r=e.target.getBoundingClientRect(),a=this.element.getBoundingClientRect();o.style.left=`${r.left-a.left}px`,o.style.top=`${r.top-a.top}px`}return this._model}}}constructor(e,t){super(),this.element=e,this._disabled=!1,this._disabled=t.disabled,this.addDisposables(cn.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}},kre=class{get _effectiveBaseCollapsed(){var e;return(e=this._measuredTabSize)!==null&&e!==void 0?e:this._baseCollapsedSize}get minimumSize(){return this._isCollapsed?this.collapsedSize:this._baseMinimumSize!==void 0?this._baseMinimumSize+this._gapAdd:this._effectiveBaseCollapsed+50+this._gapAdd}get maximumSize(){return this._isCollapsed?this.collapsedSize:this._expandedMaximumSize}get element(){return this._group.element}get isCollapsed(){return this._isCollapsed}get lastExpandedSize(){return this._lastExpandedSize}get collapsedSize(){return this._effectiveBaseCollapsed+this._gapAdd}get configuredMinimumSize(){return this._baseMinimumSize}get configuredMaximumSize(){return this._expandedMaximumSize}get configuredCollapsedSize(){return this._baseCollapsedSize}constructor(e,t,n,s=0){var o,r,a;this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this.snap=!1,this.priority="low",this._isCollapsed=!1,this._tabSizeDisposables=new pt,this._group=t,this._orientation=n,t.element.classList.add("dv-edge-group"),t.element.dataset.testid=`dv-edge-group-${e.id}`,this._baseCollapsedSize=(o=e.collapsedSize)!==null&&o!==void 0?o:35,this._baseMinimumSize=e.minimumSize,this._gapAdd=s,this._expandedMaximumSize=(r=e.maximumSize)!==null&&r!==void 0?r:Number.POSITIVE_INFINITY,this._lastExpandedSize=(a=e.initialSize)!==null&&a!==void 0?a:200,e.collapsed&&(this._isCollapsed=!0,t.element.classList.add("dv-edge-collapsed")),this._observeTabStrip()}_observeTabStrip(){const e=this._group.element.querySelector(".dv-tabs-and-actions-container");e&&this._tabSizeDisposables.addDisposables(Ir(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()}},jre=class{get element(){return this._dockviewElement}constructor(e,t){this._dockviewElement=e,this._layoutDockview=t,this.priority="high",this.minimumSize=100,this.maximumSize=Number.POSITIVE_INFINITY,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event}layout(e,t){this._layoutDockview(t,e)}setVisible(e){}dispose(){this._onDidChange.dispose()}},_re=class{get element(){return this._element}constructor(e,t=0){this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this.minimumSize=100,this.maximumSize=Number.POSITIVE_INFINITY,this.priority="high",this._element=document.createElement("div"),this._element.className="dv-shell-middle-column",this._element.style.height="100%",this._element.style.width="100%",this._splitview=new _r(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()}},Nre=class{constructor(e,t,n,s=0,o=35){this._disposables=new pt,this._viewConfigs=new Map,this._currentWidth=0,this._currentHeight=0,this._gap=s,this._defaultCollapsedSize=o,this._shellElement=document.createElement("div"),this._shellElement.className="dv-shell",this._shellElement.style.height="100%",this._shellElement.style.width="100%",this._shellElement.style.position="relative",e.appendChild(this._shellElement);const r=new jre(t,n);this._middleColumn=new _re(r,s),this._outerSplitview=new _r(this._shellElement,{orientation:"HORIZONTAL",proportionalLayout:!1,margin:s}),this._middleIndex=0,this._outerSplitview.addView(this._middleColumn,{type:"distribute"},0),this._disposables.addDisposables(Ir(this._shellElement,a=>{if(!this._shellElement.offsetParent||!hP(this._shellElement))return;const l=Math.round(a.contentRect.width),c=Math.round(a.contentRect.height);l===this._currentWidth&&c===this._currentHeight||(this._currentWidth=l,this._currentHeight=c,this.layout(l,c))}),this._outerSplitview,this._middleColumn,r)}get element(){return this._shellElement}addEdgeView(e,t,n){if(this.hasEdgeGroup(e))throw new Error(`dockview: edge group already registered at position '${e}'`);this._viewConfigs.set(e,t);const s=1+(this._viewConfigs.has("left")?1:0)+(this._viewConfigs.has("right")?1:0),o=1+(this._viewConfigs.has("top")?1:0)+(this._viewConfigs.has("bottom")?1:0),r=s>1?this._gap*(s-1)/s:0,a=o>1?this._gap*(o-1)/o:0,l=e==="left"||e==="right",c=l?r:a,d=l?"horizontal":"vertical",u=new kre(gt({collapsedSize:this._defaultCollapsedSize},t),n,d,c),h=u.isCollapsed?u.collapsedSize:u.lastExpandedSize;switch(e){case"left":this._outerSplitview.addView(u,h,0),this._leftIndex=0,this._middleIndex+=1,this._rightIndex!==void 0&&(this._rightIndex+=1),this._leftView=u;break;case"right":{const p=this._outerSplitview.length;this._outerSplitview.addView(u,h,p),this._rightIndex=p,this._rightView=u}break;case"top":this._middleColumn.addTopView(u,h),this._topView=u;break;case"bottom":this._middleColumn.addBottomView(u,h),this._bottomView=u;break}return this._disposables.addDisposables(u),this.updateTheme(this._gap,this._defaultCollapsedSize),u}layout(e,t){this._outerSplitview.layout(e,t)}updateTheme(e,t){var n,s,o,r;this._gap=e,this._defaultCollapsedSize=t;const a=1+(this._viewConfigs.has("left")?1:0)+(this._viewConfigs.has("right")?1:0),l=1+(this._viewConfigs.has("top")?1:0)+(this._viewConfigs.has("bottom")?1:0),c=a>1?e*(a-1)/a:0,d=l>1?e*(l-1)/l:0;this._outerSplitview.margin=e,this._middleColumn.updateMargin(e);const u=(x,v,y)=>{var b;const w=(b=v.collapsedSize)!==null&&b!==void 0?b:t;x.updateSizing(w,v.minimumSize,y)},h=this._viewConfigs.get("top");this._topView&&h&&u(this._topView,h,d);const p=this._viewConfigs.get("bottom");this._bottomView&&p&&u(this._bottomView,p,d);const f=this._viewConfigs.get("left");this._leftView&&f&&u(this._leftView,f,c);const g=this._viewConfigs.get("right");this._rightView&&g&&u(this._rightView,g,c),!((n=this._leftView)===null||n===void 0)&&n.isCollapsed&&this._leftIndex!==void 0&&this._outerSplitview.resizeView(this._leftIndex,this._leftView.collapsedSize),!((s=this._rightView)===null||s===void 0)&&s.isCollapsed&&this._rightIndex!==void 0&&this._outerSplitview.resizeView(this._rightIndex,this._rightView.collapsedSize),!((o=this._topView)===null||o===void 0)&&o.isCollapsed&&this._middleColumn.resizeView("top",this._topView.collapsedSize),!((r=this._bottomView)===null||r===void 0)&&r.isCollapsed&&this._middleColumn.resizeView("bottom",this._bottomView.collapsedSize),this._currentWidth>0&&this._currentHeight>0&&this.layout(this._currentWidth,this._currentHeight)}removeEdgeView(e){const t=this._getView(e);if(t){switch(e){case"left":this._outerSplitview.removeView(this._leftIndex),this._leftIndex=void 0,this._leftView=void 0,this._middleIndex-=1,this._rightIndex!==void 0&&(this._rightIndex-=1);break;case"right":this._outerSplitview.removeView(this._rightIndex),this._rightIndex=void 0,this._rightView=void 0;break;case"top":this._middleColumn.removeView("top"),this._topView=void 0;break;case"bottom":this._middleColumn.removeView("bottom"),this._bottomView=void 0;break}this._disposables.removeDisposable(t),t.dispose(),this._viewConfigs.delete(e),this.updateTheme(this._gap,this._defaultCollapsedSize)}}hasEdgeGroup(e){switch(e){case"top":return this._topView!==void 0;case"bottom":return this._bottomView!==void 0;case"left":return this._leftView!==void 0;case"right":return this._rightView!==void 0}}setEdgeGroupVisible(e,t){switch(e){case"left":this._leftIndex!==void 0&&this._outerSplitview.setViewVisible(this._leftIndex,t);break;case"right":this._rightIndex!==void 0&&this._outerSplitview.setViewVisible(this._rightIndex,t);break;case"top":case"bottom":this._middleColumn.setViewVisible(e,t);break}}isEdgeGroupVisible(e){switch(e){case"left":return this._leftIndex!==void 0?this._outerSplitview.isViewVisible(this._leftIndex):!1;case"right":return this._rightIndex!==void 0?this._outerSplitview.isViewVisible(this._rightIndex):!1;case"top":case"bottom":return this._middleColumn.isViewVisible(e)}}setEdgeGroupCollapsed(e,t){const n=this._getView(e);if(!n)return;n.setCollapsed(t);const s=t?n.collapsedSize:n.lastExpandedSize;switch(e){case"left":this._leftIndex!==void 0&&this._outerSplitview.resizeView(this._leftIndex,s);break;case"right":this._rightIndex!==void 0&&this._outerSplitview.resizeView(this._rightIndex,s);break;case"top":case"bottom":this._middleColumn.resizeView(e,s);break}}isEdgeGroupCollapsed(e){var t,n;return(t=(n=this._getView(e))===null||n===void 0?void 0:n.isCollapsed)!==null&&t!==void 0?t:!1}getEdgeGroupExpandedSize(e){var t,n;return(t=(n=this._getView(e))===null||n===void 0?void 0:n.lastExpandedSize)!==null&&t!==void 0?t:0}_getView(e){switch(e){case"top":return this._topView;case"bottom":return this._bottomView;case"left":return this._leftView;case"right":return this._rightView}}toJSON(){const e={},t=s=>({minimumSize:s.configuredMinimumSize,maximumSize:Number.isFinite(s.configuredMaximumSize)?s.configuredMaximumSize:void 0,collapsedSize:s.configuredCollapsedSize}),n=(s,o,r,a)=>s.isCollapsed?s.lastExpandedSize:o?r:a??s.lastExpandedSize;if(this._leftView&&this._leftIndex!==void 0){const s=this._outerSplitview.isViewVisible(this._leftIndex);e.left=gt({size:n(this._leftView,s,this._outerSplitview.getViewSize(this._leftIndex),this._outerSplitview.getViewCachedVisibleSize(this._leftIndex)),visible:s,collapsed:this._leftView.isCollapsed||void 0},t(this._leftView))}if(this._rightView&&this._rightIndex!==void 0){const s=this._outerSplitview.isViewVisible(this._rightIndex);e.right=gt({size:n(this._rightView,s,this._outerSplitview.getViewSize(this._rightIndex),this._outerSplitview.getViewCachedVisibleSize(this._rightIndex)),visible:s,collapsed:this._rightView.isCollapsed||void 0},t(this._rightView))}if(this._topView){const s=this._middleColumn.isViewVisible("top");e.top=gt({size:n(this._topView,s,this._middleColumn.getViewSize("top"),this._middleColumn.getViewCachedVisibleSize("top")),visible:s,collapsed:this._topView.isCollapsed||void 0},t(this._topView))}if(this._bottomView){const s=this._middleColumn.isViewVisible("bottom");e.bottom=gt({size:n(this._bottomView,s,this._middleColumn.getViewSize("bottom"),this._middleColumn.getViewCachedVisibleSize("bottom")),visible:s,collapsed:this._bottomView.isCollapsed||void 0},t(this._bottomView))}return e}fromJSON(e){if(e.left&&this._leftIndex!==void 0){var t,n,s,o,r;(t=this._leftView)===null||t===void 0||t.restoreExpandedSize(e.left.size),(n=this._leftView)===null||n===void 0||n.setCollapsed((s=e.left.collapsed)!==null&&s!==void 0?s:!1),this._outerSplitview.resizeView(this._leftIndex,e.left.collapsed&&(o=(r=this._leftView)===null||r===void 0?void 0:r.collapsedSize)!==null&&o!==void 0?o:e.left.size),e.left.visible||this._outerSplitview.setViewVisible(this._leftIndex,!1)}if(e.right&&this._rightIndex!==void 0){var a,l,c,d,u;(a=this._rightView)===null||a===void 0||a.restoreExpandedSize(e.right.size),(l=this._rightView)===null||l===void 0||l.setCollapsed((c=e.right.collapsed)!==null&&c!==void 0?c:!1),this._outerSplitview.resizeView(this._rightIndex,e.right.collapsed&&(d=(u=this._rightView)===null||u===void 0?void 0:u.collapsedSize)!==null&&d!==void 0?d:e.right.size),e.right.visible||this._outerSplitview.setViewVisible(this._rightIndex,!1)}if(e.top){var h,p,f,g,x;(h=this._topView)===null||h===void 0||h.restoreExpandedSize(e.top.size),(p=this._topView)===null||p===void 0||p.setCollapsed((f=e.top.collapsed)!==null&&f!==void 0?f:!1),this._middleColumn.resizeView("top",e.top.collapsed&&(g=(x=this._topView)===null||x===void 0?void 0:x.collapsedSize)!==null&&g!==void 0?g:e.top.size),e.top.visible||this._middleColumn.setViewVisible("top",!1)}if(e.bottom){var v,y,b,w,C;(v=this._bottomView)===null||v===void 0||v.restoreExpandedSize(e.bottom.size),(y=this._bottomView)===null||y===void 0||y.setCollapsed((b=e.bottom.collapsed)!==null&&b!==void 0?b:!1),this._middleColumn.resizeView("bottom",e.bottom.collapsed&&(w=(C=this._bottomView)===null||C===void 0?void 0:C.collapsedSize)!==null&&w!==void 0?w:e.bottom.size),e.bottom.visible||this._middleColumn.setViewVisible("bottom",!1)}}dispose(){this._disposables.dispose(),this._shellElement.remove()}};function Tre(e){var t;return new GP((t=e.tabGroupColors)!==null&&t!==void 0?t:Qv,e.tabGroupAccent!=="off")}function yd(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 Eg=()=>({dispose:()=>{}}),Ire=Eg;var Dre=class extends vP{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=Ls(this._smartGuidesService,"SmartGuides","api.setSmartGuidesEnabled"))===null||t===void 0||t.setEnabled(e)}updateSmartGuidesOptions(e){var t;(t=Ls(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:Eg}get onDidSnapTogether(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.onDidSnapTogether)!==null&&e!==void 0?e:Eg}_buildFloatingDragTransform(e,t){const n=this.options.transformFloatingGroupDrag,s=!t;if(!(!n&&!(s&&this._smartGuidesService)))return o=>{var r,a;const l=n?.({group:e,proposed:o.proposed,container:o.container,others:o.others,modifiers:o.modifiers}),c=l?gt(gt({},o.proposed),l):o.proposed,d=s?(r=this._smartGuidesService)===null||r===void 0?void 0:r.transformFloatingGroupDrag({group:e,proposed:c,container:o.container,others:o.others,modifiers:o.modifiers}):void 0;return(a=d??l)!==null&&a!==void 0?a:void 0}}get _floatingGroupService(){return this._moduleRegistry.services.floatingGroupService}get _popoutWindowService(){return this._moduleRegistry.services.popoutWindowService}get _watermarkService(){return this._moduleRegistry.services.watermarkService}get _edgeGroupService(){return this._moduleRegistry.services.edgeGroupService}get _rootDropTargetService(){return this._moduleRegistry.services.rootDropTargetService}get _advancedDnDService(){return this._moduleRegistry.services.advancedDnDService}get _dndCompassService(){return this._moduleRegistry.services.dndCompassService}canDropOnGroup(e,t,n){return e.model.canDisplayContentOverlay(n,t)}getDropOverlayElement(e){var t,n;const s=e.element.querySelector(".dv-content-container");if(s)return((t=this.options.theme)===null||t===void 0?void 0:t.dndPanelOverlay)==="group"&&(n=s.parentElement)!==null&&n!==void 0?n:s}getTabsListElement(e){return e.model.header.hidden?void 0:e.model.tabsListElement}relayoutGroup(e){e.relayout()}setForcedOverflow(e,t){e.model.header.setForcedOverflow(t)}getLayoutElement(){return this.gridview.element}getDropPositionResolver(){var e;if(this.options.dropPositionResolver)return this.options.dropPositionResolver;const t=(e=this._dndCompassService)===null||e===void 0?void 0:e.resolver,n=this._moduleRegistry.services.autoEdgeGroupService;return t&&n?{resolve:s=>{var o;return(o=n.resolveEdge(s))!==null&&o!==void 0?o:t.resolve(s)}}:t??n?.resolver}dockToLayoutEdge(e,t){const n=new BP({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:On,kind:"edge"});if(this._onWillDrop.fire(n),n.defaultPrevented)return;const s=On();if(s){var o;this.moveGroupOrPanel({from:{groupId:s.groupId,panelId:(o=s.panelId)!==null&&o!==void 0?o:void 0},to:{group:this.orthogonalize(t),position:"center"}})}else this._onDidDrop.fire(new n0({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:On}))}get headerActionsService(){return this._moduleRegistry.services.headerActionsService}get _layoutHistoryService(){return this._moduleRegistry.services.layoutHistoryService}undo(){var e;(e=Ls(this._layoutHistoryService,"LayoutHistory","api.undo"))===null||e===void 0||e.undo()}redo(){var e;(e=Ls(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:Ire}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 zP(e,"edge",t,On);return this._onUnhandledDragOver.fire(n),n.isAccepted}fireWillDragPanel(e){this._onWillDragPanel.fire(e)}fireWillDragGroup(e){this._onWillDragGroup.fire(e)}fireWillDrop(e){this._onWillDrop.fire(e)}fireWillShowOverlay(e){this._onWillShowOverlay.fire(e)}buildGroupDragGhost(e){var t;return(t=this._advancedDnDService)===null||t===void 0?void 0:t.buildGroupDragGhost(e)}resolveDropOverlayModel(e,t){var n;return(n=this._advancedDnDService)===null||n===void 0?void 0:n.resolveOverlayModel(e,t)}get rootElement(){var e,t;return(e=(t=this._shellManager)===null||t===void 0?void 0:t.element)!==null&&e!==void 0?e:this.element}ownsElement(e){if(this.rootElement.contains(e))return!0;const t=this.rootElement.ownerDocument,n=e.ownerDocument;return!n||n===t?!1:this.getPopoutWindows().some(s=>s.document===n)}adjacentGroup(e,t){var n;if(e.api.location.type!=="grid")return;const s=Tn(e.element);return(n=t?this.gridview.previous(s):this.gridview.next(s))===null||n===void 0?void 0:n.view}adjacentGroupInDirection(e,t){if(e.api.location.type!=="grid")return;const n=e.element.getBoundingClientRect(),s=n.left+n.width/2,o=n.top+n.height/2;let r,a=Number.POSITIVE_INFINITY;for(const l of this.groups){if(l===e||l.api.location.type!=="grid")continue;const c=l.element.getBoundingClientRect(),d=c.left+c.width/2-s,u=c.top+c.height/2-o;let h;switch(t){case"left":h=d<0&&Math.abs(d)>=Math.abs(u);break;case"right":h=d>0&&Math.abs(d)>=Math.abs(u);break;case"up":h=u<0&&Math.abs(u)>=Math.abs(d);break;default:h=u>0&&Math.abs(u)>=Math.abs(d);break}if(!h)continue;const p=d*d+u*u;p<a&&(a=p,r=l)}return r}showDropPreview(e,t){var n,s;return(n=(s=this._advancedDnDService)===null||s===void 0?void 0:s.showPreviewOverlay(e,t))!==null&&n!==void 0?n:cn.NONE}announce(e){var t;(t=this._moduleRegistry.services.liveRegionService)===null||t===void 0||t.announce(e)}dockPanel(e,t,n){this.moveGroupOrPanel({from:{groupId:e.group.id,panelId:e.id},to:{group:t,position:n}})}floatPanel(e){this.addFloatingGroup(e)}get contextMenuService(){return this._moduleRegistry.services.contextMenuService}get pinnedTabsService(){return this._moduleRegistry.services.pinnedTabsService}get advancedOverflowService(){return this._moduleRegistry.services.advancedOverflowService}setPanelPinned(e,t){var n;e.isPinned!==t&&!((n=this.options.pinnedTabs)===null||n===void 0)&&n.enabled&&this.pinnedTabsService&&(e.setPinned(t),this._onDidPanelPinnedChange.fire({panel:e,isPinned:t}))}get mountElement(){return this.gridview.element}hasVisibleGridGroup(){return this.groups.some(e=>e.api.location.type==="grid"&&e.api.isVisible)}fireLayoutChange(){this._bufferOnDidLayoutChange.fire()}get popoutRestorationPromise(){var e,t;return(e=(t=this._popoutWindowService)===null||t===void 0?void 0:t.restorationPromise)!==null&&e!==void 0?e:Promise.resolve()}constructor(e,t){var n,s,o,r,a;super(e,{proportionalLayout:!0,orientation:"HORIZONTAL",styles:t.hideBorders?{separatorBorder:"transparent"}:void 0,disableAutoResizing:t.disableAutoResizing,locked:t.locked,margin:(n=(s=t.theme)===null||s===void 0?void 0:s.gap)!==null&&n!==void 0?n:0,className:t.className}),this.nextGroupId=qv(),this._deserializer=new Loe(this),this._moduleRegistry=new Hoe,this._onWillDragPanel=new ve,this.onWillDragPanel=this._onWillDragPanel.event,this._onWillDragGroup=new ve,this.onWillDragGroup=this._onWillDragGroup.event,this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new ve,this.onWillDrop=this._onWillDrop.event,this._mutationDepth=0,this._pendingLocationChanges=new Map,this._origin="user",this._originDepth=0,this._onWillMutateLayout=new ve,this.onWillMutateLayout=this._onWillMutateLayout.event,this._onDidMutateLayout=new ve,this.onDidMutateLayout=this._onDidMutateLayout.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._onDidRemovePanel=new ve,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidAddPanel=new ve,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPopoutGroupSizeChange=new ve,this.onDidPopoutGroupSizeChange=this._onDidPopoutGroupSizeChange.event,this._onDidPopoutGroupPositionChange=new ve,this.onDidPopoutGroupPositionChange=this._onDidPopoutGroupPositionChange.event,this._onDidAddPopoutGroup=new ve,this.onDidAddPopoutGroup=this._onDidAddPopoutGroup.event,this._onDidRemovePopoutGroup=new ve,this.onDidRemovePopoutGroup=this._onDidRemovePopoutGroup.event,this._onDidChangePopouts=new ve,this.onDidChangePopouts=this._onDidChangePopouts.event,this._onDidOpenPopoutWindowFail=new ve,this.onDidOpenPopoutWindowFail=this._onDidOpenPopoutWindowFail.event,this._onDidStartFloatingGroupDrag=new ve,this.onDidStartFloatingGroupDrag=this._onDidStartFloatingGroupDrag.event,this._onDidEndFloatingGroupDrag=new ve,this.onDidEndFloatingGroupDrag=this._onDidEndFloatingGroupDrag.event,this._onDidLayoutFromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutFromJSON.event,this._onDidActivePanelChange=new ve({replay:!0}),this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidPanelPinnedChange=new ve,this.onDidPanelPinnedChange=this._onDidPanelPinnedChange.event,this._onDidMovePanel=new ve,this.onDidMovePanel=this._onDidMovePanel.event,this._onDidCreateTabGroup=new ve,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new ve,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new ve,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new ve,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new ve,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new ve,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,this._onDidMaximizedGroupChange=new ve,this.onDidMaximizedGroupChange=this._onDidMaximizedGroupChange.event,this._inShellLayout=!1,this._onDidRemoveGroup=new ve,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidEdgeGroupAutoHideChange=new ve,this.onDidEdgeGroupAutoHideChange=this._onDidEdgeGroupAutoHideChange.event,this._onDidAddGroup=new ve,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidOptionsChange=new ve,this.onDidOptionsChange=this._onDidOptionsChange.event,this._onDidActiveGroupChange=new ve,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._peekingGroups=new Set,this._moving=!1,this._options=t,this._tabGroupColorPalette=Tre(t);const l=t.modules,c=l??[...gre,...Voe()];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 ck(this.element),this._api=new Xv(this),this.disableResizing=!0,this.element.remove(),this._shellManager=new Nre(e,this.element,(h,p)=>this._layoutFromShell(h,p),(o=(r=t.theme)===null||r===void 0?void 0:r.gap)!==null&&o!==void 0?o:0,(a=t.theme)===null||a===void 0?void 0:a.edgeGroupCollapsedSize),this.popupService.updateRoot(this._shellManager.element),this._shellThemeClassnames=new ep(this._shellManager.element),this.rootDropTargetContainer=new Ef(this._shellManager.element,{disabled:!0}),this.floatingDropTargetContainer=new Ef(this._shellManager.element,{disabled:!1}),this.overlayRenderContainer=new ak(this._shellManager.element,this),this._floatingOverlayHost=document.createElement("div"),this._floatingOverlayHost.className="dv-floating-overlay-host",this._shellManager.element.appendChild(this._floatingOverlayHost),Qe(this.gridview.element,"dv-dockview",!0),Qe(this.element,"dv-debug",!!t.debug),this.updateTheme(),t.debug&&this.addDisposables(new yre(this)),this.addDisposables(cn.from(()=>this._pendingLocationChanges.clear()),this.rootDropTargetContainer,this.floatingDropTargetContainer,ct(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,ei.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})}),ei.any(this.onDidAddPanel,this.onDidRemovePanel,this.onDidAddGroup,this.onDidRemove,this.onDidRemoveGroup,this.onDidMovePanel,this.onDidActivePanelChange)(()=>{this._bufferOnDidLayoutChange.fire()}),cn.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 ac(h,{kind:"edge",panel:void 0,api:this._api,group:void 0,getData:On}))}),u.onDrop(h=>this.dockToLayoutEdge(h.nativeEvent,h.position))),this._moduleRegistry.postConstruct(this)}setVisible(e,t){switch(e.api.location.type){case"grid":super.setVisible(e,t);break;case"floating":{const n=this.floatingGroups.find(s=>s.group===e);n&&(n.overlay.setVisible(t),e.api._onDidVisibilityChange.fire({isVisible:t}));break}case"popout":console.warn("dockview: You cannot hide a group that is in a popout window");break}}getPopupServiceForGroup(e){var t,n;return(t=(n=this._popoutWindowService)===null||n===void 0||(n=n.findByGroup(e))===null||n===void 0?void 0:n.popupService)!==null&&t!==void 0?t:this.popupService}addPopoutGroup(e,t){return this.mutationAsync("popout",()=>this._doAddPopoutGroup(e,t))}getPopouts(){var e,t;return(e=(t=this._popoutWindowService)===null||t===void 0?void 0:t.entries.map(n=>({id:n.popoutGroup.id,group:n.popoutGroup,window:n.getWindow()})))!==null&&e!==void 0?e:[]}getPopoutWindows(){return this.getPopouts().map(e=>e.window)}_doAddPopoutGroup(e,t){var n,s,o,r,a;const l=Ls(this._popoutWindowService,"PopoutWindow","api.addPopoutGroup");if(!l||e instanceof vd&&e.model.location.type==="edge")return Promise.resolve(!1);if(e instanceof Wr&&e.group.size===1)return this.addPopoutGroup(e.group,t);const c=gie(this.gridview.element),d=this.element;function u(){var v,y;if(t?.position)return t.position;const b=(e instanceof vd?e.element:(v=(y=e.group)===null||y===void 0?void 0:y.element)!==null&&v!==void 0?v:d).getBoundingClientRect();return{left:window.screenX+b.left,top:window.screenY+b.top,width:b.width,height:b.height}}const h=u(),p=(n=t==null||(s=t.overridePopoutGroup)===null||s===void 0?void 0:s.id)!==null&&n!==void 0?n:this.getNextGroupId(),f=(o=t?.popoutUrl)!==null&&o!==void 0?o:(r=this.options)===null||r===void 0?void 0:r.popoutUrl,g=new wre(`${this.id}-${p}`,c??"",{url:f??"/popout.html",left:h.left,top:h.top,width:h.width,height:h.height,onDidOpen:t?.onDidOpen,onWillClose:t?.onWillClose,nonce:(a=this.options)===null||a===void 0?void 0:a.nonce}),x=new pt(g,g.onDidClose(()=>{x.dispose()}));return g.open().then(v=>{var y,b;if(g.isDisposed)return!1;const w=(y=t?.referenceGroup)!==null&&y!==void 0?y:e instanceof Wr?e.group:e,C=e.api.location.type,_=w.element.parentElement!==null;let N;if(t?.overridePopoutGridview){var k;N=(k=t.overridePopoutGroup)!==null&&k!==void 0?k:w}else _?t?.overridePopoutGroup?N=t.overridePopoutGroup:(N=this.createGroup({id:p}),v&&this._onDidAddGroup.fire(N)):N=w;if(v===null)return this.handleBlockedPopout({group:N,referenceGroup:w,options:t,popoutWindowDisposable:x}),!1;const S=document.createElement("div");S.className="dv-overlay-render-container";const A=new ak(S,this);N.model.renderContainer=A;const T=(b=t?.overridePopoutGridview)!==null&&b!==void 0?b:this.createNestedGridview();t?.overridePopoutGridview||T.addView(N,_s.Distribute,[0]),T.element.style.width="100%",T.element.style.height="100%",T.layout(g.window.innerWidth,g.window.innerHeight);let I=!1;const P=()=>{I||(I=!0,T.dispose())};let D,O=[];if(!t?.overridePopoutGroup&&!t?.overridePopoutGridview&&_)if(e instanceof Wr){const Ce=e.group;this.movingLock(()=>{const Re=w.model.removePanel(e);N.model.openPanel(Re)}),O=[{panel:e,from:Ce}]}else switch(this.movingLock(()=>yd({from:w,to:N})),O=N.panels.map(Ce=>({panel:Ce,from:w})),C){case"grid":w.api.setVisible(!1);break;case"floating":case"popout":var z;D=(z=this.floatingGroups.find(Ce=>Ce.group.api.id===e.api.id))===null||z===void 0?void 0:z.overlay.toJSON(),this.removeGroup(w);break}v.classList.add("dv-dockview"),v.style.overflow="hidden",v.appendChild(S),v.appendChild(T.element);const R=document.createElement("div"),$=new Ef(R,{disabled:this.rootDropTargetContainer.disabled});v.appendChild(R),N.model.dropTargetContainer=$;const X=new ck(v,g.window);if(x.addDisposables(X),N.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f},t?.overridePopoutGridview){const Ce=this.groups.filter(Re=>T.element.contains(Re.element));for(const Re of Ce)Re.model.renderContainer=A,Re.model.dropTargetContainer=$,Re.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f}}_&&e.api.location.type==="grid"&&e.api.setVisible(!1),this.doSetGroupAndPanelActive(N);const H=l.observeGridviewSize(g,T,A);H&&x.addDisposables(H);const te=new Bn;x.addDisposables(te);const V=Ce=>{te.value=new pt(Ce.api.onDidActiveChange(Re=>{if(Re.isActive){var fe;(fe=g.window)===null||fe===void 0||fe.focus()}}),Ce.api.onWillFocus(()=>{var Re;(Re=g.window)===null||Re===void 0||Re.focus()}))};V(N);const Y={},q=_&&w&&this.getPanel(w.id),ee={window:g,popoutGroup:N,gridview:T,overlayRenderContainer:A,dropTargetContainer:$,getWindow:()=>g.window,popoutUrl:f,referenceGroup:q?w.id:void 0,popupService:X,setAnchorGroup:Ce=>{ee.popoutGroup=Ce,V(Ce)},disposable:{dispose:()=>(x.dispose(),Y.returnedGroup)}},ge=xie(g.window);x.addDisposables(ge,vie(g.window,()=>{this._onDidPopoutGroupSizeChange.fire({width:g.window.innerWidth,height:g.window.innerHeight,group:ee.popoutGroup})}),ge.event(()=>{this._onDidPopoutGroupPositionChange.fire({screenX:g.window.screenX,screenY:g.window.screenY,group:ee.popoutGroup})}),ct(g.window,"resize",()=>{T.layout(g.window.innerWidth,g.window.innerHeight)}),A,cn.from(()=>this.disposePopoutWindow({group:N,referenceGroup:w,popoutGridview:T,isGroupAddedToDom:_,floatingBox:D,disposePopoutGridview:P,closeResult:Y}))),l.add(ee),this._onDidAddPopoutGroup.fire({id:ee.popoutGroup.id,group:ee.popoutGroup,window:ee.getWindow()});for(const{panel:Ce,from:Re}of O)this.fireDidMovePanel(Ce,Re);return!0}).catch(v=>(console.error("dockview: failed to create popout.",v),!1))}handleBlockedPopout(e){const{group:t,referenceGroup:n,options:s,popoutWindowDisposable:o}=e;if(console.error("dockview: failed to create popout. perhaps you need to allow pop-ups for this website"),o.dispose(),this._onDidOpenPopoutWindowFail.fire(),s?.overridePopoutGridview){const r=s.overridePopoutGridview,a=this.groups.filter(l=>r.element.contains(l.element));for(const l of a)this.movingLock(()=>{r.remove(l),this.redockGroupToMainGrid(l)});r.dispose(),n&&!n.api.isVisible&&n.api.setVisible(!0);return}t===n?this.gridview.element.contains(t.element)||(this.movingLock(()=>this.doAddGroup(t,[0])),t.model.location={type:"grid"}):(this.movingLock(()=>yd({from:t,to:n})),t.model.size===0&&this._groups.has(t.id)&&(t.dispose(),this._groups.delete(t.id),this._onDidRemoveGroup.fire(t))),n.api.isVisible||n.api.setVisible(!0)}redockGroupToMainGrid(e){e.model.renderContainer=this.overlayRenderContainer,e.model.dropTargetContainer=this.rootDropTargetContainer,e.model.location={type:"grid"},this.doAddGroup(e,[0])}disposePopoutWindow(e){var t;const{group:n,referenceGroup:s,popoutGridview:o,isGroupAddedToDom:r,floatingBox:a,disposePopoutGridview:l,closeResult:c}=e;if(this.isDisposed){l();return}const d=!!(!((t=this._popoutWindowService)===null||t===void 0)&&t.entries.find(g=>g.gridview===o)),u=this.groups.filter(g=>o.element.contains(g.element)),h=u.includes(n),p=h&&u.length===1,f=[];if(d){for(const g of u)if(g!==n){this.movingLock(()=>{this.doRemoveGroup(g,{skipDispose:!0,skipActive:!0,skipPopoutReturn:!0}),this.redockGroupToMainGrid(g)});for(const x of g.panels)f.push({panel:x,from:g})}}if(h&&r&&this.getPanel(s.id)){const g=[...n.panels];this.movingLock(()=>yd({from:n,to:s}));for(const x of g)f.push({panel:x,from:n});s.api.isVisible||s.api.setVisible(!0),this.getPanel(n.id)&&this.doRemoveGroup(n,{skipPopoutAssociated:!0})}else if(h&&this.getPanel(n.id)){if(n.model.renderContainer=this.overlayRenderContainer,n.model.dropTargetContainer=this.rootDropTargetContainer,c.returnedGroup=n,!d){l();return}if(a&&p)this.addFloatingGroup(n,{height:a.height,width:a.width,position:a});else{this.doRemoveGroup(n,{skipDispose:!0,skipActive:!0,skipPopoutReturn:!0}),n.model.location={type:"grid"},this.movingLock(()=>{this.doAddGroup(n,[0])});for(const g of n.panels)f.push({panel:g,from:n})}this.doSetGroupAndPanelActive(n)}l();for(const{panel:g,from:x}of f)this.fireDidMovePanel(g,x)}addFloatingGroup(e,t){this.mutation("float",()=>this._doAddFloatingGroup(e,t))}_doAddFloatingGroup(e,t){if(!Ls(this._floatingGroupService,"FloatingGroup","api.addFloatingGroup")||e instanceof vd&&e.model.location.type==="edge")return;let n,s=[];if(e instanceof Wr){const c=e.group;n=this.createGroup(),this._onDidAddGroup.fire(n),this.movingLock(()=>this.removePanel(e,{removeEmptyGroup:!0,skipDispose:!0,skipSetActiveGroup:!0})),this.movingLock(()=>n.model.openPanel(e,{skipSetGroupActive:!0})),s=[{panel:e,from:c}]}else{var o;n=e;const c=(o=this._popoutWindowService)===null||o===void 0?void 0:o.findReferenceGroupId(n),d=c?this.getPanel(c):void 0;typeof t?.skipRemoveGroup=="boolean"&&t.skipRemoveGroup||(d?(this.movingLock(()=>yd({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=Po.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=Po.top,typeof t.width=="number"?c.width=Math.max(t.width,0):c.width=Po.width,typeof t.height=="number"?c.height=Math.max(t.height,0):c.height=Po.height,c}return{left:typeof t?.x=="number"?Math.max(t.x,0):Po.left,top:typeof t?.y=="number"?Math.max(t.y,0):Po.top,width:typeof t?.width=="number"?Math.max(t.width,0):Po.width,height:typeof t?.height=="number"?Math.max(t.height,0):Po.height}}const a=r(),l=this.createNestedGridview();l.addView(n,_s.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 xP(!0,this.options.hideBorders?{separatorBorder:"transparent"}:void 0,e,!1,(t=(n=this.options.theme)===null||n===void 0?void 0:n.gap)!==null&&t!==void 0?t:0)}mountFloatingWindow(e,t,n,s,o){var r,a,l,c,d,u,h,p,f;const g=Ls(this._floatingGroupService,"FloatingGroup","api.addFloatingGroup");if(!g)return;const x=((r=(a=o?.dragHandle)!==null&&a!==void 0?a:this.options.floatingGroupDragHandle)!==null&&r!==void 0?r:"titlebar")==="titlebar"?new Goe(this,t):void 0,v=new i0(gt(gt({container:(l=this._floatingOverlayHost)!==null&&l!==void 0?l:this.gridview.element,content:e.element,header:x?.element},s),{},{minimumInViewportWidth:this.options.floatingGroupBounds==="boundedWithinViewport"?void 0:(c=(d=this.options.floatingGroupBounds)===null||d===void 0?void 0:d.minimumWidthWithinViewport)!==null&&c!==void 0?c:100,minimumInViewportHeight:this.options.floatingGroupBounds==="boundedWithinViewport"?void 0:(u=(h=this.options.floatingGroupBounds)===null||h===void 0?void 0:h.minimumHeightWithinViewport)!==null&&u!==void 0?u:100,transformDragPosition:this._buildFloatingDragTransform(t,(p=o?.disableSmartGuides)!==null&&p!==void 0?p:!1),getSiblingBoxes:()=>this._gatherFloatingGroupBoxes(t)})),y=(f=x?.element)!==null&&f!==void 0?f:t.element.querySelector(".dv-void-container");if(!y)throw new Error("dockview: failed to find drag handle");v.setupDrag(y,{inDragMode:typeof o?.inDragMode=="boolean"?o.inDragMode:!1});const b=g.add(t,v,e);b.addDisposables(v.onDidStartMoving(()=>this._onDidStartFloatingGroupDrag.fire(t)),v.onDidChangeEnd(()=>this._onDidEndFloatingGroupDrag.fire(t))),x&&(b.setTitleBar(x),b.addDisposables(x,cn.from(()=>b.setTitleBar(void 0)),x.onDragStart(w=>{this._onWillDragGroup.fire({nativeEvent:w,group:b.group})})));for(const w of n)w.model.location={type:"floating"};o?.skipActiveGroup||this.doSetGroupAndPanelActive(t)}orthogonalize(e,t){switch(this.gridview.normalize(),e){case"top":case"bottom":this.gridview.orientation==="HORIZONTAL"&&this.gridview.insertOrthogonalSplitviewAtRoot();break;case"left":case"right":this.gridview.orientation==="VERTICAL"&&this.gridview.insertOrthogonalSplitviewAtRoot();break}switch(e){case"top":case"left":case"center":return this.createGroupAtLocation([0],void 0,t);case"bottom":case"right":return this.createGroupAtLocation([this.gridview.length],void 0,t);default:throw new Error(`dockview: unsupported position ${e}`)}}updateOptions(e){var t,n;super.updateOptions(e),this.reportMissingOptionModules(e),(t=this._floatingGroupService)===null||t===void 0||t.updateBounds(e),(n=this._rootDropTargetService)===null||n===void 0||n.setOptions(e);const s=this.options.disableDnd,o=this.options.dndStrategy;this._options=gt(gt({},this.options),e);const r=this.options.disableDnd,a=this.options.dndStrategy;if((s!==r||o!==a)&&this.updateDragAndDropState(),"theme"in e&&this.updateTheme(),"createRightHeaderActionComponent"in e||"createLeftHeaderActionComponent"in e||"createPrefixHeaderActionComponent"in e){var l;(l=this.headerActionsService)===null||l===void 0||l.refreshAll()}if("createWatermarkComponent"in e){var c;(c=this._watermarkService)===null||c===void 0||c.refresh();for(const u of this.groups)u.model.refreshWatermark()}if("tabGroupColors"in e||"tabGroupAccent"in e){var d;this._tabGroupColorPalette.setEntries((d=this._options.tabGroupColors)!==null&&d!==void 0?d:Qv),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){Woe(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(WP("EdgeGroup","api.addEdgeGroup"));if(n.has(e))throw new Error(`dockview: edge group already exists at position '${e}'`);return this.mutation("add",()=>{const s=this.createGroup({id:t.id});s.model.location={type:"edge",position:e},s.model.headerPosition=e;const o=s.model.onDidRemovePanel(()=>{s.model.isEmpty&&(n.isAutoReveal(s)?queueMicrotask(()=>{var r;s.model.isEmpty&&(!((r=this._edgeGroupService)===null||r===void 0)&&r.includes(s))&&this.removeEdgeGroup(e)}):this.setEdgeGroupCollapsed(s,!0))});return n.add(e,s,o),t.autoHide!==void 0&&n.setAutoHide(s,t.autoHide),t.autoReveal!==void 0&&n.setAutoReveal(s,t.autoReveal),this._onDidAddGroup.fire(s),this._shellManager.addEdgeView(e,t,s),s.api})}revealEdgeGroupWithData(e,t,n){const s=this._edgeGroupService;s&&this.mutation("add",()=>{var o;let r=s.get(e);r||(this.addEdgeGroup(e,{id:this.getNextGroupId(),autoReveal:!0,autoHide:n?.autoHide,collapsed:!0}),r=s.get(e)),r&&this.moveGroupOrPanel({from:{groupId:t.groupId,panelId:(o=t.panelId)!==null&&o!==void 0?o:void 0},to:{group:r,position:"center"}})})}getEdgeGroup(e){var t;return(t=this._edgeGroupService)===null||t===void 0||(t=t.get(e))===null||t===void 0?void 0:t.api}getEdgeGroupPanel(e){var t;return(t=this._edgeGroupService)===null||t===void 0?void 0:t.get(e)}pinEdgeGroup(e){var t;(t=Ls(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.pinEdgeGroup"))===null||t===void 0||t.pin(e)}autoHideEdgeGroup(e){var t;(t=Ls(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.autoHideEdgeGroup"))===null||t===void 0||t.autoHide(e)}peekEdgeGroup(e,t){var n;(n=Ls(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=Ls(this._edgeGroupService,"EdgeGroup","api.removeEdgeGroup");if(!t)return;const n=t.get(e);if(!n)throw new Error(`dockview: no edge group exists at position '${e}'`);this.mutation("remove",()=>{for(const s of[...n.panels])this.removePanel(s,{removeEmptyGroup:!1,skipDispose:!1});this._shellManager.removeEdgeView(e),t.remove(e),n.dispose(),this._groups.delete(n.id),this._onDidRemoveGroup.fire(n)})}setEdgeGroupCollapsed(e,t){var n;const s=(n=this._edgeGroupService)===null||n===void 0?void 0:n.findPositionOf(e);s&&this._shellManager.isEdgeGroupCollapsed(s)!==t&&(this._shellManager.setEdgeGroupCollapsed(s,t),e.api._onDidCollapsedChange.fire({isCollapsed:t}))}isEdgeGroupCollapsed(e){var t;const n=(t=this._edgeGroupService)===null||t===void 0?void 0:t.findPositionOf(e);return n?this._shellManager.isEdgeGroupCollapsed(n):!1}isEdgeGroupPeeking(e){return this._peekingGroups.has(e)}setEdgeGroupPeeking(e,t){this._peekingGroups.has(e)!==t&&(t?this._peekingGroups.add(e):this._peekingGroups.delete(e),e.api._onDidPeekChange.fire({isPeeking:t}))}isEdgeGroupAutoHide(e){var t,n;const s=(t=this._edgeGroupService)===null||t===void 0?void 0:t.isAutoHide(e);if(s!==void 0)return s;const o=(n=this._edgeGroupService)===null||n===void 0?void 0:n.findPositionOf(e);return o===void 0?!1:poe(this.options.autoHideEdgeGroups,o)}setEdgeGroupAutoHide(e,t){const n=this._edgeGroupService;n?.includes(e)&&(n.setAutoHide(e,t),this._onDidEdgeGroupAutoHideChange.fire(e))}updateDragAndDropState(){for(const e of this.groups)e.model.updateDragAndDropState()}focus(){var e;(e=this.activeGroup)===null||e===void 0||e.focus()}getGroupPanel(e){return this.panels.find(t=>t.id===e)}setActivePanel(e){e.group.model.openPanel(e),this.doSetGroupAndPanelActive(e.group)}activateNext(e={}){var t;if(!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}if(e.includePanel&&e.group&&e.group.activePanel!==e.group.panels[e.group.panels.length-1]){e.group.model.moveToNext({suppressRoll:!0});return}const n=Tn(e.group.element),s=(t=this.gridview.next(n))===null||t===void 0?void 0:t.view;this.doSetGroupAndPanelActive(s)}activatePrevious(e={}){var t;if(!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}if(e.includePanel&&e.group&&e.group.activePanel!==e.group.panels[0]){e.group.model.moveToPrevious({suppressRoll:!0});return}const n=Tn(e.group.element),s=(t=this.gridview.previous(n))===null||t===void 0?void 0:t.view;s&&this.doSetGroupAndPanelActive(s)}toJSON(){var e,t,n,s,o;const r=this.gridview.serialize(),a=this.panels.reduce((h,p)=>(h[p.id]=p.toJSON(),h),{}),l=(e=(t=this._floatingGroupService)===null||t===void 0?void 0:t.serialize())!==null&&e!==void 0?e:[],c=(n=(s=this._popoutWindowService)===null||s===void 0?void 0:s.serialize())!==null&&n!==void 0?n:[],d={grid:r,panels:a,activeGroup:(o=this.activeGroup)===null||o===void 0?void 0:o.id};l.length>0&&(d.floatingGroups=l),c.length>0&&(d.popoutGroups=c);const u=this._serializeEdgeGroups();return u&&(d.edgeGroups=u),d}_serializeEdgeGroups(){var e;if(!(!((e=this._edgeGroupService)===null||e===void 0)&&e.hasAny()))return;const t=this._shellManager.toJSON();for(const[n,s]of this._edgeGroupService.entries()){const o=t[n];if(!o)continue;if(this._edgeGroupService.isAutoReveal(s)&&s.model.isEmpty){delete t[n];continue}o.group=s.toJSON(),this._edgeGroupService.isAutoReveal(s)&&(o.autoReveal=!0);const r=this._edgeGroupService.isAutoHide(s);r!==void 0&&(o.autoHide=r)}return t}fromJSON(e,t){this.mutation("load",()=>this._doFromJSON(e,t))}_doFromJSON(e,t){var n,s;if((n=this._popoutWindowService)===null||n===void 0||n.cancelPendingRestorations(),typeof e!="object"||e===null)throw new Error("dockview: serialized layout must be a non-null object");if(!e.grid||((s=e.grid.root)===null||s===void 0?void 0:s.type)!=="branch"||!Array.isArray(e.grid.root.data))throw new Error("dockview: root must be of type branch");const o=new Map,r=new Map,a=[],l=[],c=()=>{for(const w of l)try{w.dispose()}catch(C){console.error("dockview: failed to dispose a temporary group created for reuseExistingPanels",C)}l.length=0};if(t?.reuseExistingPanels){const w=Object.keys(e.panels);let C;const _=()=>{const N=this.createGroup(),k=this._groups.get(N.api.id);return this._groups.delete(N.api.id),l.push(cn.from(()=>{this.movingLock(()=>{for(const S of N.panels.slice())N.model.removePanel(S)}),k?.disposable.dispose(),N.dispose()})),N};try{for(const N of this.panels)if(w.includes(N.api.id)){o.set(N.api.id,N);let k;if(N.api.renderer==="always"&&N.api.isVisible)k=_();else{var d;(d=C)!==null&&d!==void 0||(C=_()),k=C}r.set(N.api.id,k),a.push({panel:N,temporaryGroup:k})}this.movingLock(()=>{a.forEach(({panel:N,temporaryGroup:k})=>{this.moveGroupOrPanel({from:{groupId:N.api.group.api.id,panelId:N.api.id},to:{group:k,position:"center"},keepEmptyGroups:!0})})}),this.clear()}catch(N){throw c(),N}}else this.clear();const{grid:u,panels:h,activeGroup:p}=e;try{var f,g,x,v,y;const w=this.width,C=this.height,_=k=>{const{id:S,locked:A,hideHeader:T,headerPosition:I,views:P,activeView:D}=k;if(typeof S!="string")throw new TypeError("dockview: group id must be of type string");const O=this.createGroup({id:S,locked:!!A,hideHeader:!!T,headerPosition:I});this._onDidAddGroup.fire(O);const z=[],R=P.filter($=>h[$]);for(const $ of R){const X=o.get($),H=r.get($);if(H&&X)this.movingLock(()=>{H.model.removePanel(X)}),z.push(X),X.updateFromStateModel(h[$]);else{const te=this._deserializer.fromJSON(h[$],O);z.push(te)}}for(const $ of z){const X=typeof D=="string"&&D===$.id;o.has($.api.id)?this.movingLock(()=>{O.model.openPanel($,{skipSetActive:!X,skipSetGroupActive:!0})}):O.model.openPanel($,{skipSetActive:!X,skipSetGroupActive:!0})}return k.tabGroups&&k.tabGroups.length>0&&O.model.restoreTabGroups(k.tabGroups),!O.activePanel&&O.panels.length>0&&O.model.openPanel(O.panels[O.panels.length-1],{skipSetGroupActive:!0}),O};this.gridview.deserialize(u,{fromJSON:k=>_(k.data)}),this._layoutFromShell(w,C),e.edgeGroups&&this.deserializeEdgeGroups(e.edgeGroups,h,o,r),this.deserializeFloatingWindows((f=e.floatingGroups)!==null&&f!==void 0?f:[],_);const N=this.deserializePopoutWindows((g=e.popoutGroups)!==null&&g!==void 0?g:[],_);if((x=this._popoutWindowService)===null||x===void 0||x.finishRestoration(N),(v=this._floatingGroupService)===null||v===void 0||v.constrainBounds(),typeof p=="string"){const k=this.getPanel(p);k&&this.doSetGroupAndPanelActive(k)}(y=this._watermarkService)===null||y===void 0||y.update()}catch(w){var b;console.error("dockview: failed to deserialize layout. Reverting changes",w);for(const C of this.groups)for(const _ of C.panels)this.removePanel(_,{removeEmptyGroup:!1,skipDispose:!1});for(const C of this.groups)C.dispose(),this._groups.delete(C.id),this._onDidRemoveGroup.fire(C);throw(b=this._floatingGroupService)===null||b===void 0||b.disposeAll(),this.clear(),w}finally{c()}this.debouncedUpdateAllPositions(),this._onDidLayoutFromJSON.fire()}deserializeNestedGridview(e,t){const n=this.createNestedGridview(e.orientation),s=[];return n.deserialize(e,{fromJSON:o=>{const r=t(o.data);return s.push(r),r}}),{gridview:n,members:s}}deserializeEdgeGroups(e,t,n,s){const o=Ls(this._edgeGroupService,"EdgeGroup","fromJSON edge restoration");if(o){for(const a of["top","bottom","left","right"]){const l=e[a];if(l&&!o.has(a)){var r;const c=l.group,d=(r=c?.id)!==null&&r!==void 0?r:`${a}-group`;this.addEdgeGroup(a,{id:d,autoReveal:l.autoReveal,autoHide:l.autoHide,minimumSize:l.minimumSize,maximumSize:l.maximumSize,collapsedSize:l.collapsedSize})}}for(const[a,l]of o.entries()){const c=e[a],d=c?.group;if(d){const{views:u,activeView:h}=d,p=[];for(const f of u){if(!t[f])continue;const g=n.get(f),x=s.get(f);if(x&&g)this.movingLock(()=>{x.model.removePanel(g)}),p.push(g),g.updateFromStateModel(t[f]);else{const v=this._deserializer.fromJSON(t[f],l);p.push(v)}}for(const f of p){const g=h===f.id;n.has(f.api.id)?this.movingLock(()=>{l.model.openPanel(f,{skipSetActive:!g,skipSetGroupActive:!0})}):l.model.openPanel(f,{skipSetActive:!g,skipSetGroupActive:!0})}d.tabGroups&&d.tabGroups.length>0&&l.model.restoreTabGroups(d.tabGroups),!l.activePanel&&l.panels.length>0&&l.model.openPanel(l.panels[l.panels.length-1],{skipSetGroupActive:!0})}}this._shellManager.fromJSON(e)}}deserializeFloatingWindows(e,t){for(const n of e){const{data:s,grid:o,position:r}=n;if(o){const{gridview:a,members:l}=this.deserializeNestedGridview(o,t);if(l.length===0)continue;this.mountFloatingWindow(a,l[0],l,r,{inDragMode:!1})}else if(s){const a=t(s);this.addFloatingGroup(a,{position:r,width:r.width,height:r.height,skipRemoveGroup:!0,inDragMode:!1})}}}deserializePopoutWindows(e,t){const n=e.length>0?Ls(this._popoutWindowService,"PopoutWindow","fromJSON popout restoration"):this._popoutWindowService;return n?e.flatMap((s,o)=>{const{data:r,grid:a,position:l,gridReferenceGroup:c,url:d}=s;let u,h=[];if(a){const f=this.deserializeNestedGridview(a,t);if(u=f.gridview,h=f.members,h.length===0)return u.dispose(),[]}const p=a?h[0]:t(r);return n.scheduleRestoration(o*100,()=>{this.addPopoutGroup(p,{position:l??void 0,overridePopoutGroup:c?p:void 0,overridePopoutGridview:u,referenceGroup:c?this.getPanel(c):void 0,popoutUrl:d})},()=>{for(const f of h.length>0?h:[p])if(!this.isDisposed&&this._groups.has(f.id)&&f.element.parentElement===null){for(const g of[...f.panels])this.removePanel(g,{removeEmptyGroup:!1});f.dispose(),this._groups.delete(f.id),this._onDidRemoveGroup.fire(f)}})}):[]}clear(){this.mutation("clear",()=>this._doClear())}_doClear(){const e=Array.from(this._groups.values()).map(s=>s.value),t=!!this.activeGroup;for(const s of e){var n;if(!((n=this._edgeGroupService)===null||n===void 0)&&n.includes(s)){const o=[...s.panels];for(const r of o)this.removePanel(r,{removeEmptyGroup:!1});continue}this.removeGroup(s,{skipActive:!0})}t&&this.doSetGroupAndPanelActive(void 0),this.gridview.clear()}closeAllGroups(){this.mutation("remove",()=>{for(const e of this._groups.entries()){const[t,n]=e;n.value.model.closeAllPanels()}})}addPanel(e){return this.mutation("add",()=>this._doAddPanel(e))}_doAddPanel(e){if(this.panels.some(u=>u.id===e.id))throw new Error(`dockview: panel with id ${e.id} already exists`);let t;if(e.position&&e.floating)throw new Error("dockview: you can only provide one of: position, floating as arguments to .addPanel(...)");const n={width:e.initialWidth,height:e.initialHeight};let s;const o=u=>!!e.inactive&&u.model.size>0;if(e.position)if(foe(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(moe(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(QC(e.position.direction)),h=this.createPanel(e,u);return u.model.openPanel(h,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(u),u.api.setSize({height:n?.height,width:n?.width}),h}else t=this.activeGroup;let c;if(t){var d;const u=Yu(((d=e.position)===null||d===void 0?void 0:d.direction)||"within");if(e.floating){const h=this.createGroup();this._onDidAddGroup.fire(h);const p=typeof e.floating=="object"&&e.floating!==null?e.floating:{};this.addFloatingGroup(h,gt(gt({},p),{},{inDragMode:!1,skipRemoveGroup:!0,skipActiveGroup:!0})),c=this.createPanel(e,h),h.model.openPanel(c,{skipSetActive:o(h),skipSetGroupActive:e.inactive,index:s})}else if(t.api.location.type==="floating"||t.api.location.type==="edge"||u==="center")c=this.createPanel(e,t),t.model.openPanel(c,{skipSetActive:o(t),skipSetGroupActive:e.inactive,index:s}),t.api.setSize({width:n?.width,height:n?.height}),e.inactive||this.doSetGroupAndPanelActive(t);else{const h=Tn(t.element),p=Us(this.gridview.orientation,h,u),f=this.createGroupAtLocation(p,this.orientationAtLocation(p)==="VERTICAL"?n?.height:n?.width);c=this.createPanel(e,f),f.model.openPanel(c,{skipSetActive:o(f),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(f)}}else if(e.floating){const u=this.createGroup();this._onDidAddGroup.fire(u);const h=typeof e.floating=="object"&&e.floating!==null?e.floating:{};this.addFloatingGroup(u,gt(gt({},h),{},{inDragMode:!1,skipRemoveGroup:!0,skipActiveGroup:!0})),c=this.createPanel(e,u),u.model.openPanel(c,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s})}else{const u=this.createGroupAtLocation([0],this.gridview.orientation==="VERTICAL"?n?.height:n?.width);c=this.createPanel(e,u),u.model.openPanel(c,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(u)}return c}removePanel(e,t){this.mutation("remove",()=>{var n;return this._doRemovePanel(e,{removeEmptyGroup:(n=t?.removeEmptyGroup)!==null&&n!==void 0?n:!0,skipDispose:t?.skipDispose,skipSetActiveGroup:t?.skipSetActiveGroup})})}_doRemovePanel(e,t){const n=e.group;if(!n)throw new Error(`dockview: cannot remove panel ${e.id}. it's missing a group.`);n.model.removePanel(e,{skipSetActiveGroup:t.skipSetActiveGroup}),t.skipDispose||(e.group.model.renderContainer.detatch(e),e.dispose()),n.size===0&&t.removeEmptyGroup&&this.removeGroup(n,{skipActive:t.skipSetActiveGroup})}createWatermarkComponent(){return this.options.createWatermarkComponent?this.options.createWatermarkComponent():new Ooe}addGroup(e){return this.mutation("add",()=>this._doAddGroup(e))}_doAddGroup(e){if(e){let o;if(goe(e)){var t;const u=typeof e.referencePanel=="string"?this.panels.find(p=>p.id===e.referencePanel):e.referencePanel,h=typeof e.referencePanel=="string"?e.referencePanel:(t=e.referencePanel)===null||t===void 0?void 0:t.id;if(!u)throw new Error(`dockview: reference panel ${h} does not exist`);if(o=this.findGroup(u),!o)throw new Error(`dockview: reference group for reference panel ${h} does not exist`)}else if(xoe(e)){var n;if(o=typeof e.referenceGroup=="string"?(n=this._groups.get(e.referenceGroup))===null||n===void 0?void 0:n.value:e.referenceGroup,!o){var s;const u=typeof e.referenceGroup=="string"?e.referenceGroup:(s=e.referenceGroup)===null||s===void 0?void 0:s.id;throw new Error(`dockview: reference group ${u} does not exist`)}}else{const u=this.orthogonalize(QC(e.direction),e);return e.skipSetActive||this.doSetGroupAndPanelActive(u),u}const r=Yu(e.direction||"within"),a=Tn(o.element),l=Us(this.gridview.orientation,a,r),c=this.createGroup(e),d=this.getLocationOrientation(l)==="VERTICAL"?e.initialHeight:e.initialWidth;return this.doAddGroup(c,l,d),e.skipSetActive||this.doSetGroupAndPanelActive(c),c}else{const o=this.createGroup(e);return this.doAddGroup(o),this.doSetGroupAndPanelActive(o),o}}getLocationOrientation(e){return e.length%2==0&&this.gridview.orientation==="HORIZONTAL"?"HORIZONTAL":"VERTICAL"}removeGroup(e,t){this.mutation("remove",()=>this.doRemoveGroup(e,t))}detachFromNestedWindow(e){var t,n;const s=(t=this._floatingGroupService)===null||t===void 0?void 0:t.findByGroup(e);if(s){const r=this.nestedWindowMembers(e);return r.length<=1?!1:(s.gridview.remove(e),s.group===e&&s.setAnchorGroup(r.find(a=>a!==e)),!0)}const o=(n=this._popoutWindowService)===null||n===void 0?void 0:n.findByGroup(e);if(o){const r=this.nestedWindowMembers(e);return r.length<=1?!1:(o.gridview.remove(e),o.popoutGroup===e&&o.setAnchorGroup(r.find(a=>a!==e)),!0)}return!1}disposeGroupRecord(e){e.dispose(),this._groups.delete(e.id),this._onDidRemoveGroup.fire(e)}activateFallbackGroupIfRemoved(e,t){if(!t&&this._activeGroup===e){const n=Array.from(this._groups.values());this.doSetGroupAndPanelActive(n.length>0?n[0].value:void 0)}}doRemoveGroup(e,t){var n;if(!((n=this._edgeGroupService)===null||n===void 0)&&n.includes(e))return e;const s=[...e.panels];if(!t?.skipDispose)for(const u of s){var o;this.removePanel(u,{removeEmptyGroup:!1,skipDispose:(o=t?.skipDispose)!==null&&o!==void 0?o:!1})}const r=this.activePanel;if(e.api.location.type==="floating"){var a;const u=(a=this._floatingGroupService)===null||a===void 0?void 0:a.findByGroup(e);if(!u)throw new Error("dockview: failed to find floating group");return this.detachFromNestedWindow(e)?(t?.skipDispose?e.model.location={type:"grid"}:this.disposeGroupRecord(e),this.activateFallbackGroupIfRemoved(e,t?.skipActive),e):(t?.skipDispose||this.disposeGroupRecord(e),u.dispose(),this.activateFallbackGroupIfRemoved(e,t?.skipActive),e)}if(e.api.location.type==="popout"){var l,c;const u=(l=this._popoutWindowService)===null||l===void 0?void 0:l.findByGroup(e);if(!u)throw new Error("dockview: failed to find popout group");if(this.detachFromNestedWindow(e))return t?.skipDispose?e.model.location={type:"grid"}:this.disposeGroupRecord(e),this.activateFallbackGroupIfRemoved(e,t?.skipActive),e;if(!t?.skipDispose){if(!t?.skipPopoutAssociated){const p=u.referenceGroup?this.getPanel(u.referenceGroup):void 0;p?.panels.length===0&&this.removeGroup(p)}u.popoutGroup.dispose(),this._groups.delete(e.id),this._onDidRemoveGroup.fire(e)}(c=this._popoutWindowService)===null||c===void 0||c.remove(u);const h=u.disposable.dispose();return!t?.skipPopoutReturn&&h&&(this.doAddGroup(h,[0]),this.doSetGroupAndPanelActive(h)),this.activateFallbackGroupIfRemoved(e,t?.skipActive),u.popoutGroup}if(!this.gridview.element.contains(e.element)){if(!t?.skipDispose){const u=this._groups.get(e.id);u?.disposable.dispose(),this.disposeGroupRecord(e)}return this.activateFallbackGroupIfRemoved(e,t?.skipActive),e}const d=super.doRemoveGroup(e,t);return t?.skipActive||this.activePanel!==r&&this.fireActivePanelChange(this.activePanel),d}debouncedUpdateAllPositions(){this._updatePositionsFrameId!==void 0&&cancelAnimationFrame(this._updatePositionsFrameId),this._updatePositionsFrameId=requestAnimationFrame(()=>{var e,t;this._updatePositionsFrameId=void 0,this.overlayRenderContainer.updateAllPositions();for(const n of(e=(t=this._popoutWindowService)===null||t===void 0?void 0:t.entries)!==null&&e!==void 0?e:[])n.overlayRenderContainer.updateAllPositions()})}movingLock(e){const t=this._moving;try{return this._moving=!0,e()}finally{this._moving=t}}mutation(e,t){const n=this.openMutation(e);try{return t()}finally{n()}}mutationAsync(e,t){var n=this;return KP(function*(){const s=n.openMutation(e);try{return yield t()}finally{s()}})()}openMutation(e){const t=this._origin;return this._mutationDepth===0&&this._onWillMutateLayout.fire({kind:e,origin:t}),this._mutationDepth++,()=>{this._mutationDepth--,this._mutationDepth===0&&(this.flushLocationChanges(),this._onDidMutateLayout.fire({kind:e,origin:t}))}}deferLocationChange(e,t){if(this._mutationDepth===0){t();return}this._pendingLocationChanges.set(e,t)}flushLocationChanges(){if(this._pendingLocationChanges.size===0)return;const e=Array.from(this._pendingLocationChanges.values());this._pendingLocationChanges.clear();for(const t of e)t()}currentOrigin(){return this._origin}withOrigin(e,t){if(this._originDepth>0||this._mutationDepth>0)return t();const n=this._origin;this._origin=e,this._originDepth++;try{return t()}finally{this._originDepth--,this._origin=n}}fireActivePanelChange(e){this._onDidActivePanelChange.fire({panel:e,origin:this._origin})}fireDidMovePanel(e,t){this._onDidMovePanel.fire({panel:e,from:t,to:e.group})}moveGroupOrPanel(e){this.mutation("move",()=>this._doMoveGroupOrPanel(e))}_doMoveGroupOrPanel(e){var t;const n=e.to.group,s=e.from.groupId,o=e.from.panelId,r=e.to.position,a=e.to.index,l=s?(t=this._groups.get(s))===null||t===void 0?void 0:t.value:void 0;if(!l)throw new Error(`dockview: Failed to find group id ${s}`);if(o===void 0){e.from.tabGroupId?this.moveTabGroupToGroup({sourceGroup:l,tabGroupId:e.from.tabGroupId,destinationGroup:n,destinationTarget:r,destinationIndex:a,skipSetActive:e.skipSetActive,keepEmptyGroups:e.keepEmptyGroups}):this.moveGroup({from:{group:l},to:{group:n,position:r},skipSetActive:e.skipSetActive});return}if(!r||r==="center"){const d=this.movingLock(()=>l.model.removePanel(o,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!d)throw new Error(`dockview: No panel with id ${o}`);!e.keepEmptyGroups&&l.model.size===0&&this.doRemoveGroup(l,{skipActive:!0});const u=n.model.size===0;this.movingLock(()=>{var h;return n.model.openPanel(d,{index:a,skipSetActive:((h=e.skipSetActive)!==null&&h!==void 0?h:!1)&&!u,skipSetGroupActive:!0})}),e.skipSetActive||this.doSetGroupAndPanelActive(n),this.fireDidMovePanel(d,l)}else{const d=this.getGridviewForGroup(n),u=Tn(n.element),h=Us(d.orientation,u,r);if(l.size<2){const[p,f]=po(h);if(l.api.location.type==="grid"&&d===this.gridview){const[y,b]=po(Tn(l.element));if(fP(y,p)){this.gridview.moveView(y,b,f),this.fireDidMovePanel(this.getGroupPanel(o),l);return}}if(l.api.location.type==="popout"&&this.nestedWindowMembers(l).length<=1){var c;const y=(c=this._popoutWindowService)===null||c===void 0?void 0:c.findByGroup(l);if(!y)return;const b=this.movingLock(()=>y.popoutGroup.model.removePanel(y.popoutGroup.panels[0],{skipSetActive:!0,skipSetActiveGroup:!0}));this.doRemoveGroup(l,{skipActive:!0});const w=Us(d.orientation,Tn(n.element),r),C=this.createGroupAtLocation(w,void 0,void 0,d);this.movingLock(()=>C.model.openPanel(b,{skipSetActive:!0})),this.doSetGroupAndPanelActive(C),this.fireDidMovePanel(this.getGroupPanel(o),l);return}if(l.api.location.type==="edge"){const y=this.movingLock(()=>l.model.removePanel(o,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!y)throw new Error(`dockview: No panel with id ${o}`);const b=this.createGroupAtLocation(h,void 0,void 0,d);this.movingLock(()=>b.model.openPanel(y,{skipSetGroupActive:!0})),this.doSetGroupAndPanelActive(b),this.fireDidMovePanel(y,l);return}const g=this.movingLock(()=>this.doRemoveGroup(l,{skipActive:!0,skipDispose:!0})),x=Tn(n.element),v=Us(d.orientation,x,r);this.movingLock(()=>this.doAddGroup(g,v,void 0,d)),this.setGroupLocationForRoot(g,d),this.doSetGroupAndPanelActive(g),this.fireDidMovePanel(this.getGroupPanel(o),l)}else{const p=this.movingLock(()=>l.model.removePanel(o,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!p)throw new Error(`dockview: No panel with id ${o}`);const f=Us(d.orientation,u,r),g=this.createGroupAtLocation(f,void 0,void 0,d);this.movingLock(()=>g.model.openPanel(p,{skipSetGroupActive:!0})),this.doSetGroupAndPanelActive(g),this.fireDidMovePanel(p,l)}}}moveTabGroupToGroup(e){const{sourceGroup:t,tabGroupId:n,destinationGroup:s,destinationTarget:o,destinationIndex:r}=e,a=t.model.getTabGroups().find(v=>v.id===n);if(!a||a.panelIds.length===0)return;const l=a.label,c=a.color,d=a.collapsed,u=a.componentParams,h=[...a.panelIds],p=o&&o!=="center"?Tn(s.element):void 0,f=this.movingLock(()=>h.map(v=>t.model.removePanel(v,{skipSetActive:!1,skipSetActiveGroup:!0})).filter(v=>v!==void 0));if(f.length===0)return;const g=v=>{this.movingLock(()=>{for(const b of f)v.model.openPanel(b,{index:r,skipSetActive:!0,skipSetGroupActive:!0})});const y=v.model.createTabGroup({label:l,color:c,collapsed:d,componentParams:u});for(const b of f)v.model.addPanelToTabGroup(y.id,b.id);e.skipSetActive||this.doSetGroupAndPanelActive(v);for(const b of f)this.fireDidMovePanel(b,t)};let x;if(!o||o==="center"||!p)x=s;else{const v=Us(this.gridview.orientation,p,o);x=this.createGroupAtLocation(v)}!e.keepEmptyGroups&&t.model.size===0&&t!==x&&this.doRemoveGroup(t,{skipActive:!0}),g(x)}moveGroup(e){this.mutation("move",()=>this._doMoveGroup(e))}maximizeGroup(e){this.mutation("maximize",()=>super.maximizeGroup(e))}exitMaximizedGroup(){this.mutation("maximize",()=>super.exitMaximizedGroup())}_doMoveGroup(e){var t;const n=e.from.group,s=e.to.group,o=e.to.position;let r=n,a;if(o==="center"){const u=n.activePanel,h=n.model.getTabGroups().map(f=>({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams,panelIds:[...f.panelIds]})),p=this.movingLock(()=>[...n.panels].map(f=>n.model.removePanel(f.id,{skipSetActive:!0})));n?.model.size===0&&this.doRemoveGroup(n,{skipActive:!0}),this.movingLock(()=>{for(const f of p)s.model.openPanel(f,{skipSetActive:f!==u,skipSetGroupActive:!0})}),a=p;for(const f of h){const g=s.model.createTabGroup({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams});for(const x of f.panelIds)s.model.addPanelToTabGroup(g.id,x)}e.skipSetActive!==!0?this.doSetGroupAndPanelActive(s):this.activePanel||this.doSetGroupAndPanelActive(s)}else{if(n.api.location.type==="edge"){const u=n.activePanel,h=n.model.getTabGroups().map(f=>({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams,panelIds:[...f.panelIds]})),p=this.movingLock(()=>[...n.panels].map(f=>n.model.removePanel(f.id,{skipSetActive:!0})));r=this.createGroup(),this._onDidAddGroup.fire(r),this.movingLock(()=>{for(const f of p)r.model.openPanel(f,{skipSetActive:f!==u,skipSetGroupActive:!0})});for(const f of h){const g=r.model.createTabGroup({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams});for(const x of f.panelIds)r.model.addPanelToTabGroup(g.id,x)}}else switch(n.api.location.type){case"grid":this.gridview.removeView(Tn(n.element));break;case"floating":{var l;const u=(l=this._floatingGroupService)===null||l===void 0?void 0:l.findByGroup(n);if(!u)throw new Error("dockview: failed to find floating group");this.detachFromNestedWindow(n)||u.dispose();break}case"popout":{var c,d;const u=(c=this._popoutWindowService)===null||c===void 0?void 0:c.findByGroup(n);if(!u)throw new Error("dockview: failed to find popout group");if(this.detachFromNestedWindow(n))break;if((d=this._popoutWindowService)===null||d===void 0||d.remove(u),u.referenceGroup){const h=this.getPanel(u.referenceGroup);h&&!h.api.isVisible&&this.doRemoveGroup(h,{skipActive:!0})}u.window.dispose();break}}if(s.api.location.type==="grid"||s.api.location.type==="floating"||s.api.location.type==="popout"){const u=this.getGridviewForGroup(s),h=Tn(s.element),p=Us(u.orientation,h,o);let f;switch(u.orientation){case"VERTICAL":f=h.length%2==0?n.api.width:n.api.height;break;case"HORIZONTAL":f=h.length%2==0?n.api.height:n.api.width;break}u.addView(r,f,p),this.setGroupLocationForRoot(r,u)}}if(((t=a)!==null&&t!==void 0?t:r.panels).forEach(u=>{this.fireDidMovePanel(u,n)}),this.debouncedUpdateAllPositions(),e.skipSetActive===!1){const u=s??n;this.doSetGroupAndPanelActive(u)}else r!==n&&e.skipSetActive!==!0&&this.doSetGroupAndPanelActive(r)}doSetGroupActive(e){var t;super.doSetGroupActive(e);const n=this.activePanel;!this._moving&&n!==((t=this._onDidActivePanelChange.value)===null||t===void 0?void 0:t.panel)&&this.fireActivePanelChange(n)}doSetGroupAndPanelActive(e){var t;super.doSetGroupActive(e);const n=this.activePanel;e&&this.hasMaximizedGroup()&&!this.isMaximizedGroup(e)&&this.exitMaximizedGroup(),!this._moving&&n!==((t=this._onDidActivePanelChange.value)===null||t===void 0?void 0:t.panel)&&this.fireActivePanelChange(n)}getNextGroupId(){let e=this.nextGroupId.next();for(;this._groups.has(e);)e=this.nextGroupId.next();return e}createGroup(e){var t;(t=e)!==null&&t!==void 0||(e={});let n=e?.id;if(n&&this._groups.has(e.id)&&(console.warn(`dockview: Duplicate group id ${e?.id}. reassigning group id to avoid errors`),n=void 0),!n)for(n=this.nextGroupId.next();this._groups.has(n);)n=this.nextGroupId.next();const s=new vd(this,n,e);if(s.init({params:{},accessor:this}),!this._groups.has(s.id)){const o=new pt(s.model.onTabDragStart(r=>{var a;(a=this._advancedDnDService)===null||a===void 0||a.dispatchWillDragPanel(r)}),s.model.onGroupDragStart(r=>{var a;(a=this._advancedDnDService)===null||a===void 0||a.dispatchWillDragGroup(r)}),s.model.onMove(r=>{const{groupId:a,itemId:l,target: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)}),ei.any(s.model.onDidPanelTitleChange,s.model.onDidPanelParametersChange)(()=>{this._bufferOnDidLayoutChange.fire()}));this._groups.set(s.id,{value:s,disposable:o})}return s.initialize(),s}createPanel(e,t){var n,s,o;const r=e.component,a=(n=e.tabComponent)!==null&&n!==void 0?n:this.options.defaultTabComponent,l=new $P(this,e.id,r,a),c=new Wr(e.id,r,a,this,this._api,t,l,{renderer:e.renderer,minimumWidth:e.minimumWidth,minimumHeight:e.minimumHeight,maximumWidth:e.maximumWidth,maximumHeight:e.maximumHeight});return c.init({title:(s=e.title)!==null&&s!==void 0?s:e.id,params:(o=e?.params)!==null&&o!==void 0?o:{}}),c}createGroupAtLocation(e,t,n,s=this.gridview){const o=this.createGroup(n);return this.doAddGroup(o,e,t,s),this.setGroupLocationForRoot(o,s),o}setGroupLocationForRoot(e,t){var n;const s=(n=this._popoutWindowService)===null||n===void 0?void 0:n.entries.find(o=>o.gridview===t);if(s){e.model.renderContainer!==s.overlayRenderContainer&&(e.model.renderContainer=s.overlayRenderContainer),e.model.dropTargetContainer=s.dropTargetContainer,e.model.location={type:"popout",getWindow:s.getWindow,popoutUrl:s.popoutUrl};return}e.model.renderContainer!==this.overlayRenderContainer&&(e.model.renderContainer=this.overlayRenderContainer),e.model.dropTargetContainer=this.rootDropTargetContainer,e.model.location=t===this.gridview?{type:"grid"}:{type:"floating"}}getGridviewForGroup(e){var t,n;const s=(t=this._floatingGroupService)===null||t===void 0?void 0:t.findByGroup(e);if(s)return s.gridview;const o=(n=this._popoutWindowService)===null||n===void 0?void 0:n.findByGroup(e);return o?o.gridview:this.gridview}nestedWindowMembers(e){const t=this.getGridviewForGroup(e);return t===this.gridview?[]:this.groups.filter(n=>t.element.contains(n.element))}findGroup(e){var t;return(t=Array.from(this._groups.values()).find(n=>n.value.model.containsPanel(e)))===null||t===void 0?void 0:t.value}orientationAtLocation(e){const t=this.gridview.orientation;return e.length%2==1?t:Ri(t)}updateTheme(){var e,t,n,s,o,r,a,l;const c=(e=this._options.theme)!==null&&e!==void 0?e:Moe;(t=this._shellThemeClassnames)===null||t===void 0||t.setClassNames(c.className);const d=(n=c.gap)!==null&&n!==void 0?n:0;this.gridview.margin=d;for(const f of this.floatingGroups)f.gridview.margin=d;for(const f of(s=(o=this._popoutWindowService)===null||o===void 0?void 0:o.entries)!==null&&s!==void 0?s:[])f.gridview.margin=d;if((r=this._shellManager)===null||r===void 0||r.updateTheme(d,(a=c.edgeGroupCollapsedSize)!==null&&a!==void 0?a:35),c.dndOverlayBorder===void 0){var u;this.element.style.removeProperty("--dv-drag-over-border"),(u=this._shellManager)===null||u===void 0||u.element.style.removeProperty("--dv-drag-over-border")}else{var h;this.element.style.setProperty("--dv-drag-over-border",c.dndOverlayBorder),(h=this._shellManager)===null||h===void 0||h.element.style.setProperty("--dv-drag-over-border",c.dndOverlayBorder)}c.dndOverlayMounting==="absolute"?this.rootDropTargetContainer.disabled=!1:this.rootDropTargetContainer.disabled=!0;const p=((l=c.tabGroupIndicator)!==null&&l!==void 0?l:"wrap")==="none";Qe(this.element,"dv-tab-group-indicator-none",p),this._shellManager&&Qe(this._shellManager.element,"dv-tab-group-indicator-none",p);for(const f of this.groups)f.model.updateTabGroups()}},Ere=class extends vP{get orientation(){return this.gridview.orientation}set orientation(e){this.gridview.orientation=e}get options(){return this._options}get deserializer(){return this._deserializer}set deserializer(e){this._deserializer=e}constructor(e,t){var n;super(e,{proportionalLayout:(n=t.proportionalLayout)!==null&&n!==void 0?n:!0,orientation:t.orientation,styles:t.hideBorders?{separatorBorder:"transparent"}:void 0,disableAutoResizing:t.disableAutoResizing,className:t.className}),this._onDidLayoutfromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidRemoveGroup=new ve,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidAddGroup=new ve,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidActiveGroupChange=new ve,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._options=t,this.addDisposables(this._onDidAddGroup,this._onDidRemoveGroup,this._onDidActiveGroupChange,this.onDidAdd(s=>{this._onDidAddGroup.fire(s)}),this.onDidRemove(s=>{this._onDidRemoveGroup.fire(s)}),this.onDidActiveChange(s=>{this._onDidActiveGroupChange.fire(s)}))}updateOptions(e){super.updateOptions(e);const t=typeof e.orientation=="string"&&this.gridview.orientation!==e.orientation;this._options=gt(gt({},this.options),e),t&&(this.gridview.orientation=e.orientation),this.layout(this.gridview.width,this.gridview.height,!0)}removePanel(e){this.removeGroup(e)}toJSON(){var e;return{grid:this.gridview.serialize(),activePanel:(e=this.activeGroup)===null||e===void 0?void 0:e.id}}setVisible(e,t){this.gridview.setViewVisible(Tn(e.element),t)}setActive(e){this._groups.forEach((t,n)=>{t.value.setActive(e===t.value)})}focus(){var e;(e=this.activeGroup)===null||e===void 0||e.focus()}fromJSON(e){this.clear();const{grid:t,activePanel:n}=e;try{const s=[],o=this.width,r=this.height;if(this.gridview.deserialize(t,{fromJSON:a=>{const{data:l}=a,c=this.options.createComponent({id:l.id,name:l.component});return s.push(()=>c.init({params:l.params,minimumWidth:l.minimumWidth,maximumWidth:l.maximumWidth,minimumHeight:l.minimumHeight,maximumHeight:l.maximumHeight,priority:l.priority,snap:!!l.snap,accessor:this,isVisible:a.visible})),this._onDidAddGroup.fire(c),this.registerPanel(c),c}}),this.layout(o,r,!0),s.forEach(a=>a()),typeof n=="string"){const a=this.getPanel(n);a&&this.doSetGroupActive(a)}}catch(s){for(const o of this.groups)o.dispose(),this._groups.delete(o.id),this._onDidRemoveGroup.fire(o);throw this.clear(),s}this._onDidLayoutfromJSON.fire()}clear(){const e=this.activeGroup,t=Array.from(this._groups.values());for(const n of t)n.disposable.dispose(),this.doRemoveGroup(n.value,{skipActive:!0});e&&this.doSetGroupActive(void 0),this.gridview.clear()}movePanel(e,t){var n;const s=(n=this._groups.get(t.reference))===null||n===void 0?void 0:n.value;if(!s)throw new Error(`reference group ${t.reference} does not exist`);const o=Yu(t.direction);if(o==="center")throw new Error(`${o} not supported as an option`);const r=Tn(s.element),a=Us(this.gridview.orientation,r,o),l=this.gridview.remove(e);this.doAddGroup(l,a,t.size)}addPanel(e){var t,n,s;let o=(t=e.location)!==null&&t!==void 0?t:[0];if(!((n=e.position)===null||n===void 0)&&n.referencePanel){var r;const l=(r=this._groups.get(e.position.referencePanel))===null||r===void 0?void 0:r.value;if(!l)throw new Error(`reference group ${e.position.referencePanel} does not exist`);const c=Yu(e.position.direction);if(c==="center")throw new Error(`${c} not supported as an option`);{const d=Tn(l.element);o=Us(this.gridview.orientation,d,c)}}const a=this.options.createComponent({id:e.id,name:e.component});return a.init({params:(s=e.params)!==null&&s!==void 0?s:{},minimumWidth:e.minimumWidth,maximumWidth:e.maximumWidth,minimumHeight:e.minimumHeight,maximumHeight:e.maximumHeight,priority:e.priority,snap:!!e.snap,accessor:this,isVisible:!0}),this.doAddGroup(a,o,e.size),this.registerPanel(a),this.doSetGroupActive(a),a}registerPanel(e){const t=new pt(e.api.onDidFocusChange(n=>{n.isFocused&&this._groups.forEach(s=>{const o=s.value;o.setActive(o===e)})}));this._groups.set(e.id,{value:e,disposable:t})}moveGroup(e,t,n){const s=this.getPanel(t);if(!s)throw new Error("invalid operation");const o=Tn(e.element),[r,a]=po(Us(this.gridview.orientation,o,n)),[l,c]=po(Tn(s.element));if(fP(l,r)){this.gridview.moveView(l,c,a);return}const d=this.doRemoveGroup(s,{skipActive:!0,skipDispose:!0}),u=Tn(e.element),h=Us(this.gridview.orientation,u,n);this.doAddGroup(d,h)}removeGroup(e){super.removeGroup(e)}dispose(){super.dispose(),this._onDidLayoutfromJSON.dispose()}},Pre=class extends Yv{get panels(){return this.splitview.getViews()}get options(){return this._options}get length(){return this._panels.size}get orientation(){return this.splitview.orientation}get splitview(){return this._splitview}set splitview(e){this._splitview&&this._splitview.dispose(),this._splitview=e,this._splitviewChangeDisposable.value=new pt(this._splitview.onDidSashEnd(()=>{this._onDidLayoutChange.fire(void 0)}),this._splitview.onDidAddView(t=>this._onDidAddView.fire(t)),this._splitview.onDidRemoveView(t=>this._onDidRemoveView.fire(t)))}get minimumSize(){return this.splitview.minimumSize}get maximumSize(){return this.splitview.maximumSize}get height(){return this.splitview.orientation==="HORIZONTAL"?this.splitview.orthogonalSize:this.splitview.size}get width(){return this.splitview.orientation==="HORIZONTAL"?this.splitview.size:this.splitview.orthogonalSize}constructor(e,t){var n;super(document.createElement("div"),t.disableAutoResizing),this._splitviewChangeDisposable=new Bn,this._panels=new Map,this._onDidLayoutfromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidAddView=new ve,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new ve,this.onDidRemoveView=this._onDidRemoveView.event,this._onDidLayoutChange=new ve,this.onDidLayoutChange=this._onDidLayoutChange.event,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new ep(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.splitview=new _r(this.element,t),this.addDisposables(this._onDidAddView,this._onDidLayoutfromJSON,this._onDidRemoveView,this._onDidLayoutChange)}updateOptions(e){if("className"in e){var t;this._classNames.setClassNames((t=e.className)!==null&&t!==void 0?t:"")}if("disableResizing"in e){var n;this.disableResizing=(n=e.disableAutoResizing)!==null&&n!==void 0?n:!1}typeof e.orientation=="string"&&(this.splitview.orientation=e.orientation),this._options=gt(gt({},this.options),e),this.splitview.layout(this.splitview.size,this.splitview.orthogonalSize)}focus(){var e;(e=this._activePanel)===null||e===void 0||e.focus()}movePanel(e,t){this.splitview.moveView(e,t)}setVisible(e,t){const n=this.panels.indexOf(e);this.splitview.setViewVisible(n,t)}setActive(e,t){this._activePanel=e,this.panels.filter(n=>n!==e).forEach(n=>{n.api._onDidActiveChange.fire({isActive:!1}),t||n.focus()}),e.api._onDidActiveChange.fire({isActive:!0}),t||e.focus()}removePanel(e,t){const n=this._panels.get(e.id);if(!n)throw new Error(`unknown splitview panel ${e.id}`);n.dispose(),this._panels.delete(e.id);const s=this.panels.indexOf(e);this.splitview.removeView(s,t).dispose();const o=this.panels;o.length>0&&this.setActive(o[o.length-1])}getPanel(e){return this.panels.find(t=>t.id===e)}addPanel(e){var t;if(this._panels.has(e.id))throw new Error(`panel ${e.id} already exists`);const n=this.options.createComponent({id:e.id,name:e.component});n.orientation=this.splitview.orientation,n.init({params:(t=e.params)!==null&&t!==void 0?t:{},minimumSize:e.minimumSize,maximumSize:e.maximumSize,snap:e.snap,priority:e.priority,accessor:this});const s=typeof e.size=="number"?e.size:_s.Distribute,o=typeof e.index=="number"?e.index:void 0;return this.splitview.addView(n,s,o),this.doAddView(n),this.setActive(n),n}layout(e,t){const[n,s]=this.splitview.orientation==="HORIZONTAL"?[e,t]:[t,e];this.splitview.layout(n,s)}doAddView(e){const t=e.api.onDidFocusChange(n=>{n.isFocused&&this.setActive(e,!0)});this._panels.set(e.id,t)}toJSON(){var e;return{views:this.splitview.getViews().map((t,n)=>({size:this.splitview.getViewSize(n),data:t.toJSON(),snap:!!t.snap,priority:t.priority})),activeView:(e=this._activePanel)===null||e===void 0?void 0:e.id,size:this.splitview.size,orientation:this.splitview.orientation}}fromJSON(e){this.clear();const{views:t,orientation:n,size:s,activeView:o}=e,r=[],a=this.width,l=this.height;if(this.splitview=new _r(this.element,{orientation:n,proportionalLayout:this.options.proportionalLayout,descriptor:{size:s,views:t.map(c=>{const d=c.data;if(this._panels.has(d.id))throw new Error(`panel ${d.id} already exists`);const u=this.options.createComponent({id:d.id,name:d.component});return r.push(()=>{var h;u.init({params:(h=d.params)!==null&&h!==void 0?h:{},minimumSize:d.minimumSize,maximumSize:d.maximumSize,snap:c.snap,priority:c.priority,accessor:this})}),u.orientation=n,this.doAddView(u),setTimeout(()=>{this._onDidAddView.fire(u)},0),{size:c.size,view:u}})}}),this.layout(a,l),r.forEach(c=>c()),typeof o=="string"){const c=this.getPanel(o);c&&this.setActive(c)}this._onDidLayoutfromJSON.fire()}clear(){for(const e of this._panels.values())e.dispose();for(this._panels.clear();this.splitview.length>0;)this.splitview.removeView(0,_s.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()}},dk=class extends pt{get element(){return this._element}constructor(){super(),this._expandedIcon=ooe(),this._collapsedIcon=AP(),this.disposable=new Bn,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(ct(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);Qe(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 Are=qv(),uk=22,hk=0,pk=Number.MAX_SAFE_INTEGER;var fk=class extends eoe{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}},Mre=class extends Yv{get id(){return this._id}get panels(){return this.paneview.getPanes()}set paneview(e){this._paneview=e,this._disposable.value=new pt(this._paneview.onDidChange(()=>{this._onDidLayoutChange.fire(void 0)}),this._paneview.onDidAddView(t=>this._onDidAddView.fire(t)),this._paneview.onDidRemoveView(t=>this._onDidRemoveView.fire(t)))}get paneview(){return this._paneview}get minimumSize(){return this.paneview.minimumSize}get maximumSize(){return this.paneview.maximumSize}get height(){return this.paneview.orientation==="HORIZONTAL"?this.paneview.orthogonalSize:this.paneview.size}get width(){return this.paneview.orientation==="HORIZONTAL"?this.paneview.size:this.paneview.orthogonalSize}get options(){return this._options}constructor(e,t){var n;super(document.createElement("div"),t.disableAutoResizing),this._id=Are.next(),this._disposable=new Bn,this._viewDisposables=new Map,this._onDidLayoutfromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidLayoutChange=new ve,this.onDidLayoutChange=this._onDidLayoutChange.event,this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onDidAddView=new ve,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new ve,this.onDidRemoveView=this._onDidRemoveView.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this.element.style.height="100%",this.element.style.width="100%",this.addDisposables(this._onDidLayoutChange,this._onDidLayoutfromJSON,this._onDidDrop,this._onDidAddView,this._onDidRemoveView,this._onUnhandledDragOver),this._classNames=new ep(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.paneview=new JC(this.element,{orientation:"VERTICAL"}),this.addDisposables(this._disposable)}setVisible(e,t){const n=this.panels.indexOf(e);this.paneview.setViewVisible(n,t)}focus(){}updateOptions(e){if("className"in e){var t;this._classNames.setClassNames((t=e.className)!==null&&t!==void 0?t:"")}if("disableAutoResizing"in e){var n;this.disableResizing=(n=e.disableAutoResizing)!==null&&n!==void 0?n:!1}this._options=gt(gt({},this.options),e)}addPanel(e){var t,n,s;const o=this.options.createComponent({id:e.id,name:e.component});let r;e.headerComponent&&this.options.createHeaderComponent&&(r=this.options.createHeaderComponent({id:e.id,name:e.headerComponent})),(t=r)!==null&&t!==void 0||(r=new dk);const a=new fk({id:e.id,component:e.component,headerComponent:e.headerComponent,header:r,body:o,orientation:"VERTICAL",isExpanded:!!e.isExpanded,disableDnd:!!this.options.disableDnd,accessor:this,headerSize:(n=e.headerSize)!==null&&n!==void 0?n:uk,minimumBodySize:hk,maximumBodySize:pk});this.doAddPanel(a);const l=typeof e.size=="number"?e.size:_s.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 rc(this),accessor:this}),this.paneview.addPane(a,l,c),a.orientation=this.paneview.orientation,a}removePanel(e){const t=this.panels.indexOf(e);this.paneview.removePane(t),this.doRemovePanel(e)}movePanel(e,t){this.paneview.moveView(e,t)}getPanel(e){return this.panels.find(t=>t.id===e)}layout(e,t){const[n,s]=this.paneview.orientation==="HORIZONTAL"?[e,t]:[t,e];this.paneview.layout(n,s)}toJSON(){const e=n=>n===Number.MAX_SAFE_INTEGER||n===Number.POSITIVE_INFINITY?void 0:n,t=n=>n<=0?void 0:n;return{views:this.paneview.getPanes().map((n,s)=>{const o=this.paneview.getViewCachedVisibleSize(s),r=typeof o=="number";return gt({size:r?o:this.paneview.getViewSize(s),data:n.toJSON(),minimumSize:t(n.minimumBodySize),maximumSize:e(n.maximumBodySize),headerSize:n.headerSize,expanded:n.isExpanded()},r?{visible:!1}:{})}),size:this.paneview.size}}fromJSON(e){this.clear();const{views:t,size:n}=e,s=[],o=this.width,r=this.height;this.paneview=new JC(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 dk);const g=new fk({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:uk,minimumBodySize:(d=a.minimumSize)!==null&&d!==void 0?d:hk,maximumBodySize:(u=a.maximumSize)!==null&&u!==void 0?u:pk});return this.doAddPanel(g),s.push(()=>{var x;g.init({params:(x=h.params)!==null&&x!==void 0?x:{},minimumBodySize:a.minimumSize,maximumBodySize:a.maximumSize,title:h.title,isExpanded:!!a.expanded,containerApi:new rc(this),accessor:this}),g.orientation=this.paneview.orientation}),setTimeout(()=>{this._onDidAddView.fire(g)},0),{size:a.size,view:g,visible:a.visible}})}}),this.layout(o,r),s.forEach(a=>a()),this._onDidLayoutfromJSON.fire()}clear(){for(const[e,t]of this._viewDisposables.entries())t.dispose();this._viewDisposables.clear(),this.paneview.dispose()}doAddPanel(e){const t=new pt(e.onDidDrop(n=>{this._onDidDrop.fire(n)}),e.onUnhandledDragOver(n=>{this._onUnhandledDragOver.fire(n)}));this._viewDisposables.set(e.id,t)}doRemovePanel(e){const t=this._viewDisposables.get(e.id);t&&(t.dispose(),this._viewDisposables.delete(e.id))}dispose(){super.dispose();for(const[e,t]of this._viewDisposables.entries())t.dispose();this._viewDisposables.clear(),this.element.remove(),this.paneview.dispose()}},Rre=class extends Jv{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 EP(e,t)),this._evaluatedMinimumSize=0,this._evaluatedMaximumSize=Number.POSITIVE_INFINITY,this._minimumSize=0,this._maximumSize=Number.POSITIVE_INFINITY,this._snap=!1,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this.api.initialize(this),this.addDisposables(this._onDidChange,this.api.onWillVisibilityChange(n=>{const{isVisible:s}=n,{accessor:o}=this._params;o.setVisible(this,s)}),this.api.onActiveChange(()=>{const{accessor:n}=this._params;n.setActive(this)}),this.api.onDidConstraintsChangeInternal(n=>{(typeof n.minimumSize=="number"||typeof n.minimumSize=="function")&&(this._minimumSize=n.minimumSize),(typeof n.maximumSize=="number"||typeof n.maximumSize=="function")&&(this._maximumSize=n.maximumSize),this.updateConstraints()}),this.api.onDidSizeChange(n=>{this._onDidChange.fire({size:n.size})}))}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}layout(e,t){const[n,s]=this.orientation==="HORIZONTAL"?[e,t]:[t,e];super.layout(n,s)}init(e){super.init(e),this._priority=e.priority,e.minimumSize&&(this._minimumSize=e.minimumSize),e.maximumSize&&(this._maximumSize=e.maximumSize),e.snap&&(this._snap=e.snap)}toJSON(){const e=n=>n===Number.MAX_SAFE_INTEGER||n===Number.POSITIVE_INFINITY?void 0:n,t=n=>n<=0?void 0:n;return gt(gt({},super.toJSON()),{},{minimumSize:t(this.minimumSize),maximumSize:e(this.maximumSize)})}updateConstraints(){this.api._onDidConstraintsChange.fire({maximumSize:this._evaluatedMaximumSize,minimumSize:this._evaluatedMinimumSize})}};function Lre(e,t){return new Dre(e,t).api}function Ore(e,t){return new wP(new Pre(e,t))}function zre(e,t){return new yP(new Ere(e,t))}function Gre(e,t){return new rc(new Mre(e,t))}function lc(e){"@babel/helpers - typeof";return lc=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},lc(e)}function Fre(e,t){if(lc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(lc(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Hre(e){var t=Fre(e,"string");return lc(t)=="symbol"?t:t+""}function Bre(e,t,n){return(t=Hre(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mk(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,s)}return n}function As(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?mk(Object(n),!0).forEach(function(s){Bre(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mk(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}const qP=(e,t)=>{const[,n]=_e.useState(0),s=_e.useRef(e.componentProps);return _e.useImperativeHandle(t,()=>({update:o=>{s.current=As(As({},s.current),o),n(r=>r+1)}}),[]),_e.createElement(e.component,s.current)};qP.displayName="DockviewReactJsBridge";const Vre=(()=>{let e=1;return{next:()=>`dockview_react_portal_key_${(e++).toString()}`}})(),$re=_e.createContext({});var Yi=class{constructor(e,t,n,s,o){this.parent=e,this.portalStore=t,this.component=n,this.parameters=s,this.context=o,this._initialProps={},this.disposed=!1,this.createPortal()}update(e){if(this.disposed)throw new Error("invalid operation: resource is already disposed");this.componentInstance?this.componentInstance.update(e):this._initialProps=As(As({},this._initialProps),e)}createPortal(){if(this.disposed)throw new Error("invalid operation: resource is already disposed");if(!Wre(this.component))throw new Error("Dockview: Only React.memo(...), React.ForwardRef(...) and functional components are accepted as components");const e=_e.createElement(_e.forwardRef(qP),{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?_e.createElement($re.Provider,{value:this.context},e):e,n=sj.createPortal(t,this.parent,Vre.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 sp=()=>{const[e,t]=_e.useState([]);return _e.useDebugValue(`Portal count: ${e.length}`),[e,_e.useCallback(n=>{t(o=>[...o,n]);let s=!1;return cn.from(()=>{if(s)throw new Error("invalid operation: resource already disposed");s=!0,t(o=>o.filter(r=>r!==n))})},[])]};function Wre(e){return typeof e=="function"||!!e?.$$typeof}var gk=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._onDidFocus=new ve,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new ve,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}focus(){}init(e){this.part=new Yi(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()}},xk=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 Yi(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()}},vk=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 Yi(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()}},Ure=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 Bn,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}init(e){this.mutableDisposable.value=new pt(this._group.model.onDidAddPanel(()=>{this.updatePanels()}),this._group.model.onDidRemovePanel(()=>{this.updatePanels()}),this._group.model.onDidActivePanelChange(()=>{this.updateActivePanel()}),e.api.onDidActiveChange(()=>{this.updateGroupActive()}),e.api.onDidLocationChange(t=>{this.updateLocation(t.location)})),this._part=new Yi(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}})}},Kre=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 Yi(this._element,this.reactPortalStore,this.component,e)}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}},bk=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 Yi(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()}},wk=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 Yi(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 Fr(e,t){return e?n=>new Ure(e,t,n):void 0}const Sd="props.defaultTabComponent";function qre(e){return Dg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const YP=_e.forwardRef((e,t)=>{const n=_e.useRef(null),s=_e.useRef(void 0),[o,r]=sp();_e.useImperativeHandle(t,()=>n.current,[]);const a=_e.useRef({});return _e.useEffect(()=>{const l={};Dg.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},Dg.map(l=>e[l])),_e.useEffect(()=>{if(!n.current)return;const l=As({},e.tabComponents);e.defaultTabComponent&&(l[Sd]=e.defaultTabComponent);const c={createLeftHeaderActionComponent:Fr(e.leftHeaderActionsComponent,{addPortal:r}),createRightHeaderActionComponent:Fr(e.rightHeaderActionsComponent,{addPortal:r}),createPrefixHeaderActionComponent:Fr(e.prefixHeaderActionsComponent,{addPortal:r}),createComponent:f=>new gk(f.id,e.components[f.name],{addPortal:r}),createTabComponent(f){return new xk(f.id,l[f.name],{addPortal:r})},createWatermarkComponent:e.watermarkComponent?()=>new vk("watermark",e.watermarkComponent,{addPortal:r}):void 0,defaultTabComponent:e.defaultTabComponent?Sd:void 0,createContextMenuItemComponent:f=>{if(f.component)return new Kre(f.id,f.component,{addPortal:r})}},d=qre(e);if(e.tabGroupChipComponent){const f=e.tabGroupChipComponent;d.createTabGroupChipComponent=()=>new bk(f,{addPortal:r})}if(e.groupDragGhostComponent){const f=e.groupDragGhostComponent;d.createGroupDragGhostComponent=()=>new wk(f,{addPortal:r})}const u=Lre(n.current,As(As({},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()}},[]),_e.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onDidDrop(c=>{e.onDidDrop&&e.onDidDrop(c)});return()=>{l.dispose()}},[e.onDidDrop]),_e.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onWillDrop(c=>{e.onWillDrop&&e.onWillDrop(c)});return()=>{l.dispose()}},[e.onWillDrop]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createTabGroupChipComponent:e.tabGroupChipComponent?()=>new bk(e.tabGroupChipComponent,{addPortal:r}):void 0})},[e.tabGroupChipComponent]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createGroupDragGhostComponent:e.groupDragGhostComponent?()=>new wk(e.groupDragGhostComponent,{addPortal:r}):void 0})},[e.groupDragGhostComponent]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new gk(l.id,e.components[l.name],{addPortal:r})})},[e.components]),_e.useEffect(()=>{if(!s.current)return;const l=As({},e.tabComponents);e.defaultTabComponent&&(l[Sd]=e.defaultTabComponent),s.current.updateOptions({defaultTabComponent:e.defaultTabComponent?Sd:void 0,createTabComponent(c){return new xk(c.id,l[c.name],{addPortal:r})}})},[e.tabComponents,e.defaultTabComponent]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createWatermarkComponent:e.watermarkComponent?()=>new vk("watermark",e.watermarkComponent,{addPortal:r}):void 0})},[e.watermarkComponent]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createRightHeaderActionComponent:Fr(e.rightHeaderActionsComponent,{addPortal:r})})},[e.rightHeaderActionsComponent]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createLeftHeaderActionComponent:Fr(e.leftHeaderActionsComponent,{addPortal:r})})},[e.leftHeaderActionsComponent]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createPrefixHeaderActionComponent:Fr(e.prefixHeaderActionsComponent,{addPortal:r})})},[e.prefixHeaderActionsComponent]),_e.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});YP.displayName="DockviewComponent";var yk=class extends Rre{constructor(e,t,n,s){super(e,t),this.reactComponent=n,this.reactPortalStore=s}getComponent(){var e,t;return new Yi(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 wP(this._params.accessor)})}};function Yre(e){return yg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Xre=_e.forwardRef((e,t)=>{const n=_e.useRef(null),s=_e.useRef(void 0),[o,r]=sp();_e.useImperativeHandle(t,()=>n.current,[]);const a=_e.useRef({});return _e.useEffect(()=>{const l={};yg.forEach(c=>{const d=c,u=e[d];d in e&&u!==a.current[d]&&(l[d]=u)}),s.current&&s.current.updateOptions(l),a.current=e},yg.map(l=>e[l])),_e.useEffect(()=>{if(!n.current)return()=>{};const l=Ore(n.current,As(As({},Yre(e)),{createComponent:u=>new yk(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()}},[]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new yk(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),_e.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Xre.displayName="SplitviewComponent";var Sk=class extends VP{constructor(e,t,n,s){super(e,t),this.reactComponent=n,this.reactPortalStore=s}getComponent(){var e,t;return new Yi(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 yP(this._params.accessor)})}};function Jre(e){return _g.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Zre=_e.forwardRef((e,t)=>{const n=_e.useRef(null),s=_e.useRef(void 0),[o,r]=sp();_e.useImperativeHandle(t,()=>n.current,[]);const a=_e.useRef({});return _e.useEffect(()=>{const l={};_g.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},_g.map(l=>e[l])),_e.useEffect(()=>{if(!n.current)return()=>{};const l=zre(n.current,As(As({},Jre(e)),{createComponent:u=>new Sk(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()}},[]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new Sk(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),_e.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Zre.displayName="GridviewComponent";var Cd=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 Yi(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 Qre(e){return Tg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const eae=_e.forwardRef((e,t)=>{const n=_e.useRef(null),s=_e.useRef(void 0),[o,r]=sp();_e.useImperativeHandle(t,()=>n.current,[]);const a=_e.useRef({});return _e.useEffect(()=>{const l={};Tg.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},Tg.map(l=>e[l])),_e.useEffect(()=>{var l;if(!n.current)return()=>{};const c=(l=e.headerComponents)!==null&&l!==void 0?l:{},d=Gre(n.current,As(As({},Qre(e)),{createComponent:p=>new Cd(p.id,e.components[p.name],{addPortal:r}),createHeaderComponent:p=>new Cd(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()}},[]),_e.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new Cd(l.id,e.components[l.name],{addPortal:r})})},[e.components]),_e.useEffect(()=>{var l;if(!s.current)return;const c=(l=e.headerComponents)!==null&&l!==void 0?l:{};s.current.updateOptions({createHeaderComponent:d=>new Cd(d.id,c[d.name],{addPortal:r})})},[e.headerComponents]),_e.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onDidDrop(c=>{e.onDidDrop&&e.onDidDrop(c)});return()=>{l.dispose()}},[e.onDidDrop]),_e.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});eae.displayName="PaneviewComponent";function la(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tae(e,t,n){if(!la(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 XP(e,t){if(la(e)){if(e.type==="leaf"){const n=la(e.data)?e.data:void 0,s=Array.isArray(n?.views)?n.views.filter(r=>typeof r=="string"&&t.has(r)):[];if(s.length===0)return;const o=typeof n?.activeView=="string"&&t.has(n.activeView)?n.activeView:s[0];return{type:"leaf",data:{...n,views:s,activeView:o},size:e.size}}if(e.type==="branch"){const n=Array.isArray(e.data)?e.data.flatMap(s=>{const o=XP(s,t);return o?[o]:[]}):[];return n.length===0?void 0:{type:"branch",data:n,size:e.size}}}}function nae(e,t){if(!la(e)||!la(e.panels))return;const n={};for(const[a,l]of Object.entries(e.panels))tae(a,l,t)&&(n[a]=l);const s=new Set(Object.keys(n));if(s.size===0)return;const o=la(e.grid)?e.grid:void 0,r=o?XP(o.root,s):void 0;if(r)return{...e,panels:n,grid:{...o,root:r}}}function Ck(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 sae(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=Ck(e)&&e!=="."?e:e.split("/").pop()??"",o=s.lastIndexOf("/"),r=o===-1?"":s.slice(0,o),a=r?`${r}/${n}`:n,l=[];for(const d of a.split("/"))if(!(d===""||d===".")){if(d===".."){if(l.length===0)return null;l.pop();continue}l.push(d)}const c=l.join("/");return!c||!Ck(c)?null:c}function kk(e,t){const n=new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>]+))`,"i").exec(e);return n?n[1]??n[2]??n[3]??"":null}function iae(e,t,n){return e.replace(new RegExp(`\\b${t}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>]+)`,"i"),`${t}="${n}"`)}function oae(e){return e?.trim().toLowerCase().split(/\s+/).includes("stylesheet")??!1}function rae(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}catch{return null}}function aae(e,t){const n=[],s=(o,r,a,l)=>{const c=r[1]??"";if(!l(c))return;const d=kk(c,a);if(d===null)return;const u=sae(t,d);u&&n.push({start:r.index,end:r.index+r[0].length,kind:o,rel:u,attrs:c,full:r[0]})};for(const o of e.matchAll(/<script\b([^>]*)>[\s\S]*?<\/script>/gi))s("script",o,"src",()=>!0);for(const o of e.matchAll(/<link\b([^>]*?)\/?>/gi))s("style",o,"href",r=>oae(kk(r,"rel")));for(const o of e.matchAll(/<img\b([^>]*?)\/?>/gi))s("img",o,"src",()=>!0);return n.sort((o,r)=>o.start-r.start),n}async function lae(e,t,n){const s=aae(e,t),o=new Map;await Promise.all([...new Set(s.map(l=>l.rel))].map(async l=>{o.set(l,await n(l))}));let r=0,a="";for(const l of s){a+=e.slice(r,l.start),r=l.end;const c=o.get(l.rel);if(!c){a+=l.full;continue}if(l.kind==="img"){const u=c.mime||"application/octet-stream";a+=`<img${iae(l.attrs,"src",`data:${u};base64,${c.base64}`)}>`;continue}const d=rae(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 cae="plugin-view.html";function jk(){return document.documentElement.classList.contains("dark")?"dark":"light"}function dae({pluginId:e,viewId:t,sessionId:n}){const{t:s}=ne(),o=O_().find(r=>r.pluginId===e&&r.id===t);return o?i.jsx(JP,{pluginId:e,entry:o.entry,title:o.title,sessionId:n}):i.jsx("div",{className:"flex h-full items-center justify-center p-6 text-sm text-muted-foreground",children:s("Plugin is not enabled")})}function JP({pluginId:e,entry:t,title:n,sessionId:s,file:o}){const r=m.useRef(null),[a,l]=m.useState(null),c=m.useRef(s);c.current=s;const d=m.useRef(o);d.current=o;const u=m.useRef(null),h=m.useRef(null);m.useEffect(()=>{const g=r.current;if(!g)return;l(null);let x=!1,v=null;const y=()=>{try{v?.port1.postMessage(TO(jk()))}catch{}},b=new MutationObserver(y);b.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const w=window.electronAPI.extensionPlugins.onViewEvent(N=>{if(!(N.pluginId!==e||typeof N.name!="string"))try{v?.port1.postMessage(_O(N.name,N.data))}catch{}}),C=PO(async(N,k)=>{const S=await window.electronAPI.extensionPlugins.call({pluginId:e,method:"renderer.call",payload:{method:N,args:k},sessionId:c.current});if(!S.ok)throw new Error(S.error);return S.value}),_=async N=>{if(N.source!==g.contentWindow||N.data?.type!=="enso-view-ready")return;v?.port1.close();const k=new MessageChannel;v=k,u.current=k,k.port1.onmessage=P=>{const D=IO(P.data);if(D){window.electronAPI.extensionPlugins.viewStateSet(e,D);return}const O=DO(P.data);if(O!==null){h.current=O,d.current?.onEdit(O);return}C(P.data).then(z=>{z&&!x&&v===k&&k.port1.postMessage(z)})};const[S,A]=await Promise.all([window.electronAPI.extensionPlugins.asset(e,t),window.electronAPI.extensionPlugins.viewStateGet(e)]);if(x||v!==k)return;if(!S.ok){l(S.error);return}const T=await lae(EO(S.base64),t,async P=>{const D=await window.electronAPI.extensionPlugins.asset(e,P);return D.ok?{mime:D.mime,base64:D.base64}:null});if(x||v!==k)return;const I=d.current;g.contentWindow?.postMessage({type:"enso-view-init",html:T,theme:jk(),storage:A.ok?A.state:{},...I?{file:{rel:I.rel,text:I.text}}:{}},"*",[k.port2])};return window.addEventListener("message",_),g.src=new URL(cae,document.baseURI).href,()=>{x=!0,b.disconnect(),w(),window.removeEventListener("message",_),v?.port1.close(),u.current=null,g.removeAttribute("src")}},[e,t]);const p=o?.rel,f=o?.text;return m.useEffect(()=>{if(!(p===void 0||f===void 0)){if(h.current===f){h.current=null;return}try{u.current?.port1.postMessage(NO(p,f))}catch{}}},[p,f]),i.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a&&i.jsx("div",{className:"shrink-0 px-3 py-2 text-xs text-destructive",children:a}),i.jsx("iframe",{ref:r,title:n,className:"min-h-0 w-full flex-1 border-0 bg-background"})]})}function uae({conversationId:e,panelApi:t}){const{t:n}=ne(),s=t.id.startsWith("btw:")?t.id.slice(4):t.id,o=Na(),r=we(R=>R.virtualModels),a=we(R=>R.defaultModel),l=we(R=>R.projects),c=we(R=>R.projectGroups),d=ko(R=>R.snapshot),u=nx(),[h,p]=m.useState("contextual"),[f,g]=m.useState(!1),[x]=m.useState(()=>KU(ie.getState().conversations[e]?.messages??[])),v=ie(qf(R=>R.conversations[s]??null)),y=v?.title,b=v?.projectId,w=m.useMemo(()=>l.find(R=>R.id===b),[b,l]),C=m.useMemo(()=>ru(w,c),[w,c]),_=m.useMemo(()=>au({defaultModel:a,...C,lastProviderId:v?.lastProviderId,lastModelId:v?.lastModelId,providers:o,credentials:Fl(d),virtualModels:r}),[r,v?.lastModelId,v?.lastProviderId,C,a,d,o]),N=_.source==="none"?void 0:u.find(R=>R.id===_.providerId),k=_.source==="none"?"":_.modelId,S=_.source==="none"?"":Yf(_)?_.providerId:N?.id??"",A=m.useMemo(()=>qU(v?.messages??[]),[v?.messages]),T=m.useRef(null),I=v?.status==="running",P=f||(v?m_({started:v.started,sessionFile:v.sessionFile,messages:v.messages,spawning:v.spawning,status:v.status,historyLoadAttempted:v.historyLoadAttempted}):!0),D=m.useMemo(()=>{const R={name:"/compact",description:n("Compact the context now (/compact [summary focus])")},$=new Set([R.name]);return[R,...(v?.commands??[]).filter(X=>!$.has(X.name))]},[v?.commands,n]);m.useEffect(()=>{const R=ie.getState().conversations[e],$=we.getState();ie.getState().ensureBtwConversation({id:s,projectId:R?.projectId??"",btwParentId:e,rolePrompt:py("contextual",x),lastProviderId:R?.lastProviderId??$.defaultModel?.providerId,lastModelId:R?.lastModelId??$.defaultModel?.modelId,reasoningEnabled:R?.reasoningEnabled??$.defaultReasoningEnabled,thinkingLevel:R?.thinkingLevel??$.defaultThinkingLevel,approvalMode:R?.approvalMode??"full",presetId:R?.presetId})},[e,s,x]),m.useEffect(()=>{y&&t.setTitle(y)},[t,y]);const O=R=>{R===h||f||(g(!0),(async()=>(ie.getState().abort(s),await ie.getState().resetBtwSession(s,py(R,x)),p(R),t.setTitle(n("Btw")),g(!1)))())},z=()=>{const R=XU(A);if(R){if(!Mh(R)){ze({type:"warning",title:n("No Composer for this selection")});return}_o()}};return i.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[i.jsx(_k,{label:n("Contextual"),active:h==="contextual",onClick:()=>O("contextual")}),i.jsx(_k,{label:n("Tangent"),active:h==="tangent",onClick:()=>O("tangent")}),i.jsx("button",{type:"button",className:"ml-auto rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",disabled:!A,onClick:z,children:n("Insert into chat")})]}),v?i.jsx(hE,{conversationId:s,cwd:w?.path,emptyTitle:n("Btw"),timelineRef:T}):i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-2 text-center text-muted-foreground",children:[i.jsx(Cr,{className:"h-5 w-5"}),i.jsx("p",{className:"text-xs",children:n("Ask a side question without sending it to the main agent.")})]}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:Ni,children:[v?.retry?i.jsx(Yh,{retry:v.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(s)}}):null,i.jsx(nh.Provider,{value:b?{conversationId:s,projectId:b,...w?.path?{cwd:w.path}:{}}:null,children:i.jsx(Fv,{sessionId:s,tasks:v?.backgroundTasks??[],subagents:v?.subagents??[]},s)}),i.jsx(Rh,{approvals:v?.pendingApprovals??[],allowSession:!0,onRespond:(R,$)=>{window.electronAPI.agent.respondApproval(s,R,$)}}),i.jsx(Lh,{asks:v?.pendingAsks??[],onAnswer:(R,$)=>{window.electronAPI.agent.respondAsk(s,R,$)}}),i.jsx(kE,{conversationId:s,queued:v?.queuedMessages??[]}),i.jsx(zv,{isolated:!0,cwd:w?.path,commands:D,running:I,busy:P,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:i.jsx(xh,{providers:u,activeAccount:tx(o,v??void 0),virtualModels:r,providerId:S,modelId:k,reasoningEnabled:v?.reasoningEnabled??!1,thinkingLevel:v?.thinkingLevel??"medium",onSelect:(R,$)=>ie.getState().setModel(s,R,$),onReasoningChange:R=>ie.getState().setReasoning(s,R),onThinkingChange:R=>ie.getState().setThinking(s,R),side:"top"}),onSend:R=>!S||!k||!w?!1:(T.current?.scrollToBottom(),ie.getState().send(R.text,{providerId:S,modelId:k,cwd:w.path},R.images,s),!0),onAbort:()=>{ie.getState().abort(s)}}),i.jsx(PE,{conversationId:s,cwd:w?.path})]})})]})}function _k({label:e,active:t,onClick:n}){return i.jsx("button",{type:"button",className:W("rounded-md px-2 py-1 text-xs transition-colors",t?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:n,children:e})}function ZP(e,t,n,s={}){const o=new Set,r=e.map(a=>{const l=`diff:${a.path}`;o.add(l);const c=t.has(l),d=n.get(l),u=s.ignoreLineEndings?a.oldText.replace(/\r\n/g,`
108
- `):a.oldText,h=s.ignoreLineEndings?a.newText.replace(/\r\n/g,`
109
- `):a.newText,p=!d||d.oldText!==u||d.newText!==h,f=p||!d?yo({name:a.path,contents:u},{name:a.path,contents:h}):d.fileDiff;(p||!d)&&(f.cacheKey=hv(a.path,u,h));const g=d?p||d.collapsed!==c?d.version+1:d.version:0;return n.set(l,{oldText:u,newText:h,collapsed:c,version:g,fileDiff:f}),{id:l,type:"diff",fileDiff:f,version:g,collapsed:c}});for(const a of n.keys())o.has(a)||n.delete(a);return r}const hae={theme:ka,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0},pae={height:"100%",overflow:"auto"},fae=new Set;function QP({result:e,loading:t}){const{t:n}=ne(),s=dc(hae),[o,r]=m.useState(!1),[a,l]=m.useState(!1),c=m.useRef(new Map);m.useEffect(()=>{let h=!0;return ha().then(()=>{h&&r(!0)},()=>{h&&l(!0)}),()=>{h=!1}},[]);const d=m.useMemo(()=>ZP(e?.ok?[e]:[],fae,c.current,{ignoreLineEndings:!0}),[e]),u=t?n("Loading..."):a?n("Could not load the diff viewer."):e?e.ok?o?e.oldText===e.newText?n("No text changes to display."):d[0]?.fileDiff.hunks.length===0?n("Only line endings changed."):null:n("Loading..."):n(e.error):n("Select a file to view its diff.");return i.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:u?i.jsx("div",{className:"flex h-full items-center justify-center px-4 py-8 text-center text-xs text-muted-foreground",role:"status",children:u}):i.jsx(xI,{className:"min-h-0 w-full flex-1",items:d,style:pae,options:s})})}function eA({tree:e,onToggle:t}){const{t:n}=ne(),s=n(e?"List view":"Tree view");return i.jsx(me,{variant:"ghost",size:"icon-xs",title:s,"aria-label":s,onClick:t,children:e?i.jsx(Ux,{className:"size-3.5"}):i.jsx(q6,{className:"size-3.5"})})}function tA({files:e,tree:t,children:n}){const s=m.useId(),[o,r]=m.useState(()=>new Set),a=m.useMemo(()=>{const c={name:"",path:"",directories:new Map,files:[]};if(!t)return c;for(const d of e){const u=d.path.split("/");let h=c;for(const p of u.slice(0,-1)){let f=h.directories.get(p);f||(f={name:p,path:h.path?`${h.path}/${p}`:p,directories:new Map,files:[]},h.directories.set(p,f)),h=f}h.files.push(d)}return c},[e,t]),l=c=>i.jsxs(i.Fragment,{children:[[...c.directories.values()].sort((d,u)=>d.name.localeCompare(u.name)).map(d=>{const u=!o.has(d.path),h=`${s}-${encodeURIComponent(d.path)}`;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",title:d.path,"aria-expanded":u,"aria-controls":u?h:void 0,className:"flex w-full min-w-0 items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",onClick:()=>r(p=>{const f=new Set(p);return f.has(d.path)?f.delete(d.path):f.add(d.path),f}),children:[i.jsx($n,{"aria-hidden":"true",className:W("size-3 shrink-0 text-muted-foreground",!u&&"-rotate-90")}),u?i.jsx(oi,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}):i.jsx(Nc,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:d.name})]}),u&&i.jsx("div",{id:h,className:"ml-3 min-w-0 border-l pl-1",children:l(d)})]},`directory:${d.path}`)}),c.files.slice().sort((d,u)=>d.path.localeCompare(u.path)).map(d=>i.jsx(m.Fragment,{children:n(d)},`file:${d.path}`))]});return t?l(a):e.map(c=>i.jsx(m.Fragment,{children:n(c)},c.path))}const mae={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 nA({file:e,selected:t,onSelect:n,actions:s,showDirectory:o=!0}){const{t:r}=ne(),a=e.path.lastIndexOf("/"),l=e.path.slice(a+1),c=e.path.slice(0,Math.max(0,a)),d=mae[e.status];return i.jsxs("div",{className:W("group flex min-w-0 items-center rounded-md pr-1 hover:bg-muted/50",t&&"bg-brand/10 dark:bg-brand/15"),children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",title:e.path,"aria-pressed":t,onClick:n,children:[i.jsx(jo,{"aria-hidden":"true",className:W("size-3.5 shrink-0",d.color)}),i.jsx("span",{className:W("truncate",!o&&"flex-1"),children:l}),o&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-[11px] text-muted-foreground",children:c}),i.jsxs("span",{className:W("shrink-0 font-mono text-[11px]",d.color),title:r(e.status),children:[i.jsx("span",{"aria-hidden":"true",children:d.label}),i.jsx("span",{className:"sr-only",children:r(e.status)})]})]}),s&&i.jsx("div",{className:"flex shrink-0 items-center opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",children:s})]})}function sA({title:e,hasSelection:t,navigation:n,actions:s,children:o}){const{t:r}=ne(),a=m.useId(),[l,c]=m.useState(!0),d=!t||l;return i.jsx("div",{className:"@container/git flex min-h-0 min-w-0 flex-1 flex-col",children:i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex-row",children:[i.jsxs("div",{className:W("flex min-h-0 min-w-0 flex-col overflow-hidden border-b @min-[720px]/git:h-full @min-[720px]/git:max-h-none @min-[720px]/git:flex-none @min-[720px]/git:border-r @min-[720px]/git:border-b-0",d?"flex-1 @min-[720px]/git:w-[280px]":"shrink-0 @min-[720px]/git:w-8",d&&t&&"max-h-[45%] basis-[45%] shrink-0"),children:[i.jsxs("div",{className:"flex shrink-0 items-center",children:[i.jsxs("button",{type:"button",className:"flex min-h-7 min-w-0 flex-1 items-center gap-1.5 px-2 py-1 text-left text-[11px] font-medium text-muted-foreground hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring","aria-expanded":d,"aria-controls":a,disabled:!t,title:r(d?"Collapse list":"Expand list"),onClick:()=>c(!d),children:[i.jsx($n,{className:W("size-3.5 shrink-0",!d&&"-rotate-90")}),i.jsx("span",{className:W("truncate",!d&&"@min-[720px]/git:hidden"),children:e})]}),d&&s&&i.jsx("div",{className:"mr-1 flex shrink-0 items-center",children:s})]}),i.jsx("div",{id:a,className:W("flex min-h-0 flex-1 flex-col overflow-hidden",!d&&"hidden"),children:n})]}),i.jsx("div",{className:W("min-h-0 min-w-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex",t?"flex":"hidden"),children:o})]})})}function gae({request:e,head:t,tree:n,onToggleTree:s}){const{t:o}=ne(),r=m.useId(),[a,l]=m.useState([]),[c,d]=m.useState(0),[u,h]=m.useState(0),[p,f]=m.useState(!1),[g,x]=m.useState(!0),[v,y]=m.useState(null),[b,w]=m.useState(null),[C,_]=m.useState([]),[N,k]=m.useState(!1),[S,A]=m.useState(null),[T,I]=m.useState(null),[P,D]=m.useState(null),[O,z]=m.useState(!1);return m.useEffect(()=>{let R=!0;return x(!0),y(null),window.electronAPI.git.history({...e,head:t??void 0,skip:c,limit:20}).then($=>{R&&($.ok?(l(X=>c===0?$.commits:[...X,...$.commits]),f($.hasMore)):y($.error))}).catch(()=>{R&&y("Could not load Git history.")}).finally(()=>{R&&x(!1)}),()=>{R=!1}},[e,t,c,u]),m.useEffect(()=>{if(!b)return;let R=!0;return k(!0),A(null),window.electronAPI.git.commitFiles({...e,hash:b.hash}).then($=>{R&&($.ok?_($.files):A($.error))}).catch(()=>{R&&A("Could not load the changed files.")}).finally(()=>{R&&k(!1)}),()=>{R=!1}},[e,b]),m.useEffect(()=>{if(!T||!b)return;let R=!0;return z(!0),window.electronAPI.git.commitDiff({...e,hash:b.hash,path:T}).then($=>{R&&D($)}).catch(()=>{R&&D({ok:!1,error:"Could not load the diff."})}).finally(()=>{R&&z(!1)}),()=>{R=!1}},[e,b,T]),i.jsxs(sA,{title:o("History"),hasSelection:T!==null,actions:i.jsx(eA,{tree:n,onToggle:s}),navigation:i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-1 pb-1",children:[a.map(R=>{const $=b?.hash===R.hash;return i.jsxs("div",{children:[i.jsxs("button",{type:"button","aria-expanded":$,"aria-controls":$?`${r}-${R.hash}`:void 0,className:W("flex w-full min-w-0 items-start gap-1.5 rounded-md px-2 py-1.5 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",$&&"bg-brand/10 dark:bg-brand/15"),title:`${R.subject}
110
- ${R.hash}
111
- ${R.author} · ${R.date}`,onClick:()=>{w($?null:R),_([]),k(!$),A(null),I(null),D(null),z(!1)},children:[i.jsx($n,{"aria-hidden":"true",className:W("mt-0.5 size-3.5 shrink-0 text-muted-foreground",!$&&"-rotate-90")}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[i.jsx("span",{className:"truncate text-xs",children:R.subject}),i.jsxs("span",{className:"flex min-w-0 gap-2 text-[11px] text-muted-foreground",children:[i.jsx("span",{className:"shrink-0 font-mono",children:R.hash.slice(0,7)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:R.author}),i.jsx("time",{className:"shrink-0",dateTime:R.date,children:new Date(R.date).toLocaleDateString()})]})]})]}),$&&i.jsx("div",{id:`${r}-${R.hash}`,className:"my-1 ml-3 border-l pl-1",children:N?i.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:o("Loading...")}):S?i.jsx("p",{role:"alert",className:"px-2 py-3 text-xs text-destructive",children:o(S)}):C.length===0?i.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:o("No file changes in this commit.")}):i.jsx(tA,{files:C,tree:n,children:X=>i.jsx(nA,{file:X,showDirectory:!n,selected:T===X.path,onSelect:()=>{T!==X.path&&(I(X.path),D(null),z(!0))}})},R.hash)})]},R.hash)}),g&&i.jsx("div",{className:"flex justify-center p-3",children:i.jsx(Xt,{className:"size-4 animate-spin","aria-label":o("Loading...")})}),v&&i.jsx("p",{role:"alert",className:"px-2 py-3 text-xs text-destructive",children:o(v)}),!g&&!v&&a.length===0&&i.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-5 text-center text-xs text-muted-foreground",children:o("No commits yet.")}),p&&!g&&!v&&i.jsx(me,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>d(a.length),children:o("Load more commits")}),v&&i.jsx(me,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>h(R=>R+1),children:o("Retry")})]}),children:[b&&T&&i.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:`${b.subject} · ${T}`,children:[b.hash.slice(0,7)," · ",T]}),i.jsx(QP,{result:P,loading:O})]})}function xae({conversationId:e,projectId:t,disabled:n,unavailable:s,editWriteKey:o}){const{t:r}=ne(),{visible:a}=QI(),l=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),[c,d]=m.useState(null),[u,h]=m.useState(!0),[p,f]=m.useState(null),[g,x]=m.useState(null),[v,y]=m.useState(null),[b,w]=m.useState("changes"),[C,_]=m.useState(!0),[N,k]=m.useState(""),[S,A]=m.useState(""),T=m.useRef(null),[I,P]=m.useState(null),[D,O]=m.useState(null),[z,R]=m.useState(null),[$,X]=m.useState(!1),[H,te]=m.useState(0),V=m.useRef(!1),Y=m.useRef(!1),q=m.useRef(0),ee=m.useRef(0),ge=m.useCallback(async(Z=!1)=>{if(!a||n||s||Y.current||ee.current!==0&&!Z)return;const ce=++q.current;ee.current=ce,Z&&h(!0);try{const De=await window.electronAPI.git.status(l);if(!V.current||ce!==q.current)return;De.ok?(d(De),f(null)):(d(null),f(De.error))}catch{V.current&&ce===q.current&&(d(null),f("Could not read Git status."))}finally{ee.current===ce&&(ee.current=0),V.current&&ce===q.current&&h(!1)}},[a,n,s,l]);m.useEffect(()=>{V.current=!0;const Z=()=>{ge()},ce=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&ge()},5e3);return window.addEventListener("focus",Z),()=>{V.current=!1,q.current+=1,window.clearInterval(ce),window.removeEventListener("focus",Z)}},[ge]),m.useEffect(()=>{ge(!0)},[ge,o]),m.useEffect(()=>{if(!I||!c)return;(I.staged?c.staged:c.unstaged).some(ce=>ce.path===I.path)||(P(null),R(null),X(!1))},[I,c]),m.useEffect(()=>{if(!a||!I||n||s||v!==null||b!=="changes")return;let Z=!0,ce=!1;const De=async()=>{if(!ce){ce=!0;try{const Ze=await window.electronAPI.git.fileDiff({...l,...I});Z&&R(Ze)}catch{Z&&R({ok:!1,error:"Could not load the diff."})}finally{ce=!1,Z&&X(!1)}}};De();const Oe=()=>{De()},Ne=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&De()},5e3);return window.addEventListener("focus",Oe),()=>{Z=!1,window.clearInterval(Ne),window.removeEventListener("focus",Oe)}},[a,l,I,H,n,s,b,v]);const Ce=async(Z,ce,De)=>{if(!(Y.current||n||s||u||!c)){Y.current=!0,q.current+=1,y(Z),x(null);try{const Oe=await ce();if(!V.current)return;Oe.ok?De?.():x(Oe.error)}catch{V.current&&x("Could not complete the Git operation.")}finally{Y.current=!1,V.current&&(y(null),te(Oe=>Oe+1),ge(!0),ie.getState().refreshWorktreeStatuses().catch(()=>{}))}}},Re=n||s||u||v!==null||!c,fe=!Re&&!!N.trim()&&!!c?.staged.length,U=(Z,ce)=>{I?.path===Z.path&&I.staged===ce||(R(null),X(!0),P({path:Z.path,staged:ce}))},oe=[{id:"staged",staged:!0,title:r("Staged changes"),files:c?.staged??[]},{id:"unstaged",staged:!1,title:r("Unstaged changes"),files:c?.unstaged.filter(Z=>Z.status!=="untracked")??[]},{id:"untracked",staged:!1,title:r("Untracked changes"),files:c?.unstaged.filter(Z=>Z.status==="untracked")??[]}],Se=S.trim().toLowerCase(),G=oe.map(Z=>({...Z,files:Z.files.filter(ce=>ce.path.toLowerCase().includes(Se))})),Q=G.reduce((Z,ce)=>Z+ce.files.length,0),ae=()=>{fe&&Ce("Commit",()=>window.electronAPI.git.commit({...l,message:N}),()=>k(""))};return i.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[c&&!n&&!s&&!p&&i.jsxs("div",{className:"flex shrink-0 items-center gap-1",role:"tablist","aria-label":r("Git views"),children:[i.jsxs(me,{role:"tab","aria-selected":b==="changes",variant:b==="changes"?"secondary":"ghost",size:"xs",onClick:()=>w("changes"),children:[i.jsx(x6,{className:"size-3.5"}),r("Changes")]}),i.jsxs(me,{role:"tab","aria-selected":b==="history",variant:b==="history"?"secondary":"ghost",size:"xs",onClick:()=>w("history"),children:[i.jsx(Yo,{className:"size-3.5"}),r("History")]})]}),i.jsx(zi,{className:"size-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-xs",title:c?.branch??void 0,children:c?.branch??r(c?"Detached HEAD":"Git")}),c?.upstream&&i.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",title:c.upstream,children:["↓",c.behind," ↑",c.ahead]}),c&&!c.upstream&&i.jsx("span",{className:"max-w-20 truncate text-[11px] text-muted-foreground",title:r("No upstream branch configured."),children:r("No upstream")}),i.jsx(or,{title:r("Fetch"),disabled:Re,onClick:()=>{Ce("Fetch",()=>window.electronAPI.git.fetch(l))},children:i.jsx(cc,{className:"size-3.5"})}),i.jsx(or,{title:r("Pull"),disabled:Re||!c?.upstream,onClick:()=>{Ce("Pull",()=>window.electronAPI.git.pull(l))},children:i.jsx(ah,{className:"size-3.5"})}),i.jsx(or,{title:r("Push"),disabled:Re||!c?.upstream,onClick:()=>{Ce("Push",()=>window.electronAPI.git.push(l))},children:i.jsx(fc,{className:"size-3.5"})}),i.jsx(or,{title:r("Refresh"),disabled:n||s||v!==null||u,onClick:()=>{te(Z=>Z+1),ge(!0)},children:i.jsx(Ko,{className:W("size-3.5",u&&!s&&!n&&"animate-spin")})})]}),v&&i.jsxs("p",{role:"status",className:"flex shrink-0 items-center gap-2 px-3 py-1 text-xs text-muted-foreground",children:[i.jsx(Xt,{className:"size-3 animate-spin"}),r(v),"…"]}),g&&i.jsx("p",{role:"alert",className:"max-h-24 shrink-0 overflow-auto whitespace-pre-wrap break-words border-b px-3 py-2 text-xs text-destructive",children:r(g)}),s||n||p||!c?i.jsx("div",{role:"status",className:"m-3 flex min-h-0 flex-1 items-center justify-center rounded-md border border-dashed p-4 text-center text-xs text-muted-foreground",children:r(s?"Git diff is not available for this workspace.":n?"Workspace is changing. Please wait.":p??"Loading...")}):b==="history"?i.jsx(gae,{request:l,head:c.head,tree:C,onToggleTree:()=>_(Z=>!Z)},`${c.head}:${H}`):i.jsxs(sA,{title:r("Changed files"),hasSelection:I!==null,actions:i.jsx(eA,{tree:C,onToggle:()=>_(Z=>!Z)}),navigation:i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"shrink-0 px-2 pb-1.5",children:i.jsxs(uh,{className:"text-xs",children:[i.jsx(ph,{ref:T,size:"sm",type:"search",value:S,onChange:Z=>A(Z.target.value),placeholder:r("Filter changed files…"),"aria-label":r("Filter changed files…")}),S.length>0&&i.jsx(hh,{align:"inline-end",children:i.jsx(me,{type:"button",variant:"ghost",size:"icon-xs",title:r("Clear"),"aria-label":r("Clear"),onClick:()=>{A(""),T.current?.focus()},children:i.jsx(dn,{className:"size-3.5"})})})]})}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-1 pb-1",children:[G.map(Z=>Z.files.length===0?null:i.jsxs("section",{className:"mb-2 last:mb-0",children:[i.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 text-[11px] font-medium text-muted-foreground",children:[i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[Z.title," ",i.jsx("span",{className:"ml-1 font-normal",children:Z.files.length})]}),i.jsx(or,{title:r(Z.staged?"Unstage all":"Stage all"),disabled:Re,onClick:()=>{Ce(Z.staged?"Unstage":"Stage",()=>window.electronAPI.git[Z.staged?"unstage":"stage"]({...l,paths:Z.files.map(ce=>ce.path)}))},children:Z.staged?i.jsx($0,{className:"size-3.5"}):i.jsx(as,{className:"size-3.5"})})]}),i.jsx(tA,{files:Z.files,tree:C,children:ce=>i.jsx(nA,{file:ce,showDirectory:!C,selected:I?.path===ce.path&&I.staged===Z.staged,onSelect:()=>U(ce,Z.staged),actions:i.jsxs(i.Fragment,{children:[!Z.staged&&i.jsx(or,{title:r(ce.status==="untracked"?"Delete untracked file":"Discard changes"),disabled:Re||ce.status==="conflicted",onClick:()=>O(ce),children:i.jsx(va,{className:"size-3.5"})}),i.jsx(or,{title:r(Z.staged?"Unstage":"Stage"),disabled:Re,onClick:()=>{Ce(Z.staged?"Unstage":"Stage",()=>window.electronAPI.git[Z.staged?"unstage":"stage"]({...l,paths:[ce.path]}))},children:Z.staged?i.jsx($0,{className:"size-3.5"}):i.jsx(as,{className:"size-3.5"})})]})})},Se)]},Z.id)),Q===0&&i.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-5 text-center text-xs text-muted-foreground",children:r(c.staged.length+c.unstaged.length===0?"Working tree clean.":"No matching files.")})]}),i.jsxs("div",{className:"flex shrink-0 items-end gap-1.5 border-t p-2",children:[i.jsx(ni,{size:"sm",rows:3,value:N,"aria-label":r("Commit message"),placeholder:r("Enter commit message…"),className:"min-w-0 flex-1 text-xs [&_textarea]:max-h-[calc(6lh+0.5rem)] [&_textarea]:min-h-[calc(3lh+0.5rem)] [&_textarea]:resize-none [&_textarea]:overflow-auto",disabled:v!==null,onChange:Z=>k(Z.target.value),onKeyDown:Z=>{(Z.ctrlKey||Z.metaKey)&&Z.key==="Enter"&&!Z.nativeEvent.isComposing&&(Z.preventDefault(),ae())}}),i.jsxs(me,{size:"xs",className:"mb-0.5 shrink-0",title:r("{{count}} staged files",{count:c.staged.length}),"aria-label":r("Commit"),disabled:!fe,onClick:ae,children:[i.jsx(L6,{className:"size-3.5"}),r("Commit"),c.staged.length>0&&i.jsx("span",{className:"font-mono text-[11px]",children:c.staged.length})]})]})]}),children:[I&&i.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:I.path,children:[r(I.staged?"Staged changes":"Unstaged changes")," · ",I.path]}),i.jsx(QP,{result:z,loading:I!==null&&$})]}),i.jsx(gs,{open:D!==null&&!Re,onOpenChange:Z=>{Z||O(null)},title:r(D?.status==="untracked"?"Delete untracked file":"Discard changes"),description:D?.status==="untracked"?r("Delete untracked file {{path}} permanently?",{path:D.path}):r("Restore {{path}} to its staged version? Unstaged changes will be lost.",{path:D?.path??""}),confirmLabel:r(D?.status==="untracked"?"Delete":"Discard"),onConfirm:()=>{D&&Ce("Discard",()=>window.electronAPI.git.discard({...l,paths:[D.path],confirmUntracked:D.status==="untracked"}))}})]})}function or({title:e,disabled:t,onClick:n,children:s}){return i.jsx(me,{variant:"ghost",size:"icon-xs",title:e,"aria-label":e,disabled:t,onClick:n,children:s})}const iA=28,vae={theme:ka,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0,itemMetrics:{diffHeaderHeight:iA}},bae={height:"max-content",overflow:"auto"},wae={files:[],snapshots:{}},Nk=[];function yae({conversationId:e,projectId:t}){const{t:n}=ne(),s=dc(vae),o=fn(te=>te.changesModeByConversation[e])??"all",r=fn(te=>te.setChangesMode),a=m.useRef(null),l=m.useRef(null),c=m.useRef(!1);m.useLayoutEffect(()=>{const te=a.current,V=l.current,Y=te?.querySelector('[aria-selected="true"]');!te||!V||!Y||(c.current||(V.style.transition="none"),V.style.transform=`translate(${Y.offsetLeft}px, ${Y.offsetTop}px)`,V.style.width=`${Y.offsetWidth}px`,V.style.height=`${Y.offsetHeight}px`,c.current||(V.offsetWidth,V.style.transition="",c.current=!0))},[o]);const d=fn(te=>te.snapshotsByConversation[e]),u=fn(te=>te.saveSnapshots),h=fn(te=>te.loadSnapshots),p=ie(te=>z_(te.conversations[e]?.messages??Nk)),f=ie(te=>te.workspaceRevisionByConversation[e]??0),g=ie(te=>!!te.conversations[e]?.workspaceMigrating),x=we(te=>te.projects.find(V=>V.id===t)),v=ie(te=>x?.kind==="scratch"?ox({kind:"scratch",canonicalPath:x.path,conversationId:e})??void 0:te.conversations[e]?.worktree?.path??x?.path),y=ie(te=>te.conversations[e]?.status==="running"),b=m.useRef([]),w=m.useMemo(()=>{const te=ie.getState().conversations[e],Y=Sr(te?.messages??Nk,y,te?.customEntries??[],v).flatMap(q=>q.kind!=="tool"?[]:q.name==="apply_patch"?(q.fileChanges??[]).map(ee=>({path:ee.path,edits:null,writeContent:null,fileChange:ee})):q.state!=="ok"||q.name!=="edit"&&q.name!=="write"?[]:q.summary?q.name==="edit"&&!(q.edits&&q.edits.length>0)?[]:q.name==="write"&&q.writeContent==null?[]:[{path:q.summary,edits:q.edits,writeContent:q.writeContent}]:[]);return AK(b.current,Y)?b.current:(b.current=Y,Y)},[e,p,v,y]),[C,_]=m.useState(!1),[N,k]=m.useState({});m.useEffect(()=>{let te=!0;return ha().then(()=>{te&&_(!0)}),()=>{te=!1}},[]),m.useEffect(()=>{o==="all"&&h(e)},[e,h,o]),m.useEffect(()=>{if(o!=="all"||g)return;const te=[...new Set(w.map(Y=>Y.path))];let V=!0;return Promise.all(te.map(async Y=>{const q=Gg(Y,v),ee=q?await window.electronAPI.files.read({conversationId:e,projectId:t,rel:q}):mj(Y)?await window.electronAPI.files.read({conversationId:e,projectId:t,path:Y}):null;return[Y,ee]})).then(Y=>{if(!V)return;const q=Object.fromEntries(Y);k(ee=>MK(ee,q)?ee:q)}),()=>{V=!1}},[e,o,t,v,w,g,f]);const S=m.useMemo(()=>d?RK({tools:w,snapshots:d,currentByPath:N}):wae,[w,d,N]);m.useEffect(()=>{if(o!=="all"||!d)return;const te=S.snapshots,V=Object.keys(te);V.length===Object.keys(d).length&&V.every(Y=>d[Y]===te[Y])||u(e,te)},[S.snapshots,e,o,u,d]);const A=S.files,T=S.incompletePaths??[],[I,P]=m.useState(()=>new Set),D=m.useCallback(te=>{P(V=>{const Y=new Set(V);return Y.delete(te)||Y.add(te),Y})},[]),O=m.useRef(new Map),z=m.useMemo(()=>ZP(A,I,O.current),[A,I]),R=z.length>0&&z.every(te=>te.collapsed),$=()=>P(R?new Set:new Set(z.map(te=>te.id))),X=m.useCallback(te=>i.jsx(Sae,{item:te,onToggle:()=>D(te.id)}),[D]),H=!C||!d;return i.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[i.jsxs("div",{ref:a,role:"tablist",className:"t-tabs",children:[i.jsx("span",{ref:l,"aria-hidden":"true",className:"t-tabs-pill"}),i.jsx(Tk,{active:o==="all",onClick:()=>r(e,"all"),children:n("Session")}),i.jsx(Tk,{active:o==="git",onClick:()=>r(e,"git"),children:n("Git")})]}),o==="all"&&z.length>0&&i.jsx("button",{type:"button",onClick:$,title:n(R?"Expand all":"Collapse all"),className:"ml-auto inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:bg-muted/50 hover:text-foreground",children:R?i.jsx(a_,{className:"h-3.5 w-3.5"}):i.jsx(B$,{className:"h-3.5 w-3.5"})})]}),i.jsx("div",{className:"min-h-0 flex-1",children:o==="git"?i.jsx(xae,{conversationId:e,projectId:t,disabled:g,unavailable:x?.kind==="ssh",editWriteKey:p},`${e}:${v}:${f}`):H||A.length===0&&T.length===0?i.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center text-sm text-muted-foreground",children:n(H?"Loading...":"No file changes in this conversation yet.")}):i.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[T.map(te=>i.jsxs("div",{className:"m-2 flex shrink-0 items-start gap-2 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(yr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate font-mono text-foreground",title:te,children:te}),i.jsx("div",{children:n("Diff unavailable because the original snapshot was truncated.")})]})]},te)),A.length>0&&i.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:i.jsx(xI,{className:"min-h-0 w-full",items:z,style:bae,options:s,renderCustomHeader:X})})]})})]})}function Sae({item:e,onToggle:t}){const n=e.type==="diff"?e.fileDiff:null;let s=0,o=0;for(const a of n?.hunks??[])s+=a.additionLines,o+=a.deletionLines;const r=n?.name??(e.type==="file"?e.file.name:"");return i.jsxs("button",{type:"button",onClick:t,style:{height:iA},className:"flex w-full min-w-0 items-center gap-1.5 px-2 text-left font-mono text-xs hover:bg-muted/50",children:[e.collapsed?i.jsx(un,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):i.jsx($n,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:r,children:r}),o>0&&i.jsxs("span",{className:"shrink-0 text-red-500",children:["-",o]}),s>0&&i.jsxs("span",{className:"shrink-0 text-green-600",children:["+",s]})]})}function Tk({active:e,onClick:t,children:n}){return i.jsx("button",{type:"button",role:"tab",onClick:t,"aria-selected":e,className:W("t-tab rounded-md px-2 py-1 text-xs transition-colors",e?"font-medium":"text-muted-foreground hover:bg-muted/50"),children:n})}function Cae(e,t){let n=0;for(const s of t)e.length>s.length&&e.endsWith(s)&&s.length>n&&(n=s.length);return n}function Pf(e,t){const n=(e.split("/").at(-1)??"").toLowerCase();return t.map(s=>({viewer:s,length:Cae(n,s.extensions)})).filter(s=>s.length>0).sort((s,o)=>o.length-s.length).map(s=>s.viewer)}const tl=e=>`${e.pluginId}:${e.id}`;let oA=[];const Pg=new Set;function Ik(e){oA=e;for(const t of Pg)t()}function kae(e){return Pg.add(e),()=>Pg.delete(e)}const Dk=()=>oA;function jae(){return m.useSyncExternalStore(kae,Dk,Dk)}function _ae({conversationId:e,projectId:t,onOpenFile:n,onClose:s,menu:o}){const{t:r}=ne(),a=m.useRef(0),[l,c]=m.useState(""),[d,u]=m.useState("names"),[h,p]=m.useState(null),[f,g]=m.useState(!1);return m.useEffect(()=>{if(!l.trim()){a.current+=1,p(null),g(!1);return}const v=++a.current;g(!0);const y=setTimeout(()=>{window.electronAPI.workspaceFiles.search({conversationId:e,projectId:t,query:l,mode:d}).then(b=>{v===a.current&&(p(b),g(!1))})},150);return()=>clearTimeout(y)},[e,d,t,l]),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs("div",{className:"flex flex-col gap-1 px-1 pb-1",children:[i.jsx(Zt,{size:"sm",autoFocus:!0,value:l,onChange:x=>c(x.target.value),onKeyDown:x=>{x.key==="Escape"&&s()},placeholder:r(d==="names"?"Search file names":"Search file contents"),"aria-label":r("Search")}),i.jsxs("div",{className:"flex gap-0.5",children:[i.jsx(Pk,{active:d==="names",onClick:()=>u("names"),label:r("File name"),icon:AO}),i.jsx(Pk,{active:d==="content",onClick:()=>u("content"),label:r("Content"),icon:jo})]})]}),i.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-1 pb-1",children:l.trim()?f&&!h?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Searching…")}):h&&!h.ok?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r(Tae(h.error))}):h?.ok&&h.hits.length===0?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("No results")}):h?.ok&&h.mode==="names"?h.hits.map(x=>{const v=Ac(x.name,!1);return i.jsx(Ek,{rel:x.relativePath,name:x.name,menu:o,onOpenFile:n,children:i.jsxs("button",{type:"button","data-search-hit":x.relativePath,className:"flex w-full items-start gap-1 rounded-sm px-1 py-0.5 text-left hover:bg-muted",onClick:()=>n(x.relativePath),children:[i.jsx(v,{className:W("mt-0.5 size-3.5 shrink-0",Mc(x.name,!1))}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs",children:x.name}),i.jsx("span",{className:"block truncate text-[10px] text-muted-foreground",children:x.relativePath})]})]})},x.relativePath)}):h?.ok&&h.mode==="content"?h.hits.map(x=>{const v=x.relativePath.split("/").pop()||x.relativePath;return i.jsx(Ek,{rel:x.relativePath,name:v,menu:o,onOpenFile:n,children:Nae(x,n)},rA(x))}):null:i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Type to search this workspace.")})})]})}function rA(e){return`${e.relativePath}:${e.line}:${e.column}`}function Nae(e,t){const n=e.relativePath.split("/").pop()||e.relativePath,s=Ac(n,!1);return i.jsxs("button",{type:"button","data-search-hit":rA(e),className:"flex w-full items-start gap-1 rounded-sm px-1 py-0.5 text-left hover:bg-muted",onClick:()=>t(e.relativePath),children:[i.jsx(s,{className:W("mt-0.5 size-3.5 shrink-0",Mc(n,!1))}),i.jsxs("span",{className:"min-w-0",children:[i.jsxs("span",{className:"block truncate text-xs",children:[n,i.jsxs("span",{className:"text-muted-foreground",children:[":",e.line]})]}),i.jsx("span",{className:"block truncate font-mono text-[10px] text-muted-foreground",children:e.content.trim()})]})]})}function Ek({rel:e,name:t,menu:n,onOpenFile:s,children:o}){return i.jsx(vh,{target:{kind:"file",rel:e,name:t},local:n.local,onNewFile:n.onNewFile,onNewFolder:n.onNewFolder,onView:s,onPreview:n.onPreview,onBrowser:n.onBrowser,onCopyPath:n.onCopyPath,onCopyRel:n.onCopyRel,onCopyFile:n.onCopyFile,onReveal:n.onReveal,onRename:n.onRename,onDelete:n.onDelete,onSend:n.onSend,children:o})}function Tae(e){switch(e){case"unsupported":return"Search is not available for SSH workspaces.";case"rg-missing":return"Search needs ripgrep (rg). Install it and make sure it is on PATH.";case"timeout":return"Search timed out. Try a more specific query or a smaller folder.";default:return"Could not complete the file action."}}function Pk({active:e,onClick:t,label:n,icon:s}){return i.jsxs(me,{type:"button",variant:"ghost",size:"sm",className:W("h-6 flex-1 px-1 text-xs",e&&"bg-muted"),"aria-pressed":e,onClick:t,children:[i.jsx(s,{className:"size-3.5"}),n]})}const Iae=/^data:image\/(png|jpe?g|gif|webp|bmp|x-icon|svg\+xml);/i;function Dae(){return{...zc,attributes:{...zc.attributes,source:[]},protocols:{...zc.protocols,src:[...zc.protocols?.src??[],"data"]}}}function Eae(){return e=>{MO(e,"element",t=>{if(t.tagName!=="img")return;const n=t.properties?.src;typeof n!="string"||!n.startsWith("data:")||Iae.test(n)||delete t.properties.src})}}const Pae=[FO],Aae=Dae(),Mae=[zO,[GO,Aae],Eae],Rae=({children:e,node:t,...n})=>i.jsx("p",{className:"my-1.5 leading-relaxed first:mt-0 last:mb-0",...n,children:e}),Lae=({children:e,node:t,...n})=>i.jsx("h1",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),Oae=({children:e,node:t,...n})=>i.jsx("h2",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),zae=({children:e,node:t,...n})=>i.jsx("h3",{className:"mt-2 mb-1 text-sm font-semibold",...n,children:e}),Gae=({children:e,node:t,...n})=>i.jsx("ul",{className:"my-1.5 list-disc pl-5 space-y-0.5",...n,children:e}),Fae=({children:e,node:t,...n})=>i.jsx("ol",{className:"my-1.5 list-decimal pl-5 space-y-0.5",...n,children:e}),Hae=({children:e,node:t,...n})=>i.jsx("th",{className:"whitespace-nowrap border-b border-border px-2 py-1 text-left font-medium",...n,children:e}),Bae=({children:e,node:t,...n})=>i.jsx("td",{className:"whitespace-nowrap border-b border-border/50 px-2 py-1",...n,children:e}),Vae={p:Rae,h1:Lae,h2:Oae,h3:zae,ul:Gae,ol:Fae,th:Hae,td:Bae};function $ae({text:e,baseDirRel:t,resolveImage:n,resolveRemoteImage:s}){const o=m.useRef(new Map),r=m.useMemo(()=>({...RO,...Vae,img:({node:c,src:d,alt:u,...h})=>i.jsx(Wae,{src:typeof d=="string"?d:void 0,alt:u,rest:h,baseDirRel:t,resolveImage:n,resolveRemoteImage:s,cache:o.current})}),[t,n,s]),a=m.useMemo(()=>({text:e,streaming:!1,searchQuery:"",activeNth:-1}),[e]);return i.jsx(LO.Provider,{value:a,children:i.jsx("div",{style:HO(BO),children:i.jsx(OO,{remarkPlugins:Pae,rehypePlugins:Mae,components:r,urlTransform:l=>l,children:e})})})}function Wae({src:e,alt:t,rest:n,baseDirRel:s,resolveImage:o,resolveRemoteImage:r,cache:a}){const l=e?VO(e):"unsupported",c=l==="local"&&e?`local:${W0(s,e)??""}`:e,[d,u]=m.useState(()=>l==="data"?e??null:c?a.get(c)??null:null);return m.useEffect(()=>{if(!e||l==="unsupported"){u(null);return}if(l==="data"){u(e);return}const h=c?a.get(c):void 0;if(h){u(h);return}let p=!0;return(l==="local"?(()=>{const g=W0(s,e);return g?o(g):Promise.resolve(null)})():r($O(e))).then(g=>{p&&(g&&c&&a.set(c,g),u(g))}),()=>{p=!1}},[e,l,s,o,r,a,c]),d?i.jsx("img",{...n,src:d,alt:t,className:"max-w-full rounded",loading:"lazy"}):null}function aA(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 kd(e){const t=aA(e);if(!t)return[];const n=t.split("/");if(n.length<=1)return[];const s=[];let o="";for(let r=0;r<n.length-1;r++)o=o?`${o}/${n[r]}`:n[r],s.push(o);return s}function Uae(e,t,n=!0){if(!n)return{refreshRels:[],nextSeen:null};const s=[],o=a=>{for(const l of a){if(l.kind==="tool-group"){o(l.children);continue}l.kind!=="tool"||l.state!=="ok"||l.name!=="write"||l.output===null&&l.durationMs===null||l.summary&&s.push({key:l.key,rel:aA(l.summary)})}};o(e);const r=new Set(s.map(a=>a.key));return t===null?{refreshRels:[],nextSeen:r}:{refreshRels:s.filter(a=>!t.has(a.key)&&a.rel).map(a=>a.rel),nextSeen:r}}const o0="\0preview";function lA(e){return`${e}${o0}`}function cA(e){return e.endsWith(o0)}function xr(e){return cA(e)?e.slice(0,-o0.length):e}function Kae(e,t){return e===t||e.startsWith(`${t}/`)}function Ag(e,t){return Kae(xr(e),t)}function qae(e,t){const n=e.trim();return!n||n===t?"cancel":"commit"}function jd(e,t,n){const s=cA(e),o=xr(e);let r=null;return o===t?r=n:o.startsWith(`${t}/`)&&(r=n+o.slice(t.length)),r==null?null:s?lA(r):r}function Yae(e){return e==="preview"?"source":"preview"}function Xae(e,t){const n=xr(e),s=[{id:"copy-path",rel:n,mode:"absolute"}];return t&&s.push({id:"reveal",rel:n}),s}function _d(e,t,n){return e.some(s=>s.epoch>n&&Ag(t,s.rel))}async function Jae(e,t){const{revision:n,migrating:s}=t();if(s)return null;const o=await e(),r=t();return r.migrating||r.revision!==n?null:o}function Ak(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 Mg(e,t,n,s){const o=e.indexOf(t);if(o<0)return[];switch(n){case"self":return[t];case"others":return e.filter(r=>r!==t);case"right":return e.slice(o+1);case"saved":return e.filter(r=>!0);case"all":return[...e]}}const Zae={theme:ka,disableFileHeader:!0,overflow:"scroll",preferredHighlighter:"shiki-js"};function Qae(e){return new JO(e)}function ele(e,t){return e?`${e}/${t}`:t}function Hr(e){return e.split("/").pop()||e}function tle(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}const Af=[];function nle({conversationId:e,projectId:t}){const{t:n}=ne(),s=dc(Zae),o=eD("files"),r=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),a=ie(K=>K.workspaceRevisionByConversation[e]??0),l=ie(K=>!!K.conversations[e]?.workspaceMigrating),c=m.useCallback(K=>Jae(()=>window.electronAPI.workspaceFiles.read({...r,rel:K}),()=>{const pe=ie.getState();return{revision:pe.workspaceRevisionByConversation[e]??0,migrating:!!pe.conversations[e]?.workspaceMigrating}}),[e,r]),[d,u]=m.useState(!1),[h,p]=m.useState([]),[f,g]=m.useState(null),x=jae(),v=m.useRef(x);v.current=x;const y=_a(),[b,w]=m.useState(!0),C=m.useCallback(K=>{g(K),w(!1)},[]);m.useEffect(()=>{f||w(!0)},[f]);const[_,N]=m.useState(0),[k,S]=m.useState(()=>new Set),[A,T]=m.useState(!1),[I,P]=m.useState(null),[D,O]=m.useState(null),[z,R]=m.useState(null),$=we(K=>K.projects.find(pe=>pe.id===t)),X=$?.kind!=="ssh",H=m.useRef(h);H.current=h;const te=m.useRef(f);te.current=f;const V=m.useRef(null),Y=m.useRef(null),q=m.useRef(null),ee=m.useRef(0),ge=m.useRef([]),Ce=m.useCallback(K=>{ee.current+=1,ge.current.push({epoch:ee.current,rel:K}),ge.current.length>200&&ge.current.splice(0,100)},[]);m.useEffect(()=>{const K=q.current;if(!K||!f)return;K.querySelector(`[data-file-tab="${CSS.escape(f)}"]`)?.scrollIntoView({inline:"nearest",block:"nearest"})},[f]),m.useEffect(()=>{let K=!0;return ha().then(()=>{K&&u(!0)}),()=>{K=!1}},[]);const Re=m.useCallback((K,pe)=>{p(Ie=>Ie.map(Ae=>Ae.rel===K?Ak(Ae,pe):Ae))},[]),fe=m.useCallback(K=>{ze({title:n(K==="exists"?"A file or folder with that name already exists.":K==="invalid-name"?"Invalid name.":"Could not complete the file action.")})},[n]),U=m.useCallback(async(K,pe)=>{if(H.current.find(nt=>nt.rel===K)){pe&&p(nt=>nt.map(be=>be.rel===K?{...be,viewMode:pe,viewer:void 0}:be)),C(K);return}const Ae=ee.current,He=await c(K);if(!(!He||_d(ge.current,K,Ae))){if(!He.ok){if(He.error!=="too-large"){fe(He.error);return}p(nt=>[...nt,{rel:K,contents:"",draft:"",version:0,dirty:!1,conflict:!1,tooLarge:!0}]),C(K);return}p(nt=>[...nt,{rel:K,contents:He.content,draft:He.content,version:0,dirty:!1,conflict:!1,viewMode:pe,viewer:pe?void 0:(()=>{const be=Pf(K,v.current).find(et=>et.default);return be?tl(be):void 0})()}]),C(K),window.electronAPI.workspaceFiles.watchStart({...r,rel:K})}},[fe,c,r,C]),[oe,Se]=m.useState(null),G=m.useCallback(K=>{const pe=H.current,Ie=pe.filter(Ae=>!K(Ae.rel));for(const Ae of pe)K(Ae.rel)&&window.electronAPI.workspaceFiles.watchStop({...r,rel:Ae.rel});p(Ie),g(Ae=>Ae&&Ie.some(He=>He.rel===Ae)?Ae:Ie.at(-1)?.rel??null)},[r]),Q=m.useCallback(K=>{G(pe=>pe===K)},[G]),ae=m.useCallback(K=>{if(H.current.find(Ie=>Ie.rel===K)?.dirty){Se({kind:"one",rel:K});return}Q(K)},[Q]);m.useEffect(()=>WO(e,()=>{const K=te.current;return!K||H.current.length===0?!1:(ae(K),!0)}),[e,ae]),m.useEffect(()=>()=>{for(const K of H.current)window.electronAPI.workspaceFiles.watchStop({...r,rel:K.rel})},[r]),m.useEffect(()=>{let K=!0;const pe=window.electronAPI.workspaceFiles.onChange(Ie=>{Ie.conversationId!==e||!H.current.find(He=>He.rel===Ie.rel)||c(Ie.rel).then(He=>{K&&He?.ok&&Re(Ie.rel,He.content)})});return()=>{K=!1,pe()}},[Re,e,c]);const Z=ie(K=>K.conversations[e]?.status==="running"),ce=ie(K=>$?.kind==="scratch"?ox({kind:"scratch",canonicalPath:$.path,conversationId:e})??void 0:K.conversations[e]?.worktree?.path??$?.path),De=ie(K=>K.conversations[e]?.historyBaseIndex),Oe=ie(K=>z_(K.conversations[e]?.messages??Af)),Ne=m.useMemo(()=>{const K=ie.getState().conversations[e];return Sr(K?.messages??Af,Z,K?.customEntries??[],ce).flatMap(pe=>pe.kind!=="tool"||pe.state!=="ok"?[]:pe.name!=="edit"&&pe.name!=="write"?[]:pe.summary?[pe.summary]:[]).join(`
112
- `)},[e,Oe,ce,Z]);m.useEffect(()=>{let K=!0;const pe=new Set(Ne?Ne.split(`
113
- `):[]);for(const Ie of pe)H.current.some(Ae=>Ae.rel===Ie)&&c(Ie).then(Ae=>{K&&Ae?.ok&&Re(Ie,Ae.content)});return()=>{K=!1}},[Re,c,Ne]);const Ze=m.useRef(null),bt=m.useRef(e),Ut=m.useRef(De),Et=m.useCallback(()=>N(K=>K+1),[]);m.useEffect(()=>{if(a===0||l)return;let K=!0;Et();for(const pe of H.current){const Ie=xr(pe.rel),Ae=ee.current;c(Ie).then(He=>{!K||!He||_d(ge.current,Ie,Ae)||p(nt=>nt.map(be=>be.rel===pe.rel?Ak(be,He.ok?He.content:null):be))})}return()=>{K=!1}},[Et,c,l,a]);const _t=m.useCallback(K=>{K&&S(pe=>{if(pe.has(K))return pe;const Ie=new Set(pe);return Ie.add(K),Ie})},[]),B=m.useCallback(K=>{K.length!==0&&S(pe=>{let Ie=!1;const Ae=new Set(pe);for(const He of K)!He||Ae.has(He)||(Ae.add(He),Ie=!0);return Ie?Ae:pe})},[]);m.useEffect(()=>{const K=ie.getState().conversations[e],pe=De;(bt.current!==e||Ut.current!==pe)&&(bt.current=e,Ut.current=pe,Ze.current=null);const Ie=Sr(K?.messages??Af,Z,K?.customEntries??[],ce),{refreshRels:Ae,nextSeen:He}=Uae(Ie,Ze.current,g_(K?.messages??[]));Ze.current=He,Ae.length!==0&&(B(Ae.flatMap(kd)),Et())},[Et,e,Oe,B,De,ce,Z]);const Te=m.useCallback(K=>{S(pe=>{const Ie=new Set(pe);return Ie.has(K)?Ie.delete(K):Ie.add(K),Ie})},[]),We=m.useCallback(K=>{_t(K),P({parent:K,kind:"file"})},[_t]),kt=m.useCallback(K=>{_t(K),P({parent:K,kind:"dir"})},[_t]),Gt=m.useCallback(async(K,pe=!1)=>{if(pe){await U(K,"preview");return}const Ie=lA(K);if(H.current.find(be=>be.rel===Ie)){C(Ie);return}const He=ee.current,nt=await c(K);if(!(!nt||_d(ge.current,K,He))){if(!nt.ok){fe(nt.error);return}p(be=>[...be,{rel:Ie,contents:nt.content,draft:nt.content,version:0,dirty:!1,conflict:!1,preview:!0}]),C(Ie)}},[fe,c,U,C]);m.useEffect(()=>UO(e,(K,pe,Ie)=>{V.current=pe?{rel:K,line:pe}:null;const Ae=Y.current,He=H.current.find(nt=>nt.rel===K);if(pe&&Ae?.rel===K&&te.current===K&&He?.viewMode!=="preview"&&!He?.viewer){V.current=null,Ae.editor.focus({lineNumber:pe});return}Ie==="markdown"&&!pe?Gt(K,!0):U(K,!pe&&Pf(K,v.current).some(nt=>nt.default)?void 0:"source")}),[e,U,Gt]);const de=m.useCallback(K=>window.electronAPI.workspaceFiles.readImage({...r,rel:K}).then(pe=>pe.ok?pe.dataUrl:null),[r]),mt=m.useCallback(K=>window.electronAPI.workspaceFiles.fetchRemoteImage({...r,url:K}).then(pe=>pe.ok?pe.dataUrl:null),[r]),Lt=m.useCallback(async K=>{const pe=await window.electronAPI.workspaceFiles.absPath({...r,rel:K});if(!pe.ok||!pe.local||!pe.fileUrl){fe(pe.ok?"unsupported":pe.error);return}const Ie=`browser:file:${e}:${K}`;ix({conversationId:e,tabId:Ie,title:Hr(K)});const Ae=await window.electronAPI.browser.navigate(Ie,e,pe.fileUrl);Ae.ok||fe(Ae.error)},[e,fe,r]),Fe=m.useCallback(async K=>{if(ie.getState().conversations[e]?.workspaceMigrating){ze({type:"error",title:n("Wait for the workspace operation to finish before saving.")});return}const pe=H.current.find(nt=>nt.rel===K);if(!pe||pe.preview||!pe.dirty)return;const Ie=pe.draft,Ae=ee.current,He=await window.electronAPI.workspaceFiles.write({...r,rel:K,content:Ie});if(!_d(ge.current,K,Ae)){if(!He.ok){fe(He.error);return}p(nt=>nt.map(be=>be.rel===K?{...be,contents:Ie,dirty:be.draft!==Ie,conflict:!1}:be))}},[e,fe,r,n]),Nt=m.useCallback(K=>{p(pe=>pe.map(Ie=>Ie.rel===K?{...Ie,viewMode:Yae(Ie.viewMode)}:Ie))},[]),Ft=m.useCallback((K,pe)=>{p(Ie=>Ie.map(Ae=>Ae.rel===K?{...Ae,viewer:pe}:Ae))},[]),on=m.useCallback((K,pe)=>{p(Ie=>Ie.map(Ae=>Ae.rel===K?{...Ae,draft:pe,dirty:pe!==Ae.contents}:Ae))},[]);m.useEffect(()=>{if(!o)return;const K=pe=>{!(Xf?pe.metaKey:pe.ctrlKey)||pe.key.toLowerCase()!=="s"||f&&(pe.preventDefault(),Fe(f))};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[f,Fe,o]);const re=h.find(K=>K.rel===f)??null,Ue=re&&!re.preview&&!re.tooLarge?Pf(re.rel,x):[],dt=re?.viewer?Ue.find(K=>tl(K)===re.viewer):void 0,Dt=m.useMemo(()=>({enabledSelectionAction:!0,renderSelectionAction(K){const pe=document.createElement("button");return pe.type="button",pe.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",pe.textContent=n("Send to conversation"),pe.addEventListener("mouseenter",()=>{pe.style.background="color-mix(in lab, currentColor 8%, transparent)"}),pe.addEventListener("mouseleave",()=>{pe.style.background="transparent"}),pe.addEventListener("mousedown",Ie=>Ie.preventDefault()),pe.addEventListener("click",()=>{const Ie=K.getSelectionText().trim(),Ae=f;if(!Ie||!Ae){K.close();return}const He=K.selection.start.line+1;let nt=K.selection.end.line+1;K.selection.end.character===0&&nt>He&&(nt-=1);const be=He===nt?`L${He}`:`L${He}-L${nt}`;Yl({kind:"file",id:`${Ae}#${be}`,label:`${Hr(Ae)}#${be}`,relativePath:`${Ae}#${be}`}),_o(),K.close()}),pe},onChange(K){const pe=f;if(!pe)return;const Ie=K.contents;p(Ae=>Ae.map(He=>He.rel===pe?{...He,draft:Ie,dirty:Ie!==He.contents}:He))},onAttach(K){if(!f)return;Y.current={rel:f,editor:K};const pe=V.current;pe?.rel===f&&(V.current=null,K.focus({lineNumber:pe.line}))}}),[f,n]),it=m.useCallback(async(K,pe)=>{const Ie=await window.electronAPI.workspaceFiles.rename({...r,rel:K,name:pe});if(!Ie.ok)return fe(Ie.error),!1;O(null);const Ae=Ie.rel;if(Ae){Ce(K);for(const He of H.current){if(He.preview||He.tooLarge)continue;const nt=jd(He.rel,K,Ae);nt!=null&&(window.electronAPI.workspaceFiles.watchStop({...r,rel:He.rel}),window.electronAPI.workspaceFiles.watchStart({...r,rel:nt}))}p(He=>He.map(nt=>{const be=jd(nt.rel,K,Ae);return be==null?nt:{...nt,rel:be}})),g(He=>He==null?He:jd(He,K,Ae)??He),S(He=>{let nt=!1;const be=new Set;for(const et of He){const tt=jd(et,K,Ae)??et;tt!==et&&(nt=!0),be.add(tt)}return nt?be:He})}return Et(),!0},[Et,fe,Ce,r]);return i.jsxs(KO,{createEditor:Qae,children:[i.jsxs("div",{className:"flex h-full min-h-0 bg-background",children:[i.jsxs("div",{className:W("flex shrink-0 flex-col overflow-hidden text-sm",y?b?"w-full":"hidden":"w-56 border-r"),children:[i.jsxs("div",{className:"flex justify-end gap-0.5 px-1 py-0.5",children:[i.jsx(me,{variant:"ghost",size:"icon-sm",onClick:()=>T(K=>!K),"aria-label":n("Search"),"aria-pressed":A,children:i.jsx(si,{})}),i.jsx(me,{variant:"ghost",size:"icon-sm",onClick:Et,"aria-label":n("Refresh"),children:i.jsx(Ko,{})})]}),A?i.jsx(_ae,{conversationId:e,projectId:t,onOpenFile:K=>{U(K)},onClose:()=>T(!1),menu:{local:X,onPreview:K=>{Gt(K)},onBrowser:K=>{Lt(K)},onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...r,rel:K}).then(pe=>{pe.ok||fe(pe.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...r,rel:K})},onNewFile:K=>{T(!1),B(kd(K)),We(K)},onNewFolder:K=>{T(!1),B(kd(K)),kt(K)},onRename:(K,pe)=>{T(!1),B(kd(K)),O({rel:K,name:pe,at:"tree"})},onDelete:(K,pe)=>R({rel:K,name:pe}),onSend:(K,pe)=>{Yl({kind:"file",id:K,label:pe,relativePath:K})}}}):i.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:i.jsx(vh,{target:{kind:"blank"},local:X,onNewFile:We,onNewFolder:kt,onCopyPath:()=>{},onCopyRel:()=>{},children:i.jsx("div",{className:"min-h-full",children:i.jsx(dA,{rel:"",depth:0,conversationId:e,projectId:t,treeEpoch:_,draft:I,renaming:D,local:X,expandedDirs:k,onToggleDir:Te,onOpen:U,onPreview:Gt,onBrowser:Lt,onCopyPath:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"absolute"})},onCopyRel:K=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:K,mode:"relative"})},onCopyFile:K=>{window.electronAPI.workspaceFiles.copyFile({...r,rel:K}).then(pe=>{pe.ok||fe(pe.error)})},onReveal:K=>{window.electronAPI.workspaceFiles.reveal({...r,rel:K})},onNewFile:We,onNewFolder:kt,onRenameStart:(K,pe)=>O({rel:K,name:pe,at:"tree"}),onDelete:(K,pe)=>R({rel:K,name:pe}),onDraftCancel:()=>P(null),onRenameCancel:()=>O(null),onDraftCommit:async(K,pe,Ie)=>{const He=await(pe==="dir"?window.electronAPI.workspaceFiles.mkdir:window.electronAPI.workspaceFiles.createFile)({...r,rel:K||void 0,name:Ie});return He.ok?(P(null),Et(),pe==="file"&&He.rel&&U(He.rel),!0):(fe(He.error),!1)},onRenameCommit:it})})})})]}),i.jsxs("div",{className:W("flex min-w-0 flex-1 flex-col",y&&b&&"hidden"),children:[h.length>0&&i.jsxs("div",{ref:q,className:"flex h-[36px] shrink-0 items-center gap-1 overflow-x-auto border-b px-2",children:[y&&i.jsx("button",{type:"button",className:"flex shrink-0 items-center rounded-md px-1 text-muted-foreground hover:bg-muted/50",onClick:()=>w(!0),"aria-label":n("Files"),title:n("Files"),children:i.jsx(qO,{className:"h-4 w-4"})}),h.map(K=>{const pe=D?.rel===K.rel&&D.at==="tab"&&!K.preview,Ie=i.jsxs("button",{type:"button","data-file-tab":K.rel,className:W("flex items-center gap-1.5 rounded-md px-2 py-1 text-xs",K.rel===f?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:()=>{pe||g(K.rel)},onDoubleClick:Ae=>{K.preview||(Ae.preventDefault(),Ae.stopPropagation(),O({rel:K.rel,name:Hr(K.rel),at:"tab"}))},children:[pe?i.jsx(Zu,{depth:0,kind:"file",variant:"tab",initial:D.name,onCancel:()=>O(null),onCommit:Ae=>it(K.rel,Ae)}):i.jsxs("span",{className:"max-w-36 truncate",children:[Hr(K.preview?xr(K.rel):K.rel),K.preview?` ${n("Preview")}`:"",K.dirty?"*":""]}),i.jsx("button",{type:"button",className:"text-muted-foreground hover:text-destructive",onClick:Ae=>{Ae.stopPropagation(),ae(K.rel)},children:"×"})]});return i.jsxs(go,{children:[i.jsx(xo,{render:Ie}),i.jsxs(vo,{className:"min-w-40",children:[Xae(K.rel,X).map(Ae=>Ae.id==="copy-path"?i.jsx($t,{onClick:()=>{window.electronAPI.workspaceFiles.copyPath({...r,rel:Ae.rel,mode:Ae.mode})},children:n("Copy Path")},Ae.id):i.jsx($t,{onClick:()=>{window.electronAPI.workspaceFiles.reveal({...r,rel:Ae.rel})},children:n(YO())},Ae.id)),i.jsx(mh,{}),!K.preview&&i.jsx($t,{onClick:()=>O({rel:K.rel,name:Hr(K.rel),at:"tab"}),children:n("Rename")}),i.jsx($t,{onClick:()=>ae(K.rel),children:n("Close")}),i.jsx($t,{onClick:()=>{const Ae=H.current,He=K.rel,nt=Ae.some(be=>be.rel!==He&&be.dirty);G(be=>be!==He&&!Ae.find(et=>et.rel===be)?.dirty),nt&&Se({kind:"others",rel:He})},children:n("Close others")}),i.jsx($t,{onClick:()=>{const Ae=H.current,He=Mg(Ae.map(be=>be.rel),K.rel,"right"),nt=He.some(be=>Ae.find(et=>et.rel===be)?.dirty);G(be=>He.includes(be)&&!Ae.find(et=>et.rel===be)?.dirty),nt&&Se({kind:"right",rel:K.rel})},children:n("Close tabs to the right")}),i.jsx($t,{onClick:()=>{const Ae=H.current;G(He=>!Ae.find(nt=>nt.rel===He)?.dirty)},children:n("Close saved")}),i.jsx($t,{onClick:()=>{const Ae=H.current,He=Ae.some(nt=>nt.dirty);G(nt=>!Ae.find(be=>be.rel===nt)?.dirty),He&&Se({kind:"all"})},children:n("Close all")}),i.jsx($t,{onClick:()=>G(Ae=>Ae!==K.rel),children:n("Force close others")}),i.jsx($t,{onClick:()=>G(()=>!0),children:n("Force close all")})]})]},K.rel)})]}),re?.conflict&&i.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b px-2 py-1 text-[11px]",children:[i.jsx("span",{children:n("This file changed on disk.")}),i.jsx("button",{type:"button",className:"underline",disabled:l,onClick:()=>{c(xr(re.rel)).then(K=>{K?.ok&&p(pe=>pe.map(Ie=>Ie.rel===re.rel?{...Ie,contents:K.content,draft:K.content,version:Ie.version+1,dirty:!1,conflict:!1}:Ie))})},children:n("Reload")})]}),i.jsxs("div",{className:"relative min-h-0 flex-1",children:[re&&!re.preview&&!re.tooLarge&&(mp(re.rel)||Ue.length>0)&&i.jsx("div",{className:"absolute top-2 right-2 z-10 flex gap-1",children:dt?i.jsxs(me,{type:"button",variant:"outline",size:"sm","aria-label":n("View Source"),onClick:()=>Ft(re.rel,void 0),children:[i.jsx(_m,{className:"h-3.5 w-3.5"}),n("View Source")]}):i.jsxs(i.Fragment,{children:[Ue.map(K=>i.jsxs(me,{type:"button",variant:"outline",size:"sm","aria-label":K.title,title:K.pluginName,onClick:()=>Ft(re.rel,tl(K)),children:[i.jsx(U0,{className:"h-3.5 w-3.5"}),K.title]},tl(K))),mp(re.rel)&&i.jsxs(me,{type:"button",variant:"outline",size:"sm","aria-label":re.viewMode==="preview"?n("View Source"):n("Preview"),onClick:()=>Nt(re.rel),children:[re.viewMode==="preview"?i.jsx(_m,{className:"h-3.5 w-3.5"}):i.jsx(U0,{className:"h-3.5 w-3.5"}),re.viewMode==="preview"?n("View Source"):n("Preview")]})]})}),!d||!re?i.jsx("div",{className:"flex h-full items-center justify-center px-3 text-center text-sm text-muted-foreground",children:n(d?"Open a file from the tree.":"Loading...")}):re.tooLarge?i.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center text-sm text-muted-foreground",children:n("This file is too large to open in the editor.")}):dt?i.jsx(JP,{pluginId:dt.pluginId,entry:dt.entry,title:dt.title,sessionId:e,file:{rel:re.rel,text:re.draft,onEdit:K=>on(re.rel,K)}},`${re.rel}:${tl(dt)}`):re.preview||re.viewMode==="preview"&&mp(re.rel)?i.jsx("div",{className:"h-full overflow-auto px-3 py-2 text-sm",children:i.jsx($ae,{text:re.preview?re.contents:re.draft,baseDirRel:tle(xr(re.rel)),resolveImage:de,resolveRemoteImage:mt})}):i.jsx(XO,{style:{height:"100%",overflow:"auto"},children:i.jsx(vj,{file:{name:Hr(re.rel),contents:re.draft},disableWorkerPool:!0,edit:!0,editorOptions:Dt,options:s},`${re.rel}:${re.version}`)})]})]})]}),i.jsx(gs,{open:oe!==null,onOpenChange:K=>{K||Se(null)},title:n("Unsaved changes"),description:oe?.kind==="one"?n("This file has unsaved changes. Close anyway?"):n("Some files have unsaved changes. Close anyway?"),confirmLabel:n("Close"),onConfirm:()=>{if(oe){if(oe.kind==="one"&&oe.rel)Q(oe.rel);else if(oe.kind==="others"&&oe.rel){const K=oe.rel;G(pe=>pe!==K)}else if(oe.kind==="right"&&oe.rel){const K=oe.rel,pe=new Set(Mg(H.current.map(Ie=>Ie.rel),K,"right"));G(Ie=>pe.has(Ie))}else G(()=>!0);Se(null)}}}),i.jsx(gs,{open:z!==null,onOpenChange:K=>{K||R(null)},title:n("Delete"),description:n("Delete {{name}} permanently?",{name:z?.name??""}),confirmLabel:n("Delete"),onConfirm:()=>{if(!z)return;const{rel:K}=z;window.electronAPI.workspaceFiles.remove({...r,rel:K}).then(pe=>{if(!pe.ok){fe(pe.error);return}Ce(K),G(Ie=>Ag(Ie,K)),S(Ie=>{let Ae=!1;const He=new Set;for(const nt of Ie){if(Ag(nt,K)){Ae=!0;continue}He.add(nt)}return Ae?He:Ie}),R(null),Et()})}})]})}function Zu({depth:e,kind:t,initial:n,onCancel:s,onCommit:o,variant:r="tree"}){const[a,l]=m.useState(n),c=m.useRef(null),d=m.useRef(!0),u=m.useRef(!1);m.useEffect(()=>{const p=window.setTimeout(()=>{const g=c.current;g&&(g.focus(),g.select())},0),f=window.setTimeout(()=>{d.current=!1},50);return()=>{window.clearTimeout(p),window.clearTimeout(f)}},[]);const h=p=>{if(!u.current){if(p==="commit"&&qae(a,n)==="commit"){u.current=!0,o(a.trim()).then(f=>{f||(u.current=!1,c.current?.focus())});return}u.current=!0,s()}};return i.jsx("input",{ref:c,className:r==="tab"?"max-w-36 rounded-sm border bg-background px-1 py-0 text-xs outline-none":"mx-1 my-0.5 w-[calc(100%-0.5rem)] rounded-sm border bg-background px-1 py-0.5 text-sm outline-none",style:r==="tree"?{marginLeft:8+e*12}:void 0,value:a,onChange:p=>l(p.target.value),onPointerDown:p=>p.stopPropagation(),onClick:p=>p.stopPropagation(),onBlur:()=>{if(d.current){c.current?.focus();return}h("commit")},onKeyDown:p=>{p.nativeEvent.isComposing||(p.key==="Escape"&&(p.preventDefault(),h("cancel")),p.key==="Enter"&&(p.preventDefault(),h("commit")))},"aria-label":t==="dir"?"New Folder":"New File"})}function dA({rel:e,depth:t,conversationId:n,projectId:s,treeEpoch:o,...r}){const[a,l]=m.useState(null);if(m.useEffect(()=>{let d=!0;return window.electronAPI.workspaceFiles.listDir({conversationId:n,projectId:s,rel:e||void 0}).then(u=>{d&&l(u.ok?u.entries:[])}),()=>{d=!1}},[n,s,e,o]),!a)return i.jsx("div",{className:"px-2 py-1 text-muted-foreground",children:"…"});const c=r.draft?.parent===e;return i.jsxs("div",{children:[a.map(d=>{const u=ele(e,d.name),h=r.expandedDirs.has(u);if(d.kind==="dir"){const f=r.renaming?.rel===u&&r.renaming.at==="tree"?i.jsx(Zu,{depth:t,kind:"dir",initial:d.name,onCancel:r.onRenameCancel,onCommit:g=>r.onRenameCommit(u,g)}):i.jsxs("button",{type:"button",className:"flex w-full items-center gap-1.5 px-2 py-1 text-left hover:bg-muted/60",style:{paddingLeft:8+t*12},onClick:()=>r.onToggleDir(u),children:[i.jsx(un,{className:W("h-3.5 w-3.5 shrink-0",h&&"rotate-90")}),(()=>{const g=Ac(d.name,!0,h);return i.jsx(g,{className:W("h-4 w-4 shrink-0",Mc(d.name,!0))})})(),i.jsx("span",{className:"truncate",children:d.name})]});return i.jsxs("div",{children:[i.jsx(vh,{target:{kind:"dir",rel:u,name:d.name},local:r.local,onNewFile:r.onNewFile,onNewFolder:r.onNewFolder,onCopyPath:r.onCopyPath,onCopyRel:r.onCopyRel,onReveal:r.onReveal,onRename:r.onRenameStart,onDelete:r.onDelete,children:f}),h&&i.jsx(dA,{rel:u,depth:t+1,conversationId:n,projectId:s,treeEpoch:o,...r})]},u)}return i.jsx(sle,{rel:u,name:d.name,depth:t,renaming:r.renaming?.rel===u&&r.renaming.at==="tree",handlers:r},u)}),c&&r.draft&&i.jsx(Zu,{depth:t,kind:r.draft.kind,initial:"",onCancel:r.onDraftCancel,onCommit:d=>r.onDraftCommit(e,r.draft.kind,d)})]})}function sle({rel:e,name:t,depth:n,renaming:s,handlers:o}){const{setNodeRef:r,listeners:a,isDragging:l}=px({id:`workspace-file:${e}`,data:{type:"workspace-file",relativePath:e,name:t}}),c=s?i.jsx(Zu,{depth:n,kind:"file",initial:t,onCancel:o.onRenameCancel,onCommit:d=>o.onRenameCommit(e,d)}):i.jsxs("button",{type:"button",ref:r,...a,style:{paddingLeft:20+n*12,opacity:l?.4:void 0},className:"flex w-full cursor-default items-center gap-1.5 px-2 py-1 text-left hover:bg-muted/60",onClick:()=>o.onOpen(e),children:[(()=>{const d=Ac(t,!1);return i.jsx(d,{className:W("h-4 w-4 shrink-0",Mc(t,!1))})})(),i.jsx("span",{className:"truncate",children:t})]});return i.jsx(vh,{target:{kind:"file",rel:e,name:t},local:o.local,onNewFile:o.onNewFile,onNewFolder:o.onNewFolder,onView:o.onOpen,onPreview:o.onPreview,onBrowser:o.onBrowser,onCopyPath:o.onCopyPath,onCopyRel:o.onCopyRel,onCopyFile:o.onCopyFile,onReveal:o.onReveal,onRename:o.onRenameStart,onDelete:o.onDelete,onSend:(d,u)=>{Yl({kind:"file",id:d,label:u,relativePath:d})},children:c})}function Mk(e){return e.closest(".dv-tabs-overflow-container")}function Rk(e){const t=new Map;for(const n of e.children){if(!n.classList.contains("dv-tab"))continue;const s=n.querySelector("[data-panel-id]")?.getAttribute("data-panel-id");s&&t.set(s,n)}return t}function ile(e){for(const t of e.children)if(t.classList.contains("dv-tab"))return!0;return!1}function ole(e){const t=e.closest(".dv-popover-anchor"),n=e.parentElement;if(t&&n&&n.parentElement===t){n.remove();return}e.remove()}function Lk(e,t){for(const n of t)n.parentElement===e&&n.remove();ile(e)||ole(e)}function rle({open:e,onClose:t,onFindNext:n,onFindPrevious:s,onClear:o,theme:r}){const{t:a}=ne(),l=m.useRef(null),[c,d]=m.useState(""),[u,h]=m.useState(!1),[p,f]=m.useState(!1),[g,x]=m.useState(!1),[v,y]=m.useState(null);m.useEffect(()=>{e?(l.current?.focus(),l.current?.select()):(o(),y(null))},[e,o]);const b=()=>({caseSensitive:u,wholeWord:p,regex:g}),w=N=>{if(!c){y(null);return}y(N==="next"?n(c,b()):s(c,b()))};if(!e)return null;const C=r?.background??"#1e1e1e",_=r?.foreground??"#d4d4d4";return i.jsxs("div",{className:"absolute top-2 right-2 z-10 flex items-center gap-1 rounded-md border px-2 py-1 shadow-lg",style:{backgroundColor:C,borderColor:`${_}30`},children:[i.jsx("input",{ref:l,value:c,onChange:N=>{const k=N.target.value;d(k),k?y(n(k,b())):(o(),y(null))},onKeyDown:N=>{N.key==="Enter"?(N.preventDefault(),w(N.shiftKey?"prev":"next")):N.key==="Escape"&&(N.preventDefault(),t())},placeholder:a("Search..."),className:W("w-40 bg-transparent text-sm outline-none placeholder:opacity-50",v===!1&&c&&"text-red-400"),style:{color:_}}),i.jsx("button",{type:"button",onClick:()=>h(N=>!N),className:W("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",u?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:_},title:a("Case sensitive"),children:"Aa"}),i.jsx("button",{type:"button",onClick:()=>f(N=>!N),className:W("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",p?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:_},title:a("Whole word"),children:"W"}),i.jsx("button",{type:"button",onClick:()=>x(N=>!N),className:W("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",g?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:_},title:a("Regular expression"),children:".*"}),i.jsx("div",{className:"mx-1 h-4 w-px",style:{backgroundColor:`${_}30`}}),i.jsx("button",{type:"button",onClick:()=>w("prev"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:_},title:a("Previous match"),children:i.jsx(f_,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:()=>w("next"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:_},title:a("Next match"),children:i.jsx($n,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:t,className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:_},title:a("Close"),children:i.jsx(dn,{className:"h-4 w-4"})})]})}function Ok(e,t){const n=oh(e);return t?nz(n):n}function ale({termId:e,conversationId:t,projectId:n,onTitle:s}){const{t:o}=ne(),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=we(O=>O.terminalTheme),g=we(O=>O.terminalFontFamily),x=we(O=>O.terminalFontSize),v=we(O=>O.terminalFontWeight),y=we(O=>O.terminalFontWeightBold),b=Qk()!==null,w=m.useRef(b);w.current=b;const[C,_]=m.useState(!1);m.useEffect(()=>{const O=r.current;if(!O)return;let z=!1,R=0,$;const X=()=>{if(z)return;if(!O.isConnected||O.clientWidth===0||O.clientHeight===0){R=requestAnimationFrame(X);return}const te=we.getState(),V=tz(e,O,{theme:Ok(te.terminalTheme,w.current),fontFamily:te.terminalFontFamily,fontSize:te.terminalFontSize,fontWeight:te.terminalFontWeight,fontWeightBold:te.terminalFontWeightBold});if(!V.opened){R=requestAnimationFrame(X);return}V.onTitle=q=>p.current?.(q);const Y=()=>{!O.isConnected||O.clientWidth===0||(V.fit.fit(),window.electronAPI.terminal.resize(e,V.term.cols,V.term.rows))};Y(),window.electronAPI.terminal.create({termId:e,conversationId:u.current,projectId:h.current,cols:V.term.cols,rows:V.term.rows}),V.term.focus(),a.current=V.term,$=new ResizeObserver(Y),$.observe(O)};document.fonts.load('14px "Enso Nerd Symbols"',"").then(X,te=>{console.warn("Failed to load terminal icon font",te),X()});const H=te=>{(te.metaKey||te.ctrlKey)&&te.key==="f"&&(te.preventDefault(),te.stopPropagation(),_(!0))};return O.addEventListener("keydown",H,!0),()=>{z=!0,cancelAnimationFrame(R),$?.disconnect(),O.removeEventListener("keydown",H,!0),a.current=null,ZO(e)}},[e]),m.useEffect(()=>{QO(Ok(f,b),g,x,v,y)},[f,g,x,v,y,b]);const N=m.useCallback((O,z)=>K0(e,O,"next",z),[e]),k=m.useCallback((O,z)=>K0(e,O,"prev",z),[e]),S=m.useCallback(()=>ez(e),[e]),A=()=>{const O=a.current?.getSelection().trim()??"";l.current=O,d(O.length>0)},T=()=>{const O=l.current||a.current?.getSelection().trim()||"";O&&(Mh(O),_o(),a.current?.clearSelection(),d(!1))},I=()=>{const O=l.current||a.current?.getSelection().trim()||"";O&&navigator.clipboard.writeText(O)},P=oh(f),D=i.jsx("div",{ref:r,"data-slot":"terminal-pane",className:"relative h-full w-full overflow-hidden p-2",style:{backgroundColor:P?.background,"--terminal-bg":P?.background},onContextMenu:A,children:i.jsx(rle,{open:C,onClose:()=>_(!1),onFindNext:N,onFindPrevious:k,onClear:S,theme:P})});return i.jsxs(go,{children:[i.jsx(xo,{render:D}),i.jsxs(vo,{className:"min-w-40",children:[i.jsx($t,{disabled:!c,onClick:I,children:o("Copy")}),i.jsx($t,{disabled:!c,onClick:T,children:o("Send to conversation")})]})]})}const uA={running:"bg-amber-500",completed:"bg-emerald-500",failed:"bg-destructive",cancelled:"bg-muted-foreground"},lle=[],cle={project:"Project",custom:"Custom",global:"Global",plugin:"Plugin",builtin:"Built-in"};function dle(e,t,n,s){const o=ie.getState(),r=o.conversations[e],a=we.getState(),l=a.projects.find(u=>u.id===r?.projectId);if(!r||!l)return!1;const c=au({defaultModel:a.defaultModel,...ru(l,a.projectGroups),lastProviderId:r.lastProviderId,lastModelId:r.lastModelId,providers:G_(),credentials:Fl(ko.getState().snapshot),virtualModels:a.virtualModels});if(c.source==="none")return ze({type:"warning",title:s("No usable model is available. Configure provider credentials and enable a model first.")}),!1;const d={};for(const u of t.args){const h=n[u.key]?.trim();h&&(d[u.key]=h)}return o.send(sz({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 ule({conversationId:e,preset:t,open:n,onToggle:s}){const{t:o}=ne(),[r,a]=m.useState({}),l=t.args.some(u=>u.required&&!u.default?.trim()&&!r[u.key]?.trim()),c=t.source==="builtin"?o(t.name):t.name,d=t.source==="builtin"?o(t.description):t.description;return i.jsxs("li",{className:"rounded-md border",children:[i.jsxs("button",{type:"button",className:"w-full px-2 py-1.5 text-left text-xs hover:bg-muted/60",onClick:s,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:c}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:o(cle[t.source])})]}),i.jsx("p",{className:"mt-0.5 line-clamp-2 text-muted-foreground",children:d})]}),n?i.jsxs("form",{className:"space-y-2 border-t px-2 py-2",onSubmit:u=>{u.preventDefault(),!(l||!dle(e,t,r,o))&&(a({}),s())},children:[t.args.map(u=>i.jsxs("label",{className:"block text-xs",children:[i.jsxs("span",{className:"text-muted-foreground",children:[t.source==="builtin"?o(u.label):u.label,u.required?" *":""]}),i.jsx(Zt,{size:"sm",className:"mt-1",value:r[u.key]??"",placeholder:u.default,onChange:h=>a(p=>({...p,[u.key]:h.target.value}))})]},u.key)),i.jsx("div",{className:"flex justify-end",children:i.jsxs(me,{type:"submit",size:"xs",disabled:l,children:[i.jsx($g,{}),o("Run")]})})]}):null]})}function hle({conversationId:e}){const{t}=ne(),[n,s]=m.useState([]),[o,r]=m.useState(null),a=we(u=>u.disabledWorkflowPresets),l=ie(u=>u.conversations[e]?.presetId),c=m.useCallback(()=>{let u=!1;return window.electronAPI.assets.listWorkflowPresets(e,l).then(h=>{u||s(h)}).catch(()=>{u||s([])}),()=>{u=!0}},[e,l]);m.useEffect(c,[c]);const d=n.filter(u=>u.source!=="builtin"||!a.includes(u.id));return i.jsxs("section",{children:[i.jsxs("div",{className:"mb-1.5 flex items-center gap-2",children:[i.jsx("h3",{className:"flex-1 text-xs font-medium text-muted-foreground",children:t("Presets")}),i.jsx(me,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Manage workflow presets"),title:t("Manage workflow presets"),onClick:()=>{window.electronAPI.window.openSettings({category:"workflows",rowId:"workflows.root"})},children:i.jsx(C_,{})}),i.jsx(me,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Refresh"),onClick:()=>c(),children:i.jsx(Ko,{})})]}),i.jsx("ul",{className:"space-y-1.5",children:d.map(u=>i.jsx(ule,{conversationId:e,preset:u,open:o===u.id,onToggle:()=>r(h=>h===u.id?null:u.id)},`${u.source}:${u.id}`))})]})}function ple(e,t){const n=ie.getState();n.activeId!==e&&n.selectConversation(e),n.selectTab(e,t)}function fle({conversationId:e,member:t}){const{t:n}=ne(),s=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:W("h-1.5 w-1.5 shrink-0 rounded-full",uA[t.status])}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),i.jsx("span",{className:"text-muted-foreground",children:n(t.status)})]}),t.prompt?i.jsx("p",{className:"mt-0.5 truncate pl-3.5 text-muted-foreground",children:t.prompt}):null,t.result?i.jsx("p",{className:"mt-0.5 line-clamp-3 whitespace-pre-wrap pl-3.5 text-foreground/80",children:t.result}):null]}),o=t.childId;return o?i.jsx("li",{children:i.jsx("button",{type:"button",className:"w-full rounded px-1 py-0.5 text-left text-xs hover:bg-muted/60",onClick:()=>ple(e,o),children:s})}):i.jsx("li",{className:"text-xs",children:s})}function mle({conversationId:e}){const{t}=ne(),n=Zf(r=>r.byConversation[e])??lle,s=Zf(r=>r.clearFinished),o=n.some(r=>r.status!=="running");return i.jsx("div",{className:"h-full overflow-auto bg-background p-3",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(hle,{conversationId:e}),o?i.jsx("div",{className:"flex justify-end",children:i.jsxs(me,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>s(e),children:[i.jsx(sx,{}),t("Clear finished runs")]})}):null,n.length===0?i.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:t("No workflow runs")}):null,n.map(r=>i.jsxs("section",{className:"rounded-md border px-3 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:W("h-2 w-2 shrink-0 rounded-full",uA[r.status])}),i.jsx("h3",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:r.name}),i.jsx("span",{className:"text-xs text-muted-foreground",children:t(r.status)}),r.status==="running"?i.jsx(me,{type:"button",variant:"ghost",size:"icon-xs",className:"text-muted-foreground hover:text-destructive","aria-label":t("Stop"),title:t("Stop"),onClick:()=>{window.electronAPI.agent.stopWorkflow(e,r.runId)},children:i.jsx(mc,{})}):null]}),i.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r.description}),i.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:t("{{count}} agents",{count:r.members.length})}),i.jsx("div",{className:"mt-2 space-y-2",children:$4(r.members).map((a,l,c)=>{const d=!!a.phase&&a.phase!==c[l-1]?.phase;return i.jsxs("div",{children:[i.jsxs("div",{className:"mb-1 flex items-center gap-2 text-xs",children:[d?i.jsx("span",{className:"font-medium",children:a.phase}):null,a.members.length>1?i.jsx("span",{className:"text-muted-foreground",children:t("Parallel")}):null]}),i.jsx("ul",{className:"space-y-1",children:a.members.map(u=>i.jsx(fle,{conversationId:e,member:u},u.seq))})]},`${a.batch}:${a.phase??""}`)})}),r.error?i.jsx("p",{className:"mt-2 text-xs text-destructive",children:r.error}):null,r.logs.length>0?i.jsx("p",{className:"mt-2 whitespace-pre-wrap text-xs text-muted-foreground",children:r.logs.join(`
114
- `)}):null]},r.runId))]})})}const ip=m.createContext({}),hA=m.createContext(!1);function r0({api:e,children:t}){const{conversationId:n}=m.useContext(ip);return n?i.jsx(PX,{dockConversationId:n,api:e,children:t}):t}function gle(e,t){const[n,s]=m.useState(!t);return m.useEffect(()=>{if(!t)return;const o=()=>{const a=t.element.closest(".dv-dockview")?.getBoundingClientRect(),l=t.element.getBoundingClientRect();s(!!a&&Math.abs(l.top-a.top)<1&&Math.abs(l.right-a.right)<1)};o();const r=e.onDidLayoutChange(o);return()=>r.dispose()},[e,t]),n}function pA(e,t){const n=e.panels.length;return n===0?t:`${t} ${n+1}`}function fA(e,t,n,s){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:pA(e,s),params:{conversationId:t,projectId:n}})}function mA(e,t,n,s){const o=e.getPanel("changes");if(o){o.focus();return}e.addPanel({id:"changes",component:"changes",title:s,params:{conversationId:t,projectId:n}})}function xle(e){return i.jsx(ale,{termId:e.api.id,conversationId:e.params.conversationId,projectId:e.params.projectId,onTitle:t=>e.api.setTitle(t)})}function vle(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(r0,{api:e.api,children:i.jsx(yae,{conversationId:t,projectId:n})})}function gA(e,t,n,s){const o=e.getPanel("files");if(o){o.focus();return}e.addPanel({id:"files",component:"files",title:s,params:{conversationId:t,projectId:n}})}function ble(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(r0,{api:e.api,children:i.jsx(nle,{conversationId:t,projectId:n})})}function xA(e,t,n,s){const o=e.panels.filter(r=>r.id.startsWith("btw:")).length;e.addPanel({id:`btw:${crypto.randomUUID()}`,component:"btw",title:o===0?s:`${s} ${o+1}`,params:{conversationId:t,projectId:n}})}function wle(e){const{conversationId:t}=e.params;return t?i.jsx(uae,{conversationId:t,panelApi:e.api}):null}function vA(e,t,n,s,o){const r=`browser:${crypto.randomUUID()}`,a=e.getPanel(r);if(a){a.focus();return}e.addPanel({id:r,component:"browser",title:s,params:{conversationId:t,projectId:n}})}function yle(e){const{conversationId:t}=e.params;return t?i.jsx(r0,{api:e.api,children:i.jsx(tD,{conversationId:t,panelApi:e.api})}):null}function bA(e,t,n,s){const o=e.getPanel("workflow");if(o){o.focus();return}e.addPanel({id:"workflow",component:"workflow",title:s,params:{conversationId:t,projectId:n}})}function a0(e){return we(t=>az(t,e))}function wA(e,t,n,s,o){const r=`plugin:${s.pluginId}:${s.id}`,a=e.getPanel(r);if(a){a.focus();return}e.addPanel({id:r,component:"plugin",title:s.title,params:{conversationId:t,projectId:n,pluginId:s.pluginId,viewId:s.id},renderer:"always",...o?{position:{referenceGroup:o}}:{}})}function Sle(e){const{conversationId:t,pluginId:n,viewId:s}=e.params;return m.useEffect(()=>{e.api.renderer!=="always"&&e.api.setRenderer("always")},[e.api]),!n||!s?null:i.jsx(dae,{pluginId:n,viewId:s,sessionId:t??null})}function Cle(e){const{conversationId:t}=e.params;return t?i.jsx(mle,{conversationId:t}):null}function kle(e,t){const n=e.group.panels.map(r=>r.id),s=new Set(Mg(n,e.id,t)),o=[];for(const r of[...e.group.panels])s.has(r.id)&&(r.api.close(),o.push(r.id));return o}function jle(e){const{t}=ne(),n=m.useRef(null),[s,o]=m.useState(e.api.isActive),[r,a]=m.useState(e.api.title??""),[l,c]=m.useState(e.params.favicon??null),[d,u]=m.useState(!1);m.useEffect(()=>{const g=e.api.onDidActiveChange(()=>o(e.api.isActive)),x=e.api.onDidTitleChange(()=>a(e.api.title??"")),v=e.api.onDidParametersChange(y=>{const b=y&&typeof y=="object"&&"favicon"in y?y.favicon??null:e.api.getParameters()?.favicon??null;c(b??null),u(!1)});return()=>{g.dispose(),x.dispose(),v.dispose()}},[e.api]);const h=e.api.id==="browser"||e.api.id.startsWith("browser:"),p=g=>{const x=n.current?Mk(n.current):null,v=x?Rk(x):null,y=kle(e.api,g);!x||!v||Lk(x,y.flatMap(b=>{const w=v.get(b);return w?[w]:[]}))},f=i.jsxs("div",{ref:g=>{n.current=g},"data-side-tab":!0,"data-panel-id":e.api.id,"data-active":s||void 0,className:W("group/tab relative flex min-w-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",s?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),children:[e.api.id==="changes"?i.jsx($x,{className:"h-3 w-3 shrink-0"}):e.api.id==="files"?i.jsx(oi,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("btw:")?i.jsx(Cr,{className:"h-3 w-3 shrink-0"}):e.api.id==="workflow"?i.jsx(Hg,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("plugin:")?i.jsx(rh,{pluginId:e.api.id.split(":")[1]??"",className:"h-3 w-3 shrink-0"}):h&&l&&!d?i.jsx("img",{src:l,alt:"",className:"h-3 w-3 shrink-0",onError:()=>u(!0)}):h?i.jsx(bo,{className:"h-3 w-3 shrink-0"}):i.jsx(Uo,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-32 truncate",children:r}),i.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/tab:opacity-100",onPointerDown:g=>g.stopPropagation(),onClick:g=>{g.preventDefault(),g.stopPropagation();const x=Mk(g.currentTarget),v=x?Rk(x).get(e.api.id):void 0;e.api.close(),x&&v&&Lk(x,[v])},children:i.jsx(dn,{className:"h-3 w-3"})})]});return i.jsxs(go,{children:[i.jsx(xo,{render:f}),i.jsxs(vo,{className:"min-w-40",children:[i.jsx($t,{onClick:()=>p("self"),children:t("Close")}),i.jsx($t,{onClick:()=>p("others"),children:t("Close others")}),i.jsx($t,{onClick:()=>p("right"),children:t("Close tabs to the right")}),i.jsx($t,{onClick:()=>p("all"),children:t("Close all")})]})]})}function yA({onNewTerminal:e,onNewChanges:t,onNewFiles:n,onNewBrowser:s,onNewBtw:o,onNewWorkflow:r,onNewPluginView:a,compact:l}){const{t:c}=ne(),d=O_();return i.jsxs($i,{children:[i.jsxs(Wi,{className:W("flex items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",l?"h-6 w-6 rounded p-1 hover:bg-muted":"h-8 gap-1.5 border border-dashed px-3 text-sm hover:border-solid"),"aria-label":c("New tab"),children:[i.jsx(as,{className:"h-4 w-4"}),!l&&i.jsx("span",{children:c("New tab")})]}),i.jsxs(Ui,{align:l?"end":"center",className:"min-w-36",children:[i.jsxs(mn,{onClick:e,children:[i.jsx(Uo,{className:"h-4 w-4"}),c("Terminal")]}),i.jsxs(mn,{onClick:t,children:[i.jsx($x,{className:"h-4 w-4"}),c("Changes")]}),i.jsxs(mn,{onClick:n,children:[i.jsx(oi,{className:"h-4 w-4"}),c("Files")]}),i.jsxs(mn,{onClick:s,children:[i.jsx(bo,{className:"h-4 w-4"}),c("Browser")]}),i.jsxs(mn,{onClick:o,children:[i.jsx(Cr,{className:"h-4 w-4"}),c("Btw")]}),r?i.jsxs(mn,{onClick:r,children:[i.jsx(Hg,{className:"h-4 w-4"}),c("Workflow")]}):null,a?d.map(u=>i.jsxs(mn,{onClick:()=>a(u),children:[i.jsx(rh,{pluginId:u.pluginId,className:"h-4 w-4"}),u.title]},`${u.pluginId}:${u.id}`)):null]})]})}function SA({containerApi:e,group:t}){const{t:n}=ne(),{conversationId:s,projectId:o}=m.useContext(ip),r=fn(f=>f.fullscreen),a=fn(f=>f.toggleFullscreen),l=a0(o),c=_a(),d=m.useContext(hA),u=gle(e,t),h=fn(f=>f.toggleOpen),p=gh()==="windows";return i.jsxs("div",{className:"flex h-full items-center gap-0.5",children:[i.jsx(yA,{compact:!0,onNewTerminal:()=>{if(t){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:pA(e,n("Terminal")),params:{conversationId:s,projectId:o},position:{referenceGroup:t}});return}fA(e,s,o,n("Terminal"))},onNewChanges:()=>mA(e,s,o,n("Changes")),onNewFiles:()=>gA(e,s,o,n("Files")),onNewBrowser:()=>vA(e,s,o,n("Browser")),onNewBtw:()=>{if(t){const f=e.panels.filter(g=>g.id.startsWith("btw:")).length;e.addPanel({id:`btw:${crypto.randomUUID()}`,component:"btw",title:f===0?n("Btw"):`${n("Btw")} ${f+1}`,params:{conversationId:s,projectId:o},position:{referenceGroup:t}});return}xA(e,s,o,n("Btw"))},onNewWorkflow:l?()=>bA(e,s,o,n("Workflow")):void 0,onNewPluginView:f=>wA(e,s,o,f,t)}),i.jsx("button",{type:"button",className:W("flex h-6 w-6 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",c&&"hidden"),onClick:a,"aria-label":n(r?"Exit side panel fullscreen":"Expand side panel"),title:n(r?"Exit side panel fullscreen":"Expand side panel"),children:r?i.jsx(dz,{className:"h-3.5 w-3.5"}):i.jsx(uz,{className:"h-3.5 w-3.5"})}),d&&u&&i.jsx("button",{type:"button",className:"ml-1 flex h-8 w-8 items-center justify-center rounded-md text-foreground transition-colors hover:bg-muted",onClick:h,"aria-label":n("Toggle side panel"),title:n("Toggle side panel"),children:i.jsx(JN,{className:"h-4 w-4"})}),d&&u&&p&&i.jsx("span",{"aria-hidden":!0,className:"shrink-0",style:{width:`calc(100vw - env(titlebar-area-width, calc(100vw - ${hz}px)) - 19px)`}})]})}function _le(e){const{t}=ne(),{conversationId:n,projectId:s}=m.useContext(ip),o=a0(s);return i.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i.jsx("div",{className:"enso-side-dock-header flex shrink-0 items-center justify-end border-b bg-background px-2 py-1",children:i.jsx(SA,{containerApi:e.containerApi})}),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-3 bg-background px-6 text-center",children:[i.jsx("p",{className:"text-sm text-muted-foreground",children:t("No tabs yet. Create one to get started.")}),i.jsx(yA,{onNewTerminal:()=>fA(e.containerApi,n,s,t("Terminal")),onNewChanges:()=>mA(e.containerApi,n,s,t("Changes")),onNewFiles:()=>gA(e.containerApi,n,s,t("Files")),onNewBrowser:()=>vA(e.containerApi,n,s,t("Browser")),onNewBtw:()=>xA(e.containerApi,n,s,t("Btw")),onNewWorkflow:o?()=>bA(e.containerApi,n,s,t("Workflow")):void 0,onNewPluginView:r=>wA(e.containerApi,n,s,r)})]})]})}function Nle(e){return i.jsx(SA,{containerApi:e.containerApi,group:e.group})}const zk={terminal:xle,changes:vle,files:ble,browser:yle,btw:wle,workflow:Cle,plugin:Sle};function Tle(){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 Ile({conversationId:e,hidden:t}){const n=ie(s=>s.conversations[e]?.projectId);return n?i.jsx("div",{className:W("absolute inset-0",t&&"hidden"),children:i.jsx(Dle,{conversationId:e,projectId:n})}):null}function Dle({conversationId:e,projectId:t}){const n=Tle(),s=a0(t),[o,r]=m.useState(null);m.useEffect(()=>{s||o?.getPanel("workflow")?.api.close()},[o,s]);const a=l=>{lz(e,l.api);const c=fn.getState().layouts[e],d=nae(c,new Set(Object.keys(zk)));let u=!!c&&!d;if(d)try{l.api.fromJSON(d)}catch{u=!0}l.api.onDidLayoutChange(()=>{const h=l.api.toJSON();u&&Object.keys(h.panels??{}).length===0||(u=!1,fn.getState().saveLayout(e,h))}),l.api.onDidRemovePanel(h=>{if(!(h.id==="changes"||h.id==="files"||h.id.startsWith("plugin:"))){if(h.id==="browser"||h.id.startsWith("browser:")){window.electronAPI.browser.closeTab(h.id);return}if(h.id.startsWith("btw:")){ie.getState().disposeBtwConversation(h.id.slice(4));return}cz(h.id),window.electronAPI.terminal.dispose(h.id)}}),r(l.api)};return i.jsx(ip.Provider,{value:{conversationId:e,projectId:t},children:i.jsx("div",{className:"enso-side-dock h-full",children:i.jsx(YP,{components:zk,defaultTabComponent:jle,watermarkComponent:_le,rightHeaderActionsComponent:Nle,theme:n?Poe:Aoe,onReady:a})})})}function Ele({width:e,resizing:t=!1,card:n=!1,titleRow:s=!1}){const{t:o}=ne(),r=ie(D=>D.activeId),a=fn(D=>r?!!D.uiByConversation[r]?.open:!1),l=_a(),d=fn(D=>D.fullscreen)||l&&a;m.useEffect(()=>{const D=window.electronAPI.browser.onReveal(z=>{L_(z.conversationId)||ix({conversationId:z.conversationId,tabId:z.tabId})}),O=window.electronAPI.browser.onTabClosed(z=>{iz(z.conversationId,z.tabId)});return window.electronAPI.browser.restoreTabs(),()=>{D(),O()}},[]),m.useEffect(()=>Zf.subscribe((D,O)=>{for(const[z,R]of Object.entries(D.byConversation)){if(O.byConversation[z]===R)continue;const $=R.find(X=>X.status==="running");$&&oz({conversationId:z,runId:$.runId,title:o("Workflow")})}}),[o]),m.useEffect(()=>ie.subscribe((D,O)=>{for(const z of Object.keys(O.conversations))D.conversations[z]||rz(z)}),[]);const u=ie(D=>D.activeId),[h,p]=m.useState([]),f=ie(D=>h.filter(O=>!!D.conversations[O]).join(`
115
- `)),[g,x]=m.useState(d),[v,y]=m.useState(0),b=n&&!s?F_:Jg,w=o_(e,v,b),C=m.useRef(null),[_,N]=m.useState({id:u,from:u});u!==_.id&&N({id:u,from:_.id}),d&&!g&&x(!0),m.useEffect(()=>{const D=C.current?.parentElement;if(!D)return;const O=()=>{const R=getComputedStyle(D);y(D.clientWidth-parseFloat(R.paddingLeft)-parseFloat(R.paddingRight))};O();const z=new ResizeObserver(O);return z.observe(D),()=>z.disconnect()},[]),m.useEffect(()=>{_.from!==_.id&&N(D=>D.from===D.id?D:{...D,from:D.id})},[_.from,_.id]);const k=g?void 0:Math.max(0,w-(a&&!n?1:0)),S=u,A=rX({resizing:t,conversationId:_.id??void 0,previousConversationId:_.from??void 0}),T=d?v||w:a?w:0,I=!!s&&!l;S&&!h.includes(S)&&p(D=>D.includes(S)?D:[...D,S]);const P=f===""?[]:f.split(`
116
- `);return i.jsxs(i.Fragment,{children:[g&&!l?i.jsx("div",{className:"shrink-0",style:{width:w},"aria-hidden":!0}):null,i.jsxs(Os.aside,{ref:C,"data-slot":"side-panel",initial:!1,animate:{width:T},style:g?{position:"absolute"}:{position:"relative",maxWidth:`max(0px, calc(100% - ${i_+b}px))`},transition:$I({skip:A,cover:g,targetW:T}),onAnimationComplete:()=>{d||x(!1)},className:W("flex min-h-0 flex-col",I&&a?"overflow-clip [overflow-clip-margin:4px]":"overflow-hidden",a&&(I||!g)?"bg-transparent":I?"":"bg-background",g?I?"top-px right-[8px] bottom-[8px]":n?"top-0 right-[8px] bottom-[8px]":"inset-y-0 right-0":"shrink-0",I?W("no-drag -mt-[44px]",g?"rounded-b-[10px]":"rounded-br-[10px]"):n?W("rounded-[10px]",a&&"shadow-surface"):a&&"border-l"),"data-enso":"side-panel","data-title-row":I||void 0,children:[a&&(I||!g)?i.jsx(Mle,{titleRow:I,full:g}):null,a&&!g&&k!==void 0?i.jsx("div",{"aria-hidden":!0,className:W("pointer-events-none absolute right-0 bottom-0 bg-background",s?"top-[44px]":"top-0"),style:{left:k}}):null,i.jsx("div",{className:W("relative flex h-full min-h-0 flex-col",g&&"w-full",!a&&"invisible"),style:{width:k,clipPath:I?g?Ale:Ple:void 0},children:P.length>0?i.jsx("div",{className:"relative min-h-0 flex-1",children:i.jsx(hA.Provider,{value:I,children:P.map(D=>i.jsx(Ile,{conversationId:D,hidden:D!==S},D))})}):i.jsx("div",{className:"flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground",children:o("Select a conversation to use the side panel.")})})]})]})}const Ple="shape(from 0 0, hline to 100%, vline to 44px, hline to calc(100% - 10px), arc to 100% 54px of 10px cw, vline to calc(100% - 10px), arc to calc(100% - 10px) 100% of 10px cw, hline to 0, close)",Ale="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 Mle({titleRow:e,full:t}){const n=m.useRef(null),s=fn(o=>o.browserHoles);return m.useLayoutEffect(()=>{const o=n.current;if(!o)return;const{left:r,top:a}=o.getBoundingClientRect(),l=Object.values(s).map(u=>({...u,x:u.x-r,y:u.y-a})),c=tT(l)??"";o.style.clipPath=c;const d=o.closest('[data-enso="side-panel"]');return d&&(c?d.style.setProperty("--enso-side-panel-holes-clip",c):d.style.removeProperty("--enso-side-panel-holes-clip")),()=>{d?.style.removeProperty("--enso-side-panel-holes-clip")}},[s]),i.jsxs(i.Fragment,{children:[e&&i.jsx("div",{"aria-hidden":!0,className:W("pointer-events-none absolute inset-x-0 top-[44px] bottom-0 shadow-surface",t?"rounded-[10px]":"rounded-r-[10px]"),style:t?void 0:{clipPath:"inset(-24px -24px -24px 0)"}}),i.jsx("div",{ref:n,"aria-hidden":!0,className:W("pointer-events-none absolute inset-x-0 bottom-0 bg-background",e?W("top-[44px]",t?"rounded-[10px]":"rounded-r-[10px]"):"top-0")})]})}function l0(){return uo()&&ie.persist.hasHydrated()&&we.persist.hasHydrated()}function Gk(e,t){l0()&&e>0&&(async()=>(t&&await ie.getState().refreshWorktreeStatuses(),await ie.getState().autoArchiveStaleConversations()))()}function Fk(e){!l0()||!(e>0)||ie.getState().autoDeleteStaleArchived()}function Rle(){const e=we(s=>s.autoArchiveIdleDays),t=we(s=>s.autoArchiveMergedWorktrees),n=we(s=>s.autoDeleteArchivedDays);m.useEffect(()=>{if(l0()){Gk(e,t),Fk(n);return}const s=()=>{Gk(e,t),Fk(n)},o=[ie.persist.onFinishHydration(s),we.persist.onFinishHydration(s)];return()=>{for(const r of o)r()}},[e,t,n])}function Lle(){const e=ie(t=>Math.min(999,pz(t.order,Ah(t.conversations))));m.useEffect(()=>{window.electronAPI.app.setBadgeCount(e)},[e])}function Ole(){const e=we(n=>n.generationStallTimeoutMin),{t}=ne();m.useEffect(()=>{if(e<=0)return;const n=new Set,s=new Set,o=new Map,r=setInterval(()=>{if(!uo())return;const a=e*6e4,l=Date.now(),c=ie.getState();for(const d of Object.values(c.conversations)){d.status==="running"&&d.lastOutputAt&&o.delete(d.id);const u=(d.coworkerIds??[]).some(p=>!!c.conversations[p]?.spawning),h=fz({shouldAbort:mz({status:d.status,spawning:d.spawning,lastOutputAt:vz(d,c.conversations),now:l,timeoutMs:a,hasLiveWork:gz({...xz(d),spawningCoworker:u})}),status:d.status,spawning:d.spawning,pendingRetry:s.has(d.id),attempts:o.get(d.id)??0});if(h==="abort"){if(n.has(d.id))continue;n.add(d.id),s.add(d.id),window.electronAPI.agent.abort(d.id).finally(()=>{n.delete(d.id)}),ze(Hk(d,t("No output for {{minutes}} minutes — retrying",{minutes:e})));continue}if(h==="retry"){s.delete(d.id),o.set(d.id,(o.get(d.id)??0)+1),c.retry(d.id);continue}h==="give-up"&&(s.delete(d.id),o.delete(d.id),ze(Hk(d,t("Stopped after repeated stalls"))))}},1e3);return()=>clearInterval(r)},[e,t])}function Hk(e,t){const n=(e.coworkerName||e.title).split(`
117
- `)[0].trim();return n?{type:"warning",title:n,description:t}:{type:"warning",title:t}}const zle=3e4;function Gle(e,t=zle){return e()?Promise.resolve(!0):new Promise(n=>{const s=l=>{clearTimeout(a);for(const c of r)c();n(l)},o=()=>e()&&s(!0),r=[ie.subscribe(o),we.subscribe(o)],a=setTimeout(()=>s(e()),t)})}function Fle(){return ie.persist.hasHydrated()&&we.persist.hasHydrated()}function Hle(){const{t:e}=ne();m.useEffect(()=>{if(!uo())return;const t=()=>{hT(async()=>{if(!await Gle(Fle))return;const s=await window.electronAPI.window.takeOpenFolders().catch(()=>[]);let o=!1;for(const r of s)try{if(!await mT(r)){ze({type:"error",title:e("Failed to add project")});continue}o=!0}catch(a){ze({type:"error",title:e("Failed to add project"),description:a instanceof Error?a.message:String(a)})}o&&Xx()})},n=window.electronAPI.window.onOpenFolderRequested(t);return t(),n},[e])}async function Ble(e,t){const n=[];for(const s of e){const o=t.conversation(s);!o||o.archived||(!o.started&&!o.spawning&&await t.resume(s),!await t.waitUntil(()=>{const a=t.conversation(s);return!!(a?.started&&!a.spawning)})||t.conversation(s)?.status==="running")||(await t.retry(s)).ok&&n.push(s)}return n}const Vle=3e4;function Bk(e,t=Vle){return e()?Promise.resolve(!0):new Promise(n=>{const s=l=>{clearTimeout(a);for(const c of r)c();n(l)},o=()=>e()&&s(!0),r=[ie.subscribe(o),ko.subscribe(o),we.subscribe(o)],a=setTimeout(()=>s(e()),t)})}function $le(){const e=ko.getState().snapshot.availability.status;return ie.persist.hasHydrated()&&we.persist.hasHydrated()&&e!=="unloaded"&&e!=="loading"}function Wle(){const{t:e}=ne();m.useEffect(()=>{uo()&&(async()=>{const t=await window.electronAPI.updater.takeInterruptedSessions().catch(()=>[]);if(t.length===0||!await Bk($le))return;const n=ie.getState,s=await Ble(t,{conversation:o=>n().conversations[o],resume:o=>n().resumeConversation(o),retry:o=>window.electronAPI.agent.retry(o,{unfinishedOnly:!0}),waitUntil:Bk});s.length!==0&&ze({type:"info",title:e("Continued {{count}} conversation(s) interrupted by the update",{count:s.length})})})()},[e])}const Vk="enso-win",CA="enso-win-flush",Nd="enso-win-pending",$k="enso-win-native";function Ule(e,t,n){return{maximized:n.maximized?e.maximized:t.maximized,fullscreen:n.fullscreen?e.fullscreen:t.fullscreen}}function Kle(e,t){return e||t}function qle(e,t){document.documentElement.classList.toggle(CA,Kle(e,t))}function Yle(){m.useEffect(()=>{if(window.electronAPI?.env.platform!=="win32")return;const e=document.documentElement;e.classList.add(Vk,Nd),e.classList.add($k);let t={maximized:!1,fullscreen:!1};const n={maximized:0,fullscreen:0};let s=!1,o=0,r;const a=()=>qle(t.maximized,t.fullscreen),l=window.electronAPI.window,c=()=>{const p=++o,f={...n};Promise.all([l.isMaximized(),l.isFullScreen()]).then(([g,x])=>{s||p!==o||(t=Ule(t,{maximized:g,fullscreen:x},{maximized:n.maximized!==f.maximized,fullscreen:n.fullscreen!==f.fullscreen}),e.classList.remove(Nd),a())}).catch(()=>{!s&&p===o&&e.classList.remove(Nd)})};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(Vk,CA,Nd,$k)}},[])}function Xle(e,t){const n=new Set,s=[];for(const o of e)for(const r of o.interceptBreakers??[]){const a=`${o.id}:${r.event}:${r.until}`;n.add(a),t.has(a)||s.push({pluginName:o.name,event:r.event})}t.clear();for(const o of n)t.add(o);return s}function Wk(e){const t=e.permissions.includes("composer.draft")?"1":"0";return`${e.id}\0${e.version}\0${e.build}\0${e.renderer??""}\0${t}`}function kA(e,t){try{t?.dispose()}catch(n){console.warn(`[plugin] ${e} 渲染模块卸载失败`,n)}}async function Jle(e,t,n,s){if(!s())return;const o=new Map;for(const a of t)a.state==="enabled"&&a.renderer&&o.set(a.id,{...a,renderer:a.renderer});const r=[];for(const[a,l]of e){const c=o.get(a);(!c||Wk(c)!==l.key)&&r.push(a)}for(const a of r)kA(a,e.get(a)),e.delete(a);await Promise.allSettled([...o.values()].filter(a=>!e.has(a.id)).map(async a=>{if(!s())return;let l;try{l=await n(a)}catch(u){if(!s())return;console.warn(`[plugin] ${a.id} 渲染模块加载失败`,u);return}if(!s()){l.dispose();return}const c=Wk(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 xs=(e,t)=>({ok:!1,code:e,error:t});async function Zle(e,t){if(e.op==="focusSession"){const a=e.payload.sessionId;if(typeof a!="string"||!a)return xs("BAD_REQUEST","缺少会话 id");const l=t.conversation(a);if(l)return t.focus(l.parentId??a,a),{ok:!0,value:null};const c=a.indexOf("::");if(c>0){const d=a.slice(0,c);return t.conversation(d)?(t.focusSubagent(d,a),{ok:!0,value:null}):xs("NOT_FOUND","会话不在本窗口")}return xs("NOT_FOUND","会话不在本窗口")}if(e.op==="openChildRun"){const a=e.payload.parentId,l=e.payload.childId;return typeof a!="string"||!a?xs("BAD_REQUEST","缺少父会话 id"):typeof l!="string"||!l?xs("BAD_REQUEST","缺少子会话 id"):t.conversation(a)?(t.openChildRun(a,l),{ok:!0,value:null}):xs("NOT_FOUND","会话不在本窗口")}if(e.op==="focusSubagent"){const a=e.payload.sessionId,l=e.payload.agentId;return typeof a!="string"||!t.conversation(a)?xs("NOT_FOUND","会话不在本窗口"):typeof l!="string"||!l?xs("BAD_REQUEST","缺少子代理 id"):(t.focusSubagent(a,l),{ok:!0,value:null})}if(e.op==="ensureSession"){const a=t.conversation(e.sessionId);if(!a)return xs("NOT_FOUND","会话不在本窗口");if(a.parentId)return xs("UNSUPPORTED","子会话随主会话恢复");const l=await t.ensure(e.sessionId);return l?xs("SESSION_FAILED",l):{ok:!0,value:null}}if(e.op==="openPluginView"){if(!t.conversation(e.sessionId))return xs("NOT_FOUND","会话不在本窗口");const{pluginId:a,viewId:l,title:c}=e.payload;return typeof a!="string"||!a||typeof l!="string"||!l||typeof c!="string"||!c?xs("BAD_REQUEST","缺少视图标识"):(t.openPluginView?.(e.sessionId,{pluginId:a,viewId:l,title:c}),{ok:!0,value:null})}const n=t.conversation(e.sessionId);if(!n)return xs("NO_SESSION","发起调用的会话不在本窗口");const s=typeof e.payload.presetId=="string"?e.payload.presetId:void 0,o=await t.create(n.projectId,s);if(!o)return xs("CREATE_FAILED","新建会话失败");const r=e.payload.text;return typeof r=="string"&&r&&t.prefill(o,r),{ok:!0,value:{sessionId:o}}}const Qle={conversation:e=>ie.getState().conversations[e]??null,focus:(e,t)=>{const n=ie.getState();n.selectConversation(e),t!==e&&n.selectTab(e,t)},focusSubagent:(e,t)=>ie.getState().focusSubagent(e,t),openChildRun:(e,t)=>ie.getState().openChildRun(e,t),create:(e,t)=>ie.getState().newConversation(e,t?{presetId:t}:void 0),prefill:Sz,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??"无法启动会话:请检查默认模型与登录状态"},openPluginView:(e,t)=>Cz({conversationId:e,...t})};function ece(){return m.useEffect(()=>{const e=jz(()=>lee(ie.getState()));let t=0;const n=new Map,s=new Set,o=()=>{const l=++t;window.electronAPI.extensionPlugins.list().then(async c=>{if(l!==t)return;for(const{pluginName:u,event:h}of Xle(c,s))ze({type:"warning",title:`插件 ${u} 的检查连续失败,已临时放行`,description:`${h} 事件 30 秒内不再经过该插件;详情见设置里的插件日志`});const d=c.filter(u=>u.state==="enabled");wz(Object.fromEntries(c.flatMap(u=>u.icon?[[u.id,u.icon]]:[]))),q0(yz(c)),oC(Nee(c)),Y0(d.flatMap(u=>u.views.map(h=>({pluginId:u.id,pluginName:u.name,...h})))),Ik(d.flatMap(u=>(u.fileViewers??[]).map(h=>({pluginId:u.id,pluginName:u.name,...h})))),lC(d.flatMap(u=>u.triggers.filter(h=>h.symbol==="#").map(h=>({pluginId:u.id,name:h.name})))),await Jle(n,c,u=>kz(u.id,u.renderer,e,{draft:u.permissions.includes("composer.draft")}),()=>l===t)})};o();const r=window.electronAPI.extensionPlugins.onChanged(o),a=window.electronAPI.extensionPlugins.onDraftRequest(l=>{if(l.op==="focusSession"||l.op==="focusSubagent"||l.op==="openChildRun"||l.op==="createSession"||l.op==="ensureSession"||l.op==="openPluginView"){Zle(l,Qle).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,...bz(l)})});return()=>{t+=1,r(),a(),q0([]),lC([]),Y0([]),Ik([]),oC([]);for(const[l,c]of n)kA(l,c);n.clear()}},[]),null}function tce(e,t=[]){return JSON.stringify({pinnedOrder:t,entries:e.map(n=>{const{updatedAt:s,...o}=n;return o})})}function nce(e){return JSON.stringify(e)}function sce(e,t,n=[]){const s=_z(e,t).map(r=>({id:r.id,name:r.name,models:r.models.map(a=>({id:a.id,...a.label?{label:a.label}:{}}))})),o=n.filter(r=>r.enabled&&s.some(a=>a.id===r.primary.providerId&&a.models.some(l=>l.id===r.primary.modelId)));return o.length>0&&s.unshift({id:S_,name:"Auto",models:o.map(r=>({id:r.id,label:r.name}))}),s}function ice(e,t,n=[]){const s=sce(e,t,n),o=t.availability.status,r=o==="unloaded"||o==="loading",a=e.some(l=>l.enabled&&l.oauthAccountKey);return{entries:s,settled:!(r&&a&&s.length===0)}}const oce=300;let Td=null,Uk=!1,Rg=null;function rce(){const e=we.getState(),t=ie.getState(),n=$v(e.projects,Mi($d)),s=new Set(e.projects.filter(w=>w.kind==="scratch").map(w=>w.id)),o=n.filter(w=>w.kind!=="scratch"),r=new Set(Mi(co)),a=Iz(Dz(e.language),"Temporary chats"),l=new Map(e.projects.map(w=>[w.id,w.kind==="scratch"?a:Ns(w)])),c=new Map(e.projects.map(w=>[w.id,w.path])),d=new Map(e.projects.map(w=>[w.id,w.kind])),u=w=>{const C=(w.parentId?t.conversations[w.parentId]:void 0)??w;return d.get(C.projectId)==="scratch"?ox({kind:"scratch",canonicalPath:c.get(C.projectId)??"",conversationId:C.id})??void 0:C.worktree?.path??c.get(w.projectId)},h=e.skills.filter(w=>w.enabled!==!1).map(w=>({name:`/skill:${w.name}`,description:w.description})),p=w=>{const C=DE(w.occupancy,w.contextWindow);return{id:w.id,title:w.parentId&&w.coworkerName||w.title,projectName:l.get(w.projectId)??"",projectId:w.projectId,...u(w)?{cwd:u(w)}:{},status:w.spawning?"running":w.status,updatedAt:H_(w),...w.parentId?{parentId:w.parentId}:{},...w.pinned===!0?{pinned:!0}:{},...w.archived===!0?{archived:!0}:{},...w.lastProviderId?{providerId:w.lastProviderId}:{},...w.lastModelId?{modelId:w.lastModelId}:{},...w.reasoningEnabled!==void 0?{reasoningEnabled:w.reasoningEnabled}:{},...w.thinkingLevel?{thinkingLevel:w.thinkingLevel}:{},...w.unread===!0?{unread:!0}:{},...w.pendingAsks&&w.pendingAsks.length>0?{pendingAskCount:w.pendingAsks.length}:{},...w.pendingApprovals&&w.pendingApprovals.length>0?{pendingApprovalCount:w.pendingApprovals.length}:{},...w.queuedMessages?.length?{queued:w.queuedMessages.map(_=>({id:_.id,text:_.text,..._.images?.length?{hasImages:!0}:{}}))}:{},...w.goal?{goal:{text:w.goal.text,status:w.goal.status,...w.goal.note?{note:w.goal.note}:{},autoTurns:w.goal.autoTurns}}:{},...h.length?{slashCommands:h}:{},...C?{context:C}:{},...w.usageTotals?{usageTotals:w.usageTotals}:{}}},f=t.order.map(w=>t.conversations[w]).filter(w=>!!w),g=new Set(t.order),x=Object.values(t.conversations).filter(w=>!!(w?.parentId&&g.has(w.parentId))),v=[...f,...x].map(p),y=e.scratchSessionsEnabled?v:v.filter(w=>!s.has(w.projectId)),b=ice(G_(),ko.getState().snapshot,e.virtualModels);return{catalog:y,pinnedOrder:Mi(Tm),projects:o.map(w=>({...Ise(w),...r.has(w.id)?{archived:!0}:{}})),projectGroups:e.projectGroups,providers:b.entries,providersSettled:b.settled,projectPaths:e.projects.map(w=>({id:w.id,path:w.path})),theme:e.theme,terminal:oh(e.terminalTheme),terminalFontFamily:e.terminalFontFamily,compactReadOnlyTools:e.compactReadOnlyTools,expandLiveEdits:e.expandLiveEdits,expandLiveReasoning:e.expandLiveReasoning,autoCollapseTurns:e.autoCollapseTurns,collapseCompletedActivity:e.collapseCompletedActivity,collapseLiveActivity:e.collapseLiveActivity,pinUnfinishedTodos:e.pinUnfinishedTodos}}function ace(e){return nce({catalog:tce(e.catalog,e.pinnedOrder??[]),projects:e.projects,projectGroups:e.projectGroups,providers:e.providers,providersSettled:e.providersSettled,projectPaths:e.projectPaths,theme:e.theme,terminal:e.terminal,terminalFontFamily:e.terminalFontFamily,compactReadOnlyTools:e.compactReadOnlyTools,expandLiveEdits:e.expandLiveEdits,expandLiveReasoning:e.expandLiveReasoning,autoCollapseTurns:e.autoCollapseTurns,collapseCompletedActivity:e.collapseCompletedActivity,collapseLiveActivity:e.collapseLiveActivity,pinUnfinishedTodos:e.pinUnfinishedTodos})}function lce(){return ie.persist.hasHydrated()&&we.persist.hasHydrated()}function no(){Td&&clearTimeout(Td),Td=setTimeout(()=>{if(Td=null,!uo()||!lce())return;const e=rce(),t=ace(e);t!==Rg&&(Rg=t,window.electronAPI.pair.pushCatalog(e))},oce)}function cce(){Uk||(Uk=!0,no(),ie.persist.onFinishHydration(no),we.persist.onFinishHydration(no),ie.subscribe((e,t)=>{(e.conversations!==t.conversations||e.order!==t.order)&&no()}),ko.subscribe((e,t)=>{e.snapshot!==t.snapshot&&no()}),Nz.subscribe((e,t)=>{e.snapshot!==t.snapshot&&no()}),we.subscribe((e,t)=>{(e.projects!==t.projects||e.projectGroups!==t.projectGroups||e.providers!==t.providers||e.theme!==t.theme||e.terminalTheme!==t.terminalTheme||e.terminalFontFamily!==t.terminalFontFamily||e.compactReadOnlyTools!==t.compactReadOnlyTools||e.expandLiveEdits!==t.expandLiveEdits||e.expandLiveReasoning!==t.expandLiveReasoning||e.autoCollapseTurns!==t.autoCollapseTurns||e.collapseCompletedActivity!==t.collapseCompletedActivity||e.collapseLiveActivity!==t.collapseLiveActivity||e.pinUnfinishedTodos!==t.pinUnfinishedTodos||e.skills!==t.skills)&&no()}),dT(no),Tz(e=>{e&&(Rg=null,no())}),window.electronAPI.pair.onResumeSession(e=>{X0(e),uo()&&(ie.getState().markConversationRead(e),ie.getState().resumeConversation(e))}),window.electronAPI.pair.onSessionCreated(e=>{X0(e.sessionId),uo()&&ie.getState().adoptPairSession(e)}),window.electronAPI.pair.onSessionConfig(e=>{if(!uo())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(!uo())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 dce=3e4;async function uce(e,t=Date.now()){const{order:n,conversations:s,activeId:o}=ie.getState(),r=n.flatMap(u=>{const h=s[u];return!h||h.parentId?[]:(u===o||h.status==="running"||h.spawning===!0||h.workspaceMigrating===!0||(h.pendingAsks?.length??0)>0||(h.pendingApprovals?.length??0)>0)&&e.kind==="stale"?[]:[{id:u,projectId:h.projectId,archived:h.archived,archivedAt:h.archivedAt,pinned:h.pinned,lastActiveAt:H_(h)}]}),a=Ez(r,e,t),l=ie.getState();for(const u of a)l.removeConversation(u);const c=Date.now()+dce,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 hce=e=>{const t=w3(e);return t.length>0?t:U_(e)},Kk="enso-sidebar-width",qk="enso-sidebar-collapsed";function Id(){const e=ie.getState(),n=(e.activeId?e.conversations[e.activeId]:null)?.projectId??we.getState().projects[0]?.id;n&&e.newConversation(n)}const Dd="no-drag flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",Yk=200,Xk=420;function pce(){const e=we(G=>G.onboarded),t=m.useSyncExternalStore(G=>we.persist?.onFinishHydration?.(G)??(()=>{}),()=>we.persist?.hasHydrated?.()??!0);Pz(),Ole(),Rle(),Wle(),Hle(),Lle();const[n,s]=m.useState(!1),[o,r]=m.useState(null);Yle();const[a,l]=m.useState(()=>{const G=Number(localStorage.getItem(Kk));return Number.isFinite(G)&&G>=Yk?Math.min(G,Xk):280}),[c,d]=m.useState(()=>localStorage.getItem(qk)==="1"),u=_a(),h=Az(),[p,f]=m.useState(!1),g=m.useCallback(()=>f(!1),[]);m.useEffect(()=>{u||f(!1)},[u]),m.useEffect(()=>ie.subscribe((G,Q)=>{G.activeId!==Q.activeId&&f(!1)}),[]);const{t:x}=ne(),v=we(G=>G.chatWide),y=ie(G=>G.activeId),b=fn(G=>y?!!G.uiByConversation[y]?.open:!1),w=fn(G=>G.uiByConversation[y??""]?.width??G.lastWidth),C=fn(G=>G.fullscreen),_=fn(G=>G.toggleOpen),N=ue(G=>G.panelOpen),k=ue(G=>G.togglePanel);m.useEffect(()=>{C&&!b&&fn.getState().setFullscreen(!1)},[b,C]),m.useEffect(()=>(document.documentElement.classList.add("enso-main-shell"),()=>document.documentElement.classList.remove("enso-main-shell")),[]),m.useEffect(()=>window.electronAPI.app.onCloseRequest(r),[]),m.useEffect(()=>window.electronAPI.app.onFlushPersist(G=>{Mz().finally(()=>{window.electronAPI.app.respondFlushPersist(G)})}),[]);const S=G=>{const Q=o;Q&&(r(null),window.electronAPI.app.respondCloseRequest(Q,{action:G}))},[A,T]=m.useState(!1),I=m.useRef(null);m.useEffect(()=>{localStorage.setItem(Kk,String(a))},[a]),m.useEffect(()=>{localStorage.setItem(qk,c?"1":"0")},[c]),m.useEffect(()=>window.electronAPI.resources.onSessionsCleanRequest(({requestId:G,request:Q})=>{uce(Q).catch(()=>0).then(ae=>window.electronAPI.resources.sessionsCleanDone(G,ae))}),[]),m.useEffect(()=>{cce()},[]),m.useEffect(()=>{const G=os.getState();if(window.electronAPI.remote){G.activeNodeId!=="local"&&G.switchNode("local");return}return G.bind()},[]);const P=os(G=>G.activeNodeId),D=P!=="local",O=qW(),z=we(G=>G.botModeEnabled),R=we(G=>G.headerSessionTabs),$=fo(G=>G.mode);m.useEffect(()=>{const G=we.persist?.hasHydrated?.()??!0;$==="bot"&&(G&&!z||D)&&fo.getState().setMode("code")},[$,z,D]),m.useEffect(()=>{if(!z)return;const G=ue.getState().bind(),Q=window.electronAPI.bots.onEvent(ae=>{ae.kind==="open"&&YW(ae)});return()=>{G(),Q()}},[z]),m.useEffect(()=>window.electronAPI.agent.onFocusSession(G=>{ie.getState().conversations[G]&&Xx()}),[]);const X=m.useCallback(G=>{l(Q=>Math.min(Xk,Math.max(Yk,Q+G)))},[]),H=we(G=>G.keybindings);m.useEffect(()=>{const G=Fi(H),Q=Z=>{const ce=ie.getState(),De=ce.activeId?ce.conversations[ce.activeId]:null;if(!De)return;const Oe=[void 0,...De.coworkerIds??[]];if(Oe.length<=1)return;const Ne=Oe.indexOf(De.activeTabId);ce.selectTab(De.id,Oe[(Ne+Z+Oe.length)%Oe.length])},ae=Z=>{const ce=Ol(Z);if(!ce)return;if(ce===G["toggle-app-mode"]){if(!we.getState().botModeEnabled||os.getState().activeNodeId!=="local")return;Z.preventDefault();const Ne=fo.getState();Ne.setMode(Ne.mode==="bot"?"code":"bot");return}const De=os.getState().activeNodeId!=="local"||$c();if($c()&&ce===G["toggle-side-panel"]){Z.preventDefault(),ue.getState().togglePanel();return}if($c()&&ce===G["search-workspace"]){Z.preventDefault(),ue.getState().setSearchOpen(!0);return}if(!(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(Oe=>ce===G[Oe]))){if(ce===G["toggle-sidebar"])Z.preventDefault(),Fz(window.innerWidth)?f(Oe=>!Oe):d(Oe=>!Oe);else if(ce===G["open-settings"])Z.preventDefault(),window.electronAPI.window.openSettings();else if(ce===G["new-conversation"])Z.preventDefault(),Id();else if(ce===G["new-side-tab"])Z.preventDefault(),Hz(Z.target)?Bz():Id();else if(ce===G["new-btw-tab"])Z.preventDefault(),Vz();else if(ce===G["next-tab"])Z.preventDefault(),Q(1);else if(ce===G["prev-tab"])Z.preventDefault(),Q(-1);else if(ce===G["toggle-side-panel"])Z.preventDefault(),fn.getState().toggleOpen();else if(ce===G["toggle-side-panel-fullscreen"])Z.preventDefault(),fn.getState().toggleFullscreen();else if(ce===G["close-side-tab"])Z.preventDefault(),$z();else if(ce===G["focus-composer"])Z.preventDefault(),_o();else if(ce===G["find-in-chat"])Z.preventDefault(),uE();else if(ce===G["search-workspace"])Z.preventDefault(),s(!0);else if(!De){const Oe=Wz(v_(),H,G).byBinding.get(ce);if(!Oe)return;Z.preventDefault();const Ne=ie.getState(),Ze=Ne.activeId?Ne.conversations[Ne.activeId]:null;Qg(Oe,Ze?Ze.activeTabId??Ze.id:null).then(bt=>{bt&&ze({type:"error",title:Oe.title,description:bt})})}}};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[H]),m.useEffect(()=>{if(!b||!C)return;const G=Q=>{Q.key==="Escape"&&os.getState().activeNodeId==="local"&&($c()||(Q.preventDefault(),fn.getState().setFullscreen(!1)))};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[b,C]);const te=u3(d3(ux,{activationConstraint:{distance:6}})),V=gh(),Y=V!=="mobile"&&!D&&!O,q=m.useCallback(G=>{const Q=I.current;if(!Q)return;const ae=getComputedStyle(Q),Z=Q.clientWidth-parseFloat(ae.paddingLeft)-parseFloat(ae.paddingRight);fn.getState().nudgeWidth(-G,Z,Y?F_:Jg)},[Y]),ee=z&&!D?i.jsx(iee,{}):null,ge=Y&&(V==="mac"||V==="windows"||V==="web"),Ce=ge&&b&&!u&&!O&&!D,Re=R&&Y&&!z&&!(Ce&&C)?i.jsx(vW,{onNew:Id}):null,fe=D?null:i.jsx("button",{type:"button",className:W("flex items-center justify-center rounded-md transition-colors hover:bg-accent/50",u?"h-9 w-9":Y?Dd:"h-7 w-7",(O?N:b)?"text-foreground":"text-muted-foreground"),onClick:O?k:_,"aria-label":x("Toggle side panel"),title:x("Toggle side panel"),children:i.jsx(JN,{className:"h-4 w-4"})}),U=i.jsx("button",{type:"button",className:W("flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-accent/50",v?"text-foreground":"text-muted-foreground",u&&"hidden"),onClick:()=>we.getState().setChatWide(!v),"aria-label":x(v?"Use reading width":"Use full chat width"),title:x(v?"Use reading width":"Use full chat width"),children:v?i.jsx(j6,{className:"h-4 w-4"}):i.jsx(M4,{className:"h-4 w-4"})}),oe=i.jsxs(i.Fragment,{children:[U,fe]}),Se=Y?{trailing:U}:null;return i.jsxs("div",{"data-enso":"canvas",className:W("relative isolate flex flex-col",u?"h-dvh":"h-screen"),children:[i.jsx(Rz,{}),i.jsx(Lz,{}),i.jsx(rW,{}),i.jsx(QW,{}),i.jsx(Oz,{}),V!=="mobile"?i.jsx(J0,{leading:i.jsxs("div",{className:"flex items-center gap-0.5",children:[!D&&i.jsx("div",{className:W(V!=="mac"&&"flex justify-center",V!=="mac"&&(Y?"w-[48px]":"w-12")),children:i.jsx("button",{type:"button","data-enso":"sidebar-toggle",className:Dd,onClick:()=>d(G=>!G),title:x(c?"Expand sidebar":"Collapse sidebar"),children:c?i.jsx(XN,{className:"h-4 w-4"}):i.jsx(Kx,{className:"h-4 w-4"})})}),Y&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-enso":"search-button",className:Dd,onClick:()=>s(!0),title:x("Search anything"),children:i.jsx(si,{className:"h-4 w-4"})}),i.jsx("button",{type:"button","data-enso":"new-session",className:Dd,onClick:Id,title:x("New conversation"),children:i.jsx(ZN,{className:"h-4 w-4"})})]})]}),centered:(Ce&&C?null:ee)??void 0,middle:Re,className:W(V!=="mac"&&!D&&"pl-0",Y&&"border-b-0",Y&&"bg-transparent",Y&&V==="mac"&&"pr-4"),actions:Y?Ce?void 0:fe:oe}):i.jsx(J0,{title:"EnsoCode",centered:ee??void 0,leading:u&&!D&&!O?i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("button",{type:"button","data-enso":"sidebar-toggle",className:"-ml-1.5 flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",onClick:()=>f(!0),"aria-label":x("Conversations"),title:x("Conversations"),children:i.jsx(Q6,{className:"h-5 w-5"})}),!ee&&i.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"EnsoCode"})]}):void 0,actions:oe}),!Y&&i.jsx(Bw,{}),!Y&&i.jsx(Vw,{}),i.jsx("div",{className:"flex min-h-0 flex-1",children:D?i.jsx(Ose,{nodeId:P,sidebarWidth:a}):O?i.jsx(QQ,{sidebarWidth:a,collapsed:c,onToggleCollapse:()=>d(G=>!G),onResize:X}):i.jsxs(hG,{sensors:te,collisionDetection:hce,children:[u?i.jsxs(i.Fragment,{children:[i.jsx(vl,{children:p&&i.jsx(Os.div,{className:"fixed inset-0 bg-black/40",style:{zIndex:yn.MOBILE_DRAWER},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:g},"drawer-backdrop")}),i.jsx(Os.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:ra,inert:!p,children:i.jsx(AC,{width:Math.min(320,Math.round(h*.85)),collapsed:!1,onToggleCollapse:g,onOpenSearch:()=>s(!0),onNavigate:g})})]}):i.jsxs(i.Fragment,{children:[i.jsx(AC,{width:c?void 0:a,collapsed:c,onToggleCollapse:()=>d(G=>!G),onOpenSearch:()=>s(!0)}),!c&&i.jsx(Du,{edge:Y,onResize:X})]}),i.jsxs("div",{ref:I,className:W("relative flex min-h-0 min-w-0 flex-1",ge?"overflow-x-clip":"overflow-hidden",Y&&"-mt-px -ml-px pt-px pr-[8px] pb-[8px] pl-px"),children:[i.jsxs("div",{"data-enso":"main",className:W("flex min-h-0 min-w-0 flex-1 flex-col bg-background",Y&&"overflow-hidden rounded-[10px] shadow-surface",Ce&&"rounded-r-none"),style:b&&C?{visibility:"hidden",transition:`visibility 0s ${Ou.duration}s`}:void 0,children:[i.jsx(ece,{}),i.jsx(zz.Provider,{value:Se,children:i.jsx(yne,{})}),Y&&i.jsx(Bw,{}),Y&&i.jsx(Vw,{})]}),b&&!C&&!u&&i.jsx(Du,{gap:Y&&!Ce,onResize:q,onResizingChange:T}),i.jsx(Ele,{width:w,resizing:A,card:Y,titleRow:ge})]})]})}),t&&!e&&!window.electronAPI.remote&&i.jsx(Gse,{}),i.jsx(lie,{open:n,onOpenChange:s}),i.jsx(j_,{open:o!==null,onOpenChange:G=>{!G&&o&&S("cancel")},children:i.jsxs(__,{className:"sm:max-w-sm",children:[i.jsxs(N_,{children:[i.jsx(T_,{className:"text-base",children:x("Confirm exit")}),i.jsx(I_,{children:x("Exit closes the app completely, so your phone can no longer connect. Minimize to tray keeps the app running in the background so your phone can still connect.")})]}),i.jsxs(D_,{variant:"bare",children:[i.jsx(Gz,{render:i.jsx(me,{variant:"outline",size:"sm"}),children:x("Cancel")}),i.jsx(me,{size:"sm",onClick:()=>S("tray"),children:x("Minimize to tray")}),i.jsx(me,{variant:"destructive",size:"sm",onClick:()=>S("quit"),children:x("Exit")})]})]})})]})}function fce(e){return new Worker(""+new URL("worker-DsKBD11i.js",import.meta.url).href,{type:"module",name:e?.name})}const mce={workerFactory:()=>new fce,poolSize:2},gce={theme:ka,langs:[...Kz],preferredHighlighter:"shiki-js"};function xce({children:e}){return i.jsx(Uz,{poolOptions:mce,highlighterOptions:gce,children:e})}function Jk({conversations:e,activeId:t}){const n=document.documentElement.dataset,s=Lne(e),o=FE(t?e[t]:void 0,e);n.ensoActivity!==s&&(n.ensoActivity=s),n.ensoSession!==o&&(n.ensoSession=o)}function vce(){Jk(ie.getState()),ie.subscribe((e,t)=>{(e.conversations!==t.conversations||e.activeId!==t.activeId)&&Jk(e)})}qz();vce();Yz();Pj();Xz.createRoot(document.getElementById("root")).render(i.jsx(m.StrictMode,{children:i.jsx(xce,{children:i.jsx(pce,{})})}));