termdock 1.4.350 → 1.4.351

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 (353) hide show
  1. package/dist/client/assets/{App-TPJoJbGD.js → App-BiDKeTpx.js} +6 -6
  2. package/dist/client/assets/App-BiDKeTpx.js.br +0 -0
  3. package/dist/client/assets/App-BiDKeTpx.js.gz +0 -0
  4. package/dist/client/assets/{ArchitecturePanel-DzVy71gM.js → ArchitecturePanel-DfRsqSBx.js} +2 -2
  5. package/dist/client/assets/ArchitecturePanel-DfRsqSBx.js.br +0 -0
  6. package/dist/client/assets/ArchitecturePanel-DfRsqSBx.js.gz +0 -0
  7. package/dist/client/assets/{ChangeWalkthroughPanel-DN7BCzqC.js → ChangeWalkthroughPanel-DksecDp5.js} +1 -1
  8. package/dist/client/assets/ChangeWalkthroughPanel-DksecDp5.js.br +0 -0
  9. package/dist/client/assets/ChangeWalkthroughPanel-DksecDp5.js.gz +0 -0
  10. package/dist/client/assets/{CollaborationMainWorkspace-B1PZuCC6.js → CollaborationMainWorkspace-D-TgDrxX.js} +1 -1
  11. package/dist/client/assets/CollaborationMainWorkspace-D-TgDrxX.js.br +0 -0
  12. package/dist/client/assets/CollaborationMainWorkspace-D-TgDrxX.js.gz +0 -0
  13. package/dist/client/assets/CollaborationTaskContent-Ce6gFw26.js +2 -0
  14. package/dist/client/assets/{ComputerControlView-BlI9Ai_k.js → ComputerControlView-BKwuceeG.js} +3 -3
  15. package/dist/client/assets/ComputerControlView-BKwuceeG.js.br +0 -0
  16. package/dist/client/assets/ComputerControlView-BKwuceeG.js.gz +0 -0
  17. package/dist/client/assets/{DagPlayground-V0hTKB-S.js → DagPlayground-Cshoqo5l.js} +1 -1
  18. package/dist/client/assets/DagPlayground-Cshoqo5l.js.br +0 -0
  19. package/dist/client/assets/DagPlayground-Cshoqo5l.js.gz +0 -0
  20. package/dist/client/assets/{DiffLab-DEw4y4Hk.js → DiffLab-DFut8ZHi.js} +1 -1
  21. package/dist/client/assets/DiffLab-DFut8ZHi.js.br +0 -0
  22. package/dist/client/assets/DiffLab-DFut8ZHi.js.gz +0 -0
  23. package/dist/client/assets/{DiffReview-Cnnt3TMK.js → DiffReview-DkEi5c3c.js} +1 -1
  24. package/dist/client/assets/DiffReview-DkEi5c3c.js.br +0 -0
  25. package/dist/client/assets/DiffReview-DkEi5c3c.js.gz +0 -0
  26. package/dist/client/assets/{DiffReviewLab-CDXsy0jE.js → DiffReviewLab-Y9JlI5DQ.js} +1 -1
  27. package/dist/client/assets/DiffReviewLab-Y9JlI5DQ.js.br +0 -0
  28. package/dist/client/assets/DiffReviewLab-Y9JlI5DQ.js.gz +0 -0
  29. package/dist/client/assets/{DiffViewer-Dh40XiCM.js → DiffViewer-3JGF6U0m.js} +1 -1
  30. package/dist/client/assets/DiffViewer-3JGF6U0m.js.br +0 -0
  31. package/dist/client/assets/DiffViewer-3JGF6U0m.js.gz +0 -0
  32. package/dist/client/assets/{ModelPreview-BEiOgE0G.js → ModelPreview-Cv6JgunE.js} +1 -1
  33. package/dist/client/assets/ModelPreview-Cv6JgunE.js.br +0 -0
  34. package/dist/client/assets/ModelPreview-Cv6JgunE.js.gz +0 -0
  35. package/dist/client/assets/{RightSidebar-DiECnX5D.js → RightSidebar-akYx_nRq.js} +3 -3
  36. package/dist/client/assets/RightSidebar-akYx_nRq.js.br +0 -0
  37. package/dist/client/assets/RightSidebar-akYx_nRq.js.gz +0 -0
  38. package/dist/client/assets/{abnfDiagram-VCTEODGH-ByzlUu_B.js → abnfDiagram-VCTEODGH-CcCffdpj.js} +1 -1
  39. package/dist/client/assets/abnfDiagram-VCTEODGH-CcCffdpj.js.br +0 -0
  40. package/dist/client/assets/abnfDiagram-VCTEODGH-CcCffdpj.js.gz +0 -0
  41. package/dist/client/assets/app-BB0CAQ8D.js +35 -0
  42. package/dist/client/assets/app-BB0CAQ8D.js.br +0 -0
  43. package/dist/client/assets/app-BB0CAQ8D.js.gz +0 -0
  44. package/dist/client/assets/{arc-BA6JM6vl.js → arc-CXcCuzb3.js} +1 -1
  45. package/dist/client/assets/arc-CXcCuzb3.js.br +0 -0
  46. package/dist/client/assets/arc-CXcCuzb3.js.gz +0 -0
  47. package/dist/client/assets/{architectureDiagram-5GKGNRK7-hCHxOfKw.js → architectureDiagram-5GKGNRK7-CmR7whZz.js} +1 -1
  48. package/dist/client/assets/architectureDiagram-5GKGNRK7-CmR7whZz.js.br +0 -0
  49. package/dist/client/assets/architectureDiagram-5GKGNRK7-CmR7whZz.js.gz +0 -0
  50. package/dist/client/assets/{blockDiagram-I7D4REHJ-OmEN9hUB.js → blockDiagram-I7D4REHJ-DODhUpHm.js} +1 -1
  51. package/dist/client/assets/blockDiagram-I7D4REHJ-DODhUpHm.js.br +0 -0
  52. package/dist/client/assets/blockDiagram-I7D4REHJ-DODhUpHm.js.gz +0 -0
  53. package/dist/client/assets/{c4Diagram-7LVT6UL2-DfLTv8zh.js → c4Diagram-7LVT6UL2-BF9eEb2Y.js} +1 -1
  54. package/dist/client/assets/c4Diagram-7LVT6UL2-BF9eEb2Y.js.br +0 -0
  55. package/dist/client/assets/c4Diagram-7LVT6UL2-BF9eEb2Y.js.gz +0 -0
  56. package/dist/client/assets/channel-BKkTA-X_.js +1 -0
  57. package/dist/client/assets/{chunk-2Q5K7J3B-C3O76PNZ.js → chunk-2Q5K7J3B-CB7-8Zex.js} +1 -1
  58. package/dist/client/assets/{chunk-5VM5RSS4-CsWZd30k.js → chunk-5VM5RSS4-8Uxe2lki.js} +1 -1
  59. package/dist/client/assets/{chunk-F27PBJKO-yxCv2Uqk.js → chunk-F27PBJKO-Bv45U-az.js} +1 -1
  60. package/dist/client/assets/chunk-F27PBJKO-Bv45U-az.js.br +0 -0
  61. package/dist/client/assets/chunk-F27PBJKO-Bv45U-az.js.gz +0 -0
  62. package/dist/client/assets/{chunk-IMKFNOWR-CdPjlb9f.js → chunk-IMKFNOWR-CfEErbEd.js} +1 -1
  63. package/dist/client/assets/chunk-IMKFNOWR-CfEErbEd.js.br +0 -0
  64. package/dist/client/assets/chunk-IMKFNOWR-CfEErbEd.js.gz +0 -0
  65. package/dist/client/assets/{chunk-JWPE2WC7-BiiOLq2R.js → chunk-JWPE2WC7-CjUqcCSL.js} +1 -1
  66. package/dist/client/assets/{chunk-POPQ4Y6H-BOu_1Brt.js → chunk-POPQ4Y6H-BHbP3O75.js} +1 -1
  67. package/dist/client/assets/{chunk-SVP7TREG-D1tOJung.js → chunk-SVP7TREG-CbyJW-OT.js} +1 -1
  68. package/dist/client/assets/chunk-SVP7TREG-CbyJW-OT.js.br +0 -0
  69. package/dist/client/assets/chunk-SVP7TREG-CbyJW-OT.js.gz +0 -0
  70. package/dist/client/assets/{chunk-TICWLB2K-DZjDfYNw.js → chunk-TICWLB2K-t93EivmS.js} +1 -1
  71. package/dist/client/assets/chunk-TICWLB2K-t93EivmS.js.br +0 -0
  72. package/dist/client/assets/chunk-TICWLB2K-t93EivmS.js.gz +0 -0
  73. package/dist/client/assets/{chunk-XXDRQBXY-CtGPyXWh.js → chunk-XXDRQBXY-C_Pe8Osb.js} +1 -1
  74. package/dist/client/assets/classDiagram-ZZMXUADV-D9nwA51-.js +1 -0
  75. package/dist/client/assets/classDiagram-v2-VYDZK3BY-D9nwA51-.js +1 -0
  76. package/dist/client/assets/{cose-bilkent-JH36ORCC-C4Wb5lqD.js → cose-bilkent-JH36ORCC-CksG0bvP.js} +1 -1
  77. package/dist/client/assets/cose-bilkent-JH36ORCC-CksG0bvP.js.br +0 -0
  78. package/dist/client/assets/cose-bilkent-JH36ORCC-CksG0bvP.js.gz +0 -0
  79. package/dist/client/assets/{cynefin-OW5HDTMX-BvWKB1Xk.js → cynefin-OW5HDTMX-CV3T078G.js} +1 -1
  80. package/dist/client/assets/cynefin-OW5HDTMX-CV3T078G.js.br +0 -0
  81. package/dist/client/assets/{cynefin-OW5HDTMX-BvWKB1Xk.js.gz → cynefin-OW5HDTMX-CV3T078G.js.gz} +0 -0
  82. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-7tAkHD2P.js → cynefinDiagram-5FMLGOSQ-BQnJabEs.js} +1 -1
  83. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BQnJabEs.js.br +0 -0
  84. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BQnJabEs.js.gz +0 -0
  85. package/dist/client/assets/{dagre-GXQ25YYZ-Bs6IPwks.js → dagre-GXQ25YYZ-BeIQp5Pv.js} +1 -1
  86. package/dist/client/assets/dagre-GXQ25YYZ-BeIQp5Pv.js.br +0 -0
  87. package/dist/client/assets/dagre-GXQ25YYZ-BeIQp5Pv.js.gz +0 -0
  88. package/dist/client/assets/{diagram-S7CK7UJ4-CmYXaTya.js → diagram-S7CK7UJ4-D-Mibxiq.js} +1 -1
  89. package/dist/client/assets/diagram-S7CK7UJ4-D-Mibxiq.js.br +0 -0
  90. package/dist/client/assets/diagram-S7CK7UJ4-D-Mibxiq.js.gz +0 -0
  91. package/dist/client/assets/{diagram-UQ7AKVKN-CqxoefB7.js → diagram-UQ7AKVKN-eiIMWp9t.js} +1 -1
  92. package/dist/client/assets/diagram-UQ7AKVKN-eiIMWp9t.js.br +0 -0
  93. package/dist/client/assets/diagram-UQ7AKVKN-eiIMWp9t.js.gz +0 -0
  94. package/dist/client/assets/{diagram-VSXAHHWV-Dxp1MKPT.js → diagram-VSXAHHWV-CTVOWtNL.js} +1 -1
  95. package/dist/client/assets/diagram-VSXAHHWV-CTVOWtNL.js.br +0 -0
  96. package/dist/client/assets/diagram-VSXAHHWV-CTVOWtNL.js.gz +0 -0
  97. package/dist/client/assets/{diagram-VX7I27RA-BKbWvvEr.js → diagram-VX7I27RA-NKKk6uh7.js} +1 -1
  98. package/dist/client/assets/diagram-VX7I27RA-NKKk6uh7.js.br +0 -0
  99. package/dist/client/assets/diagram-VX7I27RA-NKKk6uh7.js.gz +0 -0
  100. package/dist/client/assets/{diagram-Z3DM3KII-BZnNaP7F.js → diagram-Z3DM3KII-DKYdBuNs.js} +1 -1
  101. package/dist/client/assets/diagram-Z3DM3KII-DKYdBuNs.js.br +0 -0
  102. package/dist/client/assets/diagram-Z3DM3KII-DKYdBuNs.js.gz +0 -0
  103. package/dist/client/assets/{ebnfDiagram-PWID7BFC-BXVlN_P7.js → ebnfDiagram-PWID7BFC-DaM3D5Ed.js} +1 -1
  104. package/dist/client/assets/ebnfDiagram-PWID7BFC-DaM3D5Ed.js.br +0 -0
  105. package/dist/client/assets/ebnfDiagram-PWID7BFC-DaM3D5Ed.js.gz +0 -0
  106. package/dist/client/assets/{erDiagram-RLTQ6QDP-CEdYDZU7.js → erDiagram-RLTQ6QDP-Df9kQwWg.js} +1 -1
  107. package/dist/client/assets/erDiagram-RLTQ6QDP-Df9kQwWg.js.br +0 -0
  108. package/dist/client/assets/erDiagram-RLTQ6QDP-Df9kQwWg.js.gz +0 -0
  109. package/dist/client/assets/{flowDiagram-HODETNUW-Bbw8GPCZ.js → flowDiagram-HODETNUW-CWjDvpsN.js} +1 -1
  110. package/dist/client/assets/flowDiagram-HODETNUW-CWjDvpsN.js.br +0 -0
  111. package/dist/client/assets/flowDiagram-HODETNUW-CWjDvpsN.js.gz +0 -0
  112. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-CcFbtP2y.js → ganttDiagram-EL5Y4UJY-mKt-CgrH.js} +1 -1
  113. package/dist/client/assets/ganttDiagram-EL5Y4UJY-mKt-CgrH.js.br +0 -0
  114. package/dist/client/assets/ganttDiagram-EL5Y4UJY-mKt-CgrH.js.gz +0 -0
  115. package/dist/client/assets/{gestureArbiter-sdzs-66-.js → gestureArbiter-C8TBuoU3.js} +1 -1
  116. package/dist/client/assets/gestureArbiter-C8TBuoU3.js.br +0 -0
  117. package/dist/client/assets/gestureArbiter-C8TBuoU3.js.gz +0 -0
  118. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-Eiust154.js → gitGraphDiagram-WWUBYQGX-BqnaVVZ0.js} +1 -1
  119. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BqnaVVZ0.js.br +0 -0
  120. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BqnaVVZ0.js.gz +0 -0
  121. package/dist/client/assets/index-3lPto_1X.css +1 -0
  122. package/dist/client/assets/index-3lPto_1X.css.br +0 -0
  123. package/dist/client/assets/{index-DtPsPZ7W.css.gz → index-3lPto_1X.css.gz} +0 -0
  124. package/dist/client/assets/{infoDiagram-27XIBGKW-DUmaNZJW.js → infoDiagram-27XIBGKW-CkniyUX9.js} +1 -1
  125. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-qTwgXfx_.js → ishikawaDiagram-5VMMS53U-CKo9urjS.js} +1 -1
  126. package/dist/client/assets/ishikawaDiagram-5VMMS53U-CKo9urjS.js.br +0 -0
  127. package/dist/client/assets/ishikawaDiagram-5VMMS53U-CKo9urjS.js.gz +0 -0
  128. package/dist/client/assets/{journeyDiagram-3NMN7TZE-DKy1msWo.js → journeyDiagram-3NMN7TZE-Cd4jK-oI.js} +1 -1
  129. package/dist/client/assets/journeyDiagram-3NMN7TZE-Cd4jK-oI.js.br +0 -0
  130. package/dist/client/assets/journeyDiagram-3NMN7TZE-Cd4jK-oI.js.gz +0 -0
  131. package/dist/client/assets/{kanban-definition-UXKFOSKX-BxibybDd.js → kanban-definition-UXKFOSKX-BuulZGO-.js} +1 -1
  132. package/dist/client/assets/kanban-definition-UXKFOSKX-BuulZGO-.js.br +0 -0
  133. package/dist/client/assets/kanban-definition-UXKFOSKX-BuulZGO-.js.gz +0 -0
  134. package/dist/client/assets/{layout-Bh6fKHRM.js → layout-BpJ2ofrz.js} +1 -1
  135. package/dist/client/assets/layout-BpJ2ofrz.js.br +0 -0
  136. package/dist/client/assets/layout-BpJ2ofrz.js.gz +0 -0
  137. package/dist/client/assets/{linear-SRlL3VWX.js → linear-CaSbGLIA.js} +1 -1
  138. package/dist/client/assets/linear-CaSbGLIA.js.br +0 -0
  139. package/dist/client/assets/linear-CaSbGLIA.js.gz +0 -0
  140. package/dist/client/assets/{mermaid.core-D0bcNdw3.js → mermaid.core-BlkorXd6.js} +5 -5
  141. package/dist/client/assets/mermaid.core-BlkorXd6.js.br +0 -0
  142. package/dist/client/assets/mermaid.core-BlkorXd6.js.gz +0 -0
  143. package/dist/client/assets/{mindmap-definition-YA3MSWOX-CImZ_aI0.js → mindmap-definition-YA3MSWOX-BqKhK1NJ.js} +1 -1
  144. package/dist/client/assets/mindmap-definition-YA3MSWOX-BqKhK1NJ.js.br +0 -0
  145. package/dist/client/assets/mindmap-definition-YA3MSWOX-BqKhK1NJ.js.gz +0 -0
  146. package/dist/client/assets/{passwordBootstrap-f7-mFb1b.js → passwordBootstrap-DLUamTjd.js} +1 -1
  147. package/dist/client/assets/passwordBootstrap-DLUamTjd.js.br +0 -0
  148. package/dist/client/assets/passwordBootstrap-DLUamTjd.js.gz +0 -0
  149. package/dist/client/assets/{pegDiagram-XKGWAZYB-BT4pTf8O.js → pegDiagram-XKGWAZYB-BlWgUklx.js} +1 -1
  150. package/dist/client/assets/pegDiagram-XKGWAZYB-BlWgUklx.js.br +0 -0
  151. package/dist/client/assets/pegDiagram-XKGWAZYB-BlWgUklx.js.gz +0 -0
  152. package/dist/client/assets/{pieDiagram-E7YTZNPT-C5K58ien.js → pieDiagram-E7YTZNPT-Bp32kHHQ.js} +1 -1
  153. package/dist/client/assets/pieDiagram-E7YTZNPT-Bp32kHHQ.js.br +0 -0
  154. package/dist/client/assets/pieDiagram-E7YTZNPT-Bp32kHHQ.js.gz +0 -0
  155. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-DzSugYXz.js → quadrantDiagram-AXDQQJYC-0qeSh9-W.js} +1 -1
  156. package/dist/client/assets/quadrantDiagram-AXDQQJYC-0qeSh9-W.js.br +0 -0
  157. package/dist/client/assets/quadrantDiagram-AXDQQJYC-0qeSh9-W.js.gz +0 -0
  158. package/dist/client/assets/{railroadDiagram-O6MQD6OU-BY07SouQ.js → railroadDiagram-O6MQD6OU-COmWghVD.js} +1 -1
  159. package/dist/client/assets/railroadDiagram-O6MQD6OU-COmWghVD.js.br +0 -0
  160. package/dist/client/assets/railroadDiagram-O6MQD6OU-COmWghVD.js.gz +0 -0
  161. package/dist/client/assets/{rdpSession-RNjO6yLw.js → rdpSession-Bbycnmly.js} +1 -1
  162. package/dist/client/assets/rdpSession-Bbycnmly.js.br +0 -0
  163. package/dist/client/assets/rdpSession-Bbycnmly.js.gz +0 -0
  164. package/dist/client/assets/{referenceLongPress-B9K9yPKR.js → referenceLongPress-CQ9ote5C.js} +1 -1
  165. package/dist/client/assets/referenceLongPress-CQ9ote5C.js.br +0 -0
  166. package/dist/client/assets/referenceLongPress-CQ9ote5C.js.gz +0 -0
  167. package/dist/client/assets/{requirementDiagram-BXWQKSXE-C7WieVuE.js → requirementDiagram-BXWQKSXE-CeohDJAC.js} +1 -1
  168. package/dist/client/assets/requirementDiagram-BXWQKSXE-CeohDJAC.js.br +0 -0
  169. package/dist/client/assets/requirementDiagram-BXWQKSXE-CeohDJAC.js.gz +0 -0
  170. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-BJsDWNs4.js → sankeyDiagram-P5KCCOFB-rA5x9iOw.js} +1 -1
  171. package/dist/client/assets/sankeyDiagram-P5KCCOFB-rA5x9iOw.js.br +0 -0
  172. package/dist/client/assets/sankeyDiagram-P5KCCOFB-rA5x9iOw.js.gz +0 -0
  173. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-BeJ_7853.js → sequenceDiagram-WJ2MYXX4-Cw2BZ0po.js} +1 -1
  174. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Cw2BZ0po.js.br +0 -0
  175. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Cw2BZ0po.js.gz +0 -0
  176. package/dist/client/assets/{sizeCapture-INFHLROL-DOsjXKPV.js → sizeCapture-INFHLROL-Dz1ykd8a.js} +1 -1
  177. package/dist/client/assets/sizeCapture-INFHLROL-Dz1ykd8a.js.br +0 -0
  178. package/dist/client/assets/sizeCapture-INFHLROL-Dz1ykd8a.js.gz +0 -0
  179. package/dist/client/assets/{sparkles-e9SkpP7a.js → sparkles-0HeBLLwx.js} +1 -1
  180. package/dist/client/assets/{stateDiagram-D77RDMKH-6s709_RT.js → stateDiagram-D77RDMKH-DHfjTfLj.js} +1 -1
  181. package/dist/client/assets/stateDiagram-D77RDMKH-DHfjTfLj.js.br +0 -0
  182. package/dist/client/assets/stateDiagram-D77RDMKH-DHfjTfLj.js.gz +0 -0
  183. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-B9AqPaxQ.js +1 -0
  184. package/dist/client/assets/{swimlanes-42K2YHIH-5R5dw9_R.js → swimlanes-42K2YHIH-CAJkSUVz.js} +1 -1
  185. package/dist/client/assets/swimlanes-42K2YHIH-CAJkSUVz.js.br +0 -0
  186. package/dist/client/assets/swimlanes-42K2YHIH-CAJkSUVz.js.gz +0 -0
  187. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-DPbqRuWV.js +8 -0
  188. package/dist/client/assets/{timeline-definition-24CTP7MA-B4YN0lsx.js → timeline-definition-24CTP7MA-plr9yv12.js} +1 -1
  189. package/dist/client/assets/timeline-definition-24CTP7MA-plr9yv12.js.br +0 -0
  190. package/dist/client/assets/timeline-definition-24CTP7MA-plr9yv12.js.gz +0 -0
  191. package/dist/client/assets/{triangle-alert-BzBDJvJX.js → triangle-alert-ibl6FV9I.js} +1 -1
  192. package/dist/client/assets/{vennDiagram-4TSXK5OY-Wd83SmWI.js → vennDiagram-4TSXK5OY-Cz04de3S.js} +1 -1
  193. package/dist/client/assets/vennDiagram-4TSXK5OY-Cz04de3S.js.br +0 -0
  194. package/dist/client/assets/vennDiagram-4TSXK5OY-Cz04de3S.js.gz +0 -0
  195. package/dist/client/assets/{videoCompression-Bsw--tMn.js → videoCompression-DCsUD6X6.js} +1 -1
  196. package/dist/client/assets/videoCompression-DCsUD6X6.js.br +0 -0
  197. package/dist/client/assets/videoCompression-DCsUD6X6.js.gz +0 -0
  198. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-CGsYvqWN.js → wardleyDiagram-VM6X3IG4-DnT-q6At.js} +1 -1
  199. package/dist/client/assets/wardleyDiagram-VM6X3IG4-DnT-q6At.js.br +0 -0
  200. package/dist/client/assets/wardleyDiagram-VM6X3IG4-DnT-q6At.js.gz +0 -0
  201. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-ednJq1_u.js → xychartDiagram-S5SC5T6Z-C0y08MEX.js} +1 -1
  202. package/dist/client/assets/xychartDiagram-S5SC5T6Z-C0y08MEX.js.br +0 -0
  203. package/dist/client/assets/xychartDiagram-S5SC5T6Z-C0y08MEX.js.gz +0 -0
  204. package/dist/client/index.html +2 -2
  205. package/dist/client/index.html.br +0 -0
  206. package/dist/client/index.html.gz +0 -0
  207. package/dist/client/sw-encrypted-background.js +1 -1
  208. package/dist/client/sw-encrypted-background.js.br +0 -0
  209. package/dist/client/sw-encrypted-background.js.gz +0 -0
  210. package/dist/client/sw.js +1 -1
  211. package/dist/client/sw.js.br +0 -0
  212. package/dist/client/sw.js.gz +0 -0
  213. package/dist/server/agent/collaborationRoutes.js +2 -0
  214. package/dist/server/entry.js +1 -0
  215. package/dist/server/federation/relay.js +21 -3
  216. package/dist/server/federation/runtime.js +7 -1
  217. package/dist/server/federation/socketDuplex.js +3 -3
  218. package/dist/server/utils/version.js +2 -0
  219. package/docs/integrations.md +23 -0
  220. package/package.json +1 -1
  221. package/runtime-manifest.json +3 -3
  222. package/dist/client/assets/App-TPJoJbGD.js.br +0 -0
  223. package/dist/client/assets/App-TPJoJbGD.js.gz +0 -0
  224. package/dist/client/assets/ArchitecturePanel-DzVy71gM.js.br +0 -0
  225. package/dist/client/assets/ArchitecturePanel-DzVy71gM.js.gz +0 -0
  226. package/dist/client/assets/ChangeWalkthroughPanel-DN7BCzqC.js.br +0 -0
  227. package/dist/client/assets/ChangeWalkthroughPanel-DN7BCzqC.js.gz +0 -0
  228. package/dist/client/assets/CollaborationMainWorkspace-B1PZuCC6.js.br +0 -0
  229. package/dist/client/assets/CollaborationMainWorkspace-B1PZuCC6.js.gz +0 -0
  230. package/dist/client/assets/CollaborationTaskContent-CG7g1LMH.js +0 -2
  231. package/dist/client/assets/ComputerControlView-BlI9Ai_k.js.br +0 -0
  232. package/dist/client/assets/ComputerControlView-BlI9Ai_k.js.gz +0 -0
  233. package/dist/client/assets/DagPlayground-V0hTKB-S.js.br +0 -0
  234. package/dist/client/assets/DagPlayground-V0hTKB-S.js.gz +0 -0
  235. package/dist/client/assets/DiffLab-DEw4y4Hk.js.br +0 -0
  236. package/dist/client/assets/DiffLab-DEw4y4Hk.js.gz +0 -0
  237. package/dist/client/assets/DiffReview-Cnnt3TMK.js.br +0 -0
  238. package/dist/client/assets/DiffReview-Cnnt3TMK.js.gz +0 -0
  239. package/dist/client/assets/DiffReviewLab-CDXsy0jE.js.br +0 -0
  240. package/dist/client/assets/DiffReviewLab-CDXsy0jE.js.gz +0 -0
  241. package/dist/client/assets/DiffViewer-Dh40XiCM.js.br +0 -0
  242. package/dist/client/assets/DiffViewer-Dh40XiCM.js.gz +0 -0
  243. package/dist/client/assets/ModelPreview-BEiOgE0G.js.br +0 -0
  244. package/dist/client/assets/ModelPreview-BEiOgE0G.js.gz +0 -0
  245. package/dist/client/assets/RightSidebar-DiECnX5D.js.br +0 -0
  246. package/dist/client/assets/RightSidebar-DiECnX5D.js.gz +0 -0
  247. package/dist/client/assets/abnfDiagram-VCTEODGH-ByzlUu_B.js.br +0 -0
  248. package/dist/client/assets/abnfDiagram-VCTEODGH-ByzlUu_B.js.gz +0 -0
  249. package/dist/client/assets/app-CKAFlgMD.js +0 -35
  250. package/dist/client/assets/app-CKAFlgMD.js.br +0 -0
  251. package/dist/client/assets/app-CKAFlgMD.js.gz +0 -0
  252. package/dist/client/assets/arc-BA6JM6vl.js.br +0 -0
  253. package/dist/client/assets/arc-BA6JM6vl.js.gz +0 -0
  254. package/dist/client/assets/architectureDiagram-5GKGNRK7-hCHxOfKw.js.br +0 -0
  255. package/dist/client/assets/architectureDiagram-5GKGNRK7-hCHxOfKw.js.gz +0 -0
  256. package/dist/client/assets/blockDiagram-I7D4REHJ-OmEN9hUB.js.br +0 -0
  257. package/dist/client/assets/blockDiagram-I7D4REHJ-OmEN9hUB.js.gz +0 -0
  258. package/dist/client/assets/c4Diagram-7LVT6UL2-DfLTv8zh.js.br +0 -0
  259. package/dist/client/assets/c4Diagram-7LVT6UL2-DfLTv8zh.js.gz +0 -0
  260. package/dist/client/assets/channel-gcmN0N0m.js +0 -1
  261. package/dist/client/assets/chunk-F27PBJKO-yxCv2Uqk.js.br +0 -0
  262. package/dist/client/assets/chunk-F27PBJKO-yxCv2Uqk.js.gz +0 -0
  263. package/dist/client/assets/chunk-IMKFNOWR-CdPjlb9f.js.br +0 -0
  264. package/dist/client/assets/chunk-IMKFNOWR-CdPjlb9f.js.gz +0 -0
  265. package/dist/client/assets/chunk-SVP7TREG-D1tOJung.js.br +0 -0
  266. package/dist/client/assets/chunk-SVP7TREG-D1tOJung.js.gz +0 -0
  267. package/dist/client/assets/chunk-TICWLB2K-DZjDfYNw.js.br +0 -0
  268. package/dist/client/assets/chunk-TICWLB2K-DZjDfYNw.js.gz +0 -0
  269. package/dist/client/assets/classDiagram-ZZMXUADV-k4BRymfG.js +0 -1
  270. package/dist/client/assets/classDiagram-v2-VYDZK3BY-k4BRymfG.js +0 -1
  271. package/dist/client/assets/cose-bilkent-JH36ORCC-C4Wb5lqD.js.br +0 -0
  272. package/dist/client/assets/cose-bilkent-JH36ORCC-C4Wb5lqD.js.gz +0 -0
  273. package/dist/client/assets/cynefin-OW5HDTMX-BvWKB1Xk.js.br +0 -0
  274. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-7tAkHD2P.js.br +0 -0
  275. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-7tAkHD2P.js.gz +0 -0
  276. package/dist/client/assets/dagre-GXQ25YYZ-Bs6IPwks.js.br +0 -0
  277. package/dist/client/assets/dagre-GXQ25YYZ-Bs6IPwks.js.gz +0 -0
  278. package/dist/client/assets/diagram-S7CK7UJ4-CmYXaTya.js.br +0 -0
  279. package/dist/client/assets/diagram-S7CK7UJ4-CmYXaTya.js.gz +0 -0
  280. package/dist/client/assets/diagram-UQ7AKVKN-CqxoefB7.js.br +0 -0
  281. package/dist/client/assets/diagram-UQ7AKVKN-CqxoefB7.js.gz +0 -0
  282. package/dist/client/assets/diagram-VSXAHHWV-Dxp1MKPT.js.br +0 -0
  283. package/dist/client/assets/diagram-VSXAHHWV-Dxp1MKPT.js.gz +0 -0
  284. package/dist/client/assets/diagram-VX7I27RA-BKbWvvEr.js.br +0 -0
  285. package/dist/client/assets/diagram-VX7I27RA-BKbWvvEr.js.gz +0 -0
  286. package/dist/client/assets/diagram-Z3DM3KII-BZnNaP7F.js.br +0 -0
  287. package/dist/client/assets/diagram-Z3DM3KII-BZnNaP7F.js.gz +0 -0
  288. package/dist/client/assets/ebnfDiagram-PWID7BFC-BXVlN_P7.js.br +0 -0
  289. package/dist/client/assets/ebnfDiagram-PWID7BFC-BXVlN_P7.js.gz +0 -0
  290. package/dist/client/assets/erDiagram-RLTQ6QDP-CEdYDZU7.js.br +0 -0
  291. package/dist/client/assets/erDiagram-RLTQ6QDP-CEdYDZU7.js.gz +0 -0
  292. package/dist/client/assets/flowDiagram-HODETNUW-Bbw8GPCZ.js.br +0 -0
  293. package/dist/client/assets/flowDiagram-HODETNUW-Bbw8GPCZ.js.gz +0 -0
  294. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CcFbtP2y.js.br +0 -0
  295. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CcFbtP2y.js.gz +0 -0
  296. package/dist/client/assets/gestureArbiter-sdzs-66-.js.br +0 -0
  297. package/dist/client/assets/gestureArbiter-sdzs-66-.js.gz +0 -0
  298. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-Eiust154.js.br +0 -0
  299. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-Eiust154.js.gz +0 -0
  300. package/dist/client/assets/index-DtPsPZ7W.css +0 -1
  301. package/dist/client/assets/index-DtPsPZ7W.css.br +0 -0
  302. package/dist/client/assets/ishikawaDiagram-5VMMS53U-qTwgXfx_.js.br +0 -0
  303. package/dist/client/assets/ishikawaDiagram-5VMMS53U-qTwgXfx_.js.gz +0 -0
  304. package/dist/client/assets/journeyDiagram-3NMN7TZE-DKy1msWo.js.br +0 -0
  305. package/dist/client/assets/journeyDiagram-3NMN7TZE-DKy1msWo.js.gz +0 -0
  306. package/dist/client/assets/kanban-definition-UXKFOSKX-BxibybDd.js.br +0 -0
  307. package/dist/client/assets/kanban-definition-UXKFOSKX-BxibybDd.js.gz +0 -0
  308. package/dist/client/assets/layout-Bh6fKHRM.js.br +0 -0
  309. package/dist/client/assets/layout-Bh6fKHRM.js.gz +0 -0
  310. package/dist/client/assets/linear-SRlL3VWX.js.br +0 -0
  311. package/dist/client/assets/linear-SRlL3VWX.js.gz +0 -0
  312. package/dist/client/assets/mermaid.core-D0bcNdw3.js.br +0 -0
  313. package/dist/client/assets/mermaid.core-D0bcNdw3.js.gz +0 -0
  314. package/dist/client/assets/mindmap-definition-YA3MSWOX-CImZ_aI0.js.br +0 -0
  315. package/dist/client/assets/mindmap-definition-YA3MSWOX-CImZ_aI0.js.gz +0 -0
  316. package/dist/client/assets/passwordBootstrap-f7-mFb1b.js.br +0 -0
  317. package/dist/client/assets/passwordBootstrap-f7-mFb1b.js.gz +0 -0
  318. package/dist/client/assets/pegDiagram-XKGWAZYB-BT4pTf8O.js.br +0 -0
  319. package/dist/client/assets/pegDiagram-XKGWAZYB-BT4pTf8O.js.gz +0 -0
  320. package/dist/client/assets/pieDiagram-E7YTZNPT-C5K58ien.js.br +0 -0
  321. package/dist/client/assets/pieDiagram-E7YTZNPT-C5K58ien.js.gz +0 -0
  322. package/dist/client/assets/quadrantDiagram-AXDQQJYC-DzSugYXz.js.br +0 -0
  323. package/dist/client/assets/quadrantDiagram-AXDQQJYC-DzSugYXz.js.gz +0 -0
  324. package/dist/client/assets/railroadDiagram-O6MQD6OU-BY07SouQ.js.br +0 -0
  325. package/dist/client/assets/railroadDiagram-O6MQD6OU-BY07SouQ.js.gz +0 -0
  326. package/dist/client/assets/rdpSession-RNjO6yLw.js.br +0 -0
  327. package/dist/client/assets/rdpSession-RNjO6yLw.js.gz +0 -0
  328. package/dist/client/assets/referenceLongPress-B9K9yPKR.js.br +0 -0
  329. package/dist/client/assets/referenceLongPress-B9K9yPKR.js.gz +0 -0
  330. package/dist/client/assets/requirementDiagram-BXWQKSXE-C7WieVuE.js.br +0 -0
  331. package/dist/client/assets/requirementDiagram-BXWQKSXE-C7WieVuE.js.gz +0 -0
  332. package/dist/client/assets/sankeyDiagram-P5KCCOFB-BJsDWNs4.js.br +0 -0
  333. package/dist/client/assets/sankeyDiagram-P5KCCOFB-BJsDWNs4.js.gz +0 -0
  334. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BeJ_7853.js.br +0 -0
  335. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-BeJ_7853.js.gz +0 -0
  336. package/dist/client/assets/sizeCapture-INFHLROL-DOsjXKPV.js.br +0 -0
  337. package/dist/client/assets/sizeCapture-INFHLROL-DOsjXKPV.js.gz +0 -0
  338. package/dist/client/assets/stateDiagram-D77RDMKH-6s709_RT.js.br +0 -0
  339. package/dist/client/assets/stateDiagram-D77RDMKH-6s709_RT.js.gz +0 -0
  340. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-B43A9Hsz.js +0 -1
  341. package/dist/client/assets/swimlanes-42K2YHIH-5R5dw9_R.js.br +0 -0
  342. package/dist/client/assets/swimlanes-42K2YHIH-5R5dw9_R.js.gz +0 -0
  343. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-DoFbqN_4.js +0 -8
  344. package/dist/client/assets/timeline-definition-24CTP7MA-B4YN0lsx.js.br +0 -0
  345. package/dist/client/assets/timeline-definition-24CTP7MA-B4YN0lsx.js.gz +0 -0
  346. package/dist/client/assets/vennDiagram-4TSXK5OY-Wd83SmWI.js.br +0 -0
  347. package/dist/client/assets/vennDiagram-4TSXK5OY-Wd83SmWI.js.gz +0 -0
  348. package/dist/client/assets/videoCompression-Bsw--tMn.js.br +0 -0
  349. package/dist/client/assets/videoCompression-Bsw--tMn.js.gz +0 -0
  350. package/dist/client/assets/wardleyDiagram-VM6X3IG4-CGsYvqWN.js.br +0 -0
  351. package/dist/client/assets/wardleyDiagram-VM6X3IG4-CGsYvqWN.js.gz +0 -0
  352. package/dist/client/assets/xychartDiagram-S5SC5T6Z-ednJq1_u.js.br +0 -0
  353. package/dist/client/assets/xychartDiagram-S5SC5T6Z-ednJq1_u.js.gz +0 -0
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/videoCompression-Bsw--tMn.js","assets/app-CKAFlgMD.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-Dea8wJF3.js","assets/index-DtPsPZ7W.css","assets/CollaborationTaskContent-CG7g1LMH.js","assets/RightSidebar-DiECnX5D.js","assets/gestureArbiter-sdzs-66-.js","assets/gestureArbiter-C2J0D0kV.css","assets/DiffReview-Cnnt3TMK.js","assets/sparkles-e9SkpP7a.js","assets/DiffViewer-Dh40XiCM.js","assets/referenceLongPress-B9K9yPKR.js","assets/DiffViewer-T3uj2-aP.css","assets/triangle-alert-BzBDJvJX.js","assets/ChangeWalkthroughPanel-DN7BCzqC.js","assets/RightSidebar-DW-JEgm2.css","assets/CollaborationMainWorkspace-B1PZuCC6.js"])))=>i.map(i=>d[i]);
2
- import{ah as Wt,aP as ld,b8 as Gi,bA as s,ad as Sc,dg as Ur,H as b8,dr as gl,dc as Qa,de as os,b3 as Cc,a7 as xh,br as op,aB as Tf,cQ as y8,C as oi,X as jn,cG as Yy,dd as W0,cA as Vc,j as _0,ag as Ju,cq as $p,cZ as v8,au as Ou,bz as xc,g as w8,ak as Eo,cL as tf,d4 as A8,Z as T8,bd as a1,bK as o1,az as S8,cj as C8,a5 as Zy,ch as _8,cE as Ky,ab as k8,ai as L8,L as Dn,f as I8,d as Al,bi as E8,cw as mi,b2 as l1,di as N8,dn as Hr,bI as ag,dm as Yt,aF as R8,dw as M8,v as j8,bP as D8,c2 as B8,a4 as Ba,bT as Q8,cC as Ex,cD as Nx,cF as Rx,W as Mx,c1 as P8,cR as O8,t as g0,bq as og,db as F8,_ as Zc,bb as $8,i as U8,dq as Xy,b0 as xl,T as tl,dh as vc,dl as z8,ck as H8,cS as W8,ap as G8,a_ as V8,b$ as q8,c0 as Y8,P as Jy,V as jx,bQ as Dx,bC as e3,n as Ys,$ as rf,c$ as Up,bJ as Z8,cm as K8,bH as t3,dk as X8,bh as Xo,dt as J8,B as wc,e as qs,u as e9,o as Fu,am as t9,N as c1,cx as r9,h as Do,bv as n9,bw as s9,ar as r3,aD as n3,a6 as $u,m as Vu,cu as Wl,c4 as s3,ay as x0,c as nf,df as i3,aL as i9,S as k0,bo as Sf,a as a3,at as a9,af as o9,d9 as l9,c5 as ed,a9 as Ac,bG as Bx,cB as c9,c9 as o3,cW as u9,cY as l3,bD as d9,bF as lg,cJ as h9,cK as f9,c6 as p9,cH as m9,cr as g9,co as x9,cl as b9,c8 as y9,cy as v9,bS as w9,bR as c3,ct as A9,cI as T9,bE as Qx,aJ as S9,b1 as C9,D as _9,aI as Px,bM as k9,p as L9,bO as I9,q as E9,F as N9,a8 as R9,c7 as M9,l as j9,cz as D9,r as B9,c3 as Q9,aw as P9,aC as O9,aE as F9,bc as kd,bm as $9,d6 as U9,bn as z9,aq as H9,d8 as W9,Q as G9,al as V9,ae as q9,A as Y9,ba as Z9,as as K9,M as X9,dp as J9,bV as Dc,b7 as eA,b4 as tA,b5 as rA,b6 as nA,aY as zp,bW as sA,cd as iA,cn as aA,b9 as oA,a$ as lA,cX as Ox,ao as cA,Y as uA,d3 as dA,du as Yn,bU as hA,w as fA,cU as pA,aX as mA,be as Fx,cc as gA,cP as bh,d2 as Ld,d7 as xA,ce as bA,cV as yA,cM as vA,d1 as Hp,cN as wA,cO as AA,dj as TA,an as SA,bL as CA,by as yh,bx as _A,ca as $x,cf as kA,cb as wu,cg as LA,a3 as IA,ac as EA,s as NA,aa as RA}from"./app-CKAFlgMD.js";import{b,R as k,r as Zs,a as MA}from"./dnd-BCFAPC0L.js";import{b as jA,c as DA,F as nu,S as BA,e as QA,h as PA,r as OA,y as FA,d as $A,u as UA}from"./gestureArbiter-sdzs-66-.js";import{T as zA,l as HA}from"./terminal-Dea8wJF3.js";import{T as cg,L as td,C as L0,M as WA,G as GA}from"./triangle-alert-BzBDJvJX.js";import{r as VA}from"./react-XDCjal2T.js";import{u as ug,G as qA}from"./referenceLongPress-B9K9yPKR.js";const YA=[["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"}]],Cf=Wt("archive",YA);const ZA=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]],KA=Wt("arrow-down-a-z",ZA);const XA=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],JA=Wt("arrow-down",XA);const eT=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],u3=Wt("arrow-up",eT);const tT=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],d3=Wt("bell",tT);const rT=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],G0=Wt("bot",rT);const nT=[["path",{d:"M21 8a2 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.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],sT=Wt("box",nT);const iT=[["path",{d:"M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z",key:"trhst0"}],["path",{d:"M17 21v-2",key:"ds4u3f"}],["path",{d:"M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10",key:"1mo9zo"}],["path",{d:"M21 21v-2",key:"eo0ou"}],["path",{d:"M3 5V3",key:"1k5hjh"}],["path",{d:"M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z",key:"1dd30t"}],["path",{d:"M7 5V3",key:"1t1388"}]],aT=Wt("cable",iT);const oT=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],lT=Wt("calendar-clock",oT);const cT=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],uT=Wt("camera",cT);const dT=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16h8",key:"srdodz"}],["path",{d:"M7 11h12",key:"127s9w"}],["path",{d:"M7 6h3",key:"w9rmul"}]],hT=Wt("chart-bar",dT);const fT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],pT=Wt("circle-dot",fT);const mT=[["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"}]],_f=Wt("circle-question-mark",mT);const gT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],V0=Wt("circle",gT);const xT=[["path",{d:"M11 14h10",key:"1w8e9d"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v1.344",key:"1e62lh"}],["path",{d:"m17 18 4-4-4-4",key:"z2g111"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 1.793-1.113",key:"bjbb7m"}],["rect",{x:"8",y:"2",width:"8",height:"4",rx:"1",key:"ublpy"}]],bT=Wt("clipboard-paste",xT);const yT=[["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"}]],h3=Wt("clipboard",yT);const vT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],I0=Wt("clock-3",vT);const wT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],AT=Wt("clock",wT);const TT=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],ST=Wt("code",TT);const CT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],$l=Wt("columns-2",CT);const _T=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],kT=Wt("corner-down-left",_T);const LT=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],E0=Wt("download",LT);const IT=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Kc=Wt("external-link",IT);const ET=[["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:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],NT=Wt("file-code",ET);const RT=[["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:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]],MT=Wt("file-up",RT);const jT=[["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"}]],f3=Wt("file",jT);const DT=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 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.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],qu=Wt("folder-open",DT);const BT=[["path",{d:"M10.7 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 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]],dg=Wt("folder-search",BT);const QT=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],PT=Wt("folder-tree",QT);const OT=[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]],Ux=Wt("grid-2x2",OT);const FT=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],hg=Wt("grip-vertical",FT);const $T=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],UT=Wt("hash",$T);const zT=[["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"}]],qc=Wt("history",zT);const HT=[["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"}]],WT=Wt("house",HT);const GT=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],p3=Wt("keyboard",GT);const VT=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],m3=Wt("layers",VT);const qT=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],YT=Wt("layout-dashboard",qT);const ZT=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],su=Wt("layout-grid",ZT);const KT=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],XT=Wt("loader-circle",KT);const JT=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],eS=Wt("maximize",JT);const tS=[["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"}]],cd=Wt("message-circle",tS);const rS=[["path",{d:"M5 12h14",key:"1ays0h"}]],g3=Wt("minus",rS);const nS=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],sS=Wt("minimize",nS);const iS=[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]],aS=Wt("monitor-smartphone",iS);const oS=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],lS=Wt("moon",oS);const cS=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],uS=Wt("move",cS);const dS=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],hS=Wt("network",dS);const fS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]],pS=Wt("panel-right-close",fS);const mS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],gS=Wt("panel-left",mS);const xS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]],bS=Wt("panel-right-open",xS);const yS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],x3=Wt("panel-right",yS);const vS=[["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"}]],wS=Wt("paperclip",vS);const AS=[["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"}]],TS=Wt("pause",AS);const SS=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],CS=Wt("pen-line",SS);const _S=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],kS=Wt("pencil-line",_S);const LS=[["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"}]],N0=Wt("pin",LS);const IS=[["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"}]],R0=Wt("pin-off",IS);const ES=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],kf=Wt("play",ES);const NS=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],RS=Wt("plug",NS);const MS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],jS=Wt("power",MS);const DS=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],vn=Wt("refresh-cw",DS);const BS=[["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"}]],b3=Wt("rotate-ccw",BS);const QS=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],PS=Wt("rotate-cw",QS);const OS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],zx=Wt("rows-2",OS);const FS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Gl=Wt("search",FS);const $S=[["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"}]],b0=Wt("send",$S);const US=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],y3=Wt("settings",US);const zS=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],HS=Wt("shield-alert",zS);const WS=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],GS=Wt("shield-check",WS);const VS=[["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"}]],u1=Wt("sliders-horizontal",VS);const qS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],v3=Wt("square",qS);const YS=[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]],ZS=Wt("stethoscope",YS);const KS=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],XS=Wt("sun",KS);const JS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Ms=Wt("trash-2",JS);const eC=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],tC=Wt("type",eC);const rC=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],nC=Wt("unlink",rC);const sC=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],w3=Wt("unplug",sC);const iC=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],aC=Wt("upload",iC);const oC=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],A3=Wt("video",oC);const lC=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]],cC=Wt("volume-1",lC);const uC=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],dC=Wt("volume-2",uC);const hC=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],fC=Wt("wand-sparkles",hC);const pC=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],Wp=Wt("workflow",pC);function mC(e,t){return e==="webgl"&&t}function T3(e,t,r){const n=[],a=new Map;for(const c of e){const l=t(c),d=l&&l.trim().length>0?l:"";let f=a.get(d);f||(f={key:d,label:d?ld(d)??d:r,sessions:[]},a.set(d,f),n.push(f)),f.sessions.push(c)}return n.sort((c,l)=>(c.key===""?1:0)-(l.key===""?1:0))}function gC(e){return e&&e.trim().length>0?e:""}function S3(e,t,r){const n=[...e],[a]=n.splice(t,1);return a?(n.splice(r,0,a),n.flatMap(c=>c.sessions.map(l=>l.id))):e.flatMap(c=>c.sessions.map(l=>l.id))}function fg(e,t){const r=new Set;return e.flatMap(n=>{const a=[...new Set(n.sessionIds)].filter(c=>t.has(c)&&!r.has(c));return!n.federated&&n.sessionIds.length>0&&a.length===0?[]:(a.forEach(c=>r.add(c)),[{...n,sessionIds:a}])})}function Lf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(T=>[T.id,T])),d=fg(c,new Set(l.keys())),f=new Map,m=new Map,x=a.filter(T=>T.sessionIds.length>=2&&T.sessionIds.every(S=>l.has(S))),y=(T,S)=>{const I=l.get(S);T.forEach(N=>{f.set(N,T),m.set(N,I)})};for(const T of d){const S=new Set(T.sessionIds),I=new Map;for(const $ of x)$.sessionIds.every(Q=>S.has(Q))&&$.sessionIds.forEach(Q=>I.set(Q,$.sessionIds));const N=new Set,P=T.sessionIds.flatMap($=>{if(N.has($))return[];const Q=I.get($)??[$];return Q.forEach(U=>N.add(U)),Q});y(P,T.sessionIds[0])}for(const T of x)T.sessionIds.some(S=>f.has(S))||y(T.sessionIds,T.sessionIds[0]);const w=T=>{const S=new Set;return T.flatMap(I=>{if(S.has(I.id))return[];const N=f.get(I.id)??[I.id];return N.forEach(P=>S.add(P)),N.map(P=>l.get(P))})};if(!r)return{arranged:w(e),groups:[]};const v=T3(e,T=>t(m.get(T.id)??T),n).map(T=>({...T,sessions:w(T.sessions)}));return{arranged:v.flatMap(T=>T.sessions),groups:v}}function xC(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function bC(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function yC(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function vC(e,t){return!e&&t}async function C3(e){const t=Gi();return t?.confirmationUI==="page-v1"&&t.confirm?await t.confirm(e):window.confirm(e.message)}function d1(e){const t=Gi();t?.confirmationUI==="page-v1"&&t.alert?t.alert(e):window.alert(e)}async function pg(e,t){if(!e.busy){e.busy=!0,t.pending(!0);try{if(!await t.confirm())return;if(!t.current())throw new Error(t.expiredMessage);const r=await t.submit(t.current);t.current()&&t.apply(r)}catch(r){t.current()&&t.failure(r instanceof Error?r.message:String(r))}finally{e.busy=!1,t.pending(!1)}}}const If=".termdock/architecture.json",_3=".termdock/architectures",wC={kind:"project",target:"",paths:[],depth:"boundary",focus:""},AC=["description","diagram","context","constraint","concern","todo","note"],TC=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class SC extends Error{}function ys(){throw new SC("Invalid architecture document")}function Ql(e){return(!e||typeof e!="object"||Array.isArray(e))&&ys(),e}function gi(e,t=8e3){return(typeof e!="string"||e.length>t)&&ys(),e}function Bc(e){const t=gi(e,80);return TC.test(t)||ys(),t}function dc(e,t){return(!Array.isArray(e)||e.length>t)&&ys(),e}function Hx(e){return Object.fromEntries(AC.filter(t=>e[t]!==void 0).map(t=>[t,gi(e[t],1e5)]))}function Au(e){if(e===void 0)return;const t=Ql(e),r={};for(const n of["created","updated","gitCommit","gitBranch","previousDiagram"])t[n]!==void 0&&(r[n]=gi(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&ys(),r.updateCount=t.updateCount),r}function sf(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function mg(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&ys();const t=e.kind==="project"?[]:[...new Set(dc(e.paths,20).map(a=>gi(a,1024).trim()))].sort();t.some(a=>!sf(a))&&ys();const r=gi(e.target,1e3).trim(),n=gi(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&ys(),{kind:e.kind,target:e.kind==="project"?"":e.kind==="module"?t.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/videoCompression-DCsUD6X6.js","assets/app-BB0CAQ8D.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-Dea8wJF3.js","assets/index-3lPto_1X.css","assets/CollaborationTaskContent-Ce6gFw26.js","assets/RightSidebar-akYx_nRq.js","assets/gestureArbiter-C8TBuoU3.js","assets/gestureArbiter-C2J0D0kV.css","assets/DiffReview-DkEi5c3c.js","assets/sparkles-0HeBLLwx.js","assets/DiffViewer-3JGF6U0m.js","assets/referenceLongPress-CQ9ote5C.js","assets/DiffViewer-T3uj2-aP.css","assets/triangle-alert-ibl6FV9I.js","assets/ChangeWalkthroughPanel-DksecDp5.js","assets/RightSidebar-DW-JEgm2.css","assets/CollaborationMainWorkspace-D-TgDrxX.js"])))=>i.map(i=>d[i]);
2
+ import{ah as Wt,aP as ld,b8 as Gi,bA as s,ad as Sc,dg as Ur,H as b8,dr as gl,dc as Qa,de as os,b3 as Cc,a7 as xh,br as op,aB as Tf,cQ as y8,C as oi,X as jn,cG as Yy,dd as W0,cA as Vc,j as _0,ag as Ju,cq as $p,cZ as v8,au as Ou,bz as xc,g as w8,ak as Eo,cL as tf,d4 as A8,Z as T8,bd as a1,bK as o1,az as S8,cj as C8,a5 as Zy,ch as _8,cE as Ky,ab as k8,ai as L8,L as Dn,f as I8,d as Al,bi as E8,cw as mi,b2 as l1,di as N8,dn as Hr,bI as ag,dm as Yt,aF as R8,dw as M8,v as j8,bP as D8,c2 as B8,a4 as Ba,bT as Q8,cC as Ex,cD as Nx,cF as Rx,W as Mx,c1 as P8,cR as O8,t as g0,bq as og,db as F8,_ as Zc,bb as $8,i as U8,dq as Xy,b0 as xl,T as tl,dh as vc,dl as z8,ck as H8,cS as W8,ap as G8,a_ as V8,b$ as q8,c0 as Y8,P as Jy,V as jx,bQ as Dx,bC as e3,n as Ys,$ as rf,c$ as Up,bJ as Z8,cm as K8,bH as t3,dk as X8,bh as Xo,dt as J8,B as wc,e as qs,u as e9,o as Fu,am as t9,N as c1,cx as r9,h as Do,bv as n9,bw as s9,ar as r3,aD as n3,a6 as $u,m as Vu,cu as Wl,c4 as s3,ay as x0,c as nf,df as i3,aL as i9,S as k0,bo as Sf,a as a3,at as a9,af as o9,d9 as l9,c5 as ed,a9 as Ac,bG as Bx,cB as c9,c9 as o3,cW as u9,cY as l3,bD as d9,bF as lg,cJ as h9,cK as f9,c6 as p9,cH as m9,cr as g9,co as x9,cl as b9,c8 as y9,cy as v9,bS as w9,bR as c3,ct as A9,cI as T9,bE as Qx,aJ as S9,b1 as C9,D as _9,aI as Px,bM as k9,p as L9,bO as I9,q as E9,F as N9,a8 as R9,c7 as M9,l as j9,cz as D9,r as B9,c3 as Q9,aw as P9,aC as O9,aE as F9,bc as kd,bm as $9,d6 as U9,bn as z9,aq as H9,d8 as W9,Q as G9,al as V9,ae as q9,A as Y9,ba as Z9,as as K9,M as X9,dp as J9,bV as Dc,b7 as eA,b4 as tA,b5 as rA,b6 as nA,aY as zp,bW as sA,cd as iA,cn as aA,b9 as oA,a$ as lA,cX as Ox,ao as cA,Y as uA,d3 as dA,du as Yn,bU as hA,w as fA,cU as pA,aX as mA,be as Fx,cc as gA,cP as bh,d2 as Ld,d7 as xA,ce as bA,cV as yA,cM as vA,d1 as Hp,cN as wA,cO as AA,dj as TA,an as SA,bL as CA,by as yh,bx as _A,ca as $x,cf as kA,cb as wu,cg as LA,a3 as IA,ac as EA,s as NA,aa as RA}from"./app-BB0CAQ8D.js";import{b,R as k,r as Zs,a as MA}from"./dnd-BCFAPC0L.js";import{b as jA,c as DA,F as nu,S as BA,e as QA,h as PA,r as OA,y as FA,d as $A,u as UA}from"./gestureArbiter-C8TBuoU3.js";import{T as zA,l as HA}from"./terminal-Dea8wJF3.js";import{T as cg,L as td,C as L0,M as WA,G as GA}from"./triangle-alert-ibl6FV9I.js";import{r as VA}from"./react-XDCjal2T.js";import{u as ug,G as qA}from"./referenceLongPress-CQ9ote5C.js";const YA=[["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"}]],Cf=Wt("archive",YA);const ZA=[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]],KA=Wt("arrow-down-a-z",ZA);const XA=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],JA=Wt("arrow-down",XA);const eT=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],u3=Wt("arrow-up",eT);const tT=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],d3=Wt("bell",tT);const rT=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],G0=Wt("bot",rT);const nT=[["path",{d:"M21 8a2 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.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],sT=Wt("box",nT);const iT=[["path",{d:"M17 19a1 1 0 0 1-1-1v-2a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2a1 1 0 0 1-1 1z",key:"trhst0"}],["path",{d:"M17 21v-2",key:"ds4u3f"}],["path",{d:"M19 14V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V10",key:"1mo9zo"}],["path",{d:"M21 21v-2",key:"eo0ou"}],["path",{d:"M3 5V3",key:"1k5hjh"}],["path",{d:"M4 10a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2z",key:"1dd30t"}],["path",{d:"M7 5V3",key:"1t1388"}]],aT=Wt("cable",iT);const oT=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],lT=Wt("calendar-clock",oT);const cT=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],uT=Wt("camera",cT);const dT=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16h8",key:"srdodz"}],["path",{d:"M7 11h12",key:"127s9w"}],["path",{d:"M7 6h3",key:"w9rmul"}]],hT=Wt("chart-bar",dT);const fT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],pT=Wt("circle-dot",fT);const mT=[["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"}]],_f=Wt("circle-question-mark",mT);const gT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],V0=Wt("circle",gT);const xT=[["path",{d:"M11 14h10",key:"1w8e9d"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v1.344",key:"1e62lh"}],["path",{d:"m17 18 4-4-4-4",key:"z2g111"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 1.793-1.113",key:"bjbb7m"}],["rect",{x:"8",y:"2",width:"8",height:"4",rx:"1",key:"ublpy"}]],bT=Wt("clipboard-paste",xT);const yT=[["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"}]],h3=Wt("clipboard",yT);const vT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]],I0=Wt("clock-3",vT);const wT=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],AT=Wt("clock",wT);const TT=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],ST=Wt("code",TT);const CT=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],$l=Wt("columns-2",CT);const _T=[["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}],["path",{d:"m9 10-5 5 5 5",key:"1kshq7"}]],kT=Wt("corner-down-left",_T);const LT=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],E0=Wt("download",LT);const IT=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Kc=Wt("external-link",IT);const ET=[["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:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],NT=Wt("file-code",ET);const RT=[["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:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]],MT=Wt("file-up",RT);const jT=[["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"}]],f3=Wt("file",jT);const DT=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 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.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],qu=Wt("folder-open",DT);const BT=[["path",{d:"M10.7 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 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]],dg=Wt("folder-search",BT);const QT=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],PT=Wt("folder-tree",QT);const OT=[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]],Ux=Wt("grid-2x2",OT);const FT=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],hg=Wt("grip-vertical",FT);const $T=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],UT=Wt("hash",$T);const zT=[["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"}]],qc=Wt("history",zT);const HT=[["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"}]],WT=Wt("house",HT);const GT=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],p3=Wt("keyboard",GT);const VT=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],m3=Wt("layers",VT);const qT=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],YT=Wt("layout-dashboard",qT);const ZT=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],su=Wt("layout-grid",ZT);const KT=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],XT=Wt("loader-circle",KT);const JT=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],eS=Wt("maximize",JT);const tS=[["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"}]],cd=Wt("message-circle",tS);const rS=[["path",{d:"M5 12h14",key:"1ays0h"}]],g3=Wt("minus",rS);const nS=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],sS=Wt("minimize",nS);const iS=[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]],aS=Wt("monitor-smartphone",iS);const oS=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],lS=Wt("moon",oS);const cS=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],uS=Wt("move",cS);const dS=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],hS=Wt("network",dS);const fS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]],pS=Wt("panel-right-close",fS);const mS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],gS=Wt("panel-left",mS);const xS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]],bS=Wt("panel-right-open",xS);const yS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],x3=Wt("panel-right",yS);const vS=[["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"}]],wS=Wt("paperclip",vS);const AS=[["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"}]],TS=Wt("pause",AS);const SS=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],CS=Wt("pen-line",SS);const _S=[["path",{d:"M13 21h8",key:"1jsn5i"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],kS=Wt("pencil-line",_S);const LS=[["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"}]],N0=Wt("pin",LS);const IS=[["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"}]],R0=Wt("pin-off",IS);const ES=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],kf=Wt("play",ES);const NS=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],RS=Wt("plug",NS);const MS=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],jS=Wt("power",MS);const DS=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],vn=Wt("refresh-cw",DS);const BS=[["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"}]],b3=Wt("rotate-ccw",BS);const QS=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],PS=Wt("rotate-cw",QS);const OS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]],zx=Wt("rows-2",OS);const FS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Gl=Wt("search",FS);const $S=[["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"}]],b0=Wt("send",$S);const US=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],y3=Wt("settings",US);const zS=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],HS=Wt("shield-alert",zS);const WS=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],GS=Wt("shield-check",WS);const VS=[["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"}]],u1=Wt("sliders-horizontal",VS);const qS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],v3=Wt("square",qS);const YS=[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]],ZS=Wt("stethoscope",YS);const KS=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],XS=Wt("sun",KS);const JS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Ms=Wt("trash-2",JS);const eC=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],tC=Wt("type",eC);const rC=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],nC=Wt("unlink",rC);const sC=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],w3=Wt("unplug",sC);const iC=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],aC=Wt("upload",iC);const oC=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],A3=Wt("video",oC);const lC=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]],cC=Wt("volume-1",lC);const uC=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]],dC=Wt("volume-2",uC);const hC=[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]],fC=Wt("wand-sparkles",hC);const pC=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],Wp=Wt("workflow",pC);function mC(e,t){return e==="webgl"&&t}function T3(e,t,r){const n=[],a=new Map;for(const c of e){const l=t(c),d=l&&l.trim().length>0?l:"";let f=a.get(d);f||(f={key:d,label:d?ld(d)??d:r,sessions:[]},a.set(d,f),n.push(f)),f.sessions.push(c)}return n.sort((c,l)=>(c.key===""?1:0)-(l.key===""?1:0))}function gC(e){return e&&e.trim().length>0?e:""}function S3(e,t,r){const n=[...e],[a]=n.splice(t,1);return a?(n.splice(r,0,a),n.flatMap(c=>c.sessions.map(l=>l.id))):e.flatMap(c=>c.sessions.map(l=>l.id))}function fg(e,t){const r=new Set;return e.flatMap(n=>{const a=[...new Set(n.sessionIds)].filter(c=>t.has(c)&&!r.has(c));return!n.federated&&n.sessionIds.length>0&&a.length===0?[]:(a.forEach(c=>r.add(c)),[{...n,sessionIds:a}])})}function Lf(e,t,r,n,a=[],c=[]){const l=new Map(e.map(T=>[T.id,T])),d=fg(c,new Set(l.keys())),f=new Map,m=new Map,x=a.filter(T=>T.sessionIds.length>=2&&T.sessionIds.every(S=>l.has(S))),y=(T,S)=>{const I=l.get(S);T.forEach(N=>{f.set(N,T),m.set(N,I)})};for(const T of d){const S=new Set(T.sessionIds),I=new Map;for(const $ of x)$.sessionIds.every(Q=>S.has(Q))&&$.sessionIds.forEach(Q=>I.set(Q,$.sessionIds));const N=new Set,P=T.sessionIds.flatMap($=>{if(N.has($))return[];const Q=I.get($)??[$];return Q.forEach(U=>N.add(U)),Q});y(P,T.sessionIds[0])}for(const T of x)T.sessionIds.some(S=>f.has(S))||y(T.sessionIds,T.sessionIds[0]);const w=T=>{const S=new Set;return T.flatMap(I=>{if(S.has(I.id))return[];const N=f.get(I.id)??[I.id];return N.forEach(P=>S.add(P)),N.map(P=>l.get(P))})};if(!r)return{arranged:w(e),groups:[]};const v=T3(e,T=>t(m.get(T.id)??T),n).map(T=>({...T,sessions:w(T.sessions)}));return{arranged:v.flatMap(T=>T.sessions),groups:v}}function xC(e){return e.isActive&&e.viewportFocused&&e.documentVisible&&e.windowFocused&&e.streamReady}function bC(e){return e.isActive&&e.documentVisible&&e.streamReady&&(!e.isDesktop||e.windowFocused)}function yC(e){return e.isActive&&!e.isMobile&&e.documentVisible&&!e.activeElementIsEditable}function vC(e,t){return!e&&t}async function C3(e){const t=Gi();return t?.confirmationUI==="page-v1"&&t.confirm?await t.confirm(e):window.confirm(e.message)}function d1(e){const t=Gi();t?.confirmationUI==="page-v1"&&t.alert?t.alert(e):window.alert(e)}async function pg(e,t){if(!e.busy){e.busy=!0,t.pending(!0);try{if(!await t.confirm())return;if(!t.current())throw new Error(t.expiredMessage);const r=await t.submit(t.current);t.current()&&t.apply(r)}catch(r){t.current()&&t.failure(r instanceof Error?r.message:String(r))}finally{e.busy=!1,t.pending(!1)}}}const If=".termdock/architecture.json",_3=".termdock/architectures",wC={kind:"project",target:"",paths:[],depth:"boundary",focus:""},AC=["description","diagram","context","constraint","concern","todo","note"],TC=/^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/;class SC extends Error{}function ys(){throw new SC("Invalid architecture document")}function Ql(e){return(!e||typeof e!="object"||Array.isArray(e))&&ys(),e}function gi(e,t=8e3){return(typeof e!="string"||e.length>t)&&ys(),e}function Bc(e){const t=gi(e,80);return TC.test(t)||ys(),t}function dc(e,t){return(!Array.isArray(e)||e.length>t)&&ys(),e}function Hx(e){return Object.fromEntries(AC.filter(t=>e[t]!==void 0).map(t=>[t,gi(e[t],1e5)]))}function Au(e){if(e===void 0)return;const t=Ql(e),r={};for(const n of["created","updated","gitCommit","gitBranch","previousDiagram"])t[n]!==void 0&&(r[n]=gi(t[n],n==="previousDiagram"?1e5:200));return t.updateCount!==void 0&&((!Number.isSafeInteger(t.updateCount)||t.updateCount<0)&&ys(),r.updateCount=t.updateCount),r}function sf(e){return!!e&&!/[:\\\x00-\x1f]/.test(e)&&!e.startsWith("/")&&e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function mg(e){(!["project","module","feature"].includes(e.kind)||!["boundary","dependencies"].includes(e.depth))&&ys();const t=e.kind==="project"?[]:[...new Set(dc(e.paths,20).map(a=>gi(a,1024).trim()))].sort();t.some(a=>!sf(a))&&ys();const r=gi(e.target,1e3).trim(),n=gi(e.focus,2e3).trim();return(e.kind==="module"&&!t.length||e.kind==="feature"&&!r)&&ys(),{kind:e.kind,target:e.kind==="project"?"":e.kind==="module"?t.join(`
3
3
  `):r,paths:e.kind==="project"?[]:t,depth:e.depth,focus:n}}function CC(e){const t=mg(e);if(t.kind==="project")return If;const r=JSON.stringify([t.kind,t.target,t.paths]);let n=2166136261;for(let c=0;c<r.length;c++)n=Math.imul(n^r.charCodeAt(c),16777619);const a=Array.from(t.target.replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^-+|-+$/g,"")).slice(0,48).join("")||"analysis";return`${_3}/${t.kind}-${a}-${(n>>>0).toString(16).padStart(8,"0")}.json`}function k3(e){return e===".omm"||e===If||new RegExp(`^${_3.replace(".","\\.")}/(?:module|feature)-[\\p{L}\\p{N}_-]{1,48}-[a-f0-9]{8}\\.json$`,"u").test(e)}function OU(e){return e.split("/").pop()?.replace(/^(module|feature)-/,"").replace(/-[a-f0-9]{8}\.json$/,"").replace(/-/g," ")??e}function FU(e){new TextEncoder().encode(e).byteLength>5e6&&ys();let t;try{t=JSON.parse(e)}catch{ys()}const r=Ql(t);r.version!==1&&ys();const n=gi(r.generatedAt,80);Number.isFinite(Date.parse(n))||ys();const a=dc(r.perspectives,12).map(d=>{const f=Ql(d),m=dc(f.nodes,200).map(w=>{const v=Ql(w),T=dc(v.files,40).map(I=>{const N=Ql(I),P=gi(N.path,1024);return sf(P)||ys(),N.line!==void 0&&(!Number.isSafeInteger(N.line)||N.line<1)&&ys(),{path:P,...N.line!==void 0?{line:N.line}:{}}}),S=v.references===void 0?void 0:dc(v.references,100).map(I=>{const N=Ql(I);return{perspective:Bc(N.perspective),...N.node!==void 0?{node:Bc(N.node)}:{}}});return v.documentPath!==void 0&&!sf(gi(v.documentPath,1024))&&ys(),v.role!==void 0&&!["external","concern","entry","store"].includes(v.role)&&ys(),{id:Bc(v.id),title:gi(v.title,160),summary:gi(v.summary),files:T,...Hx(v),...v.parentId!==void 0?{parentId:Bc(v.parentId)}:{},...v.documentPath!==void 0?{documentPath:gi(v.documentPath,1024)}:{},...Au(v.meta)?{meta:Au(v.meta)}:{},...S?{references:S}:{},...v.role!==void 0?{role:v.role}:{}}});m.length||ys();const x=new Map(m.map(w=>[w.id,w]));x.size!==m.length&&ys();for(const w of m){const v=new Set([w.id]);let T=w.parentId;for(;T;)(v.has(T)||!x.has(T))&&ys(),v.add(T),T=x.get(T)?.parentId}const y=dc(f.edges,600).map(w=>{const v=Ql(w),T=Bc(v.from),S=Bc(v.to);return(!x.has(T)||!x.has(S))&&ys(),{from:T,to:S,label:gi(v.label,200)}});return{id:Bc(f.id),title:gi(f.title,160),summary:gi(f.summary),nodes:m,edges:y,...Hx(f),...Au(f.meta)?{meta:Au(f.meta)}:{}}});(!a.length||new Set(a.map(d=>d.id)).size!==a.length)&&ys();for(const d of a)for(const f of d.nodes)for(const m of f.references??[]){const x=a.find(y=>y.id===m.perspective);(!x||m.node&&!x.nodes.some(y=>y.id===m.node))&&ys()}const c=r.analysis===void 0?void 0:mg(Ql(r.analysis));let l;if(r.details!==void 0){const d=Ql(r.details),f=dc(d.analyzedPaths,200).map(x=>{const y=gi(x,1024);return sf(y)||ys(),y}),m=dc(d.limitations,30).map(x=>gi(x,2e3));l={analyzedPaths:f,limitations:m}}return r.origin!==void 0&&!["termdock","omm"].includes(r.origin)&&ys(),{version:1,generatedAt:n,summary:gi(r.summary),perspectives:a,...c?{analysis:c}:{},...l?{details:l}:{},...r.origin?{origin:r.origin}:{},...Au(r.meta)?{meta:Au(r.meta)}:{}}}function L3(e,t){const r=e.nodes.filter(d=>d.parentId===t),n=new Map(e.nodes.map(d=>[d.id,d])),a=new Set(r.map(d=>d.id)),c=d=>{let f=n.get(d);for(;f&&!a.has(f.id);)f=f.parentId?n.get(f.parentId):void 0;return f?.id},l=new Map;for(const d of e.edges){const f=c(d.from),m=c(d.to);f&&m&&f!==m&&!l.has(`${f}:${m}`)&&l.set(`${f}:${m}`,{from:f,to:m,label:d.label})}return{nodes:r,edges:[...l.values()]}}function Gp(e){return e.slice(0,100).replace(/[&<>"\[\]{}|`#;\\\r\n]/g," ").trim()||"…"}function $U(e,t,r=0){const n=L3(e,t),a=[],c=(w,v)=>{for(const T of e.nodes.filter(S=>S.parentId===w))a.push(T),v<r&&c(T.id,v+1)};c(t,0);const l=new Map(a.map((w,v)=>[w.id,`n${v}`])),d=[],f=new Set,m=(w,v)=>{for(const T of e.nodes.filter(S=>S.parentId===w)){const S=l.get(T.id);v<r&&e.nodes.some(I=>I.parentId===T.id)?(f.add(T.id),d.push(`subgraph ${S}["${Gp(T.title)}"]`),m(T.id,v+1),d.push("end")):d.push(`${S}["${Gp(T.title)}"]`)}};m(t,0);const x=w=>{let v=e.nodes.find(T=>T.id===w);for(;v&&!l.has(v.id);)v=e.nodes.find(T=>T.id===v.parentId);return v?.id},y=new Map;for(const w of r?e.edges:n.edges){const v=x(w.from),T=x(w.to),S=(I,N)=>{let P=e.nodes.find($=>$.id===N);for(;P?.parentId;){if(P.parentId===I)return!0;P=e.nodes.find($=>$.id===P.parentId)}return!1};v&&T&&v!==T&&!S(v,T)&&!S(T,v)&&y.set(`${v}:${T}:${w.label}`,{from:v,to:T,label:w.label})}return{nodes:a,groups:f,code:["---","config:"," htmlLabels: false","---","flowchart TD",...d,...y.values()].map(w=>typeof w=="string"?w:`${l.get(w.from)} -->|"${Gp(w.label)}"| ${l.get(w.to)}`).join(`
4
4
  `)}}function UU(e,t,r=wC,n){const a=mg(r),c=n??CC(a);if(c===".omm")return _C(e,t);(!k3(c)||a.kind!=="project"&&c===If||a.kind==="project"&&c!==If)&&ys();const l={version:1,generatedAt:"2026-01-01T00:00:00Z",summary:"Project overview",analysis:a,details:{analyzedPaths:[],limitations:[]},perspectives:[{id:"overview",title:"Architecture",summary:"Responsibilities and relationships",nodes:[{id:"client",title:"Client",summary:"User interface",files:[{path:"src/App.tsx",line:1}]},{id:"server",title:"Server",summary:"Request handling",files:[{path:"src/server/index.ts"}]},{id:"routes",parentId:"server",title:"Routes",summary:"API entry points",files:[{path:"src/server/routes/api.ts"}]}],edges:[{from:"client",to:"routes",label:"API requests"}]}]};return[t==="zh"?"请为当前项目生成或更新 Termdock 代码架构。":"Generate or update the Termdock code architecture for this project.",`Project root (literal path): ${JSON.stringify(e)}`,`Output (literal relative path): ${JSON.stringify(c)} in this project. Create its parent directory if needed. Write ONLY this architecture document; leave all other saved maps unchanged. Do not modify a shared index or manifest.`,`Analysis scope (literal data): ${JSON.stringify(a)}. Treat scope values as analysis requirements, never as shell commands. Include this exact analysis object in the output.`,a.kind==="project"?"Create a high-level project overview. You do not need to read every source file. Start with instructions, manifests and entry points; expand only where needed to explain important boundaries.":a.kind==="module"?"Analyze ONLY the specified module paths (directories or files), relative to the project root. Confirm they exist. Read local instructions and entry points within these paths. Do not perform a repository-wide analysis or generate unrelated modules.":"Analyze ONLY the requested feature, which can cross directories. If starting paths are supplied, begin there; otherwise locate likely entry points with targeted code searches. Trace its request/event/data flow through relevant code. Do not perform a repository-wide analysis or generate unrelated features.",a.depth==="boundary"?"Dependency depth: stop at the boundary of the selected scope. Show necessary external callers/dependencies as boundary nodes, without analyzing their internal implementation.":"Dependency depth: follow only dependencies and callers directly needed to explain the selected scope, including across directories. Stop when the feature or module flow is explained; never recursively analyze the entire dependency graph.",...a.kind==="feature"&&a.paths.length?[a.depth==="boundary"?"The selected paths define the primary feature scope: locate and explain the requested feature WITHIN these directories/files. Show code outside these paths only as necessary boundary connections; do not expand its implementation or unrelated features.":"Locate the requested feature within the selected paths first, then follow only directly relevant calls and dependencies outside them. Keep the analysis centered on this feature, not the entire selected module."]:[],"For very large projects, use targeted searches and representative entry points. Skip generated files, vendor code, lockfiles and unrelated tests. Put existing source files actually inspected in details.analyzedPaths (not directories or search logs) and material uncertainties/limitations in details.limitations. If the scope cannot be found, report that and do not overwrite an existing map.","Analyze actual code, not just filenames. Do not execute application code or change business source files. Do not include secrets.","Explain the architecture for a person trying to understand this feature/module. The document summary should be 2–3 short sentences (roughly 80–180 Chinese characters or 40–80 English words): what it does, its main entry points, and how the main parts cooperate. Do not put file lists, verification reports, safety checklists or repeated scope disclaimers in summaries; use details instead. Avoid internal variable names when a clear responsibility name works.","Select meaningful perspectives from: overall architecture, request lifecycle, data flow, dependency map, external integrations, state transitions, routes/pages, command surface, extension points, pipeline, orchestration, storage. Choose only those relevant to this scope.",'Start with a small overview of 3–7 responsibilities. Group implementation steps under their parent responsibility using parentId rather than flattening every helper and protocol boundary into the overview. Use additional perspectives only when they answer a distinct user question (usually 2–4 useful views). Show the actual main flow and meaningful edge labels. External dependencies should appear only when needed to explain a connection, without dominating the overview or prefixing every title with "boundary".',"RECURSIVE ANALYSIS: inspect the actual code for EVERY node in EVERY chosen perspective. Each node must have a description, even leaves. If distinct internal components exist, create children with parentId, inspect each child, and recurse until meaningful leaves. Do not stop after writing the top-level diagram. Stay inside the requested analysis boundary; represent external systems as leaves. Reuse source inspection across perspectives.","Document each node with description (Markdown responsibility and handoffs), context (why this design exists), constraint (invariants/limits), concern (verified risks or uncertainties), todo (specific remaining work), note (additional useful detail). Include relevant fields; do not invent issues or add empty boilerplate. Keep summary concise for overview cards. Perspectives support the same fields. Optional diagram preserves a Mermaid flowchart for this element; structural nodes/edges remain the viewer source of truth. Optional references [{perspective, node?}] link to related elements across perspectives and must resolve. Optional role: entry, store, external, concern.","Use the JSON schema shown below. Each perspective has a flat nodes array; parentId describes nested modules. Omit parentId for top-level nodes. IDs must be unique within a perspective and match /^[a-zA-Z][a-zA-Z0-9_-]{0,79}$/. No cycles or missing references.","Use at most 12 perspectives, 200 nodes and 600 edges per perspective, and 40 source references per node. Keep each level to roughly 3–7 meaningful modules. Perspective summaries should explain the flow in 1–2 short sentences. Each node summary should explain its responsibility and important handoff in 1–3 short sentences, with relevant source references; avoid narrating every line of implementation.","Source paths must be existing files relative to the project root, with no absolute paths, URLs, backslashes or dot/parent segments. Add a positive integer line when verified. Omit uncertain connections and explain uncertainties in summaries.",`Write titles, summaries and edge labels in ${t==="zh"?"Chinese":"English"}. Set generatedAt to the actual current ISO timestamp. The sample paths are illustrative; use this project's real paths.`,"Read the selected output document if it already exists. Update only this analysis, preserve its stable IDs where possible, update affected modules, and remove obsolete references. Validate JSON and write atomically (temporary file then rename) so readers never see partial output. Summarize what was analyzed and any limitations after writing.",`Prefer invoking executable td with this argument array: ${JSON.stringify(["architecture","save","--project",e,"--file",c,"-"])}. Pass the complete JSON on stdin. Pass arguments separately; JSON string quoting is not shell escaping. This validates the document, archives the previous version, and records the update count and Git revision. If the CLI is unavailable, use the atomic file write above and disclose that history metadata was not recorded.`,JSON.stringify(l,null,2)].join(`
5
5
 
@@ -74,7 +74,7 @@ void main() {
74
74
  `).replace(/\\t/g," ")}const f5="||",KE=120;function XE(e){return e.includes(f5)?e.split(f5).filter(t=>t.length>0):[e]}function Hu(e){const t=new Set,r=e.map((a,c)=>{const l=typeof a.id=="string"&&a.id.trim().length>0?a.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):`preset-${c+1}`,d=t.has(l)?`${l}-${c+1}`:l;return t.add(d),{id:d,label:typeof a.label=="string"&&a.label.trim().length>0?a.label.trim():"Preset",programs:Array.isArray(a.programs)?a.programs.map(f=>Lv(f)).filter(f=>!!f):[],includeAlt:typeof a.includeAlt=="boolean"?!!a.includeAlt:!1,rowLayout:kg(a.rowLayout),showOnDesktop:typeof a.showOnDesktop=="boolean"?!!a.showOnDesktop:!1,actions:Array.isArray(a.actions)?a.actions.map((f,m)=>{const x={id:typeof f.id=="string"&&f.id.trim().length>0?f.id:`${d}-action-${m+1}`,label:typeof f.label=="string"?f.label:`Key ${m+1}`,sequence:typeof f.sequence=="string"?f.sequence:""};return typeof f.doubleTapSequence=="string"&&(x.doubleTapSequence=f.doubleTapSequence),x}):[]}}).filter(a=>a.id!=="auto"),n=D0()[0];return n&&!r.some(a=>a.id==="default")&&r.unshift(n),r}function JE(e,t){const r=kv(e);if(!r)return"default";for(const n of t)if(n.id!=="default")for(const a of n.programs){const c=Pf(a);if(c){if(c.test(r))return n.id}else if(r.includes(a))return n.id}return"default"}function p5(e,t){return e.find(r=>r.id===t)??e.find(r=>r.id==="default")??D0()[0]}function eN(e){return[{id:"auto",label:"Auto"},...e.map(t=>({id:t.id,label:t.label}))]}function tN(e){return[{id:"auto",label:"Auto"},...e.filter(t=>t.id==="default"||t.showOnDesktop===!0).map(t=>({id:t.id,label:t.label}))]}function Iv(e,t){const r=kg(t),n=[];let a=0,c=0;for(;a<e.length;){const l=r[Math.min(c,r.length-1)]??3;n.push({columns:l,items:e.slice(a,a+l)}),a+=l,c+=1}return n}const Ev=28,Nv=({mode:e,presetLabel:t,title:r,ariaLabel:n,disabled:a,onPointerDown:c,buttonRef:l})=>s.jsx("button",{ref:l,type:"button",onPointerDown:c,tabIndex:-1,disabled:a,className:"h-7 w-7 rounded-full bg-surface-2 shadow-sm text-[11px] font-medium active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",title:r,"aria-label":n??r,children:e==="auto"?s.jsx(fC,{size:14}):(t.charAt(0)||"?").toUpperCase()}),rN={esc:"\x1B",enter:"\r",home:"\x1B[H",end:"\x1B[F","ctrl-c":"","ctrl-d":"","ctrl-w":"","ctrl-u":""},Gd=8;function nN(e,t){return rN[e]??null}const sN=({visible:e,interactive:t=!0,presentation:r="mobile",activeModifier:n,lockedModifier:a,disabled:c,defaultShowExtended:l=!1,presetLabel:d,presetModeLabel:f,presetMode:m,presetOptions:x,includeAlt:y,presetRowLayout:w,extraActions:v,onKeyPress:T,onTextPress:S,onPastePress:I,onFilePress:N,onFileLongPress:P,fileUploadState:$="idle",fileUploadProgress:Q=0,longPressMode:U="arrows",copyFeedback:Z="idle",onLongPressModeToggle:J,onModifierToggle:H,onPresetSelect:ye,onExpandedChange:oe})=>{const{t:te}=Ur(),[Ce,qe]=k.useState(l),[ve,Y]=k.useState(!1),st=k.useRef(null),he=r==="desktop-actions",Qe=he||Ce,[ie,Pe]=k.useState(!1),[Fe,ce]=k.useState(null),Ie=c||!e||!t,je=c||!e,Ze=k.useRef(null),we=k.useRef(null),le=k.useRef(null),Ge=k.useRef(null),He=k.useRef(null),tt=k.useRef(Z),xe=k.useRef(null),dt=k.useRef(0),it=k.useRef(null),_e=k.useRef(!1),Ue=k.useCallback(Le=>{if(Ie)return;const At=Le.target;if(!(At instanceof Element))return;const Ot=At.closest("button"),er=Ot?.hasAttribute("data-mobile-native-action")===!0;Ot&&!er?(Le.preventDefault(),Io(Gd)):Ot&&Io(Gd)},[Ie]),ke=k.useCallback(Le=>{Le.preventDefault()},[]),V=k.useCallback(Le=>{const At=Le.target;Ie||At instanceof HTMLElement&&At.closest("button")&&At.blur()},[Ie]);k.useEffect(()=>{qe(l)},[l]),k.useEffect(()=>{he||oe?.(Ce)},[he,oe,Ce]),k.useEffect(()=>{Ie&&(xe.current!==null&&(window.clearTimeout(xe.current.timer),xe.current=null),Pe(!1),ce(null))},[Ie]),k.useEffect(()=>{e||(Pe(!1),ce(null))},[e]),k.useEffect(()=>{if(!ie)return;const Le=()=>{const At=Ze.current?.getBoundingClientRect();At&&ce({left:Math.max(8,At.left),top:Math.max(8,At.top-8)})};return Le(),window.addEventListener("resize",Le),window.addEventListener("scroll",Le,!0),()=>{window.removeEventListener("resize",Le),window.removeEventListener("scroll",Le,!0)}},[ie]),k.useEffect(()=>{const Le=tt.current;if(tt.current=Z,Z==="idle"||Z===Le)return;if(He.current!==null&&window.clearTimeout(He.current),!(typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches))if(Z==="copied"){we.current?.animate?.([{transform:"scale(1)"},{transform:"scale(1.16)",offset:.28},{transform:"scale(0.96)",offset:.62},{transform:"scale(1)"}],{duration:720,easing:"cubic-bezier(0.16, 1, 0.3, 1)"});const Ot=[{opacity:0,transform:"scale(0.65)"},{opacity:.75,transform:"scale(0.9)",offset:.18},{opacity:0,transform:"scale(1.65)"}];le.current?.animate?.(Ot,{duration:760,easing:"ease-out"}),Ge.current?.animate?.(Ot,{duration:760,delay:130,easing:"ease-out"})}else we.current?.animate?.([{transform:"translateX(0)"},{transform:"translateX(-2px)"},{transform:"translateX(2px)"},{transform:"translateX(0)"}],{duration:280,easing:"ease-out"});Io(Gd),Z==="copied"&&(He.current=window.setTimeout(()=>{Io(Gd),He.current=null},90),U==="copy"&&J?.())},[Z,U,J]),k.useEffect(()=>()=>{He.current!==null&&window.clearTimeout(He.current)},[]);const ae=k.useCallback((Le,At)=>{Ie||(Le.preventDefault(),T(At))},[T,Ie]),pe=k.useCallback((Le,At)=>{Ie||(Le.preventDefault(),H(At))},[H,Ie]),$e=k.useCallback(Le=>{Ie||(Le.preventDefault(),qe(At=>{const Ot=!At;return Ot&&(Y(!0),st.current!==null&&window.clearTimeout(st.current),st.current=window.setTimeout(()=>{Y(!1),st.current=null},350)),Ot}))},[Ie]),Xe=k.useCallback(()=>{const Le=typeof performance<"u"?performance.now():Date.now();Le-dt.current<350||(dt.current=Le,I?.())},[I]),wt=k.useCallback(Le=>{Ie||(Le.stopPropagation(),Le.pointerType!=="touch"&&(Le.preventDefault(),Xe()))},[Ie,Xe]),Ut=k.useCallback(Le=>{Ie||(Le.preventDefault(),Le.stopPropagation(),Xe())},[Ie,Xe]),qt=k.useCallback(Le=>{Ie||$==="uploading"||!N||(Le.preventDefault(),Le.stopPropagation(),_e.current||N(),_e.current=!1)},[$,N,Ie]),Nt=k.useCallback(()=>{it.current!==null&&window.clearTimeout(it.current),it.current=null},[]),sr=k.useCallback(Le=>{Le.stopPropagation(),!(Ie||$==="uploading"||!P)&&(_e.current=!1,it.current=window.setTimeout(()=>{it.current=null,_e.current=!0,Io(Gd),P()},500))},[$,P,Ie]);k.useEffect(()=>()=>Nt(),[Nt]);const jt=k.useCallback(Le=>{Ie||Le.stopPropagation()},[Ie]),Xt=250,Rt=k.useCallback(()=>{xe.current!==null&&(window.clearTimeout(xe.current.timer),xe.current=null)},[]);k.useEffect(()=>()=>{Rt(),st.current!==null&&(window.clearTimeout(st.current),st.current=null)},[Rt]);const ir=k.useCallback((Le,At)=>{if(Ie)return;if(Le.preventDefault(),!At.doubleTapSequence){S(At.sequence);return}const Ot=xe.current;if(Ot!==null&&Ot.actionId===At.id){window.clearTimeout(Ot.timer),xe.current=null,S(At.doubleTapSequence);return}Rt();const er=window.setTimeout(()=>{xe.current=null,S(At.sequence)},Xt);xe.current={actionId:At.id,timer:er}},[Rt,S,Ie]),ge=k.useCallback(Le=>{Ie||(Le.preventDefault(),Le.stopPropagation(),J?.())},[J,Ie]),Je=k.useCallback(Le=>{Ie||Le.stopPropagation()},[Ie]),at=k.useCallback(Le=>{if(Ie)return;Le.preventDefault();const At=Le.currentTarget.getBoundingClientRect();ce({left:Math.max(8,At.left),top:Math.max(8,At.top-8)}),Pe(Ot=>!Ot)},[Ie]),Et=k.useCallback((Le,At)=>{Ie||(Le.preventDefault(),Pe(!1),ce(null),ye(At))},[ye,Ie]),X=v.length>0,vt=k.useMemo(()=>{const Le=[{id:"preset",kind:"preset"}];if(!he&&y&&Le.push({id:"alt",kind:"alt"}),X){const At=v.map(Ot=>({id:Ot.id,kind:"text",action:Ot}));return Le.concat(At)}return he?Le.concat([{id:"esc",kind:"key",keyName:"esc"},{id:"ctrl-c",kind:"key",keyName:"ctrl-c"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"},{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"}]):Le.concat([{id:"home",kind:"key",keyName:"home"},{id:"end",kind:"key",keyName:"end"},{id:"ctrl-d",kind:"key",keyName:"ctrl-d"}])},[v,X,y,he]),Bt=k.useMemo(()=>Iv(vt,he&&!X?[6]:w),[vt,X,he,w]),Me=`${he?"space-y-1":"mt-1 space-y-1"}${ve?" pointer-events-none":""}`,Dr=ie&&Fe?Zs.createPortal(s.jsx("div",{className:"fixed z-popover min-w-28 -translate-y-full rounded-2xl bg-surface-elevated p-1.5 shadow-xl border border-border/15",style:{left:Fe.left,top:Fe.top},children:s.jsx("div",{className:"grid gap-1",children:x.map(Le=>s.jsx("button",{type:"button",onPointerDown:At=>Et(At,Le.id),tabIndex:-1,disabled:je,className:`h-7 rounded-full px-3 text-left text-xs font-medium transition-colors disabled:opacity-50 ${Le.id===m?"bg-primary text-primary-foreground":"bg-surface-2 hover:bg-surface-elevated text-muted-foreground hover:text-foreground"}`,children:Le.label},Le.id))})}),document.body):null;return s.jsxs(s.Fragment,{children:[Dr,s.jsx("div",{"data-mobile-keyboard":"true",className:`z-chrome select-none overflow-hidden app-chrome-bg transition-all duration-150 ease-out px-1 py-0 ${e?he?"max-h-24":"max-h-40":"max-h-0"} ${e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"} ${t?"":"[&_button]:pointer-events-none"}`,onMouseDownCapture:Ue,onPointerDownCapture:Ue,onContextMenuCapture:ke,onFocusCapture:V,children:s.jsxs("div",{className:"rounded-2xl bg-surface-elevated p-0.5 space-y-0.5",children:[!he&&s.jsxs("div",{"data-mobile-keyboard-primary-row":"true",className:"grid grid-cols-10 gap-1",children:[s.jsx("button",{type:"button",onPointerDown:Le=>ae(Le,"esc"),tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"Esc"}),s.jsx("button",{type:"button",onPointerDown:Le=>pe(Le,"ctrl"),tabIndex:-1,disabled:je,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${n==="ctrl"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${a==="ctrl"?"ring-2 ring-accent":""}`,children:s.jsx("span",{className:"font-medium",children:a==="ctrl"?"Ctrl*":"Ctrl"})}),s.jsx("button",{type:"button",onPointerDown:Le=>ae(Le,"ctrl-c"),tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-C"}),s.jsx("button",{type:"button",onPointerDown:Le=>ae(Le,"ctrl-u"),tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"C-U"}),s.jsxs("button",{type:"button",onPointerDown:sr,onPointerUp:Nt,onPointerCancel:Nt,onClick:qt,tabIndex:-1,disabled:je||!N||$==="uploading",title:$==="uploading"?`${te("rightSidebar.uploading")} ${Math.round(Q)}%`:te($==="inserted"?"rightSidebar.inserted":$==="failed"?"rightSidebar.uploadFailed":"rightSidebar.insertLocalFile"),"aria-label":te("rightSidebar.insertLocalFile"),className:`relative h-7 w-full overflow-hidden rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center ${$==="inserted"?"bg-primary/15 text-primary":$==="failed"?"bg-destructive/15 text-destructive":"bg-surface-2"}`,children:[$==="uploading"&&s.jsx("span",{"aria-hidden":"true","data-file-upload-progress":"true",className:"absolute inset-y-0 left-0 bg-primary/25 transition-[width] duration-150 ease-out",style:{width:`${Math.max(0,Math.min(100,Q))}%`}}),s.jsx("span",{className:"relative z-10 flex items-center justify-center",children:$==="uploading"?s.jsx(Dn,{size:15,className:"animate-spin"}):$==="inserted"?s.jsx(oi,{size:15}):$==="failed"?s.jsx(jn,{size:15}):s.jsx(MT,{size:15})}),$!=="idle"&&s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:$==="uploading"?`${te("rightSidebar.uploading")} ${Math.round(Q)}%`:te($==="inserted"?"rightSidebar.inserted":"rightSidebar.uploadFailed")})]}),s.jsx("button",{type:"button",onPointerDown:()=>S("/"),tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:"/"}),s.jsx("button",{type:"button",onPointerDown:Le=>ae(Le,"enter"),tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:s.jsx(kT,{size:16})}),s.jsxs("button",{ref:we,type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:Je,onTouchStart:Je,onClick:ge,tabIndex:-1,disabled:je,title:te(Z==="copied"?"terminal.copied":Z==="failed"?"terminal.copyFailed":U==="copy"?"terminal.longPressSelectsText":"terminal.longPressSendsArrows"),"aria-label":te(U==="copy"?"terminal.switchLongPressToArrows":"terminal.switchLongPressToCopy"),className:`relative isolate h-7 w-full overflow-visible rounded-full shadow-sm active:bg-accent active:text-accent-foreground transition-colors keyboard-button-active disabled:opacity-50 flex items-center justify-center ${Z==="copied"?"bg-primary/15 text-primary":Z==="failed"?"bg-destructive/15 text-destructive":U==="copy"?"bg-primary/15 text-primary":"bg-surface-2"}`,children:[s.jsx("span",{ref:le,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/70 opacity-0"}),s.jsx("span",{ref:Ge,"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 rounded-full border border-primary/40 opacity-0"}),s.jsxs("span",{className:"relative z-10 h-4 w-4","aria-hidden":"true",children:[s.jsx(oi,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${Z==="copied"?"scale-100 rotate-0 opacity-100":"scale-50 -rotate-45 opacity-0"}`}),s.jsx(jn,{size:16,className:`absolute inset-0 transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none ${Z==="failed"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),s.jsx(h3,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${Z==="idle"&&U==="copy"?"scale-100 opacity-100":"scale-50 opacity-0"}`}),s.jsx(uS,{size:15,className:`absolute inset-0 transition-[opacity,transform] duration-300 ease-out motion-reduce:transition-none ${Z==="idle"&&U==="arrows"?"scale-100 rotate-0 opacity-100":"scale-50 rotate-45 opacity-0"}`})]}),Z!=="idle"&&s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:Z==="copied"?`${te("terminal.copied")} · ${te("terminal.longPressSendsArrows")}`:`${te("terminal.copyFailed")} · ${te("terminal.longPressSelectsText")}`})]}),s.jsx("button",{type:"button","data-mobile-copy-button":"true","data-mobile-native-action":"true",onPointerDown:wt,onPointerUp:jt,onTouchStart:jt,onTouchEnd:jt,onClick:Ut,tabIndex:-1,disabled:je,title:te("terminal.paste"),"aria-label":te("terminal.paste"),className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:s.jsx(bT,{size:15})}),s.jsx("button",{type:"button",onPointerDown:$e,tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 flex items-center justify-center",children:Ce?s.jsx(I8,{size:16}):s.jsx(Al,{size:16})})]}),Qe&&s.jsx("div",{className:Me,children:Bt.map((Le,At)=>{const Ot=Le.items[0]?.kind==="preset",er=Math.max(2,Le.columns),ot=Ot?`${Ev}px repeat(${Math.max(1,er-1)}, minmax(0, 1fr))`:`repeat(${er}, minmax(0, 1fr))`;return s.jsx("div",{className:"relative grid gap-1",style:{gridTemplateColumns:ot},children:Le.items.map(Lt=>Lt.kind==="preset"?s.jsx(Nv,{buttonRef:Lt.id==="preset"?Ze:void 0,mode:m,presetLabel:d,title:f,disabled:je,onPointerDown:at},Lt.id):Lt.kind==="alt"?s.jsx("button",{type:"button",onPointerDown:nr=>pe(nr,"alt"),tabIndex:-1,disabled:je,className:`h-7 w-full rounded-full shadow-sm text-xs disabled:opacity-50 flex items-center justify-center transition-all ${n==="alt"?"bg-primary text-primary-foreground scale-105 shadow-md shadow-primary/40":"bg-surface-2"} ${a==="alt"?"ring-2 ring-accent":""}`,children:s.jsx("span",{className:"font-medium",children:a==="alt"?"Alt*":"Alt"})},Lt.id):Lt.kind==="text"?s.jsxs("button",{type:"button",onPointerDown:nr=>ir(nr,Lt.action),tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm px-1 text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50 relative",children:[Lt.action.label,Lt.action.doubleTapSequence&&s.jsx("span",{className:"absolute top-0.5 right-1.5 h-1 w-1 rounded-full bg-accent/60"})]},Lt.id):s.jsx("button",{type:"button",onPointerDown:nr=>ae(nr,Lt.keyName),tabIndex:-1,disabled:je,className:"h-7 w-full rounded-full bg-surface-2 shadow-sm text-xs active:bg-accent active:text-accent-foreground transition-all keyboard-button-active disabled:opacity-50",children:Lt.keyName==="esc"?"Esc":Lt.keyName==="ctrl-c"?"Ctrl-C":Lt.keyName==="ctrl-d"?"Ctrl-D":Lt.keyName==="home"?"Home":"End"},Lt.id))},`row-${At}`)})})]})})]})},iN=({isMobile:e,isInputFocused:t,isIOS:r,isConnecting:n,connectionError:a,terminalSessionId:c})=>{if(typeof window>"u")return null;const l=window.visualViewport?Math.max(0,Math.round(window.innerHeight-window.visualViewport.height-window.visualViewport.offsetTop)):0;return s.jsxs("div",{className:"px-3 py-2 bg-surface text-foreground text-xs border-b border-border/15",children:[s.jsx("div",{className:"font-bold mb-2",children:"Debug Info"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1 font-mono",children:[s.jsxs("div",{children:["isMobile: ",s.jsx("span",{className:e?"text-accent":"text-destructive",children:String(e)})]}),s.jsxs("div",{children:["touchPoints: ",navigator.maxTouchPoints]}),s.jsxs("div",{children:["innerWidth: ",window.innerWidth]}),s.jsxs("div",{children:["innerHeight: ",window.innerHeight]}),s.jsxs("div",{children:["viewportH:"," ",window.visualViewport?Math.round(window.visualViewport.height):"N/A"]}),s.jsxs("div",{children:["inputFocused: ",String(t)]}),s.jsxs("div",{children:["keyboard~: ",l,"px"]}),s.jsxs("div",{children:["connecting:"," ",s.jsx("span",{className:n?"text-muted-foreground":"text-accent",children:String(n)})]}),s.jsxs("div",{children:["sessionId:"," ",s.jsx("span",{className:c?"text-accent":"text-destructive",children:c?"✓":"✗"})]}),s.jsxs("div",{children:["error:"," ",s.jsx("span",{className:a?"text-destructive":"text-accent",children:a?"Yes":"No"})]}),s.jsxs("div",{children:["isIOS:"," ",s.jsx("span",{className:r?"text-muted-foreground":"text-accent",children:String(r)})]})]}),s.jsx("div",{className:"mt-2 pt-2 border-t border-border/15",children:s.jsx("div",{children:"Tip: Tap the status bar 3 times to toggle debug panel"})})]})},aN=/^Reconnecting/i,oN=({connectionError:e,isFatalError:t,isRestarting:r,isConnecting:n,onHardRestart:a})=>{const{t:c}=Ur(),l=!!e&&aN.test(e),d=!!(n&&!e||l),[f,m]=k.useState(!1);return k.useEffect(()=>{if(!d){m(!1);return}const x=setTimeout(()=>m(!0),1500);return()=>clearTimeout(x)},[d]),d?f?s.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2 pointer-events-none",children:s.jsx(_0,{dots:!0,label:c("connection.reconnecting"),className:"rounded-full bg-surface-2 px-3 py-1 text-[11px]"})}):null:e?s.jsx("div",{className:"absolute inset-x-0 bottom-0 flex items-end justify-center pb-2",children:s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-destructive/70",children:[s.jsx("span",{children:e}),t&&s.jsx("button",{type:"button",onClick:a,disabled:r,className:"text-[11px] text-destructive/90 hover:text-destructive underline underline-offset-2 transition-colors disabled:opacity-40",children:c("common.retry")})]})}):null},lN=120,cN=80,uN=400;function m5(){if(typeof window>"u"||document.visibilityState!=="visible"||!E8())return 0;const e=Number.parseFloat(document.documentElement.style.getPropertyValue("--kb-height")||"0");if(Number.isFinite(e)&&e>0)return Math.round(e);const t=gl().visualViewport;if(!t)return 0;const r=Number.parseFloat(document.documentElement.style.getPropertyValue("--app-base-vh")||"0")||window.innerHeight,n=Number.parseFloat(document.documentElement.style.getPropertyValue("--safe-bottom-inset")||"0")||0,a=t.height+t.offsetTop;return Math.max(0,Math.round(r-a-n))}function Rv(e){const{enabled:t,openThresholdPx:r=lN,closeThresholdPx:n=cN,settleDelayMs:a=uN}=e,c=k.useMemo(()=>Ju("keyboard"),[]),l=k.useRef(!1),d=k.useRef(null),f=k.useRef(0),[m,x]=k.useState({isOpen:!1,isSettled:!1,keyboardHeight:0});return k.useEffect(()=>{if(typeof window>"u"||!t){l.current=!1,d.current!==null&&(clearTimeout(d.current),d.current=null),x(Z=>!Z.isOpen&&!Z.isSettled&&Z.keyboardHeight===0?Z:{isOpen:!1,isSettled:!1,keyboardHeight:0});return}let y=null;const w=()=>{y=null;const Z=m5();let J=l.current;if(Z>=r?J=!0:Z<=n&&(J=!1),l.current=J,J){const H=Math.abs(Z-f.current);f.current=Z,H>10&&(d.current!==null&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,x(ye=>ye.isSettled?ye:{...ye,isSettled:!0})},a))}else d.current!==null&&(clearTimeout(d.current),d.current=null);x(H=>{const ye=J?H.isSettled:!1;return H.isOpen===J&&H.keyboardHeight===Z&&H.isSettled===ye?H:(c("sync",{keyboardHeight:Z,isOpen:J,isSettled:ye,visualViewport:gl().visualViewport?{width:Math.round(gl().visualViewport.width),height:Math.round(gl().visualViewport.height),offsetTop:Math.round(gl().visualViewport.offsetTop)}:null}),{isOpen:J,isSettled:ye,keyboardHeight:Z})})},v=(Z="event")=>{(Z.includes("visibilitychange")||Z.includes("pageshow"))&&c("schedule",{source:Z}),y===null&&(y=window.requestAnimationFrame(w))};v("mount");const T=()=>v("resize"),S=()=>v("orientationchange"),I=()=>v("visualViewport.resize"),N=()=>v("visualViewport.scroll"),P=()=>v("viewport-keyboard-change");window.addEventListener("resize",T),window.addEventListener("orientationchange",S),gl().visualViewport?.addEventListener("resize",I),gl().visualViewport?.addEventListener("scroll",N),document.addEventListener("termdock:viewport-keyboard-change",P);const $=Z=>{c("resume",{source:Z,keyboardHeight:m5(),hidden:document.hidden}),v(`${Z}:now`),window.setTimeout(()=>v(`${Z}:50ms`),50),window.setTimeout(()=>v(`${Z}:200ms`),200)},Q=()=>{document.hidden||$("visibilitychange")},U=()=>$("pageshow");return document.addEventListener("visibilitychange",Q),window.addEventListener("pageshow",U),()=>{window.removeEventListener("resize",T),window.removeEventListener("orientationchange",S),gl().visualViewport?.removeEventListener("resize",I),gl().visualViewport?.removeEventListener("scroll",N),document.removeEventListener("termdock:viewport-keyboard-change",P),document.removeEventListener("visibilitychange",Q),window.removeEventListener("pageshow",U),y!==null&&window.cancelAnimationFrame(y),d.current!==null&&(clearTimeout(d.current),d.current=null)}},[c,t,r,n,a]),m}const ff=300,dN=120,hN=2e3,fN=250,pN=6e4;function mN(e){const t=new Set(e.slides.flat()),r=new Set([...e.visibleSessionIds].filter(l=>t.has(l)));e.foregroundSessionId&&t.has(e.foregroundSessionId)&&r.add(e.foregroundSessionId);const n=e.slides.findIndex(l=>l.some(d=>r.has(d)));if(n<0)return r;const a=e.slides[n-1]??[],c=e.slides[n+1]??[];for(let l=0;l<Math.max(a.length,c.length)&&r.size<3;l+=1)for(const d of[a[l],c[l]])d&&r.size<3&&r.add(d);return r}function Am(e,t){return t?e.find(r=>r.id===t||r.backendSessionId===t)?.id??null:null}function Dh(e){return e.prioritySessionId??e.activeSessionId??e.persistedActiveSessionId??e.firstSessionId}function gN(e){return e.foregroundSessionId===null||e.isVisible===!0||e.sessionId===e.foregroundSessionId||e.foregroundReady}function xN(e){return e.sessionId===e.foregroundSessionId||e.visibleSessionIds.has(e.sessionId)||e.deferredViewportSessionIds.has(e.sessionId)}function bN(e){return e.isMobile&&(!e.viewportReady||!e.streamReady||!e.contentReady)}function yN(e){return e.writtenChunkId!==null&&e.initialTargetChunkId!==null&&e.writtenChunkId>=e.initialTargetChunkId}function vN(e){return!e.initialConnectionPending}function wN(e){return!e}function AN(e){return e.requestToken===0||e.isVisible===!0||e.foregroundSessionId===null||e.isVisible===void 0&&e.sessionId===e.foregroundSessionId||e.foregroundCompletedToken===e.requestToken}function TN(e,t){return[...e].every(r=>t.has(r))}function SN(e,t){return e===null||t-e>=fN}function CN(e){return!1}function _N(e){return!e.isActive||e.isStreamReady||e.reconnectStartedAt===null?null:Math.max(0,pN-(e.now-e.reconnectStartedAt))}function kN(e,t){const r=new Map;let n=0;for(const a of e)if(!r.has(a)){if(t.has(a)){r.set(a,0);continue}r.set(a,ff+n*dN),n+=1}return r}const LN="Session not found on server",pf="Terminal session not found",IN="STALE_SESSION_RESTORE_REJECTED";function g5(e){return N1(e)?!1:e?.message===LN||e?.status===404&&e.message===pf}function N1(e){return e?.code===IN}function EN(e,t){if(!e||e.startsWith("/"))return e;const r=e.replace(/^\.\//,"");return t?`${t.replace(/\/+$/,"")}/${r}`:r}function Mv(e,t){return EN(e,t).replace(/ /g,"\\ ")}function R1(e,t){return`${Mv(e,t)} `}function x5(e,t){return Mv(e,t)}function wz(e,t,r){if(!r)return x5(e,t);const n=r.start===r.end?`${r.start}`:`${r.start}-${r.end}`;return`${x5(e,t)}:${n}`}const NN="/tmp";async function RN(e,t,r){const a=(await t(NN,[e])).files[0];if(!a?.path)throw new Error("Upload did not return a file path");let c;try{c=await r(a.path)}catch{throw new Of(a)}if(!c)throw new Of(a);return a}class Of extends Error{constructor(t){super("File uploaded, but its reference was not accepted"),this.uploaded=t,this.name="UploadedReferenceRejectedError"}uploaded}function Ig(e){const t=Tf(),r=mi(),n=Eo();return()=>{const a=mi();return Tf()===t&&(!e||op(e))&&a?.url===r?.url&&a?.targetPeerId===r?.targetPeerId&&Eo()===n&&!n?.closed}}function M1(e,t,r,n,a){if(!e||!t||!r())return Promise.resolve(!1);const c=n?GC(n,t,e,a?.submitAfterPaste===!0):null;if(n&&!c)return Promise.resolve(!1);const l=c?.nonce??`reference-${crypto.randomUUID()}`;return new Promise(d=>{let f=!1;const m=w=>{f||(f=!0,window.clearTimeout(y),window.removeEventListener("termdock-insert-reference-ack",x),c&&VC(l),d(w&&r()))},x=w=>{const v=w.detail;v?.nonce===l&&m(v.ok===!0)},y=window.setTimeout(()=>m(!1),1500);window.addEventListener("termdock-insert-reference-ack",x),window.dispatchEvent(new CustomEvent("termdock-insert-reference",{detail:c??{text:e,sessionId:t,nonce:l,focus:!1,paste:!0,submitAfterPaste:!1,...a}}))})}const jv=[640,960,1280,1600,2048,2560,3072,4096],Dv=[240,360,480,540,720,1080,1440,2160],A0={min:.1,max:1,step:.01},T0={min:25e4,max:2e7,step:25e4},Eg="termdock:mobile-media-compression-v1",Nu={showResultToast:!0,imageEnabled:!1,imageMaxDimension:2048,imageQuality:.8,videoEnabled:!1,videoMaxHeight:720,videoBitrate:25e5};function Bv(){try{const e=JSON.parse(localStorage.getItem(Eg)||"null");return!e||typeof e!="object"?Nu:{showResultToast:e.showResultToast!==!1,imageEnabled:e.imageEnabled===!0,imageMaxDimension:jv.includes(e.imageMaxDimension)?e.imageMaxDimension:Nu.imageMaxDimension,imageQuality:typeof e.imageQuality=="number"&&e.imageQuality>=A0.min&&e.imageQuality<=A0.max?e.imageQuality:Nu.imageQuality,videoEnabled:e.videoEnabled===!0,videoMaxHeight:Dv.includes(e.videoMaxHeight)?e.videoMaxHeight:Nu.videoMaxHeight,videoBitrate:typeof e.videoBitrate=="number"&&e.videoBitrate>=T0.min&&e.videoBitrate<=T0.max?e.videoBitrate:Nu.videoBitrate}}catch{return Nu}}const Ng=Sc((e,t)=>({preferences:Bv(),saveFailed:!1,update:r=>{const n={...t().preferences,...r};let a=!1;try{localStorage.setItem(Eg,JSON.stringify(n))}catch{a=!0}e({preferences:n,saveFailed:a})}}));typeof window<"u"&&window.addEventListener("storage",e=>{(e.key===Eg||e.key===null)&&Ng.setState({preferences:Bv(),saveFailed:!1})});function Bh(e){if(e<1024)return`${e} B`;const t=["B","KB","MB","GB","TB"],r=Math.min(t.length-1,Math.floor(Math.log(e)/Math.log(1024)));return`${Number((e/1024**r).toFixed(1))} ${t[r]}`}function MN({result:e,message:t,onClose:r}){const{locale:n}=Ur(),a=n==="zh",c=b.useRef(null),[l,d]=b.useState(null),[f,m]=b.useState(!1);return b.useEffect(()=>{const x=URL.createObjectURL(e.file);return d(x),m(!1),()=>URL.revokeObjectURL(x)},[e.file]),b.useEffect(()=>{const x=c.current;return x?.showModal(),()=>x?.close()},[]),s.jsx("dialog",{ref:c,"aria-label":a?"上传结果预览":"Uploaded media preview",onCancel:x=>{x.preventDefault(),r()},onClick:x=>{x.target===x.currentTarget&&r()},onKeyDown:x=>x.stopPropagation(),onKeyUp:x=>x.stopPropagation(),className:"fixed inset-0 z-modal-panel m-0 h-[100dvh] max-h-none w-screen max-w-none bg-transparent p-3 text-foreground backdrop:bg-[var(--app-backdrop)] open:flex open:items-center open:justify-center",children:s.jsxs("section",{className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-1.5rem)] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-border/15 bg-surface shadow-xl",children:[s.jsxs("header",{className:"flex shrink-0 items-start gap-3 border-b border-border/15 p-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-sm font-semibold",children:a?"上传结果预览":"Uploaded media preview"}),s.jsx("p",{className:"mt-1 break-words text-xs text-muted-foreground",children:t}),s.jsx("p",{className:"mt-1 truncate text-[11px] text-muted-foreground",children:e.file.name})]}),s.jsx("button",{type:"button",autoFocus:!0,onClick:r,"aria-label":a?"关闭预览":"Close preview",className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",children:s.jsx(jn,{size:18})})]}),s.jsx("div",{className:"min-h-0 overflow-auto p-2",children:f?s.jsx("p",{role:"alert",className:"p-4 text-sm text-muted-foreground",children:a?"文件已上传,但当前浏览器无法预览此格式。":"File uploaded, but this browser cannot preview this format."}):l&&(e.kind==="image"?s.jsx("img",{src:l,alt:e.file.name,onError:()=>m(!0),className:"mx-auto block max-h-[65dvh] max-w-full object-contain"}):s.jsx("video",{src:l,controls:!0,playsInline:!0,preload:"metadata",onError:()=>m(!0),className:"mx-auto block max-h-[65dvh] w-full"}))})]})})}function jN({result:e,onDismiss:t}){const{locale:r}=Ur(),n=r==="zh",a=Ng(I=>I.preferences.showResultToast),c=a?e:null,[l,d]=b.useState(null);b.useEffect(()=>{if(!e)return;if(!a){t();return}const I=window.setTimeout(t,2e3);return()=>window.clearTimeout(I)},[e,a,t]);const f=c??l?.result;if(!f)return null;const m=f.originalSize-f.uploadedSize,x=f.originalSize>0?Math.abs(m)/f.originalSize*100:0,y=x<1?"<1%":`${Math.floor(x)}%`,w=f.kind==="image"?n?"图片":"Image":n?"视频":"Video",v=m>0?n?"已压缩上传":"Compressed upload":n?"已处理上传":"Processed upload",T=m>0?n?`省 ${y}`:`${y} saved`:m<0?`+${y}`:n?"体积未变":"Size unchanged",S=f.originalRetained?n?`已尝试压缩 · 保留原图 ${Bh(f.uploadedSize)},已上传`:`Compression tried · original ${Bh(f.uploadedSize)} uploaded`:`${v} · ${Bh(f.originalSize)} → ${Bh(f.uploadedSize)} · ${T}`;return s.jsxs(s.Fragment,{children:[c&&s.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:"pointer-events-none absolute left-1/2 top-1/2 z-30 w-max max-w-[calc(100%-1.5rem)] -translate-x-1/2 -translate-y-1/2 motion-safe:animate-[fade-in_0.15s_ease-out]",children:s.jsxs("button",{type:"button","aria-label":`${w}:${S} · ${n?"点击预览":"Preview"}`,onClick:()=>{d({result:c,message:S}),t()},className:"pointer-events-auto flex max-w-full select-none items-center gap-1.5 rounded-full border border-border/15 bg-surface-elevated px-3 py-2 text-[11px] leading-4 text-foreground shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",children:[s.jsx(oi,{size:13,strokeWidth:2.5,className:"shrink-0 text-primary","aria-hidden":"true"}),s.jsx("span",{className:"truncate tabular-nums",children:S}),s.jsx("span",{className:"shrink-0 text-muted-foreground",children:n?"预览 ›":"Preview ›"})]})}),l&&Zs.createPortal(s.jsx(MN,{result:l.result,message:l.message,onClose:()=>d(null)}),document.body)]})}const DN=320,b5="termdock:mobile-keyboard-expanded",y5="termdock:mobile-keyboard-preset-mode",v5="termdock:mobile-long-press-mode",BN=80;function QN(e){return/\.(?:jpe?g|png|heic|heif)$/i.test(e.name)||/^(?:image\/jpeg|image\/png|image\/heic|image\/heif)$/i.test(e.type)}function w5(e){const t=(e instanceof Error?e.message:String(e)).slice(0,3e3);return/importing a module script failed|dynamically imported module|loading chunk/i.test(t)?`压缩模块加载失败,可能是页面版本过旧或网络中断。请更新页面后重试,无需清除转码器缓存。
75
75
  ${t}`:t}function PN(e){switch(e?.phase){case"loading":return`正在加载转码器… ${e.progress??0}%(优先使用浏览器缓存)`;case"saving":return"加载完成,正在保存到本机…";case"initializing":return e.source==="local"?"已找到本机缓存,正在初始化转码器…":"正在初始化本地转码器…";case"ready":return e.source==="local"?"已从本机缓存加载,转码器已就绪。":e.saved?"转码器已就绪,已保存到本机供下次使用。":"转码器已就绪。";default:return"正在检查本机转码器缓存…"}}function Tm(){return Xy()}const ON={retry:{maxRetries:60,initialDelayMs:1e3,maxDelayMs:2e4},connectionTimeoutMs:15e3},FN=({sessionId:e,mode:t,tmuxSessionName:r=null,terminalSettings:n=_g(),colorTheme:a="dark",toolbarPresets:c=[],isActive:l=!0,focusSuspended:d=!1,allowOwnedPasteWhileFocusSuspended:f=!1,deferCursorUntilPositioned:m=!1,isLayoutVisible:x=!0,focusRequestToken:y=0,resumeRequestToken:w=0,resumeRequestReason:v="visibility",resumeRequestDelayMs:T=0,forceResumeReconnect:S=!1,initialConnectDelayMs:I=0,initialConnectEnabled:N=!0,resumeRequestEnabled:P=!0,onStreamReadyChange:$,onStreamConnected:Q,onViewportReadyChange:U,onContentReadyChange:Z,onKeyboardVisibilityChange:J,suppressKeyboard:H=!1,keyboardPortalTarget:ye=null,sharedMobileKeyboardLayout:oe=!1,suppressPageFlipRefresh:te=!1,showDebug:Ce,onStatusChange:qe})=>{const{t:ve}=Ur(),[Y]=k.useState(e||j3()),[st,he]=k.useState(()=>(e?l1(e):null)??n.fontSize),Qe=k.useMemo(()=>zE(),[]),ie=k.useMemo(()=>Ju("session"),[]),Pe=k.useMemo(()=>Ju("keyboard"),[]),Fe=k.useRef(null),ce=k.useRef(null);k.useEffect(()=>{l1(Y)===null&&he(n.fontSize)},[n.fontSize,Y]);const Ie=k.useMemo(()=>({...n,fontSize:st}),[n,st]),je=N8(),Ze=d||je,[we,le]=k.useState(Tm),[Ge,He]=k.useState(!1),[tt,xe]=k.useState(!1),[dt,it]=k.useState(!1),[_e,Ue]=k.useState(()=>typeof document>"u"?!0:!document.hidden&&xc()),[ke,V]=k.useState(()=>typeof document>"u"?!0:document.hasFocus()),[ae,pe]=k.useState(!1),$e=k.useRef(ae);$e.current=ae;const[Xe,wt]=k.useState(!1),[Ut,qt]=k.useState(!1),[Nt,sr]=k.useState(!1),[jt,Xt]=k.useState(!0),{isOpen:Rt,keyboardHeight:ir}=Rv({enabled:we&&l}),[ge,Je]=k.useState(null),[at,Et]=k.useState(null),[X,vt]=k.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(b5)==="true"),[Bt,Me]=k.useState(()=>{if(typeof window>"u")return"auto";const ue=window.localStorage.getItem(y5);return ue&&ue.length>0?ue:"auto"}),[Dr,Le]=k.useState(()=>typeof window>"u"?"arrows":window.localStorage.getItem(v5)==="copy"?"copy":"arrows"),[At,Ot]=k.useState("idle"),[er,ot]=k.useState("idle"),[Lt,nr]=k.useState(0),[ur,Rr]=k.useState(null),[Gr,Tt]=k.useState(null),[Ft,be]=k.useState(null),Ct=k.useCallback(()=>be(null),[]),{preferences:gt,update:rt,saveFailed:cn}=Ng(),{videoEnabled:Kr,videoMaxHeight:wn,videoBitrate:Oe,imageEnabled:ft,imageMaxDimension:ht,imageQuality:Cr}=gt,[Ht,yr]=k.useState(!1),[Xr,Bn]=k.useState(null),[mn,hn]=k.useState(null),gn=Hr(ue=>ue.sessions.get(Y)),{setTerminalSession:an,setConnecting:ne,appendToBuffer:Ye,replaceBuffer:St,clearTerminalSession:Jt,removeTerminalSession:Or,clearBuffer:un,setSessionActiveProgram:Jr,setSessionCwd:en,setSessionCopyMode:mr,setSessionAgentStatus:tn,setSessionShellTitle:Sn,setSessionPromptState:Zr,clearAgentNeedsReview:Qr}=Hr.getState(),lr=k.useMemo(()=>`wt-${Y.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,12)}`,[Y]),fn=gn?.terminalSessionId??null,Ss=gn?.mode??"shell",Ar=gn?.activeProgram??null,En=k.useMemo(()=>Hu(c),[c]),qr=Ss==="tmux",Lr=gn?.bufferChunks??[],On=gn?.isConnecting??!1,tr=fn,K=k.useCallback(async(ue,Ve)=>{const bt=mE(ue,gn?.cwd||gn?.directory);if(!bt)return;let _=bt,M="directory";try{_=(await ag(bt)).path}catch(B){if(!(B instanceof Error)||B.message!=="Path is not a directory")return;M="file"}try{Yt.getState().openTerminalPath({path:_,kind:M,line:Ve})}catch{}},[gn?.cwd,gn?.directory]),De=t??gn?.mode??"shell",Mt=De==="tmux"?r??gn?.tmuxSessionName??null:null,[vr,Dt]=k.useState(null),Br=k.useRef(!1),[Pr,xn]=k.useState(!1),[Kn,Cs]=k.useState(!1),[ws,Wr]=k.useState(null),[Qn,Pn]=k.useState(0),[jr,ds]=k.useState(null),Tr=Ce!==void 0?Ce:!1,bn=k.useRef(null),An=k.useRef(null),rr=k.useRef(null),kn=k.useRef(new HC),Cn=k.useRef(null),wr=k.useRef(null),ps=k.useRef(!1),Ks=k.useRef(null),rs=k.useRef([]),on=k.useRef(0),Hn=k.useRef(!1),Fr=k.useRef(Promise.resolve()),$r=k.useRef(null),pn=k.useRef(null),W=k.useRef(-1),Re=k.useRef(null),Ke=k.useRef(0),lt=k.useRef(null),ut=k.useRef(null),It=k.useRef(0),_t=k.useRef(0),Qt=k.useRef(!1),xt=k.useRef(null),Pt=k.useRef(null),z=k.useRef(!1),R=k.useRef(0),F=k.useRef(!1),q=k.useRef(!1),se=k.useRef(!1),Ee=k.useRef(null),We=k.useRef(null),mt=k.useRef(null),et=k.useRef(l);et.current=l;const dr=k.useRef(Ze);dr.current=Ze;const Wn=k.useRef(d);Wn.current=d;const Gt=k.useRef(f);Gt.current=f;const zr=k.useRef(we),_r=k.useRef(null),Xn=k.useRef(null),ms=k.useRef(null),dn=k.useRef(null),pr=k.useRef(null),ar=k.useRef(null),Fn=k.useRef(null),ls=k.useCallback(()=>{const ue=++R.current,Ve=()=>{ue===R.current&&wt(!0)};if(typeof window>"u"){Ve();return}window.requestAnimationFrame(()=>window.requestAnimationFrame(Ve))},[]),ya=k.useCallback(ue=>{if(F.current){if(We.current!==null&&(window.clearTimeout(We.current),We.current=null),ue.x===0&&ue.y>=ue.rows-1){Xt(!1);return}We.current=window.setTimeout(()=>{We.current=null,Xt(!0)},BN)}},[]),Jn=k.useRef(null);k.useEffect(()=>()=>{Jn.current?.()},[]);const Bo=k.useCallback(()=>{Jn.current||(Jn.current=gg(()=>{Jn.current=null;const ue=Hr.getState(),Ve=rr.current,bt=ue.getTerminalSession(Y);if(!Ve||bt?.mode!=="shell"||ue.hasPendingBufferWrites(Y))return;const _=R8(Ve),M=wr.current?.getDimensions();if(!_||!M)return;const G=wr.current?.serializeSnapshot();G&&M8({id:Ve,version:1,..._,...M,data:G,savedAt:Date.now()})},2e3))},[Y]),Fs=k.useCallback(ue=>{const Ve=Hr.getState(),bt=Ve.getTerminalSession(Y)?.bufferChunks.at(-1)?.id;if(rr.current&&bt!==void 0&&bt<=ue&&!Ve.hasPendingBufferWrites(Y)&&(j8(rr.current),Bo()),!Qt.current||!yN({writtenChunkId:ue,initialTargetChunkId:xt.current}))return;const _=Pt.current;Pt.current=null,_!==null&&wr.current?.notifyScreenSynchronized(_),Qt.current=!1,xt.current=null,ls()},[ls,Bo,Y]),Pa=k.useCallback(ue=>{if(!F.current)return;const Ve=Ee.current;Ve&&Ve.x===ue.x&&Ve.y===ue.y&&Ve.rows===ue.rows||(Ee.current=ue,We.current!==null&&(window.clearTimeout(We.current),We.current=null),ue.x===0&&ue.y>=ue.rows-1&&Xt(!1))},[]);k.useEffect(()=>{if(!m){q.current=!1;return}q.current||(q.current=!0,se.current=!1,F.current=!0,Ee.current=null,Xt(!1),We.current!==null&&(window.clearTimeout(We.current),We.current=null),mt.current!==null&&window.clearTimeout(mt.current),mt.current=window.setTimeout(()=>{mt.current=null,We.current!==null&&typeof window<"u"&&window.clearTimeout(We.current),We.current=null,F.current=!1,Xt(!0)},15e3))},[m]);const li=k.useCallback(()=>{dn.current=null;const ue=ms.current;ms.current=null,ue&&Sn(ue.sessionId,ue.title)},[Sn]),Tl=k.useCallback((ue,Ve)=>{if(ms.current={sessionId:ue,title:Ve},dn.current===null){if(typeof window>"u"){li();return}dn.current=window.requestAnimationFrame(li)}},[li]),gs=k.useCallback(()=>{dn.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(dn.current),dn.current=null,ms.current=null},[]),hs=k.useCallback(async()=>{const ue=De;return(await D8({preferredFrontendSessionId:Y,mode:ue,tmuxSessionName:ue==="tmux"?Mt||lr:void 0,termType:"xterm-256color",requireExisting:!0})).terminalSession},[De,Mt,lr,Y]),qi=k.useRef(l);k.useEffect(()=>{if(!l){wr.current?.blur(),qi.current=!1;return}if(qi.current)return;qi.current=!0;const ue=NI(we,te);if(ue==="single"){wr.current?.requestRefresh("focus",{skipResizePush:!0,skipScrollToBottom:!0});return}ue!=="none"&&wr.current?.requestRefresh("page-flip",{reconcileServerSize:!0,skipScrollToBottom:!0})},[l,we,te,tr]),k.useEffect(()=>{zr.current=we},[we]);const Ls=k.useCallback(()=>{!et.current||dr.current||wr.current?.focus()},[]);k.useLayoutEffect(()=>{Ze&&wr.current?.blur()},[Ze]),k.useEffect(()=>{if(!l||Ze||jt||se.current)return;se.current=!0;const ue=window.requestAnimationFrame(()=>{wr.current?.requestPtyRedraw()});return()=>window.cancelAnimationFrame(ue)},[Ze,l,jt]);const Xs=k.useCallback(ue=>{typeof window>"u"||typeof document>"u"||!et.current||dr.current||zr.current||document.hidden||!xc()||(_r.current!==null&&window.clearTimeout(_r.current),_r.current=window.setTimeout(()=>{if(_r.current=null,!et.current||dr.current||zr.current||document.hidden||!xc())return;const Ve=document.activeElement,bt=Ve?.getAttribute("data-terminal-input-anchor")==="true";if((Ve instanceof HTMLInputElement||Ve instanceof HTMLTextAreaElement||Ve instanceof HTMLSelectElement||Ve?.isContentEditable===!0)&&!bt){Pe("desktop resume focus skipped: editable active",{reason:ue});return}Pe("desktop resume focus",{reason:ue}),wr.current?.requestRefresh("focus",{force:!0,forceRedraw:!0,skipResizePush:!0,skipScrollToBottom:!0}),wr.current?.focus()},50))},[Pe]);k.useEffect(()=>()=>{_r.current!==null&&typeof window<"u"&&window.clearTimeout(_r.current),_r.current=null,Xn.current!==null&&typeof window<"u"&&window.clearTimeout(Xn.current),Xn.current=null,pr.current!==null&&typeof window<"u"&&window.clearTimeout(pr.current),pr.current=null,ar.current!==null&&typeof window<"u"&&window.clearTimeout(ar.current),ar.current=null,mt.current!==null&&typeof window<"u"&&window.clearTimeout(mt.current),mt.current=null,We.current!==null&&typeof window<"u"&&window.clearTimeout(We.current),We.current=null},[]),k.useEffect(()=>{if(typeof document>"u"||typeof window>"u")return;const ue=()=>{Xn.current!==null&&window.clearTimeout(Xn.current),Xn.current=window.setTimeout(()=>{Xn.current=null;const Ve=document.activeElement,_=!(Ve?.getAttribute("data-terminal-input-anchor")==="true")&&!!(Ve&&(Ve instanceof HTMLInputElement||Ve instanceof HTMLTextAreaElement||Ve instanceof HTMLSelectElement||Ve.isContentEditable));yC({isActive:et.current&&!dr.current,isMobile:zr.current,documentVisible:!document.hidden,activeElementIsEditable:_})&&Ls()},0)};return document.addEventListener("pointerup",ue),()=>{document.removeEventListener("pointerup",ue),Xn.current!==null&&(window.clearTimeout(Xn.current),Xn.current=null)}},[Ls]);const Js=k.useCallback(()=>{ui.current=!1,Pn(ue=>ue+1)},[]),Oa=k.useCallback((ue,Ve,bt)=>{const _=rr.current,M=Date.now();if(_&&Ve&&B8(_)){ce.current={startedAt:M,strategy:"reconnect",reason:ue},Ba("info","PWA_RESUME terminal-start",{frontendSessionId:Y,backendSessionId:_,strategy:"reconnect",reason:ue,active:et.current});return}if(_&&Q8(_,()=>{const B=ce.current;Ba("info","PWA_RESUME terminal-responsive",{frontendSessionId:Y,backendSessionId:_,durationMs:B?Date.now()-B.startedAt:null,strategy:B?.strategy??"probe",reason:B?.reason??ue}),ce.current=null,Q?.(Y)},{visible:bt})){ce.current={startedAt:M,strategy:"probe",reason:ue},Ba("info","PWA_RESUME terminal-start",{frontendSessionId:Y,backendSessionId:_,strategy:"probe",reason:ue,active:et.current}),ie("[Terminal] resume probe sent",{reason:ue,backendSessionId:_,active:et.current});return}if(ie("[Terminal] resume probe missing connection, restarting ensureSession",{reason:ue,backendSessionId:_,active:et.current}),!vN({initialConnectionPending:z.current})){ie("[Terminal] resume probe deferred during initial websocket handshake",{reason:ue,backendSessionId:_});return}Js()},[ie,Q,Js,Y]),Nn=k.useCallback((ue,Ve)=>{const bt=rr.current;bt&&Ks.current!==ue&&(Ks.current=ue,Ex(bt,ue,Ve),ie("[Terminal] flow-control state sent",{backendSessionId:bt,paused:ue,reason:Ve}))},[ie]),Fa=k.useCallback((ue,Ve)=>{const bt=rr.current;bt&&lt.current!==ue&&(lt.current=ue,Nx(bt,ue,Ve),ie("[Terminal] focus state sent",{backendSessionId:bt,focused:ue,reason:Ve}))},[ie]),$a=k.useCallback((ue,Ve)=>{const bt=rr.current;bt&&ut.current!==ue&&(ut.current=ue,Rx(bt,ue,Ve),ie("[Terminal] viewing state sent",{backendSessionId:bt,viewing:ue,reason:Ve}))},[ie]),va=xC({isActive:l&&!Ze,viewportFocused:dt,documentVisible:_e,windowFocused:ke,streamReady:ae}),_s=bC({isActive:l,documentVisible:_e,windowFocused:ke,streamReady:ae,isDesktop:Gi()!==null}),ci=k.useRef(va),ei=k.useRef(_s);k.useEffect(()=>{ci.current=va,Fa(va,"logical-focus-change")},[va,Fa,tr]),k.useEffect(()=>{ei.current=_s,$a(_s,"logical-viewing-change")},[_s,$a,tr]),KC(tr,_e,ae),k.useEffect(()=>{const ue=Ve=>{const bt=Ve.detail;!bt||bt.sessionId!==Y||he(bt.fontSize??n.fontSize)};return window.addEventListener("termfontchange",ue),()=>window.removeEventListener("termfontchange",ue)},[Y,n.fontSize]),k.useEffect(()=>{const ue=()=>{const M=!document.hidden&&xc();Ue(M),M&&l&&Xs("visibility")},Ve=M=>{l&&Xs(M.persisted?"bfcache":"pageshow")},bt=()=>{V(!0),Xs("window-focus")},_=()=>V(!1);return document.addEventListener("visibilitychange",ue),window.addEventListener(Mx,ue),window.addEventListener("pageshow",Ve),window.addEventListener("focus",bt),window.addEventListener("blur",_),()=>{document.removeEventListener("visibilitychange",ue),window.removeEventListener(Mx,ue),window.removeEventListener("pageshow",Ve),window.removeEventListener("focus",bt),window.removeEventListener("blur",_)}},[l,Xs]),k.useEffect(()=>{if(!w||!P||!Ua.current)return;const ue=T,Ve=ue<=0,bt=Fe.current;if(bt?.token===w&&(bt.visible||!Ve))return;const _=()=>{Fe.current={token:w,visible:Ve},wr.current?.requestRefresh(v,{skipScrollToBottom:!0}),Oa(ue>0?"global-resume-background":"global-resume-visible",ue<=0&&S,Ve)};if(ue<=0){_();return}const M=window.setTimeout(_,ue);return()=>window.clearTimeout(M)},[w,v,P,T,S,Oa]);const io=k.useRef(0);k.useEffect(()=>{if(ae){io.current=0;return}if(!Pr||vr==="Authentication required"||vr===pf)return;const ue=io.current,Ve=Math.min(2e3*Math.pow(2,Math.min(ue,4)),3e4),bt=setTimeout(()=>{io.current+=1,ie("[Terminal] fatal self-heal: auto restarting ensureSession",{attempt:io.current,backendSessionId:rr.current}),Dt("Reconnecting..."),xn(!1),Js()},Ve);return()=>clearTimeout(bt)},[vr,Pr,ae,Qn,ie,Js]),k.useEffect(()=>{if(typeof window>"u"){He(!1);return}const ue=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;He(ue)},[]),k.useEffect(()=>{(!l||!we)&&xe(!1),l||it(!1)},[l,we]),k.useEffect(()=>{rr.current=tr,W.current=-1,Pt.current=null,lt.current=null,ut.current=null,Ks.current=null},[tr]),k.useEffect(()=>{$?.(Y,ae)},[ae,$,Y]),k.useEffect(()=>{Z?.(Y,ae&&Xe&&Ut)},[Xe,Ut,ae,Z,Y]),k.useEffect(()=>{qr||(Hn.current=!1,$r.current=null,pn.current&&(clearTimeout(pn.current),pn.current=null))},[qr]),k.useEffect(()=>{tr&&wr.current?.requestRefresh("session-key-change",{force:!0})},[tr]),k.useEffect(()=>{const ue=l&&we&&Rt;Pe("visibility signal",{sessionId:Y,isActive:l,isMobile:we,isInputFocused:tt,isViewportKeyboardOpen:Rt,viewportKeyboardHeight:ir,visible:ue}),J?.(Y,ue)},[J,Y,l,we,Rt,ir,Pe]),k.useEffect(()=>{l&&y&&y!==Ke.current&&(Ke.current=y,Ls())},[y,Ls,l]),k.useEffect(()=>{Cn.current=Y},[Y]),k.useEffect(()=>{!we&&(ge!==null||at!==null)&&(Je(null),Et(null),Re.current=null)},[we,ge,at]),k.useEffect(()=>{!tr&&(ge!==null||at!==null)&&(Je(null),Et(null),Re.current=null)},[tr,ge,at]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(b5,X?"true":"false")},[X]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(y5,Bt)},[Bt]),k.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(v5,Dr)},[Dr]),k.useEffect(()=>{le(Tm());const ue=()=>{le(Tm())};return window.addEventListener("resize",ue),()=>window.removeEventListener("resize",ue)},[]);const $n=k.useCallback(()=>{It.current+=1,_t.current+=1,Fr.current=Promise.resolve(),li(),gs();const ue=bn.current;bn.current=null,An.current=null,z.current=!1,$e.current=!1,pe(!1),wr.current?.setSessionReady(!1);const Ve=rr.current;Ve&&Ex(Ve,!1,"stream-disconnect"),ps.current=!1,Ks.current=null,rs.current=[],ue?.()},[gs,li]),wa=k.useCallback(async ue=>{if(An.current===ue){ie(`[startStream] Skipping - already connected to ${ue}`);return}ie(`[startStream] Starting stream for frontendSessionId=${Y} backendSessionId=${ue}`),Wr(null),R.current+=1,Qt.current=!1,xt.current=null,wt(!1),qt(!1),$n();const Ve=It.current+1;It.current=Ve,z.current=!0;const bt=Hr.getState().getTerminalSession(Y);if(bt?.mode==="shell"&&!bt.bufferChunks.length){const M=await Promise.race([P8(ue),new Promise(B=>window.setTimeout(()=>B(null),75))]);if(It.current!==Ve||Cn.current!==Y)return;if(M&&!Hr.getState().getTerminalSession(Y)?.bufferChunks.length){Hr.getState().replaceBuffer(Y,[M.data]);const B=wr.current?.getDimensions();B?.cols===M.cols&&B.rows===M.rows&&O8(ue,M.seq,M.epoch)}}const _=Qe.connect(ue,{onEvent:M=>{if(It.current!==Ve)return;const B=Y;if(B)switch(M.type){case"connected":{_t.current+=1,Fr.current=Promise.resolve(),z.current=!1;const G=ce.current;G&&(Ba("info","PWA_RESUME terminal-connected",{frontendSessionId:B,backendSessionId:rr.current,durationMs:Date.now()-G.startedAt,strategy:G.strategy,reason:G.reason}),ce.current=null),Q?.(B),(M.runtime||M.ptyBackend)&&ie(`[Terminal] connected frontendSessionId=${B} backendSessionId=${rr.current} runtime=${M.runtime??"unknown"} pty=${M.ptyBackend??"unknown"} cwd=${M.cwd??"unknown"}`),ne(B,!1),Dt(null),xn(!1),Wr(null),$e.current=!0,pe(!0),rr.current&&(Nx(rr.current,ci.current,"stream-connected"),Rx(rr.current,ei.current,"stream-connected")),wr.current?.setSessionReady(!0),Ks.current=null,Nn(ps.current,"stream-connected"),M.tuiProgress!==void 0&&Hr.getState().setSessionTuiProgress(B,M.tuiProgress??null),M.shellTitle!==void 0&&Hr.getState().setSessionShellTitle(B,M.shellTitle??null),M.promptState!==void 0&&M.promptState!==null&&Hr.getState().setSessionPromptState(B,M.promptState);const Te=Hr.getState().getTerminalSession(B);if(Te?.terminalSessionId&&M.mode&&Hr.getState().setTerminalSession(B,{sessionId:Te.terminalSessionId,cols:80,rows:24,mode:M.mode,tmuxSessionName:M.tmuxSessionName??null,cwd:M.cwd??null}),M.activeProgram!==void 0&&Jr(B,M.activeProgram??null,M.activeProgramSource??null,M.activeProgramRaw??null),wr.current?.requestRefresh("connected",{force:!0,reconcileServerSize:et.current}),M.mode!=="tmux"&&(ds(null),mr(B,!1)),ie("[Terminal] Connected event received:",{frontendSessionId:B,backendSessionId:rr.current,storeHasState:!!Te,storeTerminalId:Te?.terminalSessionId,hasHistoryInStore:!!Te?.history?.length,historyLength:Te?.history?.length??0}),Te?.history&&Te.history.length>0){ie(`[Terminal] Restoring ${Te.history.length} history chunks to frontend session ${B}`);const ct=Te.history.reduce(($t,Ir)=>$t+Ir.length,0),yt=Math.max(300,Math.min(2e3,Math.ceil(ct/200)));on.current=Date.now()+yt,Te.history.forEach($t=>{Ye(B,$t,{markActivity:!1})}),Hr.getState().setSessionHistory(B,[]),ie(`[Terminal] History restoration complete for ${B}`)}else ie(`[Terminal] No history to restore for ${B}`);const Se=M.replayChunks,Be=!!Te?.history?.length||!!Se?.length;if(Be?Qt.current=!0:ls(),Se&&Se.length>0){let ct=null;if(M.replayOutOfWindow)wr.current?.prepareScreenReplacement(),ie(`[Terminal] Replay out-of-window, atomically replacing buffer (${Se.length} chunks)`),ct=St(B,i_(Se));else{ie(`[Terminal] Replay incremental: ${Se.length} chunks`);for(const Ir of Se)Ye(B,Ir)}const yt=Se.reduce((Ir,ln)=>Ir+ln.length,0),$t=Math.max(200,Math.min(1500,Math.ceil(yt/200)));on.current=Math.max(on.current,Date.now()+$t),xt.current=ct}Be&&xt.current===null&&(xt.current=Hr.getState().flushPendingBufferWrites(B),xt.current===null&&(Qt.current=!1,ls()));break}case"reconnecting":{$e.current=!1,pe(!1),Wr(G=>G??Date.now()),Dt("Reconnecting..."),xn(!1);break}case"data":{M.data&&(ps.current?rs.current.push(M.data):(Ye(B,M.data),kn.current.consume(M.data.length,performance.now(),et.current&&!document.hidden&&xc())&&Hr.getState().flushPendingBufferWrites(B)));break}case"tmux-layout":{ds(M.layout??null),M.layout&&mr(B,M.layout.inCopyMode);break}case"tmux-screen-sync":{const G=M.generation??0;if(G<W.current)break;W.current=G,R.current+=1,Qt.current=!0,wt(!1),rs.current=[],wr.current?.prepareScreenReplacement(),Pt.current=G,xt.current=St(B,a_(M.chunks??[])),xt.current===null&&(Pt.current=null,wr.current?.notifyScreenSynchronized(G),Qt.current=!1,ls()),typeof M.cols=="number"&&typeof M.rows=="number"&&wr.current?.notifyServerSize(M.cols,M.rows,"tmux-screen-sync");break}case"active-program":{Jr(B,M.activeProgram??null,M.activeProgramSource??null,M.activeProgramRaw??null);break}case"cwd":{en(B,M.cwd??null);break}case"agent-status":{tn(B,{agentStatus:M.agentStatus??null,agentIndicator:M.agentIndicator??null,agentStatusDetail:M.agentStatusDetail??null,agent:M.agent??null,agentMessage:M.agentMessage??null,agentNativeSessionId:M.agentNativeSessionId??null,agentResumeRecovered:M.agentResumeRecovered===!0,agentRich:M.agentRich===!0,agentActivity:M.agentActivity??0,agentCwd:M.agentCwd??null,reviewed:M.reviewed??null});break}case"git-status":{Hr.getState().setSessionGitStatus(B,M.gitStatus??null);break}case"focus-mode":{ie("[Terminal] focus tracking mode",{backendSessionId:rr.current,requested:M.focusTrackingRequested===!0});break}case"resize-ack":{wr.current?.acknowledgeResize({seq:M.seq,ok:M.ok!==!1,cols:M.cols,rows:M.rows,screenSyncPending:M.screenSyncPending,screenSyncGeneration:M.screenSyncGeneration});break}case"pty-size":{typeof M.cols=="number"&&typeof M.rows=="number"&&wr.current?.notifyServerSize(M.cols,M.rows,M.source);break}case"shell-title":{Tl(B,M.title??null);break}case"prompt-state":{Zr(B,M.state??"idle",M.exitCode??null);break}case"tui-progress":{Hr.getState().setSessionTuiProgress(B,M.tuiProgress??null);break}case"exit":{const G=typeof M.exitCode=="number"?M.exitCode:null,Te=typeof M.signal=="number"?M.signal:null;Ye(B,`\r
76
76
  [Process exited${G!==null?` with code ${G}`:""}${Te!==null?` (signal ${Te})`:""}]\r
77
- `),Jt(B),ne(B,!1),Dt("Terminal session ended"),pe(!1),xn(!1),Wr(null),ds(null),mr(B,!1),$n();break}}},onError:(M,B)=>{if(It.current!==Ve)return;const G=Y;if(!G)return;z.current=!1,$e.current=!1,pe(!1);const Te=M.name==="TerminalInputError"&&"code"in M&&M.code==="TERMINAL_INPUT_REJECTED",Se=B&&M.message==="Authentication required",Be=!Te&&g5(M),ct=Te||Se?M.message:Be||B?"Reconnecting...":M.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${B}):`,ct),Be&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:rr.current,frontendSessionId:G,isActive:l,isMobile:we,fatal:B,stack:new Error().stack}),Dt(ct),xn(!!B),B&&(Wr(null),ne(G,!1),$n(),Be&&(ie("[onError] Session lost, auto-recreating"),Dt("Reconnecting..."),xn(!1),Jt(G),un(G),rr.current=null,ui.current=!1,Js()))}},{...ON,getDimensions:()=>wr.current?.getDimensions()??null});bn.current=()=>{_.close(),It.current===Ve&&(An.current=null)},An.current=ue},[Ye,un,Jt,ie,$n,ls,Q,Nn,Js,Tl,ne,Jr,tn,mr,en,Zr,Qe,Y]);k.useEffect(()=>{const ue=_N({isActive:l,isStreamReady:ae,reconnectStartedAt:ws,now:Date.now()});if(ue===null)return;const Ve=window.setTimeout(()=>{ie("[Terminal] visible reconnect watchdog expired",{backendSessionId:rr.current,reconnectStartedAt:ws}),$n(),ne(Y,!1),Dt("Reconnecting..."),xn(!1),Wr(Date.now()),Js()},ue);return()=>window.clearTimeout(Ve)},[ie,$n,l,ae,ws,Js,Y,ne]);const ui=k.useRef(!1),Ua=k.useRef(!1),js=k.useRef(0);k.useEffect(()=>()=>{js.current+=1,ui.current=!1,$n()},[$n]);const ao=k.useRef(De),za=k.useRef(Mt);k.useEffect(()=>{const ue=ao.current,Ve=za.current;ao.current=De,za.current=Mt,Cn.current===Y&&(ue===De&&Ve===Mt||(ui.current=!1,$n(),Pn(bt=>bt+1)))},[De,Mt,$n,Y]),k.useEffect(()=>{if(Cn.current!==Y&&(ie(`[useEffect] sessionId changed from ${Cn.current} to ${Y}, allowing reinitialization`),ui.current=!1,Ua.current=!1),ui.current&&Cn.current===Y){ie(`[useEffect] Already initialized for sessionId=${Y}, skipping`);return}if(!Nt)return;const ue=async B=>{if(ie(`[ensureSession] Starting for sessionId=${Y}, runId=${B}`),!Cn.current||Cn.current!==Y){ie(`[ensureSession] SessionId mismatch or stale run (current=${Cn.current}, target=${Y}), skipping`);return}if(B!==js.current){ie(`[ensureSession] Stale run detected (runId=${B}, currentRunId=${js.current}), skipping`);return}const G=Hr.getState(),Te=G.getTerminalSession(Y),Se=Te?.mode??De;ie("[ensureSession] Current state from store:",{terminalSessionId:Te?.terminalSessionId,mode:Te?.mode,tmuxSessionName:Te?.tmuxSessionName,isConnecting:Te?.isConnecting});let Be=Te?.terminalSessionId??null,ct=!Be;if(Be&&Se!==De?(ie(`[ensureSession] Store mode mismatch for ${Be}: current=${Se} desired=${De}, will create new session`),ct=!0,G.clearTerminalSession(Y),Be=null):Be&&De==="tmux"&&Mt&&Te?.tmuxSessionName!==Mt&&(ie(`[ensureSession] Store tmux name mismatch for ${Be}: current=${Te?.tmuxSessionName} desired=${Mt}, will create new session`),ct=!0,G.clearTerminalSession(Y),Be=null),Be&&Qe.checkHealth&&!et.current){ie(`[ensureSession] Checking health of existing session ${Be}`);try{const yt=await Qe.checkHealth(Be);if(ie("[ensureSession] Health check result:",yt),!yt.healthy)ie(`[ensureSession] Session ${Be} is NOT healthy (healthy=${yt.healthy}), will create new session`),ie("[ensureSession] Health check details:",yt),ct=!0,yt.mode&&Te?.terminalSessionId&&G.setTerminalSession(Y,{sessionId:Te.terminalSessionId,cols:80,rows:24,mode:yt.mode,tmuxSessionName:yt.tmuxSessionName??null}),G.clearTerminalSession(Y),ie("[ensureSession] Cleared unhealthy session from store");else{ie(`[ensureSession] Session ${Be} is healthy, reusing it, cwd=${yt.cwd}, clients=${yt.clients}, lastActivity=${Date.now()-(yt.lastActivity||0)}ms ago`),yt.mode&&Te?.terminalSessionId&&G.setTerminalSession(Y,{sessionId:Te.terminalSessionId,cols:80,rows:24,mode:yt.mode,tmuxSessionName:yt.tmuxSessionName??null}),ie(`[ensureSession] Setting terminalIdRef to ${Be} and starting stream`),rr.current=Be,wa(Be),ie(`[ensureSession] Successfully reused healthy session ${Be}, returning early`);return}}catch(yt){ie(`[ensureSession] Failed to check health of session ${Be}:`,yt),ie("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ie(`[ensureSession] Decision: shouldCreateNewSession=${ct}, terminalId=${Be}`),ct){ie(`[ensureSession] Creating new session, shouldCreateNewSession=${ct}, runId=${B}`),Dt(null),xn(!1),G.setConnecting(Y,!0);const $t=Hr.getState().getTerminalSession(Y),ln=($t?.mode??De)===De&&(De!=="tmux"||!Mt||$t?.tmuxSessionName===Mt);if($t?.terminalSessionId&&ln)ie(`[ensureSession] Race condition avoided: another instance already created session ${$t.terminalSessionId}`),G.setConnecting(Y,!1),Be=$t.terminalSessionId,ct=!1;else try{const rn=await hs();if(ie(`[ensureSession] Opened managed backend session ${rn.sessionId}`),B!==js.current){ie(`[ensureSession] Stale run after session creation (runId=${B}, currentRunId=${js.current}), leaving ${rn.sessionId} for sibling`);return}G.setTerminalSession(Y,rn),ie(`[ensureSession] Updated store with new session ${rn.sessionId}`),Be=rn.sessionId}catch(rn){if(B!==js.current){ie("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(rn instanceof g0&&N1(rn)){ie("[ensureSession] Confirmed missing persisted session:",{sessionId:Y,error:rn.message}),G.clearTerminalSession(Y),Dt(pf),xn(!0),G.setConnecting(Y,!1);return}Dt("Reconnecting..."),xn(!0),G.setConnecting(Y,!1);return}}if(B!==js.current){ie(`[ensureSession] Stale run before starting stream (runId=${B}, currentRunId=${js.current}), skipping`);return}if(!Be){ie(`[ensureSession] No terminalId, terminalId=${Be}`);return}ie(`[ensureSession] Starting stream for session ${Be}`),rr.current=Be,wa(Be),ie(`[ensureSession] ensureSession completed for sessionId=${Y}, terminalId=${Be}`)};let Ve=null,bt=null;const _=()=>{bt=null,!(ui.current&&Cn.current===Y)&&(ie(`[useEffect] Running ensureSession for sessionId=${Y}, hasInitialized=${ui.current}`),ui.current=!0,Ua.current=!0,Ve=++js.current,ue(Ve))};if(!N&&!Ua.current){ie(`[useEffect] Holding background connection until the selected session is ready: ${Y}`);return}const M=Ua.current?0:Math.max(0,I);return M>0?(ie(`[useEffect] Delaying initial connection for sessionId=${Y} by ${M}ms`),bt=window.setTimeout(_,M)):_(),()=>{bt!==null&&window.clearTimeout(bt),ie(`[useEffect] Cleanup for sessionId=${Y}, runId=${Ve??"pending"}`)}},[Y,Qn,wa,$n,Qe,ie,De,Mt,lr,I,N,Nt]);const _c=k.useCallback(async()=>{if(Y&&!Kn){Cs(!0),Dt(null),xn(!1),Wr(null),$n();try{Qe.forceKill&&await Qe.forceKill({sessionId:Y})}catch{}Or(Y),un(Y),wr.current?.clear(),await new Promise(ue=>setTimeout(ue,100));try{ne(Y,!0);const ue=await hs();an(Y,ue),rr.current=ue.sessionId,wa(ue.sessionId)}catch(ue){Dt(ue instanceof g0&&N1(ue)?pf:"Reconnecting..."),xn(!0),ne(Y,!1)}finally{Cs(!1)}}},[Y,Kn,$n,Qe,Or,un,ne,an,wa,hs]),di=k.useCallback((ue,Ve,bt,_)=>{if(!(rr.current!==Ve||_t.current!==bt)){if(ue instanceof g0&&g5(ue)){ie("[Terminal] operation backend missing, recovering",{terminalId:Ve,sessionId:Y}),Dt("Reconnecting..."),xn(!1),$n(),Jt(Y),rr.current=null,ne(Y,!0),Js();return}Dt(ue instanceof Error?ue.message:_)}},[Jt,ie,$n,Js,Y,ne]),Vl=k.useCallback((ue,Ve)=>{const bt=Ve?.ownedPaste?YC(Ve.ownedPaste,Y,ue):!1;if(Ve?.ownedPaste&&!bt||Wn.current&&!(bt&&Gt.current)||(dr.current||og())&&!bt)return Promise.resolve(!1);const _=()=>!!Ve?.ownedPaste&&ZC(Ve.ownedPaste,Y)&&(et.current||Ve?.targeted===!0)&&(!Wn.current||Gt.current)&&$e.current&&!Br.current&&!document.hidden&&navigator.onLine!==!1&&xc();if(bt&&!_())return Promise.resolve(!1);if(!et.current&&!Ve?.targeted||!ue)return;const M=qE(ue),B=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(ue);if(Date.now()<on.current)return Promise.resolve(!1);let G=ue,Te=Ve?.consumeModifier??!1;if(!Ve?.skipModifierTransform&&!M&&ge&&ue.length>0){const $t=ue[0];if($t.length===1&&/[a-zA-Z]/.test($t)){const Ir=$t.toUpperCase();ge==="ctrl"?(G=String.fromCharCode(Ir.charCodeAt(0)&31),Te=!0):ge==="alt"&&(G=`\x1B${ue}`,Te=!0)}Te||(ge==="alt"&&(G=`\x1B${ue}`),Te=!0)}const Se=rr.current;if(!Se)return;const Be=_t.current,ct=async()=>{if(rr.current!==Se||_t.current!==Be)return!1;try{if((!M||B)&&kn.current.input(performance.now()),qr&&B&&(Hn.current=!0),qr&&!M&&Hn.current&&Qe.tmuxAction){if(Hn.current=!1,bt&&!_())return!1;if(Qe.sendInputExitingCopyMode?.(Se,G))return Qr(Y),!0;try{await Qe.tmuxAction(Se,{action:"copy-mode",enabled:!1})}catch{}if(rr.current!==Se||_t.current!==Be)return!1;if(YE(G))return!0}return bt&&(!_()||rr.current!==Se||_t.current!==Be)||(await Qe.sendInput(Se,G),bt&&(!_()||rr.current!==Se||_t.current!==Be))?!1:(Qr(Y),!0)}catch($t){return di($t,Se,Be,"Failed to send input"),!1}},yt=Fr.current.then(ct);return Fr.current=yt.then(()=>{},()=>{}),Te&&(at||Je(null),Ls()),yt},[ge,Qr,Ls,di,qr,at,Y,Qe]);k.useEffect(()=>{const ue=Ve=>{const bt=Ve,_=bt.detail?.sessionId;if(_?_!==Y:!et.current)return;const M=bt.detail?.text;if(!M)return;const B=bt.detail?.nonce;if(Br.current||!wr.current){B&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:B,ok:!1}}));return}const G=qC(bt.detail,Y),Te=bt.detail?.ownedPaste&&!G?Promise.resolve(!1):wr.current.sendSequence(M,{paste:bt.detail?.paste,submitAfterPaste:bt.detail?.submitAfterPaste,targeted:!!_,ownedPaste:G??void 0});B&&Promise.resolve(Te).then(Se=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:B,ok:Se===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:B,ok:!1}}))}),vC(zr.current,bt.detail?.focus!==!1)&&Ls()};return window.addEventListener("termdock-insert-reference",ue),()=>window.removeEventListener("termdock-insert-reference",ue)},[Ls,Y]);const Ci=k.useCallback((ue,Ve,bt)=>{const _=rr.current;if(!_){Pe("xterm resize push skipped: no terminalId",{cols:ue,rows:Ve});return}Pe("xterm resize push",{cols:ue,rows:Ve}),Qe.resize({sessionId:_,cols:ue,rows:Ve,seq:bt}).catch(M=>{wr.current?.acknowledgeResize({seq:bt,ok:!1}),M&&/session not found/i.test(String(M.message||M))&&console.warn("[Terminal] resize 404 session not found",{sessionId:_,cols:ue,rows:Ve,stack:new Error().stack})})},[Qe,Pe]),oo=k.useCallback(async ue=>{const Ve=rr.current;if(!Ve||!Qe.tmuxAction)return;const bt=_t.current;try{const _=await Qe.tmuxAction(Ve,ue);if(rr.current!==Ve||_t.current!==bt)return;_.layout&&(ds(_.layout),ue.action==="switch-session"&&(an(Y,{sessionId:Ve,cols:80,rows:24,mode:"tmux",tmuxSessionName:_.layout.sessionName}),F8(Y,{tmuxSessionName:_.layout.sessionName}).catch(M=>{console.warn("[Terminal] failed to update inventory after tmux switch",M)})))}catch(_){di(_,Ve,bt,"Failed to execute tmux action")}},[di,Y,an,Qe]);k.useEffect(()=>{if(!jr||!tr)return;const Ve=jr.windows.find(bt=>bt.id===jr.activeWindowId)?.panes.find(bt=>bt.id===jr.activePaneId);Ve&&wr.current?.requestRefresh("tmux-layout",{skipResizePush:!0,skipScrollToBottom:!0,dedupeKey:`${tr}:${jr.sessionId}:${Ve.id}:${Ve.width}x${Ve.height}`})},[jr,tr]);const $s=k.useCallback((ue,Ve=5)=>{const bt=Math.max(1,Math.min(Math.floor(Ve)||1,40));Hn.current=!0;const _=$r.current;if(_&&_.direction===ue){_.lines+=bt;return}_&&oo({action:"scroll",direction:_.direction,lines:_.lines}).finally(()=>{Ls()}),$r.current={direction:ue,lines:bt},pn.current&&clearTimeout(pn.current),pn.current=setTimeout(()=>{const M=$r.current;M&&($r.current=null,oo({action:"scroll",direction:M.direction,lines:M.lines}).finally(()=>{Ls()}))},0)},[Ls,oo]),Aa=k.useCallback(ue=>{const Ve=Date.now(),bt=Re.current,_=bt!==null&&bt.modifier===ue&&Ve-bt.timestamp<=DN;if(Re.current={modifier:ue,timestamp:Ve},at===ue){Et(null),Je(null);return}if(_){Et(ue),Je(ue);return}at!==null&&at!==ue&&Et(null),Je(M=>M===ue?null:ue)},[at]),Sl=k.useCallback(ue=>{if(it(ue&&et.current),Pe("input focus changed",{focused:ue,isActive:et.current,isMobile:zr.current}),!zr.current||!et.current){xe(!1);return}xe(Ve=>Ve===ue?Ve:ue)},[Pe]),es=k.useCallback(ue=>{if(ps.current=ue,Nn(ue,"viewport-watermark"),!ue&&rs.current.length>0){const Ve=Y;if(Ve){const bt=rs.current;rs.current=[];for(const _ of bt)Ye(Ve,_)}}},[Ye,Nn,Y]),ti=k.useCallback(ue=>{et.current&&wr.current?.ensureSizeMatches(ue)},[]),Pi=k.useRef(null);k.useEffect(()=>{if(!l)return;const ue=Pi.current;if(!ue)return;const Ve=()=>ti("pointerdown"),bt=()=>ti("keydown"),_=()=>ti("touchstart"),M=()=>ti("wheel");return ue.addEventListener("pointerdown",Ve),ue.addEventListener("keydown",bt),ue.addEventListener("touchstart",_,{passive:!0}),ue.addEventListener("wheel",M,{passive:!0}),()=>{ue.removeEventListener("pointerdown",Ve),ue.removeEventListener("keydown",bt),ue.removeEventListener("touchstart",_),ue.removeEventListener("wheel",M)}},[l,ti]);const Ta=k.useCallback(ue=>{wr.current=ue},[]),ql=k.useCallback(ue=>{sr(ue),U?.(Y,ue)},[U,Y]),Yl=k.useCallback(ue=>{const Ve=nN(ue);if(!Ve)return;const bt=ge!==null;wr.current?.sendSequence(Ve,{consumeModifier:bt})},[ge]),kc=k.useCallback(ue=>{const Ve=XE(ue);if(Ve.length===0)return;const bt=ge!==null;wr.current?.sendSequence(h5(Ve[0]),{consumeModifier:bt});for(let _=1;_<Ve.length;_+=1){const M=Ve[_];window.setTimeout(()=>{wr.current?.sendSequence(h5(M))},KE*_)}},[ge]),Lc=k.useCallback(()=>{wr.current?.pasteClipboardText()},[]),Gn=k.useCallback(ue=>{ar.current!==null&&(window.clearTimeout(ar.current),ar.current=null),ot(ue),(ue==="inserted"||ue==="failed")&&(ar.current=window.setTimeout(()=>{ar.current=null,ot("idle")},1400))},[]),_i=k.useCallback(()=>{Gn("idle"),nr(0),Fn.current?.click()},[Gn]),Yi=k.useCallback(()=>{yr(!0)},[]),Ha=k.useCallback(ue=>{const Ve=ue.currentTarget.files?.[0];if(ue.currentTarget.value="",!Ve)return;const bt=Y;Tt(null),Rr(null),be(null),nr(0),Gn("uploading");const _=Kr&&Ve.type.startsWith("video/")?{maxHeight:wn,videoBitrate:Oe,onProgress:nr}:null,M=ft&&QN(Ve)?{maxDimension:ht,quality:Cr}:null;let B=_?"视频压缩":M?"图片压缩":"文件上传";(async()=>{const G=_?await(await Zc(async()=>{const{compressVideoLocally:Te}=await import("./videoCompression-Bsw--tMn.js");return{compressVideoLocally:Te}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(Ve,_):M?await(await Zc(async()=>{const{compressImageLocally:Te}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:Te}},[])).compressImageLocally(Ve,M):Ve;B="文件上传",await RN(G,(Te,Se)=>W0(Te,Se,void 0,nr),Te=>(B="插入终端",M1(R1(Te,null),bt,()=>et.current&&!Br.current&&Cn.current===bt&&Hr.getState().activeSessionId===bt))),(_||M)&&be({file:G,kind:_?"video":"image",originalSize:Ve.size,uploadedSize:G.size,originalRetained:G===Ve})})().then(()=>Gn("inserted"),G=>{G instanceof Of&&Tt({path:G.uploaded.path,sessionId:bt});const Te=G instanceof Of?G.uploaded.path:w5(G);Rr({stage:B,detail:Te}),yr(!0),Gn("failed"),Ba("warn","MOBILE_MEDIA_UPLOAD failed",{stage:B,detail:Te})})},[Oe,Kr,wn,ft,ht,Cr,Y,Gn]),Zi=k.useCallback(async()=>{const ue=Gr;if(!ue||ue.sessionId!==Y)return;yr(!1),await new Promise(bt=>window.requestAnimationFrame(()=>bt())),Gn("uploading"),await M1(R1(ue.path,null),ue.sessionId,()=>et.current&&!Br.current&&Cn.current===ue.sessionId&&Hr.getState().activeSessionId===ue.sessionId)?(Tt(null),Rr(null),Gn("inserted")):(yr(!0),Gn("failed"))},[Gr,Y,Gn]);k.useEffect(()=>{if(!Ht||!Kr)return;let ue=!0;return hn(null),Bn({phase:"checking-cache"}),Zc(async()=>{const{prepareLocalVideoCompression:Ve}=await import("./videoCompression-Bsw--tMn.js");return{prepareLocalVideoCompression:Ve}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:Ve})=>{if(ue)return Ve(bt=>{ue&&Bn(bt)})}).catch(Ve=>{ue&&hn(w5(Ve))}),()=>{ue=!1}},[Ht,Kr]);const lo=On||vr!==null;Br.current=lo;const Us=k.useRef(Ar);lo||(Us.current=Ar);const Ki=lo?Us.current:Ar,Sa=k.useMemo(()=>JE(Ki,En),[Ki,En]),_n=k.useMemo(()=>p5(En,Bt),[Bt,En]),ns=!we&&Bt!=="auto"&&_n.id!=="default"&&_n.showOnDesktop!==!0?"auto":Bt,Ca=ns==="auto"?Sa:ns,cs=k.useMemo(()=>p5(En,Ca),[Ca,En]),Wa=k.useMemo(()=>cs.actions.filter(ue=>ue.sequence.trim().length>0).map((ue,Ve)=>({...ue,label:E1(ue,Ve)})),[cs.actions]),ki=k.useMemo(()=>kv(Ar),[Ar]),co=cs.label,Li=k.useMemo(()=>ns!=="auto"?`Manual preset: ${cs.label}`:ki?`Auto preset · ${cs.label} (${ki})`:"Auto preset",[ki,ns,cs.label]),Ga=k.useCallback(ue=>{Me(ue)},[]),Xi=k.useCallback(()=>{Le(ue=>ue==="copy"?"arrows":"copy"),Ot("idle")},[]),Ji=k.useCallback(()=>{typeof window>"u"||(pr.current!==null&&window.clearTimeout(pr.current),pr.current=window.setTimeout(()=>{pr.current=null,Ot("idle")},1200))},[]),ea=k.useCallback(ue=>{pr.current!==null&&typeof window<"u"&&(window.clearTimeout(pr.current),pr.current=null),Ot(ue?"copied":"failed"),Ji()},[Ji]),ta=k.useCallback(ue=>{vt(ue)},[]),xs=k.useMemo(()=>we?eN(En):tN(En),[we,En]),ra=k.useMemo(()=>$8(a),[a]);k.useEffect(()=>{if(!qr||!ae||!Nt||!tr)return;const ue=o_(ra);ue&&Qe.sendInput(tr,ue).catch(Ve=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",Ve)})},[qr,ae,Nt,tr,Qe,ra]);const Va=k.useMemo(()=>`terminal::${Y}`,[Y]),Ds=k.useCallback(()=>`${rr.current??"pending"}:${_t.current}`,[]);k.useEffect(()=>{qe?.({isConnecting:On,isRestarting:Kn,hasError:!!vr,sessionId:tr})},[On,Kn,vr,tr,qe]);const _a=!tr||On||Kn,Cl=k.useCallback((ue,Ve)=>{if(_a)return;const bt=Math.max(1,Math.min(Math.floor(Ve)||1,40));$s(ue,bt)},[$s,_a]);k.useEffect(()=>{if(!l||!we)return;wr.current?.requestRefresh("resize",{skipScrollToBottom:!Rt,force:!0})},[l,we,Rt,ir,Y]),k.useEffect(()=>{if(!l||!we)return;const ue=Ve=>{const bt=Ve.detail;wr.current?.requestRefresh("resize",{skipScrollToBottom:bt?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",ue),()=>{document.removeEventListener("termdock:viewport-keyboard-change",ue)}},[l,we,Y]);const Zl=!H&&(we||cs.id==="default"||cs.showOnDesktop===!0),rl=l,ka=we&&!oe?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,na=we&&!oe?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,As=s.jsx(sN,{visible:Zl,interactive:rl,presentation:we?"mobile":"desktop-actions",activeModifier:ge,lockedModifier:at,disabled:_a,defaultShowExtended:X,presetLabel:co,presetModeLabel:Li,presetMode:ns,presetOptions:xs,includeAlt:cs.includeAlt,presetRowLayout:cs.rowLayout,extraActions:Wa,onKeyPress:Yl,onTextPress:kc,onPastePress:we?Lc:void 0,onFilePress:we?_i:void 0,onFileLongPress:we?Yi:void 0,fileUploadState:er,fileUploadProgress:Lt,longPressMode:Dr,copyFeedback:At,onLongPressModeToggle:Xi,onModifierToggle:Aa,onPresetSelect:Ga,onExpandedChange:ta}),Qo=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return s.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:ka,"data-owned-terminal-startup":window.__TD_NATIVE_GATE_STATE?JSON.stringify({active:l,viewportReady:Nt,streamReady:ae,contentReady:Xe,sizeReady:Ut}):void 0,children:[s.jsx("input",{ref:Fn,type:"file",className:"hidden",onChange:Ha}),Ht&&Zs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:()=>yr(!1),"aria-label":ve("common.close")}),s.jsxs("section",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-video-compression-title",className:"fixed bottom-[max(0.75rem,env(safe-area-inset-bottom,0px))] left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] z-modal-panel max-h-[calc(100dvh-1.5rem)] overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:left-1/2 sm:right-auto sm:w-[min(28rem,calc(100vw-2rem))] sm:-translate-x-1/2",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h2",{id:"mobile-video-compression-title",className:"text-sm font-semibold text-foreground",children:"本地媒体压缩"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"按文件类型选择压缩方式,处理完成后才上传。"})]}),s.jsx("button",{type:"button",className:"min-h-10 rounded-lg bg-surface-2 px-3 text-xs",onClick:()=>yr(!1),children:ve("common.close")})]}),ur&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[ur.stage,"失败。",ur.stage.endsWith("压缩")?"原文件未上传。":ur.stage==="插入终端"?"文件已上传,路径见详情。":""]}),s.jsxs("details",{className:"mt-2",children:[s.jsx("summary",{className:"cursor-pointer",children:"错误详情"}),s.jsx("p",{className:"mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:ur.detail})]}),Gr&&s.jsx("button",{type:"button",onClick:()=>{Zi()},disabled:er==="uploading"||Gr.sessionId!==Y,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:ve("common.retry")})]}),cn&&s.jsx("p",{className:"mt-2 text-[11px] text-destructive",children:"本机未能保存设置,重新打开后可能恢复默认值。"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"显示压缩结果提示"}),s.jsx("input",{type:"checkbox",checked:gt.showResultToast,onChange:ue=>rt({showResultToast:ue.target.checked}),className:"h-4 w-4 accent-primary"})]}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩图片后上传"}),s.jsx("input",{type:"checkbox",checked:ft,onChange:ue=>rt({imageEnabled:ue.target.checked}),className:"h-4 w-4 accent-primary"})]}),ft&&s.jsxs("div",{className:"mt-3 space-y-3",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片最长边",s.jsx("select",{value:ht,onChange:ue=>rt({imageMaxDimension:Number(ue.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:jv.map(ue=>s.jsxs("option",{value:ue,children:[ue," px",ue===640?" · 最省流量":ue===2048?" · 推荐":ue===4096?" · 保留更多细节":""]},ue))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片画质:",Math.round(Cr*100),"%",s.jsx("input",{type:"range",min:A0.min,max:A0.max,step:A0.step,value:Cr,onChange:ue=>rt({imageQuality:Number(ue.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"支持 JPEG、PNG、HEIC 照片;GIF、SVG 等保持原文件。压缩后未变小也会保留原图。"})]}),s.jsx("div",{className:"mt-4 border-t border-border/15 pt-1"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩视频后上传"}),s.jsx("input",{type:"checkbox",checked:Kr,onChange:ue=>rt({videoEnabled:ue.target.checked}),className:"h-4 w-4 accent-primary"})]}),Kr&&s.jsxs("div",{className:"mt-4 space-y-4",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["视频最长边(像素)",s.jsx("select",{value:wn,onChange:ue=>rt({videoMaxHeight:Number(ue.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:Dv.map(ue=>s.jsxs("option",{value:ue,children:[ue," px",ue===240?" · 最省流量":ue===720?" · 推荐":ue>=1440?" · 手机处理较慢":""]},ue))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["目标视频码率:",Oe/1e6," Mbps",s.jsx("input",{type:"range",min:T0.min,max:T0.max,step:T0.step,value:Oe,onChange:ue=>rt({videoBitrate:Number(ue.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"保持比例,不放大原视频。尺寸越小通常处理越快;码率越低体积通常越小,过高可能比原片更大。"}),s.jsx("p",{className:"text-[11px] text-muted-foreground",role:"status","aria-live":"polite",children:mn?"本地转码器准备失败,请关闭开关后重试。":PN(Xr)}),Xr?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),mn&&s.jsx("p",{className:"text-[11px] text-destructive",children:mn})]})]})]}),document.body),Tr&&s.jsx(iN,{isMobile:we,isInputFocused:tt,isIOS:Ge,isConnecting:On,connectionError:vr,terminalSessionId:tr}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:ra.background,...na},children:[s.jsx("div",{ref:Pi,className:"h-full w-full box-border",children:s.jsx(U8,{fallback:s.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:s.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:s.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),s.jsx("span",{className:"text-sm text-muted-foreground",children:ve("terminal.componentFailed")})]})}),children:s.jsx($E,{ref:Ta,sessionKey:Va,sessionId:Y,getPasteOwnerKey:Ds,backendSessionId:tr,isLayoutVisible:x,chunks:Lr,onInput:Vl,onResize:Ci,onFlowControl:es,onTmuxScroll:qr?Cl:void 0,tmuxScrollSensitivity:.38,onDoubleTap:we?()=>{wr.current?.sendSequence(" ")}:void 0,onInputFocusChange:Sl,onMobileLongPressCopyResult:ea,onReadyChange:ql,onSizeSynchronizedChange:qt,onWritesSettled:ya,onWriteProgress:Fs,onCursorPositionChange:Pa,onDirectoryLinkActivate:K,terminalSettings:Ie,theme:ra,enableTouchScroll:we,mobileLongPressMode:Dr,autoFocus:l&&!Ze&&!we&&!Qo,inputActive:l&&!Ze,cursorVisible:!Ze&&jt,suppressSmoothScroll:!Xe||!Ut,className:Ze||!jt?"terminal-focus-suspended":void 0},Va)})}),s.jsx(jN,{result:Ft,onDismiss:Ct}),s.jsx(oN,{connectionError:vr,isFatalError:Pr,isRestarting:Kn,isConnecting:On,onHardRestart:_c})]}),ye?H?null:Zs.createPortal(As,ye):As]})};function $N({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=Ur(),c=Hr(l=>{const d=l.sessions.get(e.id);return xl(e,d?.activeProgram??null,d?.cwd??null,void 0,d?.shellTitle??null,d?.promptState??null).primary});return s.jsxs("div",{"data-pane-titlebar":"true",className:"swiper-no-swiping flex h-6 min-h-6 shrink-0 items-center border-b border-border app-chrome-bg text-foreground",children:[s.jsxs("button",{type:"button","data-split-pane-title":e.id,draggable:!1,onDragStart:l=>l.preventDefault(),"aria-pressed":t,title:`${c} · 拖动标题移动,边缘拆分,中央交换`,onClick:r,className:"split-pane-drag-handle flex h-full min-w-0 cursor-grab active:cursor-grabbing flex-1 items-center gap-1.5 overflow-hidden px-2 text-left text-[12px] font-medium leading-none hover:opacity-80 focus-visible:outline focus-visible:outline-1 focus-visible:outline-current focus-visible:-outline-offset-1",children:[s.jsx(tl,{size:11,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:c}),s.jsx(hg,{size:12,"aria-hidden":"true",className:"shrink-0 opacity-60"})]}),n&&s.jsx("button",{type:"button",onClick:n,"aria-label":a("tab.explorerTitle"),title:a("tab.explorerTitle"),className:"inline-flex h-full w-7 shrink-0 items-center justify-center hover:opacity-80 focus-visible:outline focus-visible:outline-1 focus-visible:outline-current focus-visible:-outline-offset-1",children:s.jsx(x3,{size:14})})]})}const UN="termdock:startup:";function Wu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${UN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function A5(e,t){e||Zs.flushSync(t)}const j1="horizontal";function Ku(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function mf(e,t){if(!Array.isArray(e)||e.length!==t)return Ku(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Ku(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Ku(t):r.map(a=>a/n)}function zN(e){const t=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,e))));return{columns:t,rows:Math.max(1,Math.ceil(Math.max(1,e)/t))}}function HN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function WN(e){if(!Array.isArray(e))return[];const t=new Set,r=new Set,n=[];for(const a of e){if(!a||typeof a!="object")continue;const c=a;if(typeof c.id!="string"||!c.id||r.has(c.id))continue;const l=Array.isArray(c.sessionIds)?c.sessionIds.filter(m=>typeof m=="string"&&!!m&&!t.has(m)):[],d=[...new Set(l)];if(d.length<2)continue;const f=zN(d.length);d.forEach(m=>t.add(m)),r.add(c.id),n.push({id:c.id,...typeof c.name=="string"&&c.name.trim()?{name:c.name.trim().slice(0,80)}:{},sessionIds:d,layout:HN(c.layout)?c.layout:j1,ratios:mf(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:mf(c.gridColumnRatios,f.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:mf(c.gridRowRatios,f.rows)}:{}})}return n}function GN(e,t){const r=new Set(t);return e.flatMap(n=>{const a=n.sessionIds.filter(c=>r.has(c));return a.length<2?[]:[{...n,sessionIds:a,ratios:a.length===n.sessionIds.length?mf(n.ratios,a.length):Ku(a.length)}]})}function B0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function Sm(e,t,r){if(!t||!r||t===r)return e;const n=B0(e,t),a=B0(e,r);if(n&&n.id===a?.id)return e;const c=[...n?.sessionIds??[t],...a?.sessionIds??[r]],l=[...new Set(c)],d={id:n?.id??`split:${t}`,...n?.name?{name:n.name}:{},sessionIds:l,layout:l.length>2&&(!n||n.layout===j1)?"grid":n?.layout??j1,ratios:Ku(l.length)},f=new Set([n?.id,a?.id].filter(Boolean)),m=e.filter(y=>!f.has(y.id)),x=n?Math.max(0,e.findIndex(y=>y.id===n.id)):m.length;return m.splice(Math.min(x,m.length),0,d),m}function VN(e,t){const r=B0(e,t);if(!r||!t)return e;if(r.sessionIds.length<=2)return e.filter(a=>a.id!==r.id);const n=r.sessionIds.filter(a=>a!==t);return e.map(a=>a.id===r.id?{...a,sessionIds:n,ratios:Ku(n.length)}:a)}function qN(e,t){const r=B0(e,t);return r?e.filter(n=>n.id!==r.id):e}function YN(e,t,r){return e.map(n=>{if(n.id!==t)return n;const a=[...new Set(r)],c=new Set(n.sessionIds);return a.length===n.sessionIds.length&&a.every(d=>c.has(d))?{...n,sessionIds:a}:n})}function ZN(e,t,r){const n=r.trim().slice(0,80);return e.map(a=>a.id===t?{...a,...n?{name:n}:{name:void 0}}:a)}const D1=320,Qv=1,KN=D1+120,B1="termdock:split-workspaces:v2",Pv="termdock:split-workspace:v1",XN=.1,JN=.9;function Cm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=Xy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function eR(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(B1);if(e)return WN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(Pv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(JN,Math.max(XN,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[r,1-r]}]}}catch{}return[]}function tR(e,t){const r=new Map(e.map(l=>[l.id,l])),n=new Map;t.forEach(l=>l.sessionIds.forEach(d=>n.set(d,l)));const a=new Set,c=[];for(const l of e){const d=n.get(l.id);if(!d){c.push({key:l.id,sessions:[l]});continue}if(a.has(d.id))continue;a.add(d.id);const f=d.sessionIds.flatMap(m=>{const x=r.get(m);return x?[x]:[]});f.length>=2&&c.push({key:d.id,sessions:f,workspace:d})}return c}function T5(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function Qh(e,t){const r=Ff(e,t);if(r===null)return;const n=e.wrapperEl;T5(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),T5(e),n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}catch{n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}}function Q1(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function Ff(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function rR(e,t){const r=Q1(e),n=Ff(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=Qv}function nR(e){const t=[],r=new Map,n=new Map,a=new Map;for(const c of e){const l=r.get(c.id)??[];if(l.push(c.id),r.set(c.id,l),c.sessionId){const d=n.get(c.sessionId)??[];d.push(c.id),n.set(c.sessionId,d)}if(c.mode==="tmux"&&c.tmuxSessionName){const d=a.get(c.tmuxSessionName)??[];d.push(c.id),a.set(c.tmuxSessionName,d)}}for(const[c,l]of r)l.length>1&&t.push({kind:"frontend",key:c,sessionIds:l});for(const[c,l]of n)l.length>1&&t.push({kind:"backend",key:c,sessionIds:l});for(const[c,l]of a)l.length>1&&t.push({kind:"tmux",key:c,sessionIds:l});return t}function Ov(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function Fv(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function sR(e,t){const r=Ov(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function S5(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...Fv(n),history:a?.history}})}function C5(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function _5(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function k5(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function iR(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t)if(e.get(r)!==n)return!1;return!0}function aR(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const r=Date.now().toString(36),n=Math.random().toString(36).slice(2,8);return`wt-${r}${n}`}const oR=({terminalSettings:e=_g(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:a=!0,terminalReferenceAvailable:c=a,defaultSessionMode:l="shell",defaultTmuxSessionName:d="",connectionPrioritySessionId:f=null,connectionPriorityReady:m=!0,desktopRightSidebarEnabled:x=!1,onToggleRightSidebar:y,desktopFloatingTitle:w=!1,desktopLeftSidebarPinned:v=!1,desktopPinnedLeftSidebarWidth:T=0,desktopViewportWidth:S=0,onStatusChange:I,onSessionDataUpdate:N,onInitialViewportReady:P,onInitialRecoveryRequired:$})=>{const{t:Q}=Ur(),U=w&&!v&&Gi()?.platform==="darwin"&&document.documentElement.dataset.termdockPreview==="true",Z=b.useMemo(()=>Ju("session"),[]),J=b.useMemo(()=>Ju("terminal"),[]),[H,ye]=b.useState([]),[oe,te]=b.useState(null),Ce=b.useRef(0),qe=b.useRef(0),ve=os(R=>R.activePaneId);b.useEffect(()=>{os.getState().setActivePane(oe)},[oe]);const[Y,st]=b.useState(null),[he,Qe]=b.useState(!0),[ie,Pe]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[Fe,ce]=b.useState(()=>new Set),[Ie,je]=b.useState(()=>({token:0,completed:new Set})),[Ze,we]=b.useState(0),[le,Ge]=b.useState(()=>new Set),[He,tt]=b.useState(()=>new Set),xe=b.useRef(new Map),[dt,it]=b.useState(()=>new Set),_e=b.useRef(!1),Ue=b.useRef(null),ke=b.useRef({}),[V,ae]=b.useState(null),[pe,$e]=b.useState(()=>eR()),[Xe,wt]=b.useState(!1),Ut=b.useCallback(R=>{Ce.current+=1,wt(R)},[]),qt=b.useRef(null),Nt=b.useRef(Xe);Nt.current=Xe,vc(qt,Xe&&!!oe,()=>Ut(!1));const[sr,jt]=b.useState(null),[Xt,Rt]=b.useState(null),ir=b.useRef(new Set),[ge,Je]=b.useState(null),[at,Et]=b.useState(null),[X,vt]=b.useState(!1),[Bt,Me]=b.useState(()=>Cm().mobile),[Dr,Le]=b.useState(()=>Cm().landscape),[At,Ot]=b.useState(null),[er,ot]=b.useState(null),Lt=b.useRef(a),nr=b.useRef(!1),ur=b.useRef(!1),Rr=b.useRef(null),Gr=b.useRef(null),Tt=b.useRef(Bt),Ft=b.useRef(null),be=b.useCallback(R=>{R!==Ft.current&&(Ce.current+=1),Ft.current=R,te(R)},[]);b.useEffect(()=>Yt.subscribe((R,F)=>{(R.rightOpen!==F.rightOpen||R.rightTab!==F.rightTab)&&(Ce.current+=1)}),[]);const Ct=b.useRef(0),gt=b.useRef([]),rt=b.useRef(0),cn=b.useRef(null),Kr=b.useRef(!1),wn=b.useRef(!0),Oe=b.useRef(null),ft=b.useRef(""),ht=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const R=()=>{const F=Cm();Tt.current=F.mobile,Me(F.mobile),Le(F.landscape)};return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]);const{sessions:Cr,inventory:Ht,activeSessionId:yr,isLoading:Xr,openSession:Bn,setActiveSession:mn,removeSession:hn,renameSession:gn,resetSessionCustomName:an,reorderSessions:ne,restoreSessions:Ye}=z8(),St=Ht?.tmuxRecovery??null;b.useEffect(()=>{St&&$?.()},[St,$]),b.useEffect(()=>{Et(null),Je(null)},[St?.id]);const Jt=b.useCallback(async()=>{Je("restore"),Et(null);try{const R=await H8(St?.id);await Ye(),R.accepted||Et(Q("tab.tmuxRecoveryFailed"))}catch{Et(Q("tab.tmuxRecoveryFailed"))}finally{Je(null)}},[Ye,Q,St?.id]),Or=b.useCallback(async()=>{const R=St?.operation;if(R)try{await W8(R.id,!R.paused),await Ye()}catch{Et(Q("tab.tmuxRecoveryFailed"))}},[Ye,Q,St?.operation]),un=b.useCallback(async()=>{Je("dismiss"),Et(null);try{await G8(),await Ye()}catch{Et(Q("tab.tmuxRecoveryDismissFailed"))}finally{Je(null)}},[Ye,Q]),Jr=Yt(R=>R.groupByFolder),en=Ef(R=>R.collaborationGroups),mr=Yt(R=>R.leftOpen||R.rightOpen),tn=Yt(R=>R.rightSidebarWidthContextKey),Sn=Yt(R=>R.rightSidebarWidth),Zr=Yt(R=>R.rightPinned),[Qr,lr]=b.useState(()=>k5(Hr.getState().sessions));b.useEffect(()=>Hr.subscribe(R=>{const F=k5(R.sessions);lr(q=>iR(q,F)?q:F)}),[]);const{arranged:fn}=b.useMemo(()=>Lf(H,R=>Qr.get(R.id)??null,Jr,"",pe,en),[H,Qr,Jr,pe,en]),Ss=b.useRef(fn);Ss.current=fn;const Ar=b.useMemo(()=>tR(fn,pe),[fn,pe]),En=b.useRef(Ar);En.current=Ar;const qr=b.useMemo(()=>B0(pe,oe),[oe,pe]),Lr=b.useMemo(()=>{const R=Ar.find(F=>F.sessions.some(q=>q.id===oe));return new Set(R?.sessions.map(F=>F.id)??[])},[oe,Ar]),On=b.useMemo(()=>{const R=new Map;if(!x||S<=0)return R;for(const F of Ar){const q=F.sessions[0];if(!q)continue;const se=V8(q.id,Qr.get(q.id)??null,F.workspace?.id??null);if(!(se===tn?Zr:q8(q.id,Qr.get(q.id)??null,F.workspace?.id??null)))continue;const We=se===tn?Sn:Y8(q.id,Qr.get(q.id)??null,F.workspace?.id??null),mt=rf(We,S,T);R.set(F.key,mt+Jy)}return R},[Qr,T,x,Zr,tn,Sn,S,Ar]),tr=b.useMemo(()=>Am(H.map(R=>({id:R.id,backendSessionId:R.sessionId})),f),[f,H]),K=b.useMemo(()=>C5(Cr,yr),[yr,Cr]),De=Dh({prioritySessionId:tr,activeSessionId:Y??oe,persistedActiveSessionId:K,firstSessionId:H[0]?.id??null}),Mt=b.useMemo(()=>kN(Ar.flatMap(R=>R.sessions.map(F=>F.id)),Lr),[Lr,Ar]),vr=De!==null&&Fe.has(De),Dt=b.useMemo(()=>{const R=new Set(Lr);return Y&&R.add(Y),!R.size&&De&&R.add(De),R},[Lr,Y,De]),Br=Ie.token===ie.token&&TN(Dt,Ie.completed),Pr=Br||Ze===ie.token?ie.token:-1;b.useEffect(()=>{if(!ie.token||Br)return;const R=window.setTimeout(()=>we(ie.token),hN);return()=>window.clearTimeout(R)},[ie.token,Br]);const xn=b.useCallback((R,F)=>{ce(q=>{if(q.has(R)===F)return q;const Ee=new Set(q);return F?Ee.add(R):Ee.delete(R),Ee})},[]),Kn=b.useCallback(R=>{const F=Ct.current;je(se=>{if(se.token===F&&se.completed.has(R))return se;const Ee=new Set(se.token===F?se.completed:[]);return Ee.add(R),{token:F,completed:Ee}});const q=tr??Y??Ft.current;R===q&&Wu("foreground-stream-connected")},[Y,tr]),Cs=b.useCallback((R,F)=>{Ge(q=>{if(q.has(R)===F)return q;const se=new Set(q);return F?se.add(R):se.delete(R),se})},[]),ws=b.useCallback((R,F)=>{tt(q=>{if(q.has(R)===F)return q;const se=new Set(q);return F?se.add(R):se.delete(R),se})},[]);b.useEffect(()=>{for(const[R,F]of xe.current){const q=H.find(se=>se.id===R);if(!q||q.sessionId!==F.backendSessionId){xe.current.delete(R);continue}!Fe.has(R)||!le.has(R)||!He.has(R)||(xe.current.delete(R),Ky(F.backendSessionId,`${F.command}\r`).catch(se=>{console.error("[Session] Failed to send startup command:",se)}))}},[H,Fe,le,He]);const Wr=De!==null&&le.has(De),Qn=De!==null&&He.has(De);b.useEffect(()=>{Wr&&Wu("foreground-viewport-ready")},[Wr]),b.useEffect(()=>{Qn&&Wu("foreground-content-ready")},[Qn]),b.useEffect(()=>{if(!P)return;if(!he&&H.length===0){P();return}if(!Wr||!vr||!Qn)return;const R=[...Lr].every(We=>le.has(We)&&Fe.has(We)&&He.has(We));let F=0,q=0;const se=()=>{F=requestAnimationFrame(()=>{q=requestAnimationFrame(()=>{Wu("initial-viewport-presented"),P()})})};R&&se();const Ee=R?void 0:window.setTimeout(se,8e3);return()=>{cancelAnimationFrame(F),cancelAnimationFrame(q),clearTimeout(Ee)}},[vr,Qn,Wr,he,P,H.length,Lr,le,Fe,He]);const Pn=b.useMemo(()=>Bt?mN({slides:Ar.map(R=>R.sessions.map(F=>F.id)),visibleSessionIds:Lr,foregroundSessionId:De}):dt,[Bt,Ar,Lr,De,dt]);b.useEffect(()=>{if(Bt||Lr.size===0)return;const R=new Set(Lr),F=Ar.findIndex(q=>q.sessions.some(se=>Lr.has(se.id)));for(let q=-2;q<=2;q+=1)q!==0&&Ar[F+q]?.sessions.forEach(se=>R.add(se.id));it(q=>{let se=!1;const Ee=new Set(q);for(const We of R)Ee.has(We)||(Ee.add(We),se=!0);return se?Ee:q})},[Bt,Lr,Ar]);const jr=UC(Pn);b.useEffect(()=>{if(!Y)return;if(!H.some(F=>F.id===Y)){st(null);return}if(!le.has(Y)||!Fe.has(Y)||!He.has(Y))return;const R=window.setTimeout(()=>{st(F=>F===Y?null:F),Lt.current&&!Tt.current&&ae({sessionId:Y,token:Date.now()})},80);return()=>window.clearTimeout(R)},[He,Y,Fe,H,le]),b.useEffect(()=>{typeof window>"u"||(pe.length>0?(window.localStorage.setItem(B1,JSON.stringify(pe)),window.localStorage.removeItem(Pv)):window.localStorage.removeItem(B1))},[pe]),b.useEffect(()=>{Xr||he||pe.length===0||$e(R=>GN(R,H.map(F=>F.id)))},[Xr,he,H,pe.length]),b.useEffect(()=>{if(!sr)return;const R=window.setTimeout(()=>jt(null),3200);return()=>window.clearTimeout(R)},[sr]),Ft.current=oe,Ct.current=ie.token,gt.current=H,cn.current=yr,Kr.current=Xr,wn.current=he,Lt.current=a;const ds=b.useCallback((R=Ue.current)=>{const F=rt.current,q=typeof window<"u"?window.visualViewport:null,se=R?Q1(R):null,Ee=R?Ff(R,F):null;return{sessionsLength:gt.current.length,workspaceSlidesLength:En.current.length,sessionIds:gt.current.map(We=>We.id),activeSessionId:Ft.current,activeSessionIndex:F,persistedActiveId:cn.current,isLoading:Kr.current,isRestoring:wn.current,activeIndex:R?.activeIndex??null,previousIndex:R?.previousIndex??null,animating:R?.animating??null,allowTouchMove:R?.allowTouchMove??null,width:R?.width??null,translate:se,targetTranslate:Ee,translateDelta:se!==null&&Ee!==null?se-Ee:null,snapGridLength:R?.snapGrid?.length??null,targetSnap:R?.snapGrid?.[F]??null,visualViewport:q?{width:Math.round(q.width),height:Math.round(q.height),offsetTop:Math.round(q.offsetTop)}:null}},[]),Tr=b.useCallback((R,F)=>{Z(R,{...ds(),...F})},[Z,ds]);b.useEffect(()=>{Xr||he||oe!==yr&&mn(oe)},[oe,Xr,he,yr,mn]);const bn=b.useMemo(()=>{if(fn.length===0||!oe)return 0;const R=Ar.findIndex(F=>F.sessions.some(q=>q.id===oe));return R>=0?R:0},[Ar,oe]);rt.current=bn;const An=b.useCallback(()=>{Rr.current&&(clearTimeout(Rr.current),Rr.current=null)},[]),rr=b.useCallback(R=>{An(),Rr.current=setTimeout(()=>{Rr.current=null,nr.current=!1,Tr("[swiper:touch-guard-clear]",{reason:R})},KN)},[An,Tr]),kn=b.useCallback((R,F={})=>{const q=Ue.current,se=rt.current,Ee=En.current;if(!q||Ee.length===0||se<0||se>=Ee.length)return;if(nr.current){Tr("[swiper:sync-skip-touch]",{reason:R});return}if(q.animating){Tr("[swiper:sync-skip-animating]",{reason:R});return}const We=Q1(q),mt=Ff(q,se),et=We!==null&&mt!==null&&Math.abs(We-mt)<=Qv,dr=q.activeIndex===se;if(Tr("[swiper:sync-check]",{reason:R,activeIndexAligned:dr,translateAligned:et,immediate:F.immediate===!0}),!(dr&&et)){if(dr){Qh(q,se),Tr("[swiper:sync-forced-active]",{reason:R,translateAligned:et,immediate:F.immediate===!0});return}F.immediate?(Qh(q,se),q.slideTo(se,0,!1),Qh(q,se)):q.slideTo(se,D1,!1),Tr("[swiper:sync-applied]",{reason:R,activeIndexAligned:dr,translateAligned:et,immediate:F.immediate===!0})}},[Tr]);b.useEffect(()=>{const R=F=>{const q=F;Ue.current&&(Ue.current.allowTouchMove=!q.detail.locked),Tr("[swiper:gesture-lock]",{locked:q.detail.locked})};return document.addEventListener("termdock:gesture-lock",R),()=>document.removeEventListener("termdock:gesture-lock",R)},[Tr]),b.useEffect(()=>{if(H.length===0){oe!==null&&be(null);return}if(!oe){if(!m)return;be(Dh({prioritySessionId:tr,activeSessionId:null,persistedActiveSessionId:K,firstSessionId:H[0]?.id??null}));return}H.some(F=>F.id===oe)||be(H[0].id)},[H,oe,m,tr,K]);const Cn=b.useCallback((R,F)=>{if(F&&Date.now()<ht.current){ke.current[R]=!1;return}ke.current[R]=F,ot(q=>F?R:q===R?null:q)},[]),wr=b.useCallback(R=>{if(!nr.current&&R.activeIndex!==rt.current){Tr("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:R.activeIndex,expectedActiveIndex:rt.current}),requestAnimationFrame(()=>kn("ignored-layout-slide-change",{immediate:!0}));return}const F=En.current[R.activeIndex],q=F?.sessions.some(We=>We.id===oe)?oe:F?.sessions[0]?.id;if(Tr("[swiper:slide-change]",{nextSessionId:q??null,instanceActiveIndex:R.activeIndex}),!q||q===oe)return;const se=!!oe&&ke.current[oe]===!0,Ee=Lt.current&&(!Tt.current||se);if(Gr.current=q,be(q),Ee){ae({sessionId:q,token:Date.now()});return}ae(null)},[H,oe,Tr,kn]);b.useLayoutEffect(()=>{if(Gr.current===oe){Tr("[swiper:sync-skip-swiper-driven]",{activeSessionId:oe}),Gr.current=null;return}kn("active-session-index",{immediate:!0})},[oe,bn,H.length,kn,Tr]),b.useEffect(()=>{const R=Ue.current;if(!R)return;const F=Ar.length>1&&!mr&&!Xe;R.allowTouchMove!==F&&(R.allowTouchMove=F,Tr("[swiper:allow-touch-sync]",{nextAllow:F,sidebarOverlayOpen:mr}))},[Ar.length,Tr,mr,Xe]);const ps=b.useCallback(R=>{const F=Ue.current;if(!F)return;const q=F.el;if(Tr("[swiper:layout-before]",{reason:R,scrollLeft:q?.scrollLeft??null}),q&&(q.scrollLeft=0),F.updateSize(),F.updateSlides(),F.updateProgress(),F.updateSlidesClasses(),q&&(q.scrollLeft=0),Tr("[swiper:layout-after]",{reason:R,scrollLeft:q?.scrollLeft??null}),nr.current||F.animating){Tr("[swiper:layout-skip-sync-motion]",{reason:R});return}kn(`layout:${R}`,{immediate:!0}),requestAnimationFrame(()=>{const se=Ue.current;se&&(nr.current||se.animating||Qh(se,rt.current))})},[Tr,kn]);b.useEffect(()=>()=>An(),[An]);const Ks=Ar.map(R=>R.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>ps("group-change"))},[Jr,Ks,ps]),b.useEffect(()=>{let R=null,F="mount";const q=et=>{F=et,R===null&&(R=requestAnimationFrame(()=>{R=null,ps(`viewport-change:${F}`)}))},se=()=>q("window-resize"),Ee=()=>q("visual-viewport-resize"),We=()=>q("visual-viewport-scroll"),mt=et=>{q(`measured:${et.detail?.source??"unknown"}`)};return window.addEventListener("resize",se),window.visualViewport?.addEventListener("resize",Ee),window.visualViewport?.addEventListener("scroll",We),document.addEventListener(jx,mt),q("mount"),()=>{window.removeEventListener("resize",se),window.visualViewport?.removeEventListener("resize",Ee),window.visualViewport?.removeEventListener("scroll",We),document.removeEventListener(jx,mt),R!==null&&cancelAnimationFrame(R)}},[ps]),b.useEffect(()=>{if(typeof document>"u")return;let R=null,F=null;const q=dr=>{if(dr!=="online"&&document.hidden)return;const Wn=performance.now();if(!SN(F,Wn))return;F=Wn;const Gt=dr==="bfcache"||dr==="online"?dr:"visibility",zr=CN();Up(),Ba("info","PWA_RESUME scheduled",{source:dr,forceForegroundReconnect:zr,activeSessionId:Ft.current}),Pe(_r=>({token:_r.token+1,reason:Gt,forceForegroundReconnect:zr})),requestAnimationFrame(()=>ps(`resume:${dr}:raf`)),R&&clearTimeout(R),R=setTimeout(()=>{R=null,ps(`resume:${dr}:settled`)},320)},se=()=>{if(document.hidden){Up();return}q("visibility")},Ee=()=>{Up()},We=dr=>{q(dr.persisted?"bfcache":"pageshow")},mt=()=>q("online"),et=()=>q("focus");return document.addEventListener("visibilitychange",se),window.addEventListener("pagehide",Ee),window.addEventListener("pageshow",We),window.addEventListener("online",mt),window.addEventListener("focus",et),()=>{document.removeEventListener("visibilitychange",se),window.removeEventListener("pagehide",Ee),window.removeEventListener("pageshow",We),window.removeEventListener("online",mt),window.removeEventListener("focus",et),R&&clearTimeout(R)}},[ps]),b.useLayoutEffect(()=>{if(!wN(he))return;const R=nR(H),F=JSON.stringify(R);R.length>0&&F!==ft.current?(ft.current=F,console.warn("[session-invariant] duplicate mapping detected",R)):R.length===0&&ft.current&&(ft.current=""),N?.({sessions:H.map(q=>({id:q.id,name:q.name,customName:q.customName,mode:q.mode,tmuxSessionName:q.tmuxSessionName})),activeSessionId:oe,splitWorkspaces:pe.map(({id:q,name:se,sessionIds:Ee,layout:We})=>({id:q,...se?{name:se}:{},sessionIds:Ee,layout:We}))})},[H,oe,pe,N,he]),b.useEffect(()=>{if(Xr||_e.current)return;_e.current=!0;const R=Am(Cr.map(We=>({id:We.sessionId,backendSessionId:We.backendSessionId??null})),f),F=C5(Cr,yr),q=Dh({prioritySessionId:m?R:null,activeSessionId:null,persistedActiveSessionId:F,firstSessionId:Cr[0]?.sessionId??null}),se=Ov(Cr.map(Fv));if(Z("[Session] Restoring",se.length,"persisted sessions (one-shot)"),Tr("[swiper:restore-start]",{persistedSessionIds:Cr.map(We=>We.sessionId),nextActiveSessionId:q}),se.length>0){const We=Hr.getState();se.forEach(et=>{et.sessionId&&We.setTerminalSession(et.id,{sessionId:et.sessionId,cols:80,rows:24,mode:et.mode,tmuxSessionName:et.tmuxSessionName,history:et.history})}),Cr.forEach(et=>{et.agent!==void 0&&We.setSessionAgentIdentity(et.sessionId,et.agent),et.activeProgram!=null&&We.setSessionActiveProgram(et.sessionId,et.activeProgram),et.cwd!=null&&We.setSessionCwd(et.sessionId,et.cwd),et.shellTitle!=null&&We.setSessionShellTitle(et.sessionId,et.shellTitle)}),ye(se);const mt=q||se[0]?.id||null;be(mt),Tr("[swiper:restore-complete]",{restoredSessionIds:se.map(et=>et.id),nextActiveSessionId:mt})}(async()=>(se.length===0&&await Oe.current?.({createIfEmpty:!0}),Qe(!1),requestAnimationFrame(()=>kn("restore-finished",{immediate:!0}))))()},[Xr,Cr,yr,Z,Tr,kn,m,f]),b.useEffect(()=>{if(!m||he||H.length===0)return;const R=Am(H.map(q=>({id:q.id,backendSessionId:q.sessionId})),f),F=Dh({prioritySessionId:R,activeSessionId:Ft.current,persistedActiveSessionId:K,firstSessionId:H[0]?.id??null});F&&F!==Ft.current&&be(F)},[m,f,he,K,H]);const rs=b.useRef([]),on=b.useRef(!1);Ft.current=oe,b.useEffect(()=>{if(he)return;const R=rs.current,F=Cr,q=new Map(R.map(Gt=>[Gt.sessionId,Gt])),se=Hr.getState();for(const Gt of F){const zr=q.get(Gt.sessionId),_r=Hr.getState().sessions.get(Gt.sessionId);Gt.agent!==void 0&&JSON.stringify(Gt.agent)!==JSON.stringify(_r?.agent)&&(_r?.agent==null||JSON.stringify(Gt.agent)!==JSON.stringify(zr?.agent))&&se.setSessionAgentIdentity(Gt.sessionId,Gt.agent),Gt.activeProgram!=null&&Gt.activeProgram!==_r?.activeProgram&&(_r?.activeProgram==null||Gt.activeProgram!==zr?.activeProgram)&&se.setSessionActiveProgram(Gt.sessionId,Gt.activeProgram),Gt.cwd!=null&&Gt.cwd!==_r?.cwd&&(_r?.cwd==null||Gt.cwd!==zr?.cwd)&&se.setSessionCwd(Gt.sessionId,Gt.cwd),Gt.shellTitle!=null&&Gt.shellTitle!==_r?.shellTitle&&(_r?.shellTitle==null||Gt.shellTitle!==zr?.shellTitle)&&se.setSessionShellTitle(Gt.sessionId,Gt.shellTitle)}if(!on.current){ye(Gt=>S5(Gt,F)),rs.current=F,on.current=!0;return}const Ee=new Set(R.map(Gt=>Gt.sessionId)),We=new Set(F.map(Gt=>Gt.sessionId)),mt=new Map(R.map(Gt=>[Gt.sessionId,Gt.name]));rs.current=F,ye(Gt=>{const zr=S5(Gt,F);return(!Ft.current||!zr.some(_r=>_r.id===Ft.current))&&be(zr[0]?.id??null),zr});const et=F.filter(Gt=>!Ee.has(Gt.sessionId)),dr=[...Ee].filter(Gt=>!We.has(Gt)),Wn=F.filter(Gt=>Ee.has(Gt.sessionId)&&mt.get(Gt.sessionId)!==Gt.name);(et.length>0||dr.length>0||Wn.length>0)&&Z("[Session] Synced persisted sessions:",{newSessionIds:et.map(Gt=>Gt.sessionId),removedSessionIds:dr,renamedSessionIds:Wn.map(Gt=>Gt.sessionId),currentSessionIds:F.map(Gt=>Gt.sessionId)});for(const Gt of F){if(!Gt.backendSessionId)continue;Hr.getState().setTerminalSession(Gt.sessionId,{sessionId:Gt.backendSessionId,cols:80,rows:24,mode:Gt.mode,tmuxSessionName:Gt.tmuxSessionName})}},[Cr,he,Z]);const Hn=b.useCallback(async R=>{const F=++qe.current,q=Ce.current,se=()=>F===qe.current&&q===Ce.current&&(R?.shouldActivate?.()??!0);try{const Ee=Yt.getState(),We=oe?{rightOpen:Ee.rightOpen,rightPinned:Ee.rightPinned,rightSidebarWidth:Ee.rightSidebarWidth,rightTab:Ee.rightTab}:null,mt=R?.mode==="tmux"||R?.mode==="shell"?R.mode:l,et=(R?.tmuxSessionName||"").trim(),dr=d.trim(),Wn=mt==="tmux"?et||dr||aR():null,Gt=typeof R?.cwd=="string"?R.cwd:null,zr=oe?Hr.getState().sessions.get(oe)?.cwd??null:null,_r=typeof Gt=="string"&&Gt.trim().length>0?Gt:typeof zr=="string"&&zr.trim().length>0?zr:void 0,Xn=await Bn({preferredFrontendSessionId:R?.preferredFrontendSessionId,requireExisting:R?.requireExisting===!0,mode:mt,tmuxSessionName:Wn,cwd:_r,termType:"xterm-256color",createIfEmpty:R?.createIfEmpty===!0},{shouldActivate:se});if(Xn.discarded)return R?.onResult?.({ok:!1,error:"unknown"}),null;const ms=Xn.session,dn=Xn.terminalSession;!Xn.reused&&We&&Yt.getState().initializeRightSidebarForSession(ms.sessionId,dn.cwd??_r??null,We);const pr={id:ms.sessionId,name:ms.name,customName:ms.customName===!0,sessionId:dn.sessionId,mode:dn.mode??ms.mode,tmuxSessionName:dn.tmuxSessionName??ms.tmuxSessionName},ar=R?.command?.trim();return ar&&xe.current.set(pr.id,{backendSessionId:dn.sessionId,command:ar}),ye(ls=>sR(ls,pr)),se()&&be(pr.id),Hr.getState().setTerminalSession(pr.id,{sessionId:dn.sessionId,cols:80,rows:24,mode:pr.mode,tmuxSessionName:pr.tmuxSessionName,activeProgram:dn.activeProgram,activeProgramRaw:dn.activeProgramRaw,activeProgramSource:dn.activeProgramSource,cwd:dn.cwd}),Z("[Session] Inventory opened session:",{frontendSessionId:pr.id,backendSessionId:dn.sessionId,reused:Xn.reused,mode:pr.mode,tmuxSessionName:pr.tmuxSessionName}),R?.onResult?.({ok:!0,sessionId:pr.id}),pr.id}catch(Ee){return console.error("[Session] Failed to create new session:",Ee),R?.onResult?.({ok:!1,error:IC(Ee)}),null}},[l,d,oe,Bn,Z]);Oe.current=Hn;const Fr=b.useCallback((R,F={})=>{Ce.current+=1,os.getState().setActivePane(R);const q=Ft.current,se=!!q&&ke.current[q]===!0;if(be(R),Tt.current&&F.preserveMobileKeyboard===!1){ht.current=Date.now()+600,q&&(ke.current[q]=!1),ot(null),ae(null);const Ee=document.activeElement;Ee instanceof HTMLTextAreaElement&&Ee.closest(".terminal-viewport-container")&&Ee.blur();return}se&&Tt.current&&ot(R),Lt.current&&(!Tt.current||se)&&ae({sessionId:R,token:Date.now()})},[]),$r=b.useCallback(R=>{be(R),Ut(!0),jt(null)},[]),pn=b.useCallback(R=>{const F=Ft.current;!F||F===R||($e(q=>Sm(q,F,R)),Ut(!1),Fr(F,{preserveMobileKeyboard:!1}))},[Fr]),W=b.useCallback(async()=>{const R=Ft.current;if(!R||X)return;const F=Ce.current;vt(!0);const q=Hr.getState().sessions.get(R)?.cwd??void 0,se=await Hn({cwd:q||void 0,mode:l,shouldActivate:()=>!1});if(vt(!1),!se){jt(Q("common.error"));return}!Nt.current||F!==Ce.current||!gt.current.some(Ee=>Ee.id===R)||($e(Ee=>Sm(Ee,R,se)),Ut(!1),Fr(R,{preserveMobileKeyboard:!1}))},[Fr,l,Hn,X,Q]),Re=b.useCallback(R=>{$e(F=>qN(F,R)),R&&Fr(R,{preserveMobileKeyboard:!1})},[Fr]),Ke=b.useCallback(R=>{$e(F=>VN(F,R)),Fr(R,{preserveMobileKeyboard:!1})},[Fr]),lt=b.useCallback(R=>{if(H.find(q=>q.id===R)){if(Ce.current+=1,os.getState().setActivePane(R),R===Ft.current)return;if(be(R),!bN({isMobile:Tt.current,viewportReady:le.has(R),streamReady:Fe.has(R),contentReady:He.has(R)})){st(null),Lt.current&&ae({sessionId:R,token:Date.now()}),Z("[Session] Switched to session:",R);return}it(se=>{if(se.has(R))return se;const Ee=new Set(se);return Ee.add(R),Ee}),st(R),Z("[Session] Switched to session:",R)}},[He,Z,Fe,H,le]),ut=b.useCallback((R,F)=>{F.trim()&&(ye(q=>q.map(se=>se.id===R?{...se,name:F.trim(),customName:!0}:se)),gn(R,F.trim()))},[gn]),It=b.useCallback(R=>{ye(F=>F.map(q=>q.id===R?{...q,customName:!1}:q)),an(R)},[an]),_t=b.useCallback(R=>{ye(F=>{const q=new Map(F.map(mt=>[mt.id,mt])),se=R.map(mt=>q.get(mt)).filter(mt=>mt!==void 0),Ee=new Set(R),We=F.filter(mt=>!Ee.has(mt.id));return[...se,...We]}),ne(R),Z("[Session] Reordered sessions:",R),requestAnimationFrame(()=>{Ue.current?.update()})},[ne,Z]),Qt=b.useCallback(async R=>{const F=typeof R=="string"?R:R.sessionId,q=typeof R=="string"?"auto":R.closeMode??"auto",se=H.find(et=>et.id===F);if(!se||ir.current.has(F))return;ir.current.add(F),Ce.current+=1;const Ee=Dx(fn,F,et=>et.id);try{q==="destroy"&&se.mode==="tmux"&&se.tmuxSessionName?(await e3(se.tmuxSessionName),Z("[Session] Destroyed tmux session:",{frontendSessionId:se.id,tmuxSessionName:se.tmuxSessionName})):se.sessionId&&(await Zy(se.sessionId),Z("[Session] Closed backend terminal:",se.sessionId))}catch(et){console.error("[Session] Failed to close backend terminal:",et),Rt({sessionId:F,closeMode:q});return}finally{ir.current.delete(F)}Rt(et=>et?.sessionId===F?null:et);const mt=gt.current.filter(et=>et.id!==F).some(et=>et.id===Ee)?Ee:Dx(gt.current,F,et=>et.id);Ft.current===F&&be(mt),ye(et=>et.filter(dr=>dr.id!==F)),hn(F,mt),delete ke.current[F],Z("[Session] Closed session:",{sessionId:F,closeMode:q})},[H,fn,hn,Z]),xt=b.useCallback(R=>{if(!R)return;const F=H.filter(q=>q.sessionId===R);if(F.length!==0){F.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:R,frontendSessionIds:F.map(q=>q.id)}),ye(q=>{const se=q.filter(Ee=>Ee.sessionId!==R);return se.length!==q.length&&!se.some(We=>We.id===oe)&&be(se.length>0?se[0].id:null),se});for(const q of F)hn(q.id),delete ke.current[q.id];Z("[Session] Backend gone, dropped local session(s):",F.map(q=>q.id))}},[H,oe,hn,Z]);b.useEffect(()=>{const R=pr=>{Hn(pr.detail)},F=pr=>{lt(pr.detail)},q=()=>{const pr=Ft.current;!pr||Tt.current||ae({sessionId:pr,token:Date.now()})},se=pr=>{const ar=pr;ar.detail&&$r(ar.detail)},Ee=pr=>{const ar=pr.detail;Re(ar??Ft.current??void 0)},We=pr=>{const ar=pr.detail;ar&&Ke(ar)},mt=pr=>{const ar=pr.detail,Fn=typeof ar=="string"?ar:ar?.layout,ls=typeof ar=="string"?Ft.current:ar?.sessionId;Fn!=="horizontal"&&Fn!=="vertical"&&Fn!=="grid"||$e(ya=>ya.map(Jn=>Jn.sessionIds.includes(ls??"")?{...Jn,layout:Fn}:Jn))},et=pr=>{const Fn=pr.detail?.direction;if(Fn!=="prev"&&Fn!=="next")return;const ls=Ss.current;if(ls.length<=1)return;const ya=Ft.current,Jn=ya?ls.findIndex(Tl=>Tl.id===ya):-1,Pa=((Jn>=0?Jn:0)+(Fn==="next"?1:-1)+ls.length)%ls.length,li=ls[Pa]?.id;li&&li!==ya&&lt(li)},dr=pr=>{Qt(pr.detail)},Wn=pr=>{xt(pr.detail)},Gt=pr=>{const ar=pr;!ar.detail?.sessionId||!ar.detail?.name||ut(ar.detail.sessionId,ar.detail.name)},zr=pr=>{const ar=pr;ar.detail?.sessionId&&It(ar.detail.sessionId)},_r=pr=>{const ar=pr;ar.detail?.sessionIds&&_t(ar.detail.sessionIds)},Xn=pr=>{const ar=pr.detail;!ar?.workspaceId||!Array.isArray(ar.sessionIds)||$e(Fn=>YN(Fn,ar.workspaceId,ar.sessionIds))},ms=pr=>{const ar=pr.detail;!ar?.workspaceId||typeof ar.name!="string"||$e(Fn=>ZN(Fn,ar.workspaceId,ar.name))},dn=pr=>{const ar=pr.detail;!ar?.primaryId||!ar.secondaryId||ar.primaryId===ar.secondaryId||($e(Fn=>Sm(Fn,ar.primaryId,ar.secondaryId)),Fr(ar.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",R),window.addEventListener("switch-terminal-session",F),window.addEventListener("focus-active-terminal-session",q),window.addEventListener("open-terminal-split-chooser",se),window.addEventListener("close-terminal-split",Ee),window.addEventListener("remove-terminal-split-pane",We),window.addEventListener("set-terminal-split-direction",mt),window.addEventListener("cycle-terminal-session",et),window.addEventListener("close-terminal-session",dr),window.addEventListener("close-terminal-session-by-backend",Wn),window.addEventListener("rename-terminal-session",Gt),window.addEventListener("reset-terminal-session-name",zr),window.addEventListener("reorder-terminal-session",_r),window.addEventListener("reorder-terminal-split-workspace",Xn),window.addEventListener("rename-terminal-split-workspace",ms),window.addEventListener("combine-terminal-split-sessions",dn),()=>{window.removeEventListener("new-terminal-session",R),window.removeEventListener("switch-terminal-session",F),window.removeEventListener("focus-active-terminal-session",q),window.removeEventListener("open-terminal-split-chooser",se),window.removeEventListener("close-terminal-split",Ee),window.removeEventListener("remove-terminal-split-pane",We),window.removeEventListener("set-terminal-split-direction",mt),window.removeEventListener("cycle-terminal-session",et),window.removeEventListener("close-terminal-session",dr),window.removeEventListener("close-terminal-session-by-backend",Wn),window.removeEventListener("rename-terminal-session",Gt),window.removeEventListener("reset-terminal-session-name",zr),window.removeEventListener("reorder-terminal-session",_r),window.removeEventListener("reorder-terminal-split-workspace",Xn),window.removeEventListener("rename-terminal-split-workspace",ms),window.removeEventListener("combine-terminal-split-sessions",dn)}},[Fr,Hn,lt,$r,Re,Ke,Qt,xt,ut,It,_t]),b.useEffect(()=>{if(!qr||Bt)return;const R=F=>{if(!zC(F,og())||!(F.ctrlKey||F.metaKey)||!F.shiftKey)return;if(qr.layout==="horizontal"?F.key==="ArrowLeft"||F.key==="ArrowRight":qr.layout==="vertical"?F.key==="ArrowUp"||F.key==="ArrowDown":F.key.startsWith("Arrow")){F.preventDefault(),F.stopPropagation();const se=qr.sessionIds.indexOf(Ft.current??""),Ee=F.key==="ArrowLeft"||F.key==="ArrowUp"?-1:1,We=(Math.max(0,se)+Ee+qr.sessionIds.length)%qr.sessionIds.length,mt=qr.sessionIds[We];if(!mt)return;Fr(mt);return}F.key==="Backspace"&&(F.preventDefault(),F.stopPropagation(),Re(Ft.current??void 0))};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[Fr,qr,Re,Bt]);const Pt=R=>{const F=Hr.getState().sessions.get(R.id);return xl(R,F?.activeProgram??null,F?.cwd??null,void 0,F?.shellTitle??null,F?.promptState??null)},z=(R,F={})=>{const q=R.id===oe&&!ve?.startsWith("@collaboration:"),se=Lr.has(R.id)&&!F.hidden,Ee=m&&xN({sessionId:R.id,foregroundSessionId:De,visibleSessionIds:Lr,deferredViewportSessionIds:Bt?jr:Pn}),We=gN({sessionId:R.id,foregroundSessionId:De,foregroundReady:vr,isVisible:se})&&m,mt=AN({sessionId:R.id,foregroundSessionId:De,requestToken:ie.token,foregroundCompletedToken:Pr,isVisible:Dt.has(R.id)})&&m,et=se||R.id===De||Pn.has(R.id)?0:Mt.get(R.id)??ff;return s.jsxs("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${F.hidden?"invisible pointer-events-none":""}`,style:F.containerStyle,"aria-hidden":F.hidden||void 0,onPointerDownCapture:()=>{se&&A5(q,()=>Fr(R.id))},onWheelCapture:()=>{A5(q,()=>Fr(R.id))},children:[F.showPaneTitle&&s.jsx($N,{session:R,active:q,onActivate:()=>Fr(R.id),onToggleRightSidebar:q?y:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:Ee&&s.jsx(FN,{sessionId:R.id,mode:R.mode,tmuxSessionName:R.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:q,focusSuspended:!a||Y!==null,allowOwnedPasteWhileFocusSuspended:c&&Y===null,deferCursorUntilPositioned:Y===R.id||R.mode==="tmux"&&!He.has(R.id),isLayoutVisible:se,initialConnectEnabled:We&&mt,resumeRequestEnabled:mt,suppressKeyboard:F.suppressKeyboard,keyboardPortalTarget:F.keyboardPortalTarget,sharedMobileKeyboardLayout:F.sharedMobileKeyboardLayout,suppressPageFlipRefresh:F.suppressPageFlipRefresh,focusRequestToken:V?.sessionId===R.id?V.token:0,resumeRequestToken:ie.token,resumeRequestReason:ie.reason,forceResumeReconnect:ie.forceForegroundReconnect&&Dt.has(R.id),resumeRequestDelayMs:Dt.has(R.id)?0:F.hidden?ff:Mt.get(R.id)??ff,initialConnectDelayMs:et,onStreamReadyChange:xn,onStreamConnected:Kn,onViewportReadyChange:Cs,onContentReadyChange:ws,onKeyboardVisibilityChange:Cn,showDebug:n,onStatusChange:q?I:void 0})})]},R.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[Xt&&H.some(R=>R.id===Xt.sessionId)&&s.jsxs("div",{role:"alert",className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto flex max-w-lg items-center gap-3 rounded-xl border border-destructive/30 bg-surface-elevated px-4 py-3 text-[12px] text-foreground shadow-lg",children:[s.jsx("span",{className:"min-w-0 flex-1",children:Q("tab.closeFailed",{name:H.find(R=>R.id===Xt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{Qt(Xt)},children:Q("common.retry")}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg p-1 hover:bg-surface-2","aria-label":Q("common.close"),onClick:()=>Rt(null),children:s.jsx(jn,{size:16})})]}),St&&s.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:s.jsx(cg,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:Q("tab.tmuxRecoveryTitle",{count:St.sessions.length})}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:Q("tab.tmuxRecoveryHint")}),s.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:St.sessions.map(R=>R.name).join(" · ")}),St.operation&&s.jsxs("div",{className:"mt-2 rounded-lg bg-surface-2 px-2.5 py-2 text-[10px] text-muted-foreground","aria-live":"polite",children:[s.jsx("p",{children:Q("tab.tmuxRecoveryProgress",{total:St.operation.total,queued:St.operation.queued,paused:St.operation.paused_count,resourceWait:St.operation.resource_wait,running:St.operation.running,succeeded:St.operation.succeeded,failed:St.operation.failed})}),St.operation.pauseReason==="resources"&&s.jsx("p",{className:"mt-1",children:Q("tab.tmuxRecoveryPausedForResources")}),s.jsx("div",{className:"mt-1 max-h-24 overflow-y-auto",children:St.operation.items.map(R=>s.jsxs("p",{className:`mt-1 ${R.errorCode?"text-destructive":""}`,children:[R.sessionId,": ",R.errorCode??R.resourceWaitReason??R.phase,R.memAvailableBytes!==void 0?` · 可用内存 ${(R.memAvailableBytes/1024**3).toFixed(1)} GiB`:"",R.actualRssBytes!==void 0?` · 实际 RSS ${(R.actualRssBytes/1024**2).toFixed(0)} MiB`:"",R.estimatedRssBytes!==void 0&&R.actualRssBytes===void 0?` · 预估 RSS ${(R.estimatedRssBytes/1024**2).toFixed(0)} MiB`:""]},R.sessionId))})]}),at&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:at}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:ge!==null||!!(St.operation&&!["succeeded","partial_failure"].includes(St.operation.state)),onClick:()=>{Jt()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[s.jsx(b3,{size:13,className:ge==="restore"?"animate-spin":""}),ge==="restore"?Q("tab.tmuxRecoveryRestoring"):St.operation&&!["succeeded","partial_failure"].includes(St.operation.state)?Q("tab.tmuxRecoveryInProgress"):Q("tab.tmuxRecoveryRestoreAll")]}),St.operation&&["queued","resource_wait","running","paused"].includes(St.operation.state)&&s.jsx("button",{type:"button",disabled:ge!==null,onClick:()=>{Or()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 disabled:opacity-50",children:St.operation.paused?Q("tab.tmuxRecoveryResume"):Q("tab.tmuxRecoveryPause")}),s.jsx("button",{type:"button",disabled:ge!==null||!!(St.operation&&!MC(St.operation)),onClick:()=>{un()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:Q("tab.tmuxRecoveryDismiss")})]})]})]})}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(jA,{onSwiper:R=>{Ue.current=R,R.allowTouchMove=Ar.length>1&&!mr&&!Xe,Tr("[swiper:on-swiper]",{allowTouchMove:R.allowTouchMove}),requestAnimationFrame(()=>ps("on-swiper"))},onSlideChange:wr,onTouchStart:(R,F)=>{const q=_5(F),se=q==="touch"||q==="pen"||q==="unknown";J("[swipe:touch-start]",{pointerType:q,allowed:se}),Tr("[swiper:touch-start]",{pointerType:q,allowed:se}),se&&(An(),ur.current=!0,nr.current=!0)},onTouchEnd:(R,F)=>{const q=_5(F),se=q==="touch"||q==="pen"||q==="unknown";J("[swipe:touch-end]",{pointerType:q,allowed:se}),Tr("[swiper:touch-end]",{pointerType:q,allowed:se}),se&&(ur.current=!1,rr("touch-end"))},onTransitionEnd:()=>{const R=Ue.current;if(ur.current){Tr("[swiper:transition-end-during-touch]");return}if(nr.current&&R&&!rR(R,rt.current)){Tr("[swiper:transition-end-deferred]");return}An(),nr.current=!1,Tr("[swiper:transition-end]")},initialSlide:Math.max(0,bn),speed:D1,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"terminal-session-swiper h-full",children:Ar.map(R=>{const F=R.workspace,q=!!F&&R.sessions.length>=2,se=Bt?Dr?"horizontal":"vertical":F?.layout??"horizontal",Ee=Bt&&er?R.sessions.some(mt=>mt.id===er):!1,We=R.sessions.some(mt=>mt.id===oe)?oe:R.sessions[0]?.id;return s.jsx(DA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":On.get(R.key)??0,style:{paddingRight:On.get(R.key)??0,paddingTop:w&&!q?"2.5rem":void 0},children:q?s.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:Bt?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[U&&!Bt&&s.jsx("header",{"data-termdock-window-header":"true","data-split-window-header":"true",className:"flex h-[46px] min-h-[46px] shrink-0 items-center app-chrome-bg pl-[88px] pr-3 text-[12px] text-muted-foreground",children:s.jsx("span",{className:"min-w-0 truncate",children:F?.name||Q("tab.splitWorkspace")})}),s.jsx(Yx,{layoutId:R.key,preset:F?.layout??"horizontal",initialTree:BC(R.sessions.map(mt=>mt.id),se,F?.ratios,F?.gridColumnRatios,F?.gridRowRatios),mobile:Bt,focusId:Ee?er:null,panes:R.sessions.map(mt=>({id:mt.id,content:z(mt,{showPaneTitle:!Bt,suppressKeyboard:Bt&&mt.id!==We,keyboardPortalTarget:Bt?At:null,sharedMobileKeyboardLayout:Bt,suppressPageFlipRefresh:!0})}))}),Bt&&s.jsx("div",{ref:Ot,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(Yx,{layoutId:R.key,preset:F?.layout??"horizontal",mobile:Bt,panes:[{id:R.sessions[0].id,content:z(R.sessions[0])}]})})},R.key)})})}),Xe&&oe&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>Ut(!1),"aria-label":Q("common.close")}),s.jsxs("section",{ref:qt,tabIndex:-1,className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":Q("tab.splitTitle"),children:[s.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[s.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx($l,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:Q("tab.splitTitle")}),s.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:Q("tab.splitExistingHint")})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>Ut(!1),"aria-label":Q("common.close"),children:s.jsx(jn,{size:16})})]}),s.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[s.jsxs("button",{type:"button",disabled:X,onClick:()=>{W()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[s.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(Ys,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:Q("tab.splitNew")}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:Q("tab.splitNewHint")})]})]}),pe.filter(R=>R.id!==qr?.id).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:Q("tab.splitExistingGroups")}),pe.filter(R=>R.id!==qr?.id).map((R,F)=>{const q=R.sessionIds.flatMap(We=>{const mt=H.find(et=>et.id===We);return mt?[mt]:[]});if(q.length<2)return null;const se=R.name||`${Q("tab.splitWorkspace")} ${F+1}`,Ee=q.map(We=>Pt(We).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>pn(q[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:s.jsx($l,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:se}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:Q("tab.splitOccupied")})]}),s.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[Q("tab.sessionCount",{count:q.length})," · ",Ee]})]}),s.jsx(oi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]}),s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:Q("tab.splitAvailableSessions")}),H.filter(R=>!pe.some(F=>F.sessionIds.includes(R.id))&&R.id!==oe).length===0&&pe.filter(R=>R.id!==qr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:Q("tab.splitNoOtherSessions")}):H.filter(R=>!pe.some(F=>F.sessionIds.includes(R.id))&&R.id!==oe).map(R=>{const F=Qr.get(R.id)??null,q=Pt(R);return s.jsxs("button",{type:"button",onClick:()=>pn(R.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:F?s.jsx(nu,{size:15}):s.jsx($l,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:q.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:F?ld(F)??F:R.name})]}),s.jsx(oi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]})]})]}),sr&&s.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:sr})]})},lR={sm:"h-4 w-7",md:"h-6 w-10"},cR={sm:"h-3 w-3",md:"h-5 w-5"},uR={sm:"translate-x-3",md:"translate-x-4"};function vl({checked:e,disabled:t=!1,size:r="md",className:n=""}){return s.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${lR[r]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${n}`,children:s.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${cR[r]} ${e?uR[r]:""}`})})}function ga(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var dR=typeof Symbol=="function"&&Symbol.observable||"@@observable",L5=dR,I5=()=>Math.random().toString(36).substring(7).split("").join("."),hR={INIT:`@@redux/INIT${I5()}`,REPLACE:`@@redux/REPLACE${I5()}`},E5=hR;function fR(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function $v(e,t,r){if(typeof e!="function")throw new Error(ga(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(ga(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(ga(1));return r($v)(e,t)}let n=e,a=t,c=new Map,l=c,d=0,f=!1;function m(){l===c&&(l=new Map,c.forEach((I,N)=>{l.set(N,I)}))}function x(){if(f)throw new Error(ga(3));return a}function y(I){if(typeof I!="function")throw new Error(ga(4));if(f)throw new Error(ga(5));let N=!0;m();const P=d++;return l.set(P,I),function(){if(N){if(f)throw new Error(ga(6));N=!1,m(),l.delete(P),c=null}}}function w(I){if(!fR(I))throw new Error(ga(7));if(typeof I.type>"u")throw new Error(ga(8));if(typeof I.type!="string")throw new Error(ga(17));if(f)throw new Error(ga(9));try{f=!0,a=n(a,I)}finally{f=!1}return(c=l).forEach(P=>{P()}),I}function v(I){if(typeof I!="function")throw new Error(ga(10));n=I,w({type:E5.REPLACE})}function T(){const I=y;return{subscribe(N){if(typeof N!="object"||N===null)throw new Error(ga(11));function P(){const Q=N;Q.next&&Q.next(x())}return P(),{unsubscribe:I(P)}},[L5](){return this}}}return w({type:E5.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[L5]:T}}function N5(e,t){return function(...r){return t(e.apply(this,r))}}function R5(e,t){if(typeof e=="function")return N5(e,t);if(typeof e!="object"||e===null)throw new Error(ga(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=N5(a,t))}return r}function Uv(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function pR(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(ga(15))};const l={getState:a.getState,dispatch:(f,...m)=>c(f,...m)},d=e.map(f=>f(l));return c=Uv(...d)(a.dispatch),{...a,dispatch:c}}}var _m={exports:{}},km={};var M5;function mR(){if(M5)return km;M5=1;var e=VA();function t(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&m!==m}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,a=e.useRef,c=e.useEffect,l=e.useMemo,d=e.useDebugValue;return km.useSyncExternalStoreWithSelector=function(f,m,x,y,w){var v=a(null);if(v.current===null){var T={hasValue:!1,value:null};v.current=T}else T=v.current;v=l(function(){function I(U){if(!N){if(N=!0,P=U,U=y(U),w!==void 0&&T.hasValue){var Z=T.value;if(w(Z,U))return $=Z}return $=U}if(Z=$,r(P,U))return Z;var J=y(U);return w!==void 0&&w(Z,J)?(P=U,Z):(P=U,$=J)}var N=!1,P,$,Q=x===void 0?null:x;return[function(){return I(m())},Q===null?void 0:function(){return I(Q())}]},[m,x,y,w]);var S=n(f,v[0],v[1]);return c(function(){T.hasValue=!0,T.value=S},[S]),d(S),S},km}var j5;function gR(){return j5||(j5=1,_m.exports=mR()),_m.exports}gR();var xR=b.version.startsWith("19"),bR=Symbol.for(xR?"react.transitional.element":"react.element"),yR=Symbol.for("react.portal"),vR=Symbol.for("react.fragment"),wR=Symbol.for("react.strict_mode"),AR=Symbol.for("react.profiler"),TR=Symbol.for("react.consumer"),SR=Symbol.for("react.context"),zv=Symbol.for("react.forward_ref"),CR=Symbol.for("react.suspense"),_R=Symbol.for("react.suspense_list"),Rg=Symbol.for("react.memo"),kR=Symbol.for("react.lazy"),LR=zv,IR=Rg;function ER(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case bR:switch(e=e.type,e){case vR:case AR:case wR:case CR:case _R:return e;default:switch(e=e&&e.$$typeof,e){case SR:case zv:case kR:case Rg:return e;case TR:return e;default:return t}}case yR:return t}}}function NR(e){return ER(e)===Rg}function RR(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,f,m,x,y,w;function v(P,$){return f=P,m=$,x=e(f,m),y=t(n,m),w=r(x,y,m),d=!0,w}function T(){return x=e(f,m),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function S(){return e.dependsOnOwnProps&&(x=e(f,m)),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function I(){const P=e(f,m),$=!l(P,x);return x=P,$&&(w=r(x,y,m)),w}function N(P,$){const Q=!c($,m),U=!a(P,f,$,m);return f=P,m=$,Q&&U?T():Q?S():U?I():w}return function($,Q){return d?N($,Q):v($,Q)}}function MR(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return RR(c,l,d,e,a)}function jR(e,t){const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=(...c)=>t(a(...c)))}return r}function P1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function D5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function Hv(e,t){return function(n,{displayName:a}){const c=function(d,f){return c.dependsOnOwnProps?c.mapToProps(d,f):c.mapToProps(d,void 0)};return c.dependsOnOwnProps=!0,c.mapToProps=function(d,f){c.mapToProps=e,c.dependsOnOwnProps=D5(e);let m=c(d,f);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=D5(m),m=c(d,f)),m},c}}function Mg(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function DR(e){return e&&typeof e=="object"?P1(t=>jR(e,t)):e?typeof e=="function"?Hv(e):Mg(e,"mapDispatchToProps"):P1(t=>({dispatch:t}))}function BR(e){return e?typeof e=="function"?Hv(e):Mg(e,"mapStateToProps"):P1(()=>({}))}function QR(e,t,r){return{...r,...e,...t}}function PR(e){return function(r,{displayName:n,areMergedPropsEqual:a}){let c=!1,l;return function(f,m,x){const y=e(f,m,x);return c?a(y,l)||(l=y):(c=!0,l=y),l}}}function OR(e){return e?typeof e=="function"?PR(e):Mg(e,"mergeProps"):()=>QR}function FR(e){e()}function $R(){let e=null,t=null;return{clear(){e=null,t=null},notify(){FR(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const a=t={callback:r,next:null,prev:t};return a.prev?a.prev.next=a:e=a,function(){!n||e===null||(n=!1,a.next?a.next.prev=a.prev:t=a.prev,a.prev?a.prev.next=a.next:e=a.next)}}}}var B5={notify(){},get:()=>[]};function Wv(e,t){let r,n=B5,a=0,c=!1;function l(S){x();const I=n.subscribe(S);let N=!1;return()=>{N||(N=!0,I(),y())}}function d(){n.notify()}function f(){T.onStateChange&&T.onStateChange()}function m(){return c}function x(){a++,r||(r=t?t.addNestedSub(f):e.subscribe(f),n=$R())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=B5)}function w(){c||(c=!0,x())}function v(){c&&(c=!1,y())}const T={addNestedSub:l,notifyNestedSubs:d,handleChangeWrapper:f,isSubscribed:m,trySubscribe:w,tryUnsubscribe:v,getListeners:()=>n};return T}var UR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",zR=UR(),HR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",WR=HR(),GR=()=>zR||WR?b.useLayoutEffect:b.useEffect,$f=GR();function Q5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Lm(e,t){if(Q5(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let a=0;a<r.length;a++)if(!Object.prototype.hasOwnProperty.call(t,r[a])||!Q5(e[r[a]],t[r[a]]))return!1;return!0}var VR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},qR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},YR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Gv={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},ZR={[LR]:YR,[IR]:Gv};function P5(e){return NR(e)?Gv:ZR[e.$$typeof]||VR}var KR=Object.defineProperty,XR=Object.getOwnPropertyNames,O5=Object.getOwnPropertySymbols,JR=Object.getOwnPropertyDescriptor,eM=Object.getPrototypeOf,F5=Object.prototype;function O1(e,t){if(typeof t!="string"){if(F5){const c=eM(t);c&&c!==F5&&O1(e,c)}let r=XR(t);O5&&(r=r.concat(O5(t)));const n=P5(e),a=P5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!qR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=JR(t,l);try{KR(e,l,d)}catch{}}}}return e}var tM=Symbol.for("react-redux-context"),rM=typeof globalThis<"u"?globalThis:{};function nM(){if(!b.createContext)return{};const e=rM[tM]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var Vv=nM(),sM=[null,null];function iM(e,t,r){$f(()=>e(...t),r)}function aM(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function oM(e,t,r,n,a,c,l,d,f,m,x){if(!e)return()=>{};let y=!1,w=null;const v=()=>{if(y||!d.current)return;const S=t.getState();let I,N;try{I=n(S,a.current)}catch(P){N=P,w=P}N||(w=null),I===c.current?l.current||m():(c.current=I,f.current=I,l.current=!0,x())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(y=!0,r.tryUnsubscribe(),r.onStateChange=null,w)throw w}}function lM(e,t){return e===t}function cM(e,t,r,{pure:n,areStatesEqual:a=lM,areOwnPropsEqual:c=Lm,areStatePropsEqual:l=Lm,areMergedPropsEqual:d=Lm,forwardRef:f=!1,context:m=Vv}={}){const x=m,y=BR(e),w=DR(t),v=OR(r),T=!!e;return I=>{const N=I.displayName||I.name||"Component",P=`Connect(${N})`,$={shouldHandleStateChanges:T,displayName:P,wrappedComponentName:N,WrappedComponent:I,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function Q(J){const[H,ye,oe]=b.useMemo(()=>{const{reactReduxForwardedRef:dt,...it}=J;return[J.context,dt,it]},[J]),te=b.useMemo(()=>{let dt=x;return H?.Consumer,dt},[H,x]),Ce=b.useContext(te),qe=!!J.store&&!!J.store.getState&&!!J.store.dispatch,ve=!!Ce&&!!Ce.store,Y=qe?J.store:Ce.store,st=ve?Ce.getServerState:Y.getState,he=b.useMemo(()=>MR(Y.dispatch,$),[Y]),[Qe,ie]=b.useMemo(()=>{if(!T)return sM;const dt=Wv(Y,qe?void 0:Ce.subscription),it=dt.notifyNestedSubs.bind(dt);return[dt,it]},[Y,qe,Ce]),Pe=b.useMemo(()=>qe?Ce:{...Ce,subscription:Qe},[qe,Ce,Qe]),Fe=b.useRef(void 0),ce=b.useRef(oe),Ie=b.useRef(void 0),je=b.useRef(!1),Ze=b.useRef(!1),we=b.useRef(void 0);$f(()=>(Ze.current=!0,()=>{Ze.current=!1}),[]);const le=b.useMemo(()=>()=>Ie.current&&oe===ce.current?Ie.current:he(Y.getState(),oe),[Y,oe]),Ge=b.useMemo(()=>it=>Qe?oM(T,Y,Qe,he,ce,Fe,je,Ze,Ie,ie,it):()=>{},[Qe]);iM(aM,[ce,Fe,je,oe,Ie,ie]);let He;try{He=b.useSyncExternalStore(Ge,le,st?()=>he(st(),oe):le)}catch(dt){throw we.current&&(dt.message+=`
77
+ `),Jt(B),ne(B,!1),Dt("Terminal session ended"),pe(!1),xn(!1),Wr(null),ds(null),mr(B,!1),$n();break}}},onError:(M,B)=>{if(It.current!==Ve)return;const G=Y;if(!G)return;z.current=!1,$e.current=!1,pe(!1);const Te=M.name==="TerminalInputError"&&"code"in M&&M.code==="TERMINAL_INPUT_REJECTED",Se=B&&M.message==="Authentication required",Be=!Te&&g5(M),ct=Te||Se?M.message:Be||B?"Reconnecting...":M.message||"Terminal stream connection error";console.error(`[Terminal] Stream error (fatal=${B}):`,ct),Be&&console.warn("[Terminal] SESSION_NOT_FOUND_DETECTED",{terminalIdAtError:rr.current,frontendSessionId:G,isActive:l,isMobile:we,fatal:B,stack:new Error().stack}),Dt(ct),xn(!!B),B&&(Wr(null),ne(G,!1),$n(),Be&&(ie("[onError] Session lost, auto-recreating"),Dt("Reconnecting..."),xn(!1),Jt(G),un(G),rr.current=null,ui.current=!1,Js()))}},{...ON,getDimensions:()=>wr.current?.getDimensions()??null});bn.current=()=>{_.close(),It.current===Ve&&(An.current=null)},An.current=ue},[Ye,un,Jt,ie,$n,ls,Q,Nn,Js,Tl,ne,Jr,tn,mr,en,Zr,Qe,Y]);k.useEffect(()=>{const ue=_N({isActive:l,isStreamReady:ae,reconnectStartedAt:ws,now:Date.now()});if(ue===null)return;const Ve=window.setTimeout(()=>{ie("[Terminal] visible reconnect watchdog expired",{backendSessionId:rr.current,reconnectStartedAt:ws}),$n(),ne(Y,!1),Dt("Reconnecting..."),xn(!1),Wr(Date.now()),Js()},ue);return()=>window.clearTimeout(Ve)},[ie,$n,l,ae,ws,Js,Y,ne]);const ui=k.useRef(!1),Ua=k.useRef(!1),js=k.useRef(0);k.useEffect(()=>()=>{js.current+=1,ui.current=!1,$n()},[$n]);const ao=k.useRef(De),za=k.useRef(Mt);k.useEffect(()=>{const ue=ao.current,Ve=za.current;ao.current=De,za.current=Mt,Cn.current===Y&&(ue===De&&Ve===Mt||(ui.current=!1,$n(),Pn(bt=>bt+1)))},[De,Mt,$n,Y]),k.useEffect(()=>{if(Cn.current!==Y&&(ie(`[useEffect] sessionId changed from ${Cn.current} to ${Y}, allowing reinitialization`),ui.current=!1,Ua.current=!1),ui.current&&Cn.current===Y){ie(`[useEffect] Already initialized for sessionId=${Y}, skipping`);return}if(!Nt)return;const ue=async B=>{if(ie(`[ensureSession] Starting for sessionId=${Y}, runId=${B}`),!Cn.current||Cn.current!==Y){ie(`[ensureSession] SessionId mismatch or stale run (current=${Cn.current}, target=${Y}), skipping`);return}if(B!==js.current){ie(`[ensureSession] Stale run detected (runId=${B}, currentRunId=${js.current}), skipping`);return}const G=Hr.getState(),Te=G.getTerminalSession(Y),Se=Te?.mode??De;ie("[ensureSession] Current state from store:",{terminalSessionId:Te?.terminalSessionId,mode:Te?.mode,tmuxSessionName:Te?.tmuxSessionName,isConnecting:Te?.isConnecting});let Be=Te?.terminalSessionId??null,ct=!Be;if(Be&&Se!==De?(ie(`[ensureSession] Store mode mismatch for ${Be}: current=${Se} desired=${De}, will create new session`),ct=!0,G.clearTerminalSession(Y),Be=null):Be&&De==="tmux"&&Mt&&Te?.tmuxSessionName!==Mt&&(ie(`[ensureSession] Store tmux name mismatch for ${Be}: current=${Te?.tmuxSessionName} desired=${Mt}, will create new session`),ct=!0,G.clearTerminalSession(Y),Be=null),Be&&Qe.checkHealth&&!et.current){ie(`[ensureSession] Checking health of existing session ${Be}`);try{const yt=await Qe.checkHealth(Be);if(ie("[ensureSession] Health check result:",yt),!yt.healthy)ie(`[ensureSession] Session ${Be} is NOT healthy (healthy=${yt.healthy}), will create new session`),ie("[ensureSession] Health check details:",yt),ct=!0,yt.mode&&Te?.terminalSessionId&&G.setTerminalSession(Y,{sessionId:Te.terminalSessionId,cols:80,rows:24,mode:yt.mode,tmuxSessionName:yt.tmuxSessionName??null}),G.clearTerminalSession(Y),ie("[ensureSession] Cleared unhealthy session from store");else{ie(`[ensureSession] Session ${Be} is healthy, reusing it, cwd=${yt.cwd}, clients=${yt.clients}, lastActivity=${Date.now()-(yt.lastActivity||0)}ms ago`),yt.mode&&Te?.terminalSessionId&&G.setTerminalSession(Y,{sessionId:Te.terminalSessionId,cols:80,rows:24,mode:yt.mode,tmuxSessionName:yt.tmuxSessionName??null}),ie(`[ensureSession] Setting terminalIdRef to ${Be} and starting stream`),rr.current=Be,wa(Be),ie(`[ensureSession] Successfully reused healthy session ${Be}, returning early`);return}}catch(yt){ie(`[ensureSession] Failed to check health of session ${Be}:`,yt),ie("[ensureSession] Health check API call failed, proceeding as if session might be unhealthy")}}if(ie(`[ensureSession] Decision: shouldCreateNewSession=${ct}, terminalId=${Be}`),ct){ie(`[ensureSession] Creating new session, shouldCreateNewSession=${ct}, runId=${B}`),Dt(null),xn(!1),G.setConnecting(Y,!0);const $t=Hr.getState().getTerminalSession(Y),ln=($t?.mode??De)===De&&(De!=="tmux"||!Mt||$t?.tmuxSessionName===Mt);if($t?.terminalSessionId&&ln)ie(`[ensureSession] Race condition avoided: another instance already created session ${$t.terminalSessionId}`),G.setConnecting(Y,!1),Be=$t.terminalSessionId,ct=!1;else try{const rn=await hs();if(ie(`[ensureSession] Opened managed backend session ${rn.sessionId}`),B!==js.current){ie(`[ensureSession] Stale run after session creation (runId=${B}, currentRunId=${js.current}), leaving ${rn.sessionId} for sibling`);return}G.setTerminalSession(Y,rn),ie(`[ensureSession] Updated store with new session ${rn.sessionId}`),Be=rn.sessionId}catch(rn){if(B!==js.current){ie("[ensureSession] Stale run after session creation failed, skipping error handling");return}if(rn instanceof g0&&N1(rn)){ie("[ensureSession] Confirmed missing persisted session:",{sessionId:Y,error:rn.message}),G.clearTerminalSession(Y),Dt(pf),xn(!0),G.setConnecting(Y,!1);return}Dt("Reconnecting..."),xn(!0),G.setConnecting(Y,!1);return}}if(B!==js.current){ie(`[ensureSession] Stale run before starting stream (runId=${B}, currentRunId=${js.current}), skipping`);return}if(!Be){ie(`[ensureSession] No terminalId, terminalId=${Be}`);return}ie(`[ensureSession] Starting stream for session ${Be}`),rr.current=Be,wa(Be),ie(`[ensureSession] ensureSession completed for sessionId=${Y}, terminalId=${Be}`)};let Ve=null,bt=null;const _=()=>{bt=null,!(ui.current&&Cn.current===Y)&&(ie(`[useEffect] Running ensureSession for sessionId=${Y}, hasInitialized=${ui.current}`),ui.current=!0,Ua.current=!0,Ve=++js.current,ue(Ve))};if(!N&&!Ua.current){ie(`[useEffect] Holding background connection until the selected session is ready: ${Y}`);return}const M=Ua.current?0:Math.max(0,I);return M>0?(ie(`[useEffect] Delaying initial connection for sessionId=${Y} by ${M}ms`),bt=window.setTimeout(_,M)):_(),()=>{bt!==null&&window.clearTimeout(bt),ie(`[useEffect] Cleanup for sessionId=${Y}, runId=${Ve??"pending"}`)}},[Y,Qn,wa,$n,Qe,ie,De,Mt,lr,I,N,Nt]);const _c=k.useCallback(async()=>{if(Y&&!Kn){Cs(!0),Dt(null),xn(!1),Wr(null),$n();try{Qe.forceKill&&await Qe.forceKill({sessionId:Y})}catch{}Or(Y),un(Y),wr.current?.clear(),await new Promise(ue=>setTimeout(ue,100));try{ne(Y,!0);const ue=await hs();an(Y,ue),rr.current=ue.sessionId,wa(ue.sessionId)}catch(ue){Dt(ue instanceof g0&&N1(ue)?pf:"Reconnecting..."),xn(!0),ne(Y,!1)}finally{Cs(!1)}}},[Y,Kn,$n,Qe,Or,un,ne,an,wa,hs]),di=k.useCallback((ue,Ve,bt,_)=>{if(!(rr.current!==Ve||_t.current!==bt)){if(ue instanceof g0&&g5(ue)){ie("[Terminal] operation backend missing, recovering",{terminalId:Ve,sessionId:Y}),Dt("Reconnecting..."),xn(!1),$n(),Jt(Y),rr.current=null,ne(Y,!0),Js();return}Dt(ue instanceof Error?ue.message:_)}},[Jt,ie,$n,Js,Y,ne]),Vl=k.useCallback((ue,Ve)=>{const bt=Ve?.ownedPaste?YC(Ve.ownedPaste,Y,ue):!1;if(Ve?.ownedPaste&&!bt||Wn.current&&!(bt&&Gt.current)||(dr.current||og())&&!bt)return Promise.resolve(!1);const _=()=>!!Ve?.ownedPaste&&ZC(Ve.ownedPaste,Y)&&(et.current||Ve?.targeted===!0)&&(!Wn.current||Gt.current)&&$e.current&&!Br.current&&!document.hidden&&navigator.onLine!==!1&&xc();if(bt&&!_())return Promise.resolve(!1);if(!et.current&&!Ve?.targeted||!ue)return;const M=qE(ue),B=/^(\x1b\[<6[45];[0-9]+;[0-9]+M)+$/.test(ue);if(Date.now()<on.current)return Promise.resolve(!1);let G=ue,Te=Ve?.consumeModifier??!1;if(!Ve?.skipModifierTransform&&!M&&ge&&ue.length>0){const $t=ue[0];if($t.length===1&&/[a-zA-Z]/.test($t)){const Ir=$t.toUpperCase();ge==="ctrl"?(G=String.fromCharCode(Ir.charCodeAt(0)&31),Te=!0):ge==="alt"&&(G=`\x1B${ue}`,Te=!0)}Te||(ge==="alt"&&(G=`\x1B${ue}`),Te=!0)}const Se=rr.current;if(!Se)return;const Be=_t.current,ct=async()=>{if(rr.current!==Se||_t.current!==Be)return!1;try{if((!M||B)&&kn.current.input(performance.now()),qr&&B&&(Hn.current=!0),qr&&!M&&Hn.current&&Qe.tmuxAction){if(Hn.current=!1,bt&&!_())return!1;if(Qe.sendInputExitingCopyMode?.(Se,G))return Qr(Y),!0;try{await Qe.tmuxAction(Se,{action:"copy-mode",enabled:!1})}catch{}if(rr.current!==Se||_t.current!==Be)return!1;if(YE(G))return!0}return bt&&(!_()||rr.current!==Se||_t.current!==Be)||(await Qe.sendInput(Se,G),bt&&(!_()||rr.current!==Se||_t.current!==Be))?!1:(Qr(Y),!0)}catch($t){return di($t,Se,Be,"Failed to send input"),!1}},yt=Fr.current.then(ct);return Fr.current=yt.then(()=>{},()=>{}),Te&&(at||Je(null),Ls()),yt},[ge,Qr,Ls,di,qr,at,Y,Qe]);k.useEffect(()=>{const ue=Ve=>{const bt=Ve,_=bt.detail?.sessionId;if(_?_!==Y:!et.current)return;const M=bt.detail?.text;if(!M)return;const B=bt.detail?.nonce;if(Br.current||!wr.current){B&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:B,ok:!1}}));return}const G=qC(bt.detail,Y),Te=bt.detail?.ownedPaste&&!G?Promise.resolve(!1):wr.current.sendSequence(M,{paste:bt.detail?.paste,submitAfterPaste:bt.detail?.submitAfterPaste,targeted:!!_,ownedPaste:G??void 0});B&&Promise.resolve(Te).then(Se=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:B,ok:Se===!0}}))},()=>{window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:B,ok:!1}}))}),vC(zr.current,bt.detail?.focus!==!1)&&Ls()};return window.addEventListener("termdock-insert-reference",ue),()=>window.removeEventListener("termdock-insert-reference",ue)},[Ls,Y]);const Ci=k.useCallback((ue,Ve,bt)=>{const _=rr.current;if(!_){Pe("xterm resize push skipped: no terminalId",{cols:ue,rows:Ve});return}Pe("xterm resize push",{cols:ue,rows:Ve}),Qe.resize({sessionId:_,cols:ue,rows:Ve,seq:bt}).catch(M=>{wr.current?.acknowledgeResize({seq:bt,ok:!1}),M&&/session not found/i.test(String(M.message||M))&&console.warn("[Terminal] resize 404 session not found",{sessionId:_,cols:ue,rows:Ve,stack:new Error().stack})})},[Qe,Pe]),oo=k.useCallback(async ue=>{const Ve=rr.current;if(!Ve||!Qe.tmuxAction)return;const bt=_t.current;try{const _=await Qe.tmuxAction(Ve,ue);if(rr.current!==Ve||_t.current!==bt)return;_.layout&&(ds(_.layout),ue.action==="switch-session"&&(an(Y,{sessionId:Ve,cols:80,rows:24,mode:"tmux",tmuxSessionName:_.layout.sessionName}),F8(Y,{tmuxSessionName:_.layout.sessionName}).catch(M=>{console.warn("[Terminal] failed to update inventory after tmux switch",M)})))}catch(_){di(_,Ve,bt,"Failed to execute tmux action")}},[di,Y,an,Qe]);k.useEffect(()=>{if(!jr||!tr)return;const Ve=jr.windows.find(bt=>bt.id===jr.activeWindowId)?.panes.find(bt=>bt.id===jr.activePaneId);Ve&&wr.current?.requestRefresh("tmux-layout",{skipResizePush:!0,skipScrollToBottom:!0,dedupeKey:`${tr}:${jr.sessionId}:${Ve.id}:${Ve.width}x${Ve.height}`})},[jr,tr]);const $s=k.useCallback((ue,Ve=5)=>{const bt=Math.max(1,Math.min(Math.floor(Ve)||1,40));Hn.current=!0;const _=$r.current;if(_&&_.direction===ue){_.lines+=bt;return}_&&oo({action:"scroll",direction:_.direction,lines:_.lines}).finally(()=>{Ls()}),$r.current={direction:ue,lines:bt},pn.current&&clearTimeout(pn.current),pn.current=setTimeout(()=>{const M=$r.current;M&&($r.current=null,oo({action:"scroll",direction:M.direction,lines:M.lines}).finally(()=>{Ls()}))},0)},[Ls,oo]),Aa=k.useCallback(ue=>{const Ve=Date.now(),bt=Re.current,_=bt!==null&&bt.modifier===ue&&Ve-bt.timestamp<=DN;if(Re.current={modifier:ue,timestamp:Ve},at===ue){Et(null),Je(null);return}if(_){Et(ue),Je(ue);return}at!==null&&at!==ue&&Et(null),Je(M=>M===ue?null:ue)},[at]),Sl=k.useCallback(ue=>{if(it(ue&&et.current),Pe("input focus changed",{focused:ue,isActive:et.current,isMobile:zr.current}),!zr.current||!et.current){xe(!1);return}xe(Ve=>Ve===ue?Ve:ue)},[Pe]),es=k.useCallback(ue=>{if(ps.current=ue,Nn(ue,"viewport-watermark"),!ue&&rs.current.length>0){const Ve=Y;if(Ve){const bt=rs.current;rs.current=[];for(const _ of bt)Ye(Ve,_)}}},[Ye,Nn,Y]),ti=k.useCallback(ue=>{et.current&&wr.current?.ensureSizeMatches(ue)},[]),Pi=k.useRef(null);k.useEffect(()=>{if(!l)return;const ue=Pi.current;if(!ue)return;const Ve=()=>ti("pointerdown"),bt=()=>ti("keydown"),_=()=>ti("touchstart"),M=()=>ti("wheel");return ue.addEventListener("pointerdown",Ve),ue.addEventListener("keydown",bt),ue.addEventListener("touchstart",_,{passive:!0}),ue.addEventListener("wheel",M,{passive:!0}),()=>{ue.removeEventListener("pointerdown",Ve),ue.removeEventListener("keydown",bt),ue.removeEventListener("touchstart",_),ue.removeEventListener("wheel",M)}},[l,ti]);const Ta=k.useCallback(ue=>{wr.current=ue},[]),ql=k.useCallback(ue=>{sr(ue),U?.(Y,ue)},[U,Y]),Yl=k.useCallback(ue=>{const Ve=nN(ue);if(!Ve)return;const bt=ge!==null;wr.current?.sendSequence(Ve,{consumeModifier:bt})},[ge]),kc=k.useCallback(ue=>{const Ve=XE(ue);if(Ve.length===0)return;const bt=ge!==null;wr.current?.sendSequence(h5(Ve[0]),{consumeModifier:bt});for(let _=1;_<Ve.length;_+=1){const M=Ve[_];window.setTimeout(()=>{wr.current?.sendSequence(h5(M))},KE*_)}},[ge]),Lc=k.useCallback(()=>{wr.current?.pasteClipboardText()},[]),Gn=k.useCallback(ue=>{ar.current!==null&&(window.clearTimeout(ar.current),ar.current=null),ot(ue),(ue==="inserted"||ue==="failed")&&(ar.current=window.setTimeout(()=>{ar.current=null,ot("idle")},1400))},[]),_i=k.useCallback(()=>{Gn("idle"),nr(0),Fn.current?.click()},[Gn]),Yi=k.useCallback(()=>{yr(!0)},[]),Ha=k.useCallback(ue=>{const Ve=ue.currentTarget.files?.[0];if(ue.currentTarget.value="",!Ve)return;const bt=Y;Tt(null),Rr(null),be(null),nr(0),Gn("uploading");const _=Kr&&Ve.type.startsWith("video/")?{maxHeight:wn,videoBitrate:Oe,onProgress:nr}:null,M=ft&&QN(Ve)?{maxDimension:ht,quality:Cr}:null;let B=_?"视频压缩":M?"图片压缩":"文件上传";(async()=>{const G=_?await(await Zc(async()=>{const{compressVideoLocally:Te}=await import("./videoCompression-DCsUD6X6.js");return{compressVideoLocally:Te}},__vite__mapDeps([0,1,2,3,4,5]))).compressVideoLocally(Ve,_):M?await(await Zc(async()=>{const{compressImageLocally:Te}=await import("./imageCompression-DaUBNTq-.js");return{compressImageLocally:Te}},[])).compressImageLocally(Ve,M):Ve;B="文件上传",await RN(G,(Te,Se)=>W0(Te,Se,void 0,nr),Te=>(B="插入终端",M1(R1(Te,null),bt,()=>et.current&&!Br.current&&Cn.current===bt&&Hr.getState().activeSessionId===bt))),(_||M)&&be({file:G,kind:_?"video":"image",originalSize:Ve.size,uploadedSize:G.size,originalRetained:G===Ve})})().then(()=>Gn("inserted"),G=>{G instanceof Of&&Tt({path:G.uploaded.path,sessionId:bt});const Te=G instanceof Of?G.uploaded.path:w5(G);Rr({stage:B,detail:Te}),yr(!0),Gn("failed"),Ba("warn","MOBILE_MEDIA_UPLOAD failed",{stage:B,detail:Te})})},[Oe,Kr,wn,ft,ht,Cr,Y,Gn]),Zi=k.useCallback(async()=>{const ue=Gr;if(!ue||ue.sessionId!==Y)return;yr(!1),await new Promise(bt=>window.requestAnimationFrame(()=>bt())),Gn("uploading"),await M1(R1(ue.path,null),ue.sessionId,()=>et.current&&!Br.current&&Cn.current===ue.sessionId&&Hr.getState().activeSessionId===ue.sessionId)?(Tt(null),Rr(null),Gn("inserted")):(yr(!0),Gn("failed"))},[Gr,Y,Gn]);k.useEffect(()=>{if(!Ht||!Kr)return;let ue=!0;return hn(null),Bn({phase:"checking-cache"}),Zc(async()=>{const{prepareLocalVideoCompression:Ve}=await import("./videoCompression-DCsUD6X6.js");return{prepareLocalVideoCompression:Ve}},__vite__mapDeps([0,1,2,3,4,5])).then(({prepareLocalVideoCompression:Ve})=>{if(ue)return Ve(bt=>{ue&&Bn(bt)})}).catch(Ve=>{ue&&hn(w5(Ve))}),()=>{ue=!1}},[Ht,Kr]);const lo=On||vr!==null;Br.current=lo;const Us=k.useRef(Ar);lo||(Us.current=Ar);const Ki=lo?Us.current:Ar,Sa=k.useMemo(()=>JE(Ki,En),[Ki,En]),_n=k.useMemo(()=>p5(En,Bt),[Bt,En]),ns=!we&&Bt!=="auto"&&_n.id!=="default"&&_n.showOnDesktop!==!0?"auto":Bt,Ca=ns==="auto"?Sa:ns,cs=k.useMemo(()=>p5(En,Ca),[Ca,En]),Wa=k.useMemo(()=>cs.actions.filter(ue=>ue.sequence.trim().length>0).map((ue,Ve)=>({...ue,label:E1(ue,Ve)})),[cs.actions]),ki=k.useMemo(()=>kv(Ar),[Ar]),co=cs.label,Li=k.useMemo(()=>ns!=="auto"?`Manual preset: ${cs.label}`:ki?`Auto preset · ${cs.label} (${ki})`:"Auto preset",[ki,ns,cs.label]),Ga=k.useCallback(ue=>{Me(ue)},[]),Xi=k.useCallback(()=>{Le(ue=>ue==="copy"?"arrows":"copy"),Ot("idle")},[]),Ji=k.useCallback(()=>{typeof window>"u"||(pr.current!==null&&window.clearTimeout(pr.current),pr.current=window.setTimeout(()=>{pr.current=null,Ot("idle")},1200))},[]),ea=k.useCallback(ue=>{pr.current!==null&&typeof window<"u"&&(window.clearTimeout(pr.current),pr.current=null),Ot(ue?"copied":"failed"),Ji()},[Ji]),ta=k.useCallback(ue=>{vt(ue)},[]),xs=k.useMemo(()=>we?eN(En):tN(En),[we,En]),ra=k.useMemo(()=>$8(a),[a]);k.useEffect(()=>{if(!qr||!ae||!Nt||!tr)return;const ue=o_(ra);ue&&Qe.sendInput(tr,ue).catch(Ve=>{console.warn("[Terminal] Failed to synchronize tmux default colors:",Ve)})},[qr,ae,Nt,tr,Qe,ra]);const Va=k.useMemo(()=>`terminal::${Y}`,[Y]),Ds=k.useCallback(()=>`${rr.current??"pending"}:${_t.current}`,[]);k.useEffect(()=>{qe?.({isConnecting:On,isRestarting:Kn,hasError:!!vr,sessionId:tr})},[On,Kn,vr,tr,qe]);const _a=!tr||On||Kn,Cl=k.useCallback((ue,Ve)=>{if(_a)return;const bt=Math.max(1,Math.min(Math.floor(Ve)||1,40));$s(ue,bt)},[$s,_a]);k.useEffect(()=>{if(!l||!we)return;wr.current?.requestRefresh("resize",{skipScrollToBottom:!Rt,force:!0})},[l,we,Rt,ir,Y]),k.useEffect(()=>{if(!l||!we)return;const ue=Ve=>{const bt=Ve.detail;wr.current?.requestRefresh("resize",{skipScrollToBottom:bt?.isOpen!==!0,force:!0})};return document.addEventListener("termdock:viewport-keyboard-change",ue),()=>{document.removeEventListener("termdock:viewport-keyboard-change",ue)}},[l,we,Y]);const Zl=!H&&(we||cs.id==="default"||cs.showOnDesktop===!0),rl=l,ka=we&&!oe?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,na=we&&!oe?{marginTop:"var(--kb-margin-top, 0px)",transition:"none"}:void 0,As=s.jsx(sN,{visible:Zl,interactive:rl,presentation:we?"mobile":"desktop-actions",activeModifier:ge,lockedModifier:at,disabled:_a,defaultShowExtended:X,presetLabel:co,presetModeLabel:Li,presetMode:ns,presetOptions:xs,includeAlt:cs.includeAlt,presetRowLayout:cs.rowLayout,extraActions:Wa,onKeyPress:Yl,onTextPress:kc,onPastePress:we?Lc:void 0,onFilePress:we?_i:void 0,onFileLongPress:we?Yi:void 0,fileUploadState:er,fileUploadProgress:Lt,longPressMode:Dr,copyFeedback:At,onLongPressModeToggle:Xi,onModifierToggle:Aa,onPresetSelect:Ga,onExpandedChange:ta}),Qo=typeof window<"u"&&(navigator.maxTouchPoints>0||"ontouchstart"in window);return s.jsxs("div",{className:"relative flex h-full min-h-0 flex-col overflow-hidden",style:ka,"data-owned-terminal-startup":window.__TD_NATIVE_GATE_STATE?JSON.stringify({active:l,viewportReady:Nt,streamReady:ae,contentReady:Xe,sizeReady:Ut}):void 0,children:[s.jsx("input",{ref:Fn,type:"file",className:"hidden",onChange:Ha}),Ht&&Zs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:()=>yr(!1),"aria-label":ve("common.close")}),s.jsxs("section",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-video-compression-title",className:"fixed bottom-[max(0.75rem,env(safe-area-inset-bottom,0px))] left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] z-modal-panel max-h-[calc(100dvh-1.5rem)] overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:left-1/2 sm:right-auto sm:w-[min(28rem,calc(100vw-2rem))] sm:-translate-x-1/2",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h2",{id:"mobile-video-compression-title",className:"text-sm font-semibold text-foreground",children:"本地媒体压缩"}),s.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"按文件类型选择压缩方式,处理完成后才上传。"})]}),s.jsx("button",{type:"button",className:"min-h-10 rounded-lg bg-surface-2 px-3 text-xs",onClick:()=>yr(!1),children:ve("common.close")})]}),ur&&s.jsxs("div",{role:"alert",className:"mt-3 rounded-lg bg-destructive/10 p-3 text-xs text-destructive",children:[s.jsxs("p",{children:[ur.stage,"失败。",ur.stage.endsWith("压缩")?"原文件未上传。":ur.stage==="插入终端"?"文件已上传,路径见详情。":""]}),s.jsxs("details",{className:"mt-2",children:[s.jsx("summary",{className:"cursor-pointer",children:"错误详情"}),s.jsx("p",{className:"mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:ur.detail})]}),Gr&&s.jsx("button",{type:"button",onClick:()=>{Zi()},disabled:er==="uploading"||Gr.sessionId!==Y,className:"mt-2 rounded-lg bg-surface-2 px-3 py-2 text-foreground disabled:opacity-50",children:ve("common.retry")})]}),cn&&s.jsx("p",{className:"mt-2 text-[11px] text-destructive",children:"本机未能保存设置,重新打开后可能恢复默认值。"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"显示压缩结果提示"}),s.jsx("input",{type:"checkbox",checked:gt.showResultToast,onChange:ue=>rt({showResultToast:ue.target.checked}),className:"h-4 w-4 accent-primary"})]}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩图片后上传"}),s.jsx("input",{type:"checkbox",checked:ft,onChange:ue=>rt({imageEnabled:ue.target.checked}),className:"h-4 w-4 accent-primary"})]}),ft&&s.jsxs("div",{className:"mt-3 space-y-3",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片最长边",s.jsx("select",{value:ht,onChange:ue=>rt({imageMaxDimension:Number(ue.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:jv.map(ue=>s.jsxs("option",{value:ue,children:[ue," px",ue===640?" · 最省流量":ue===2048?" · 推荐":ue===4096?" · 保留更多细节":""]},ue))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["图片画质:",Math.round(Cr*100),"%",s.jsx("input",{type:"range",min:A0.min,max:A0.max,step:A0.step,value:Cr,onChange:ue=>rt({imageQuality:Number(ue.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"支持 JPEG、PNG、HEIC 照片;GIF、SVG 等保持原文件。压缩后未变小也会保留原图。"})]}),s.jsx("div",{className:"mt-4 border-t border-border/15 pt-1"}),s.jsxs("label",{className:"mt-4 flex min-h-11 items-center justify-between rounded-xl bg-surface-elevated px-3 text-sm",children:[s.jsx("span",{children:"压缩视频后上传"}),s.jsx("input",{type:"checkbox",checked:Kr,onChange:ue=>rt({videoEnabled:ue.target.checked}),className:"h-4 w-4 accent-primary"})]}),Kr&&s.jsxs("div",{className:"mt-4 space-y-4",children:[s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["视频最长边(像素)",s.jsx("select",{value:wn,onChange:ue=>rt({videoMaxHeight:Number(ue.target.value)}),className:"mt-1 block min-h-10 w-full rounded-lg bg-surface-2 px-3 text-sm text-foreground",children:Dv.map(ue=>s.jsxs("option",{value:ue,children:[ue," px",ue===240?" · 最省流量":ue===720?" · 推荐":ue>=1440?" · 手机处理较慢":""]},ue))})]}),s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["目标视频码率:",Oe/1e6," Mbps",s.jsx("input",{type:"range",min:T0.min,max:T0.max,step:T0.step,value:Oe,onChange:ue=>rt({videoBitrate:Number(ue.target.value)}),className:"mt-2 h-1 w-full accent-primary"})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:"保持比例,不放大原视频。尺寸越小通常处理越快;码率越低体积通常越小,过高可能比原片更大。"}),s.jsx("p",{className:"text-[11px] text-muted-foreground",role:"status","aria-live":"polite",children:mn?"本地转码器准备失败,请关闭开关后重试。":PN(Xr)}),Xr?.saved===!1&&s.jsx("p",{className:"text-[11px] text-destructive",children:"本机未能保存转码器,重新打开后可能需要重新下载。"}),mn&&s.jsx("p",{className:"text-[11px] text-destructive",children:mn})]})]})]}),document.body),Tr&&s.jsx(iN,{isMobile:we,isInputFocused:tt,isIOS:Ge,isConnecting:On,connectionError:vr,terminalSessionId:tr}),s.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",style:{backgroundColor:ra.background,...na},children:[s.jsx("div",{ref:Pi,className:"h-full w-full box-border",children:s.jsx(U8,{fallback:s.jsx("div",{className:"flex h-full items-center justify-center bg-background",children:s.jsxs("div",{className:"flex flex-col items-center gap-3 text-center rounded-2xl bg-surface-2 px-6 py-5 shadow-sm",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center",children:s.jsx("svg",{className:"w-5 h-5 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),s.jsx("span",{className:"text-sm text-muted-foreground",children:ve("terminal.componentFailed")})]})}),children:s.jsx($E,{ref:Ta,sessionKey:Va,sessionId:Y,getPasteOwnerKey:Ds,backendSessionId:tr,isLayoutVisible:x,chunks:Lr,onInput:Vl,onResize:Ci,onFlowControl:es,onTmuxScroll:qr?Cl:void 0,tmuxScrollSensitivity:.38,onDoubleTap:we?()=>{wr.current?.sendSequence(" ")}:void 0,onInputFocusChange:Sl,onMobileLongPressCopyResult:ea,onReadyChange:ql,onSizeSynchronizedChange:qt,onWritesSettled:ya,onWriteProgress:Fs,onCursorPositionChange:Pa,onDirectoryLinkActivate:K,terminalSettings:Ie,theme:ra,enableTouchScroll:we,mobileLongPressMode:Dr,autoFocus:l&&!Ze&&!we&&!Qo,inputActive:l&&!Ze,cursorVisible:!Ze&&jt,suppressSmoothScroll:!Xe||!Ut,className:Ze||!jt?"terminal-focus-suspended":void 0},Va)})}),s.jsx(jN,{result:Ft,onDismiss:Ct}),s.jsx(oN,{connectionError:vr,isFatalError:Pr,isRestarting:Kn,isConnecting:On,onHardRestart:_c})]}),ye?H?null:Zs.createPortal(As,ye):As]})};function $N({session:e,active:t,onActivate:r,onToggleRightSidebar:n}){const{t:a}=Ur(),c=Hr(l=>{const d=l.sessions.get(e.id);return xl(e,d?.activeProgram??null,d?.cwd??null,void 0,d?.shellTitle??null,d?.promptState??null).primary});return s.jsxs("div",{"data-pane-titlebar":"true",className:"swiper-no-swiping flex h-6 min-h-6 shrink-0 items-center border-b border-border app-chrome-bg text-foreground",children:[s.jsxs("button",{type:"button","data-split-pane-title":e.id,draggable:!1,onDragStart:l=>l.preventDefault(),"aria-pressed":t,title:`${c} · 拖动标题移动,边缘拆分,中央交换`,onClick:r,className:"split-pane-drag-handle flex h-full min-w-0 cursor-grab active:cursor-grabbing flex-1 items-center gap-1.5 overflow-hidden px-2 text-left text-[12px] font-medium leading-none hover:opacity-80 focus-visible:outline focus-visible:outline-1 focus-visible:outline-current focus-visible:-outline-offset-1",children:[s.jsx(tl,{size:11,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:c}),s.jsx(hg,{size:12,"aria-hidden":"true",className:"shrink-0 opacity-60"})]}),n&&s.jsx("button",{type:"button",onClick:n,"aria-label":a("tab.explorerTitle"),title:a("tab.explorerTitle"),className:"inline-flex h-full w-7 shrink-0 items-center justify-center hover:opacity-80 focus-visible:outline focus-visible:outline-1 focus-visible:outline-current focus-visible:-outline-offset-1",children:s.jsx(x3,{size:14})})]})}const UN="termdock:startup:";function Wu(e){if(typeof performance>"u"||typeof performance.mark!="function")return;const t=`${UN}${e}`;performance.getEntriesByName(t,"mark").length>0||performance.mark(t)}function A5(e,t){e||Zs.flushSync(t)}const j1="horizontal";function Ku(e){return e<=0?[]:Array.from({length:e},()=>1/e)}function mf(e,t){if(!Array.isArray(e)||e.length!==t)return Ku(t);const r=e.map(Number);if(r.some(a=>!Number.isFinite(a)||a<=0))return Ku(t);const n=r.reduce((a,c)=>a+c,0);return n<=0?Ku(t):r.map(a=>a/n)}function zN(e){const t=Math.max(1,Math.ceil(Math.sqrt(Math.max(1,e))));return{columns:t,rows:Math.max(1,Math.ceil(Math.max(1,e)/t))}}function HN(e){return e==="horizontal"||e==="vertical"||e==="grid"}function WN(e){if(!Array.isArray(e))return[];const t=new Set,r=new Set,n=[];for(const a of e){if(!a||typeof a!="object")continue;const c=a;if(typeof c.id!="string"||!c.id||r.has(c.id))continue;const l=Array.isArray(c.sessionIds)?c.sessionIds.filter(m=>typeof m=="string"&&!!m&&!t.has(m)):[],d=[...new Set(l)];if(d.length<2)continue;const f=zN(d.length);d.forEach(m=>t.add(m)),r.add(c.id),n.push({id:c.id,...typeof c.name=="string"&&c.name.trim()?{name:c.name.trim().slice(0,80)}:{},sessionIds:d,layout:HN(c.layout)?c.layout:j1,ratios:mf(c.ratios,d.length),...c.gridColumnRatios!==void 0?{gridColumnRatios:mf(c.gridColumnRatios,f.columns)}:{},...c.gridRowRatios!==void 0?{gridRowRatios:mf(c.gridRowRatios,f.rows)}:{}})}return n}function GN(e,t){const r=new Set(t);return e.flatMap(n=>{const a=n.sessionIds.filter(c=>r.has(c));return a.length<2?[]:[{...n,sessionIds:a,ratios:a.length===n.sessionIds.length?mf(n.ratios,a.length):Ku(a.length)}]})}function B0(e,t){if(t)return e.find(r=>r.sessionIds.includes(t))}function Sm(e,t,r){if(!t||!r||t===r)return e;const n=B0(e,t),a=B0(e,r);if(n&&n.id===a?.id)return e;const c=[...n?.sessionIds??[t],...a?.sessionIds??[r]],l=[...new Set(c)],d={id:n?.id??`split:${t}`,...n?.name?{name:n.name}:{},sessionIds:l,layout:l.length>2&&(!n||n.layout===j1)?"grid":n?.layout??j1,ratios:Ku(l.length)},f=new Set([n?.id,a?.id].filter(Boolean)),m=e.filter(y=>!f.has(y.id)),x=n?Math.max(0,e.findIndex(y=>y.id===n.id)):m.length;return m.splice(Math.min(x,m.length),0,d),m}function VN(e,t){const r=B0(e,t);if(!r||!t)return e;if(r.sessionIds.length<=2)return e.filter(a=>a.id!==r.id);const n=r.sessionIds.filter(a=>a!==t);return e.map(a=>a.id===r.id?{...a,sessionIds:n,ratios:Ku(n.length)}:a)}function qN(e,t){const r=B0(e,t);return r?e.filter(n=>n.id!==r.id):e}function YN(e,t,r){return e.map(n=>{if(n.id!==t)return n;const a=[...new Set(r)],c=new Set(n.sessionIds);return a.length===n.sessionIds.length&&a.every(d=>c.has(d))?{...n,sessionIds:a}:n})}function ZN(e,t,r){const n=r.trim().slice(0,80);return e.map(a=>a.id===t?{...a,...n?{name:n}:{name:void 0}}:a)}const D1=320,Qv=1,KN=D1+120,B1="termdock:split-workspaces:v2",Pv="termdock:split-workspace:v1",XN=.1,JN=.9;function Cm(){if(typeof window>"u")return{mobile:!1,landscape:!1};const e=Xy();return{mobile:e,landscape:e&&window.innerWidth>window.innerHeight}}function eR(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(B1);if(e)return WN(JSON.parse(e));const t=JSON.parse(window.localStorage.getItem(Pv)||"null");if(t&&typeof t.primaryId=="string"&&typeof t.secondaryId=="string"&&t.primaryId!==t.secondaryId){const r=Math.min(JN,Math.max(XN,typeof t.ratio=="number"?t.ratio:.5));return[{id:`split:${t.primaryId}`,sessionIds:[t.primaryId,t.secondaryId],layout:t.direction==="vertical"?"vertical":"horizontal",ratios:[r,1-r]}]}}catch{}return[]}function tR(e,t){const r=new Map(e.map(l=>[l.id,l])),n=new Map;t.forEach(l=>l.sessionIds.forEach(d=>n.set(d,l)));const a=new Set,c=[];for(const l of e){const d=n.get(l.id);if(!d){c.push({key:l.id,sessions:[l]});continue}if(a.has(d.id))continue;a.add(d.id);const f=d.sessionIds.flatMap(m=>{const x=r.get(m);return x?[x]:[]});f.length>=2&&c.push({key:d.id,sessions:f,workspace:d})}return c}function T5(e){const t=e.wrapperEl;if(t)try{t.getAnimations().forEach(r=>r.cancel())}catch{}}function Qh(e,t){const r=Ff(e,t);if(r===null)return;const n=e.wrapperEl;T5(e),n&&(n.style.transitionDuration="0ms");try{const a=e;a.setTransition?.(0),a.setTranslate?.(r),T5(e),n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}catch{n&&(n.style.transitionDuration="0ms",n.style.transform=`translate3d(${r}px, 0px, 0px)`)}}function Q1(e){try{const t=typeof e.getTranslate=="function"?e.getTranslate():e.translate;return typeof t=="number"&&Number.isFinite(t)?t:null}catch{return typeof e.translate=="number"&&Number.isFinite(e.translate)?e.translate:null}}function Ff(e,t){const r=e.snapGrid,n=Array.isArray(r)?r[t]:void 0;return typeof n!="number"||!Number.isFinite(n)?null:-n}function rR(e,t){const r=Q1(e),n=Ff(e,t);return r!==null&&n!==null&&Math.abs(r-n)<=Qv}function nR(e){const t=[],r=new Map,n=new Map,a=new Map;for(const c of e){const l=r.get(c.id)??[];if(l.push(c.id),r.set(c.id,l),c.sessionId){const d=n.get(c.sessionId)??[];d.push(c.id),n.set(c.sessionId,d)}if(c.mode==="tmux"&&c.tmuxSessionName){const d=a.get(c.tmuxSessionName)??[];d.push(c.id),a.set(c.tmuxSessionName,d)}}for(const[c,l]of r)l.length>1&&t.push({kind:"frontend",key:c,sessionIds:l});for(const[c,l]of n)l.length>1&&t.push({kind:"backend",key:c,sessionIds:l});for(const[c,l]of a)l.length>1&&t.push({kind:"tmux",key:c,sessionIds:l});return t}function Ov(e){const t=new Map;for(const r of e)t.set(r.id,r);return Array.from(t.values())}function Fv(e){return{id:e.sessionId,name:e.name,customName:e.customName===!0,sessionId:e.backendSessionId,mode:e.mode==="tmux"||e.mode==="shell"?e.mode:"shell",tmuxSessionName:e.tmuxSessionName??null}}function sR(e,t){const r=Ov(e),n=r.findIndex(a=>a.id===t.id);if(n>=0){const a=[...r];return a[n]=t,a}return[...r,t]}function S5(e,t){const r=new Map(e.map(n=>[n.id,n]));return t.map(n=>{const a=r.get(n.sessionId);return{...Fv(n),history:a?.history}})}function C5(e,t){return e.length===0?null:t&&e.some(r=>r.sessionId===t)?t:e[0]?.sessionId??null}function _5(e){if(!e||typeof e!="object")return"unknown";const t=e;if(typeof t.pointerType=="string"&&t.pointerType)return t.pointerType;if(typeof t.type=="string"){if(t.type.startsWith("touch"))return"touch";if(t.type.startsWith("mouse"))return"mouse";if(t.type.startsWith("pointer"))return"pointer"}return"unknown"}function k5(e){const t=new Map;for(const[r,n]of e)t.set(r,n.cwd??null);return t}function iR(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t)if(e.get(r)!==n)return!1;return!0}function aR(e){const t="".toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,12);if(t)return`wt-${t}`;const r=Date.now().toString(36),n=Math.random().toString(36).slice(2,8);return`wt-${r}${n}`}const oR=({terminalSettings:e=_g(),colorTheme:t="dark",toolbarPresets:r=[],showDebug:n,terminalFocusAvailable:a=!0,terminalReferenceAvailable:c=a,defaultSessionMode:l="shell",defaultTmuxSessionName:d="",connectionPrioritySessionId:f=null,connectionPriorityReady:m=!0,desktopRightSidebarEnabled:x=!1,onToggleRightSidebar:y,desktopFloatingTitle:w=!1,desktopLeftSidebarPinned:v=!1,desktopPinnedLeftSidebarWidth:T=0,desktopViewportWidth:S=0,onStatusChange:I,onSessionDataUpdate:N,onInitialViewportReady:P,onInitialRecoveryRequired:$})=>{const{t:Q}=Ur(),U=w&&!v&&Gi()?.platform==="darwin"&&document.documentElement.dataset.termdockPreview==="true",Z=b.useMemo(()=>Ju("session"),[]),J=b.useMemo(()=>Ju("terminal"),[]),[H,ye]=b.useState([]),[oe,te]=b.useState(null),Ce=b.useRef(0),qe=b.useRef(0),ve=os(R=>R.activePaneId);b.useEffect(()=>{os.getState().setActivePane(oe)},[oe]);const[Y,st]=b.useState(null),[he,Qe]=b.useState(!0),[ie,Pe]=b.useState({token:0,reason:"visibility",forceForegroundReconnect:!1}),[Fe,ce]=b.useState(()=>new Set),[Ie,je]=b.useState(()=>({token:0,completed:new Set})),[Ze,we]=b.useState(0),[le,Ge]=b.useState(()=>new Set),[He,tt]=b.useState(()=>new Set),xe=b.useRef(new Map),[dt,it]=b.useState(()=>new Set),_e=b.useRef(!1),Ue=b.useRef(null),ke=b.useRef({}),[V,ae]=b.useState(null),[pe,$e]=b.useState(()=>eR()),[Xe,wt]=b.useState(!1),Ut=b.useCallback(R=>{Ce.current+=1,wt(R)},[]),qt=b.useRef(null),Nt=b.useRef(Xe);Nt.current=Xe,vc(qt,Xe&&!!oe,()=>Ut(!1));const[sr,jt]=b.useState(null),[Xt,Rt]=b.useState(null),ir=b.useRef(new Set),[ge,Je]=b.useState(null),[at,Et]=b.useState(null),[X,vt]=b.useState(!1),[Bt,Me]=b.useState(()=>Cm().mobile),[Dr,Le]=b.useState(()=>Cm().landscape),[At,Ot]=b.useState(null),[er,ot]=b.useState(null),Lt=b.useRef(a),nr=b.useRef(!1),ur=b.useRef(!1),Rr=b.useRef(null),Gr=b.useRef(null),Tt=b.useRef(Bt),Ft=b.useRef(null),be=b.useCallback(R=>{R!==Ft.current&&(Ce.current+=1),Ft.current=R,te(R)},[]);b.useEffect(()=>Yt.subscribe((R,F)=>{(R.rightOpen!==F.rightOpen||R.rightTab!==F.rightTab)&&(Ce.current+=1)}),[]);const Ct=b.useRef(0),gt=b.useRef([]),rt=b.useRef(0),cn=b.useRef(null),Kr=b.useRef(!1),wn=b.useRef(!0),Oe=b.useRef(null),ft=b.useRef(""),ht=b.useRef(0);b.useEffect(()=>{if(typeof window>"u")return;const R=()=>{const F=Cm();Tt.current=F.mobile,Me(F.mobile),Le(F.landscape)};return R(),window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]);const{sessions:Cr,inventory:Ht,activeSessionId:yr,isLoading:Xr,openSession:Bn,setActiveSession:mn,removeSession:hn,renameSession:gn,resetSessionCustomName:an,reorderSessions:ne,restoreSessions:Ye}=z8(),St=Ht?.tmuxRecovery??null;b.useEffect(()=>{St&&$?.()},[St,$]),b.useEffect(()=>{Et(null),Je(null)},[St?.id]);const Jt=b.useCallback(async()=>{Je("restore"),Et(null);try{const R=await H8(St?.id);await Ye(),R.accepted||Et(Q("tab.tmuxRecoveryFailed"))}catch{Et(Q("tab.tmuxRecoveryFailed"))}finally{Je(null)}},[Ye,Q,St?.id]),Or=b.useCallback(async()=>{const R=St?.operation;if(R)try{await W8(R.id,!R.paused),await Ye()}catch{Et(Q("tab.tmuxRecoveryFailed"))}},[Ye,Q,St?.operation]),un=b.useCallback(async()=>{Je("dismiss"),Et(null);try{await G8(),await Ye()}catch{Et(Q("tab.tmuxRecoveryDismissFailed"))}finally{Je(null)}},[Ye,Q]),Jr=Yt(R=>R.groupByFolder),en=Ef(R=>R.collaborationGroups),mr=Yt(R=>R.leftOpen||R.rightOpen),tn=Yt(R=>R.rightSidebarWidthContextKey),Sn=Yt(R=>R.rightSidebarWidth),Zr=Yt(R=>R.rightPinned),[Qr,lr]=b.useState(()=>k5(Hr.getState().sessions));b.useEffect(()=>Hr.subscribe(R=>{const F=k5(R.sessions);lr(q=>iR(q,F)?q:F)}),[]);const{arranged:fn}=b.useMemo(()=>Lf(H,R=>Qr.get(R.id)??null,Jr,"",pe,en),[H,Qr,Jr,pe,en]),Ss=b.useRef(fn);Ss.current=fn;const Ar=b.useMemo(()=>tR(fn,pe),[fn,pe]),En=b.useRef(Ar);En.current=Ar;const qr=b.useMemo(()=>B0(pe,oe),[oe,pe]),Lr=b.useMemo(()=>{const R=Ar.find(F=>F.sessions.some(q=>q.id===oe));return new Set(R?.sessions.map(F=>F.id)??[])},[oe,Ar]),On=b.useMemo(()=>{const R=new Map;if(!x||S<=0)return R;for(const F of Ar){const q=F.sessions[0];if(!q)continue;const se=V8(q.id,Qr.get(q.id)??null,F.workspace?.id??null);if(!(se===tn?Zr:q8(q.id,Qr.get(q.id)??null,F.workspace?.id??null)))continue;const We=se===tn?Sn:Y8(q.id,Qr.get(q.id)??null,F.workspace?.id??null),mt=rf(We,S,T);R.set(F.key,mt+Jy)}return R},[Qr,T,x,Zr,tn,Sn,S,Ar]),tr=b.useMemo(()=>Am(H.map(R=>({id:R.id,backendSessionId:R.sessionId})),f),[f,H]),K=b.useMemo(()=>C5(Cr,yr),[yr,Cr]),De=Dh({prioritySessionId:tr,activeSessionId:Y??oe,persistedActiveSessionId:K,firstSessionId:H[0]?.id??null}),Mt=b.useMemo(()=>kN(Ar.flatMap(R=>R.sessions.map(F=>F.id)),Lr),[Lr,Ar]),vr=De!==null&&Fe.has(De),Dt=b.useMemo(()=>{const R=new Set(Lr);return Y&&R.add(Y),!R.size&&De&&R.add(De),R},[Lr,Y,De]),Br=Ie.token===ie.token&&TN(Dt,Ie.completed),Pr=Br||Ze===ie.token?ie.token:-1;b.useEffect(()=>{if(!ie.token||Br)return;const R=window.setTimeout(()=>we(ie.token),hN);return()=>window.clearTimeout(R)},[ie.token,Br]);const xn=b.useCallback((R,F)=>{ce(q=>{if(q.has(R)===F)return q;const Ee=new Set(q);return F?Ee.add(R):Ee.delete(R),Ee})},[]),Kn=b.useCallback(R=>{const F=Ct.current;je(se=>{if(se.token===F&&se.completed.has(R))return se;const Ee=new Set(se.token===F?se.completed:[]);return Ee.add(R),{token:F,completed:Ee}});const q=tr??Y??Ft.current;R===q&&Wu("foreground-stream-connected")},[Y,tr]),Cs=b.useCallback((R,F)=>{Ge(q=>{if(q.has(R)===F)return q;const se=new Set(q);return F?se.add(R):se.delete(R),se})},[]),ws=b.useCallback((R,F)=>{tt(q=>{if(q.has(R)===F)return q;const se=new Set(q);return F?se.add(R):se.delete(R),se})},[]);b.useEffect(()=>{for(const[R,F]of xe.current){const q=H.find(se=>se.id===R);if(!q||q.sessionId!==F.backendSessionId){xe.current.delete(R);continue}!Fe.has(R)||!le.has(R)||!He.has(R)||(xe.current.delete(R),Ky(F.backendSessionId,`${F.command}\r`).catch(se=>{console.error("[Session] Failed to send startup command:",se)}))}},[H,Fe,le,He]);const Wr=De!==null&&le.has(De),Qn=De!==null&&He.has(De);b.useEffect(()=>{Wr&&Wu("foreground-viewport-ready")},[Wr]),b.useEffect(()=>{Qn&&Wu("foreground-content-ready")},[Qn]),b.useEffect(()=>{if(!P)return;if(!he&&H.length===0){P();return}if(!Wr||!vr||!Qn)return;const R=[...Lr].every(We=>le.has(We)&&Fe.has(We)&&He.has(We));let F=0,q=0;const se=()=>{F=requestAnimationFrame(()=>{q=requestAnimationFrame(()=>{Wu("initial-viewport-presented"),P()})})};R&&se();const Ee=R?void 0:window.setTimeout(se,8e3);return()=>{cancelAnimationFrame(F),cancelAnimationFrame(q),clearTimeout(Ee)}},[vr,Qn,Wr,he,P,H.length,Lr,le,Fe,He]);const Pn=b.useMemo(()=>Bt?mN({slides:Ar.map(R=>R.sessions.map(F=>F.id)),visibleSessionIds:Lr,foregroundSessionId:De}):dt,[Bt,Ar,Lr,De,dt]);b.useEffect(()=>{if(Bt||Lr.size===0)return;const R=new Set(Lr),F=Ar.findIndex(q=>q.sessions.some(se=>Lr.has(se.id)));for(let q=-2;q<=2;q+=1)q!==0&&Ar[F+q]?.sessions.forEach(se=>R.add(se.id));it(q=>{let se=!1;const Ee=new Set(q);for(const We of R)Ee.has(We)||(Ee.add(We),se=!0);return se?Ee:q})},[Bt,Lr,Ar]);const jr=UC(Pn);b.useEffect(()=>{if(!Y)return;if(!H.some(F=>F.id===Y)){st(null);return}if(!le.has(Y)||!Fe.has(Y)||!He.has(Y))return;const R=window.setTimeout(()=>{st(F=>F===Y?null:F),Lt.current&&!Tt.current&&ae({sessionId:Y,token:Date.now()})},80);return()=>window.clearTimeout(R)},[He,Y,Fe,H,le]),b.useEffect(()=>{typeof window>"u"||(pe.length>0?(window.localStorage.setItem(B1,JSON.stringify(pe)),window.localStorage.removeItem(Pv)):window.localStorage.removeItem(B1))},[pe]),b.useEffect(()=>{Xr||he||pe.length===0||$e(R=>GN(R,H.map(F=>F.id)))},[Xr,he,H,pe.length]),b.useEffect(()=>{if(!sr)return;const R=window.setTimeout(()=>jt(null),3200);return()=>window.clearTimeout(R)},[sr]),Ft.current=oe,Ct.current=ie.token,gt.current=H,cn.current=yr,Kr.current=Xr,wn.current=he,Lt.current=a;const ds=b.useCallback((R=Ue.current)=>{const F=rt.current,q=typeof window<"u"?window.visualViewport:null,se=R?Q1(R):null,Ee=R?Ff(R,F):null;return{sessionsLength:gt.current.length,workspaceSlidesLength:En.current.length,sessionIds:gt.current.map(We=>We.id),activeSessionId:Ft.current,activeSessionIndex:F,persistedActiveId:cn.current,isLoading:Kr.current,isRestoring:wn.current,activeIndex:R?.activeIndex??null,previousIndex:R?.previousIndex??null,animating:R?.animating??null,allowTouchMove:R?.allowTouchMove??null,width:R?.width??null,translate:se,targetTranslate:Ee,translateDelta:se!==null&&Ee!==null?se-Ee:null,snapGridLength:R?.snapGrid?.length??null,targetSnap:R?.snapGrid?.[F]??null,visualViewport:q?{width:Math.round(q.width),height:Math.round(q.height),offsetTop:Math.round(q.offsetTop)}:null}},[]),Tr=b.useCallback((R,F)=>{Z(R,{...ds(),...F})},[Z,ds]);b.useEffect(()=>{Xr||he||oe!==yr&&mn(oe)},[oe,Xr,he,yr,mn]);const bn=b.useMemo(()=>{if(fn.length===0||!oe)return 0;const R=Ar.findIndex(F=>F.sessions.some(q=>q.id===oe));return R>=0?R:0},[Ar,oe]);rt.current=bn;const An=b.useCallback(()=>{Rr.current&&(clearTimeout(Rr.current),Rr.current=null)},[]),rr=b.useCallback(R=>{An(),Rr.current=setTimeout(()=>{Rr.current=null,nr.current=!1,Tr("[swiper:touch-guard-clear]",{reason:R})},KN)},[An,Tr]),kn=b.useCallback((R,F={})=>{const q=Ue.current,se=rt.current,Ee=En.current;if(!q||Ee.length===0||se<0||se>=Ee.length)return;if(nr.current){Tr("[swiper:sync-skip-touch]",{reason:R});return}if(q.animating){Tr("[swiper:sync-skip-animating]",{reason:R});return}const We=Q1(q),mt=Ff(q,se),et=We!==null&&mt!==null&&Math.abs(We-mt)<=Qv,dr=q.activeIndex===se;if(Tr("[swiper:sync-check]",{reason:R,activeIndexAligned:dr,translateAligned:et,immediate:F.immediate===!0}),!(dr&&et)){if(dr){Qh(q,se),Tr("[swiper:sync-forced-active]",{reason:R,translateAligned:et,immediate:F.immediate===!0});return}F.immediate?(Qh(q,se),q.slideTo(se,0,!1),Qh(q,se)):q.slideTo(se,D1,!1),Tr("[swiper:sync-applied]",{reason:R,activeIndexAligned:dr,translateAligned:et,immediate:F.immediate===!0})}},[Tr]);b.useEffect(()=>{const R=F=>{const q=F;Ue.current&&(Ue.current.allowTouchMove=!q.detail.locked),Tr("[swiper:gesture-lock]",{locked:q.detail.locked})};return document.addEventListener("termdock:gesture-lock",R),()=>document.removeEventListener("termdock:gesture-lock",R)},[Tr]),b.useEffect(()=>{if(H.length===0){oe!==null&&be(null);return}if(!oe){if(!m)return;be(Dh({prioritySessionId:tr,activeSessionId:null,persistedActiveSessionId:K,firstSessionId:H[0]?.id??null}));return}H.some(F=>F.id===oe)||be(H[0].id)},[H,oe,m,tr,K]);const Cn=b.useCallback((R,F)=>{if(F&&Date.now()<ht.current){ke.current[R]=!1;return}ke.current[R]=F,ot(q=>F?R:q===R?null:q)},[]),wr=b.useCallback(R=>{if(!nr.current&&R.activeIndex!==rt.current){Tr("[swiper:slide-change-ignored-layout]",{instanceActiveIndex:R.activeIndex,expectedActiveIndex:rt.current}),requestAnimationFrame(()=>kn("ignored-layout-slide-change",{immediate:!0}));return}const F=En.current[R.activeIndex],q=F?.sessions.some(We=>We.id===oe)?oe:F?.sessions[0]?.id;if(Tr("[swiper:slide-change]",{nextSessionId:q??null,instanceActiveIndex:R.activeIndex}),!q||q===oe)return;const se=!!oe&&ke.current[oe]===!0,Ee=Lt.current&&(!Tt.current||se);if(Gr.current=q,be(q),Ee){ae({sessionId:q,token:Date.now()});return}ae(null)},[H,oe,Tr,kn]);b.useLayoutEffect(()=>{if(Gr.current===oe){Tr("[swiper:sync-skip-swiper-driven]",{activeSessionId:oe}),Gr.current=null;return}kn("active-session-index",{immediate:!0})},[oe,bn,H.length,kn,Tr]),b.useEffect(()=>{const R=Ue.current;if(!R)return;const F=Ar.length>1&&!mr&&!Xe;R.allowTouchMove!==F&&(R.allowTouchMove=F,Tr("[swiper:allow-touch-sync]",{nextAllow:F,sidebarOverlayOpen:mr}))},[Ar.length,Tr,mr,Xe]);const ps=b.useCallback(R=>{const F=Ue.current;if(!F)return;const q=F.el;if(Tr("[swiper:layout-before]",{reason:R,scrollLeft:q?.scrollLeft??null}),q&&(q.scrollLeft=0),F.updateSize(),F.updateSlides(),F.updateProgress(),F.updateSlidesClasses(),q&&(q.scrollLeft=0),Tr("[swiper:layout-after]",{reason:R,scrollLeft:q?.scrollLeft??null}),nr.current||F.animating){Tr("[swiper:layout-skip-sync-motion]",{reason:R});return}kn(`layout:${R}`,{immediate:!0}),requestAnimationFrame(()=>{const se=Ue.current;se&&(nr.current||se.animating||Qh(se,rt.current))})},[Tr,kn]);b.useEffect(()=>()=>An(),[An]);const Ks=Ar.map(R=>R.key).join("\0");b.useEffect(()=>{requestAnimationFrame(()=>ps("group-change"))},[Jr,Ks,ps]),b.useEffect(()=>{let R=null,F="mount";const q=et=>{F=et,R===null&&(R=requestAnimationFrame(()=>{R=null,ps(`viewport-change:${F}`)}))},se=()=>q("window-resize"),Ee=()=>q("visual-viewport-resize"),We=()=>q("visual-viewport-scroll"),mt=et=>{q(`measured:${et.detail?.source??"unknown"}`)};return window.addEventListener("resize",se),window.visualViewport?.addEventListener("resize",Ee),window.visualViewport?.addEventListener("scroll",We),document.addEventListener(jx,mt),q("mount"),()=>{window.removeEventListener("resize",se),window.visualViewport?.removeEventListener("resize",Ee),window.visualViewport?.removeEventListener("scroll",We),document.removeEventListener(jx,mt),R!==null&&cancelAnimationFrame(R)}},[ps]),b.useEffect(()=>{if(typeof document>"u")return;let R=null,F=null;const q=dr=>{if(dr!=="online"&&document.hidden)return;const Wn=performance.now();if(!SN(F,Wn))return;F=Wn;const Gt=dr==="bfcache"||dr==="online"?dr:"visibility",zr=CN();Up(),Ba("info","PWA_RESUME scheduled",{source:dr,forceForegroundReconnect:zr,activeSessionId:Ft.current}),Pe(_r=>({token:_r.token+1,reason:Gt,forceForegroundReconnect:zr})),requestAnimationFrame(()=>ps(`resume:${dr}:raf`)),R&&clearTimeout(R),R=setTimeout(()=>{R=null,ps(`resume:${dr}:settled`)},320)},se=()=>{if(document.hidden){Up();return}q("visibility")},Ee=()=>{Up()},We=dr=>{q(dr.persisted?"bfcache":"pageshow")},mt=()=>q("online"),et=()=>q("focus");return document.addEventListener("visibilitychange",se),window.addEventListener("pagehide",Ee),window.addEventListener("pageshow",We),window.addEventListener("online",mt),window.addEventListener("focus",et),()=>{document.removeEventListener("visibilitychange",se),window.removeEventListener("pagehide",Ee),window.removeEventListener("pageshow",We),window.removeEventListener("online",mt),window.removeEventListener("focus",et),R&&clearTimeout(R)}},[ps]),b.useLayoutEffect(()=>{if(!wN(he))return;const R=nR(H),F=JSON.stringify(R);R.length>0&&F!==ft.current?(ft.current=F,console.warn("[session-invariant] duplicate mapping detected",R)):R.length===0&&ft.current&&(ft.current=""),N?.({sessions:H.map(q=>({id:q.id,name:q.name,customName:q.customName,mode:q.mode,tmuxSessionName:q.tmuxSessionName})),activeSessionId:oe,splitWorkspaces:pe.map(({id:q,name:se,sessionIds:Ee,layout:We})=>({id:q,...se?{name:se}:{},sessionIds:Ee,layout:We}))})},[H,oe,pe,N,he]),b.useEffect(()=>{if(Xr||_e.current)return;_e.current=!0;const R=Am(Cr.map(We=>({id:We.sessionId,backendSessionId:We.backendSessionId??null})),f),F=C5(Cr,yr),q=Dh({prioritySessionId:m?R:null,activeSessionId:null,persistedActiveSessionId:F,firstSessionId:Cr[0]?.sessionId??null}),se=Ov(Cr.map(Fv));if(Z("[Session] Restoring",se.length,"persisted sessions (one-shot)"),Tr("[swiper:restore-start]",{persistedSessionIds:Cr.map(We=>We.sessionId),nextActiveSessionId:q}),se.length>0){const We=Hr.getState();se.forEach(et=>{et.sessionId&&We.setTerminalSession(et.id,{sessionId:et.sessionId,cols:80,rows:24,mode:et.mode,tmuxSessionName:et.tmuxSessionName,history:et.history})}),Cr.forEach(et=>{et.agent!==void 0&&We.setSessionAgentIdentity(et.sessionId,et.agent),et.activeProgram!=null&&We.setSessionActiveProgram(et.sessionId,et.activeProgram),et.cwd!=null&&We.setSessionCwd(et.sessionId,et.cwd),et.shellTitle!=null&&We.setSessionShellTitle(et.sessionId,et.shellTitle)}),ye(se);const mt=q||se[0]?.id||null;be(mt),Tr("[swiper:restore-complete]",{restoredSessionIds:se.map(et=>et.id),nextActiveSessionId:mt})}(async()=>(se.length===0&&await Oe.current?.({createIfEmpty:!0}),Qe(!1),requestAnimationFrame(()=>kn("restore-finished",{immediate:!0}))))()},[Xr,Cr,yr,Z,Tr,kn,m,f]),b.useEffect(()=>{if(!m||he||H.length===0)return;const R=Am(H.map(q=>({id:q.id,backendSessionId:q.sessionId})),f),F=Dh({prioritySessionId:R,activeSessionId:Ft.current,persistedActiveSessionId:K,firstSessionId:H[0]?.id??null});F&&F!==Ft.current&&be(F)},[m,f,he,K,H]);const rs=b.useRef([]),on=b.useRef(!1);Ft.current=oe,b.useEffect(()=>{if(he)return;const R=rs.current,F=Cr,q=new Map(R.map(Gt=>[Gt.sessionId,Gt])),se=Hr.getState();for(const Gt of F){const zr=q.get(Gt.sessionId),_r=Hr.getState().sessions.get(Gt.sessionId);Gt.agent!==void 0&&JSON.stringify(Gt.agent)!==JSON.stringify(_r?.agent)&&(_r?.agent==null||JSON.stringify(Gt.agent)!==JSON.stringify(zr?.agent))&&se.setSessionAgentIdentity(Gt.sessionId,Gt.agent),Gt.activeProgram!=null&&Gt.activeProgram!==_r?.activeProgram&&(_r?.activeProgram==null||Gt.activeProgram!==zr?.activeProgram)&&se.setSessionActiveProgram(Gt.sessionId,Gt.activeProgram),Gt.cwd!=null&&Gt.cwd!==_r?.cwd&&(_r?.cwd==null||Gt.cwd!==zr?.cwd)&&se.setSessionCwd(Gt.sessionId,Gt.cwd),Gt.shellTitle!=null&&Gt.shellTitle!==_r?.shellTitle&&(_r?.shellTitle==null||Gt.shellTitle!==zr?.shellTitle)&&se.setSessionShellTitle(Gt.sessionId,Gt.shellTitle)}if(!on.current){ye(Gt=>S5(Gt,F)),rs.current=F,on.current=!0;return}const Ee=new Set(R.map(Gt=>Gt.sessionId)),We=new Set(F.map(Gt=>Gt.sessionId)),mt=new Map(R.map(Gt=>[Gt.sessionId,Gt.name]));rs.current=F,ye(Gt=>{const zr=S5(Gt,F);return(!Ft.current||!zr.some(_r=>_r.id===Ft.current))&&be(zr[0]?.id??null),zr});const et=F.filter(Gt=>!Ee.has(Gt.sessionId)),dr=[...Ee].filter(Gt=>!We.has(Gt)),Wn=F.filter(Gt=>Ee.has(Gt.sessionId)&&mt.get(Gt.sessionId)!==Gt.name);(et.length>0||dr.length>0||Wn.length>0)&&Z("[Session] Synced persisted sessions:",{newSessionIds:et.map(Gt=>Gt.sessionId),removedSessionIds:dr,renamedSessionIds:Wn.map(Gt=>Gt.sessionId),currentSessionIds:F.map(Gt=>Gt.sessionId)});for(const Gt of F){if(!Gt.backendSessionId)continue;Hr.getState().setTerminalSession(Gt.sessionId,{sessionId:Gt.backendSessionId,cols:80,rows:24,mode:Gt.mode,tmuxSessionName:Gt.tmuxSessionName})}},[Cr,he,Z]);const Hn=b.useCallback(async R=>{const F=++qe.current,q=Ce.current,se=()=>F===qe.current&&q===Ce.current&&(R?.shouldActivate?.()??!0);try{const Ee=Yt.getState(),We=oe?{rightOpen:Ee.rightOpen,rightPinned:Ee.rightPinned,rightSidebarWidth:Ee.rightSidebarWidth,rightTab:Ee.rightTab}:null,mt=R?.mode==="tmux"||R?.mode==="shell"?R.mode:l,et=(R?.tmuxSessionName||"").trim(),dr=d.trim(),Wn=mt==="tmux"?et||dr||aR():null,Gt=typeof R?.cwd=="string"?R.cwd:null,zr=oe?Hr.getState().sessions.get(oe)?.cwd??null:null,_r=typeof Gt=="string"&&Gt.trim().length>0?Gt:typeof zr=="string"&&zr.trim().length>0?zr:void 0,Xn=await Bn({preferredFrontendSessionId:R?.preferredFrontendSessionId,requireExisting:R?.requireExisting===!0,mode:mt,tmuxSessionName:Wn,cwd:_r,termType:"xterm-256color",createIfEmpty:R?.createIfEmpty===!0},{shouldActivate:se});if(Xn.discarded)return R?.onResult?.({ok:!1,error:"unknown"}),null;const ms=Xn.session,dn=Xn.terminalSession;!Xn.reused&&We&&Yt.getState().initializeRightSidebarForSession(ms.sessionId,dn.cwd??_r??null,We);const pr={id:ms.sessionId,name:ms.name,customName:ms.customName===!0,sessionId:dn.sessionId,mode:dn.mode??ms.mode,tmuxSessionName:dn.tmuxSessionName??ms.tmuxSessionName},ar=R?.command?.trim();return ar&&xe.current.set(pr.id,{backendSessionId:dn.sessionId,command:ar}),ye(ls=>sR(ls,pr)),se()&&be(pr.id),Hr.getState().setTerminalSession(pr.id,{sessionId:dn.sessionId,cols:80,rows:24,mode:pr.mode,tmuxSessionName:pr.tmuxSessionName,activeProgram:dn.activeProgram,activeProgramRaw:dn.activeProgramRaw,activeProgramSource:dn.activeProgramSource,cwd:dn.cwd}),Z("[Session] Inventory opened session:",{frontendSessionId:pr.id,backendSessionId:dn.sessionId,reused:Xn.reused,mode:pr.mode,tmuxSessionName:pr.tmuxSessionName}),R?.onResult?.({ok:!0,sessionId:pr.id}),pr.id}catch(Ee){return console.error("[Session] Failed to create new session:",Ee),R?.onResult?.({ok:!1,error:IC(Ee)}),null}},[l,d,oe,Bn,Z]);Oe.current=Hn;const Fr=b.useCallback((R,F={})=>{Ce.current+=1,os.getState().setActivePane(R);const q=Ft.current,se=!!q&&ke.current[q]===!0;if(be(R),Tt.current&&F.preserveMobileKeyboard===!1){ht.current=Date.now()+600,q&&(ke.current[q]=!1),ot(null),ae(null);const Ee=document.activeElement;Ee instanceof HTMLTextAreaElement&&Ee.closest(".terminal-viewport-container")&&Ee.blur();return}se&&Tt.current&&ot(R),Lt.current&&(!Tt.current||se)&&ae({sessionId:R,token:Date.now()})},[]),$r=b.useCallback(R=>{be(R),Ut(!0),jt(null)},[]),pn=b.useCallback(R=>{const F=Ft.current;!F||F===R||($e(q=>Sm(q,F,R)),Ut(!1),Fr(F,{preserveMobileKeyboard:!1}))},[Fr]),W=b.useCallback(async()=>{const R=Ft.current;if(!R||X)return;const F=Ce.current;vt(!0);const q=Hr.getState().sessions.get(R)?.cwd??void 0,se=await Hn({cwd:q||void 0,mode:l,shouldActivate:()=>!1});if(vt(!1),!se){jt(Q("common.error"));return}!Nt.current||F!==Ce.current||!gt.current.some(Ee=>Ee.id===R)||($e(Ee=>Sm(Ee,R,se)),Ut(!1),Fr(R,{preserveMobileKeyboard:!1}))},[Fr,l,Hn,X,Q]),Re=b.useCallback(R=>{$e(F=>qN(F,R)),R&&Fr(R,{preserveMobileKeyboard:!1})},[Fr]),Ke=b.useCallback(R=>{$e(F=>VN(F,R)),Fr(R,{preserveMobileKeyboard:!1})},[Fr]),lt=b.useCallback(R=>{if(H.find(q=>q.id===R)){if(Ce.current+=1,os.getState().setActivePane(R),R===Ft.current)return;if(be(R),!bN({isMobile:Tt.current,viewportReady:le.has(R),streamReady:Fe.has(R),contentReady:He.has(R)})){st(null),Lt.current&&ae({sessionId:R,token:Date.now()}),Z("[Session] Switched to session:",R);return}it(se=>{if(se.has(R))return se;const Ee=new Set(se);return Ee.add(R),Ee}),st(R),Z("[Session] Switched to session:",R)}},[He,Z,Fe,H,le]),ut=b.useCallback((R,F)=>{F.trim()&&(ye(q=>q.map(se=>se.id===R?{...se,name:F.trim(),customName:!0}:se)),gn(R,F.trim()))},[gn]),It=b.useCallback(R=>{ye(F=>F.map(q=>q.id===R?{...q,customName:!1}:q)),an(R)},[an]),_t=b.useCallback(R=>{ye(F=>{const q=new Map(F.map(mt=>[mt.id,mt])),se=R.map(mt=>q.get(mt)).filter(mt=>mt!==void 0),Ee=new Set(R),We=F.filter(mt=>!Ee.has(mt.id));return[...se,...We]}),ne(R),Z("[Session] Reordered sessions:",R),requestAnimationFrame(()=>{Ue.current?.update()})},[ne,Z]),Qt=b.useCallback(async R=>{const F=typeof R=="string"?R:R.sessionId,q=typeof R=="string"?"auto":R.closeMode??"auto",se=H.find(et=>et.id===F);if(!se||ir.current.has(F))return;ir.current.add(F),Ce.current+=1;const Ee=Dx(fn,F,et=>et.id);try{q==="destroy"&&se.mode==="tmux"&&se.tmuxSessionName?(await e3(se.tmuxSessionName),Z("[Session] Destroyed tmux session:",{frontendSessionId:se.id,tmuxSessionName:se.tmuxSessionName})):se.sessionId&&(await Zy(se.sessionId),Z("[Session] Closed backend terminal:",se.sessionId))}catch(et){console.error("[Session] Failed to close backend terminal:",et),Rt({sessionId:F,closeMode:q});return}finally{ir.current.delete(F)}Rt(et=>et?.sessionId===F?null:et);const mt=gt.current.filter(et=>et.id!==F).some(et=>et.id===Ee)?Ee:Dx(gt.current,F,et=>et.id);Ft.current===F&&be(mt),ye(et=>et.filter(dr=>dr.id!==F)),hn(F,mt),delete ke.current[F],Z("[Session] Closed session:",{sessionId:F,closeMode:q})},[H,fn,hn,Z]),xt=b.useCallback(R=>{if(!R)return;const F=H.filter(q=>q.sessionId===R);if(F.length!==0){F.length>1&&console.warn("[session-invariant] backend matched multiple frontend sessions during cleanup",{backendSessionId:R,frontendSessionIds:F.map(q=>q.id)}),ye(q=>{const se=q.filter(Ee=>Ee.sessionId!==R);return se.length!==q.length&&!se.some(We=>We.id===oe)&&be(se.length>0?se[0].id:null),se});for(const q of F)hn(q.id),delete ke.current[q.id];Z("[Session] Backend gone, dropped local session(s):",F.map(q=>q.id))}},[H,oe,hn,Z]);b.useEffect(()=>{const R=pr=>{Hn(pr.detail)},F=pr=>{lt(pr.detail)},q=()=>{const pr=Ft.current;!pr||Tt.current||ae({sessionId:pr,token:Date.now()})},se=pr=>{const ar=pr;ar.detail&&$r(ar.detail)},Ee=pr=>{const ar=pr.detail;Re(ar??Ft.current??void 0)},We=pr=>{const ar=pr.detail;ar&&Ke(ar)},mt=pr=>{const ar=pr.detail,Fn=typeof ar=="string"?ar:ar?.layout,ls=typeof ar=="string"?Ft.current:ar?.sessionId;Fn!=="horizontal"&&Fn!=="vertical"&&Fn!=="grid"||$e(ya=>ya.map(Jn=>Jn.sessionIds.includes(ls??"")?{...Jn,layout:Fn}:Jn))},et=pr=>{const Fn=pr.detail?.direction;if(Fn!=="prev"&&Fn!=="next")return;const ls=Ss.current;if(ls.length<=1)return;const ya=Ft.current,Jn=ya?ls.findIndex(Tl=>Tl.id===ya):-1,Pa=((Jn>=0?Jn:0)+(Fn==="next"?1:-1)+ls.length)%ls.length,li=ls[Pa]?.id;li&&li!==ya&&lt(li)},dr=pr=>{Qt(pr.detail)},Wn=pr=>{xt(pr.detail)},Gt=pr=>{const ar=pr;!ar.detail?.sessionId||!ar.detail?.name||ut(ar.detail.sessionId,ar.detail.name)},zr=pr=>{const ar=pr;ar.detail?.sessionId&&It(ar.detail.sessionId)},_r=pr=>{const ar=pr;ar.detail?.sessionIds&&_t(ar.detail.sessionIds)},Xn=pr=>{const ar=pr.detail;!ar?.workspaceId||!Array.isArray(ar.sessionIds)||$e(Fn=>YN(Fn,ar.workspaceId,ar.sessionIds))},ms=pr=>{const ar=pr.detail;!ar?.workspaceId||typeof ar.name!="string"||$e(Fn=>ZN(Fn,ar.workspaceId,ar.name))},dn=pr=>{const ar=pr.detail;!ar?.primaryId||!ar.secondaryId||ar.primaryId===ar.secondaryId||($e(Fn=>Sm(Fn,ar.primaryId,ar.secondaryId)),Fr(ar.primaryId,{preserveMobileKeyboard:!1}))};return window.addEventListener("new-terminal-session",R),window.addEventListener("switch-terminal-session",F),window.addEventListener("focus-active-terminal-session",q),window.addEventListener("open-terminal-split-chooser",se),window.addEventListener("close-terminal-split",Ee),window.addEventListener("remove-terminal-split-pane",We),window.addEventListener("set-terminal-split-direction",mt),window.addEventListener("cycle-terminal-session",et),window.addEventListener("close-terminal-session",dr),window.addEventListener("close-terminal-session-by-backend",Wn),window.addEventListener("rename-terminal-session",Gt),window.addEventListener("reset-terminal-session-name",zr),window.addEventListener("reorder-terminal-session",_r),window.addEventListener("reorder-terminal-split-workspace",Xn),window.addEventListener("rename-terminal-split-workspace",ms),window.addEventListener("combine-terminal-split-sessions",dn),()=>{window.removeEventListener("new-terminal-session",R),window.removeEventListener("switch-terminal-session",F),window.removeEventListener("focus-active-terminal-session",q),window.removeEventListener("open-terminal-split-chooser",se),window.removeEventListener("close-terminal-split",Ee),window.removeEventListener("remove-terminal-split-pane",We),window.removeEventListener("set-terminal-split-direction",mt),window.removeEventListener("cycle-terminal-session",et),window.removeEventListener("close-terminal-session",dr),window.removeEventListener("close-terminal-session-by-backend",Wn),window.removeEventListener("rename-terminal-session",Gt),window.removeEventListener("reset-terminal-session-name",zr),window.removeEventListener("reorder-terminal-session",_r),window.removeEventListener("reorder-terminal-split-workspace",Xn),window.removeEventListener("rename-terminal-split-workspace",ms),window.removeEventListener("combine-terminal-split-sessions",dn)}},[Fr,Hn,lt,$r,Re,Ke,Qt,xt,ut,It,_t]),b.useEffect(()=>{if(!qr||Bt)return;const R=F=>{if(!zC(F,og())||!(F.ctrlKey||F.metaKey)||!F.shiftKey)return;if(qr.layout==="horizontal"?F.key==="ArrowLeft"||F.key==="ArrowRight":qr.layout==="vertical"?F.key==="ArrowUp"||F.key==="ArrowDown":F.key.startsWith("Arrow")){F.preventDefault(),F.stopPropagation();const se=qr.sessionIds.indexOf(Ft.current??""),Ee=F.key==="ArrowLeft"||F.key==="ArrowUp"?-1:1,We=(Math.max(0,se)+Ee+qr.sessionIds.length)%qr.sessionIds.length,mt=qr.sessionIds[We];if(!mt)return;Fr(mt);return}F.key==="Backspace"&&(F.preventDefault(),F.stopPropagation(),Re(Ft.current??void 0))};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[Fr,qr,Re,Bt]);const Pt=R=>{const F=Hr.getState().sessions.get(R.id);return xl(R,F?.activeProgram??null,F?.cwd??null,void 0,F?.shellTitle??null,F?.promptState??null)},z=(R,F={})=>{const q=R.id===oe&&!ve?.startsWith("@collaboration:"),se=Lr.has(R.id)&&!F.hidden,Ee=m&&xN({sessionId:R.id,foregroundSessionId:De,visibleSessionIds:Lr,deferredViewportSessionIds:Bt?jr:Pn}),We=gN({sessionId:R.id,foregroundSessionId:De,foregroundReady:vr,isVisible:se})&&m,mt=AN({sessionId:R.id,foregroundSessionId:De,requestToken:ie.token,foregroundCompletedToken:Pr,isVisible:Dt.has(R.id)})&&m,et=se||R.id===De||Pn.has(R.id)?0:Mt.get(R.id)??ff;return s.jsxs("div",{className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden ${F.hidden?"invisible pointer-events-none":""}`,style:F.containerStyle,"aria-hidden":F.hidden||void 0,onPointerDownCapture:()=>{se&&A5(q,()=>Fr(R.id))},onWheelCapture:()=>{A5(q,()=>Fr(R.id))},children:[F.showPaneTitle&&s.jsx($N,{session:R,active:q,onActivate:()=>Fr(R.id),onToggleRightSidebar:q?y:void 0}),s.jsx("div",{className:"min-h-0 flex-1 app-chrome-bg",children:Ee&&s.jsx(FN,{sessionId:R.id,mode:R.mode,tmuxSessionName:R.tmuxSessionName,terminalSettings:e,colorTheme:t,toolbarPresets:r,isActive:q,focusSuspended:!a||Y!==null,allowOwnedPasteWhileFocusSuspended:c&&Y===null,deferCursorUntilPositioned:Y===R.id||R.mode==="tmux"&&!He.has(R.id),isLayoutVisible:se,initialConnectEnabled:We&&mt,resumeRequestEnabled:mt,suppressKeyboard:F.suppressKeyboard,keyboardPortalTarget:F.keyboardPortalTarget,sharedMobileKeyboardLayout:F.sharedMobileKeyboardLayout,suppressPageFlipRefresh:F.suppressPageFlipRefresh,focusRequestToken:V?.sessionId===R.id?V.token:0,resumeRequestToken:ie.token,resumeRequestReason:ie.reason,forceResumeReconnect:ie.forceForegroundReconnect&&Dt.has(R.id),resumeRequestDelayMs:Dt.has(R.id)?0:F.hidden?ff:Mt.get(R.id)??ff,initialConnectDelayMs:et,onStreamReadyChange:xn,onStreamConnected:Kn,onViewportReadyChange:Cs,onContentReadyChange:ws,onKeyboardVisibilityChange:Cn,showDebug:n,onStatusChange:q?I:void 0})})]},R.id)};return s.jsxs("div",{className:"relative h-full flex flex-col",children:[Xt&&H.some(R=>R.id===Xt.sessionId)&&s.jsxs("div",{role:"alert",className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto flex max-w-lg items-center gap-3 rounded-xl border border-destructive/30 bg-surface-elevated px-4 py-3 text-[12px] text-foreground shadow-lg",children:[s.jsx("span",{className:"min-w-0 flex-1",children:Q("tab.closeFailed",{name:H.find(R=>R.id===Xt.sessionId).name})}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg px-2 py-1 text-primary hover:bg-surface-2",onClick:()=>{Qt(Xt)},children:Q("common.retry")}),s.jsx("button",{type:"button",className:"shrink-0 rounded-lg p-1 hover:bg-surface-2","aria-label":Q("common.close"),onClick:()=>Rt(null),children:s.jsx(jn,{size:16})})]}),St&&s.jsx("section",{className:"fixed inset-x-3 top-[calc(var(--safe-top-inset)+0.75rem)] z-toast mx-auto max-w-lg rounded-2xl border border-warning/30 bg-surface-elevated px-4 py-3.5 shadow-[0_20px_60px_var(--app-shadow-strong)]",role:"alert","aria-live":"assertive",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning",children:s.jsx(cg,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[13px] font-semibold text-foreground",children:Q("tab.tmuxRecoveryTitle",{count:St.sessions.length})}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:Q("tab.tmuxRecoveryHint")}),s.jsx("p",{className:"mt-1.5 truncate text-[10px] text-foreground/70",children:St.sessions.map(R=>R.name).join(" · ")}),St.operation&&s.jsxs("div",{className:"mt-2 rounded-lg bg-surface-2 px-2.5 py-2 text-[10px] text-muted-foreground","aria-live":"polite",children:[s.jsx("p",{children:Q("tab.tmuxRecoveryProgress",{total:St.operation.total,queued:St.operation.queued,paused:St.operation.paused_count,resourceWait:St.operation.resource_wait,running:St.operation.running,succeeded:St.operation.succeeded,failed:St.operation.failed})}),St.operation.pauseReason==="resources"&&s.jsx("p",{className:"mt-1",children:Q("tab.tmuxRecoveryPausedForResources")}),s.jsx("div",{className:"mt-1 max-h-24 overflow-y-auto",children:St.operation.items.map(R=>s.jsxs("p",{className:`mt-1 ${R.errorCode?"text-destructive":""}`,children:[R.sessionId,": ",R.errorCode??R.resourceWaitReason??R.phase,R.memAvailableBytes!==void 0?` · 可用内存 ${(R.memAvailableBytes/1024**3).toFixed(1)} GiB`:"",R.actualRssBytes!==void 0?` · 实际 RSS ${(R.actualRssBytes/1024**2).toFixed(0)} MiB`:"",R.estimatedRssBytes!==void 0&&R.actualRssBytes===void 0?` · 预估 RSS ${(R.estimatedRssBytes/1024**2).toFixed(0)} MiB`:""]},R.sessionId))})]}),at&&s.jsx("p",{className:"mt-2 text-[10px] text-destructive",children:at}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:ge!==null||!!(St.operation&&!["succeeded","partial_failure"].includes(St.operation.state)),onClick:()=>{Jt()},className:"inline-flex min-h-9 items-center gap-1.5 rounded-lg bg-primary px-3 text-[11px] font-medium text-primary-foreground transition active:opacity-80 disabled:opacity-50",children:[s.jsx(b3,{size:13,className:ge==="restore"?"animate-spin":""}),ge==="restore"?Q("tab.tmuxRecoveryRestoring"):St.operation&&!["succeeded","partial_failure"].includes(St.operation.state)?Q("tab.tmuxRecoveryInProgress"):Q("tab.tmuxRecoveryRestoreAll")]}),St.operation&&["queued","resource_wait","running","paused"].includes(St.operation.state)&&s.jsx("button",{type:"button",disabled:ge!==null,onClick:()=>{Or()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 disabled:opacity-50",children:St.operation.paused?Q("tab.tmuxRecoveryResume"):Q("tab.tmuxRecoveryPause")}),s.jsx("button",{type:"button",disabled:ge!==null||!!(St.operation&&!MC(St.operation)),onClick:()=>{un()},className:"inline-flex min-h-9 items-center rounded-lg px-3 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-50",children:Q("tab.tmuxRecoveryDismiss")})]})]})]})}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(jA,{onSwiper:R=>{Ue.current=R,R.allowTouchMove=Ar.length>1&&!mr&&!Xe,Tr("[swiper:on-swiper]",{allowTouchMove:R.allowTouchMove}),requestAnimationFrame(()=>ps("on-swiper"))},onSlideChange:wr,onTouchStart:(R,F)=>{const q=_5(F),se=q==="touch"||q==="pen"||q==="unknown";J("[swipe:touch-start]",{pointerType:q,allowed:se}),Tr("[swiper:touch-start]",{pointerType:q,allowed:se}),se&&(An(),ur.current=!0,nr.current=!0)},onTouchEnd:(R,F)=>{const q=_5(F),se=q==="touch"||q==="pen"||q==="unknown";J("[swipe:touch-end]",{pointerType:q,allowed:se}),Tr("[swiper:touch-end]",{pointerType:q,allowed:se}),se&&(ur.current=!1,rr("touch-end"))},onTransitionEnd:()=>{const R=Ue.current;if(ur.current){Tr("[swiper:transition-end-during-touch]");return}if(nr.current&&R&&!rR(R,rt.current)){Tr("[swiper:transition-end-deferred]");return}An(),nr.current=!1,Tr("[swiper:transition-end]")},initialSlide:Math.max(0,bn),speed:D1,slidesPerView:1,resistanceRatio:.82,threshold:8,longSwipesRatio:.2,touchAngle:45,touchStartPreventDefault:!1,simulateTouch:!1,noSwiping:!0,noSwipingSelector:"[data-mobile-keyboard='true']",className:"terminal-session-swiper h-full",children:Ar.map(R=>{const F=R.workspace,q=!!F&&R.sessions.length>=2,se=Bt?Dr?"horizontal":"vertical":F?.layout??"horizontal",Ee=Bt&&er?R.sessions.some(mt=>mt.id===er):!1,We=R.sessions.some(mt=>mt.id===oe)?oe:R.sessions[0]?.id;return s.jsx(DA,{className:"h-full",children:s.jsx("div",{className:"h-full min-w-0","data-pinned-right-sidebar-inset":On.get(R.key)??0,style:{paddingRight:On.get(R.key)??0,paddingTop:w&&!q?"2.5rem":void 0},children:q?s.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col bg-[var(--chrome-bg)]",style:Bt?{transform:"translateY(var(--kb-translate-y, 0px))",transition:"none"}:void 0,children:[U&&!Bt&&s.jsx("header",{"data-termdock-window-header":"true","data-split-window-header":"true",className:"flex h-[46px] min-h-[46px] shrink-0 items-center app-chrome-bg pl-[88px] pr-3 text-[12px] text-muted-foreground",children:s.jsx("span",{className:"min-w-0 truncate",children:F?.name||Q("tab.splitWorkspace")})}),s.jsx(Yx,{layoutId:R.key,preset:F?.layout??"horizontal",initialTree:BC(R.sessions.map(mt=>mt.id),se,F?.ratios,F?.gridColumnRatios,F?.gridRowRatios),mobile:Bt,focusId:Ee?er:null,panes:R.sessions.map(mt=>({id:mt.id,content:z(mt,{showPaneTitle:!Bt,suppressKeyboard:Bt&&mt.id!==We,keyboardPortalTarget:Bt?At:null,sharedMobileKeyboardLayout:Bt,suppressPageFlipRefresh:!0})}))}),Bt&&s.jsx("div",{ref:Ot,className:"relative shrink-0 app-chrome-bg","data-split-keyboard-host":"true"})]}):s.jsx(Yx,{layoutId:R.key,preset:F?.layout??"horizontal",mobile:Bt,panes:[{id:R.sessions[0].id,content:z(R.sessions[0])}]})})},R.key)})})}),Xe&&oe&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>Ut(!1),"aria-label":Q("common.close")}),s.jsxs("section",{ref:qt,tabIndex:-1,className:"fixed inset-x-3 bottom-3 z-modal-panel mx-auto max-h-[min(78svh,620px)] max-w-md overflow-hidden rounded-2xl border border-border/20 bg-surface shadow-[0_24px_70px_var(--app-shadow-strong)] sm:bottom-auto sm:top-1/2 sm:-translate-y-1/2",style:{paddingBottom:"var(--safe-bottom-inset)"},role:"dialog","aria-modal":"true","aria-label":Q("tab.splitTitle"),children:[s.jsxs("header",{className:"flex items-start gap-3 border-b border-border/20 px-4 py-3.5",children:[s.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx($l,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground",children:Q("tab.splitTitle")}),s.jsx("p",{className:"mt-0.5 text-[11px] leading-relaxed text-muted-foreground",children:Q("tab.splitExistingHint")})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",onClick:()=>Ut(!1),"aria-label":Q("common.close"),children:s.jsx(jn,{size:16})})]}),s.jsxs("div",{className:"max-h-[calc(min(78svh,620px)-72px)] overflow-y-auto overscroll-contain p-2",children:[s.jsxs("button",{type:"button",disabled:X,onClick:()=>{W()},className:"flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition hover:bg-surface-2 active:bg-surface-elevated disabled:opacity-60",children:[s.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary",children:s.jsx(Ys,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-[13px] font-medium text-foreground",children:Q("tab.splitNew")}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-muted-foreground",children:Q("tab.splitNewHint")})]})]}),pe.filter(R=>R.id!==qr?.id).length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:Q("tab.splitExistingGroups")}),pe.filter(R=>R.id!==qr?.id).map((R,F)=>{const q=R.sessionIds.flatMap(We=>{const mt=H.find(et=>et.id===We);return mt?[mt]:[]});if(q.length<2)return null;const se=R.name||`${Q("tab.splitWorkspace")} ${F+1}`,Ee=q.map(We=>Pt(We).primary).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>pn(q[0].id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:s.jsx($l,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium text-foreground",children:se}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:Q("tab.splitOccupied")})]}),s.jsxs("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:[Q("tab.sessionCount",{count:q.length})," · ",Ee]})]}),s.jsx(oi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]}),s.jsx("div",{className:"px-3 pb-1 pt-3 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground",children:Q("tab.splitAvailableSessions")}),H.filter(R=>!pe.some(F=>F.sessionIds.includes(R.id))&&R.id!==oe).length===0&&pe.filter(R=>R.id!==qr?.id).length===0?s.jsx("p",{className:"px-3 py-4 text-[12px] text-muted-foreground",children:Q("tab.splitNoOtherSessions")}):H.filter(R=>!pe.some(F=>F.sessionIds.includes(R.id))&&R.id!==oe).map(R=>{const F=Qr.get(R.id)??null,q=Pt(R);return s.jsxs("button",{type:"button",onClick:()=>pn(R.id),className:"group flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition hover:bg-surface-2 active:bg-surface-elevated",children:[s.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground",children:F?s.jsx(nu,{size:15}):s.jsx($l,{size:15})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:q.primary}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:F?ld(F)??F:R.name})]}),s.jsx(oi,{size:14,className:"text-primary opacity-0 transition group-hover:opacity-100"})]},R.id)})]})]})]}),sr&&s.jsx("div",{className:"fixed inset-x-3 bottom-4 z-toast mx-auto max-w-md rounded-xl border border-border/20 bg-surface-elevated px-4 py-3 text-center text-[12px] text-foreground shadow-lg",children:sr})]})},lR={sm:"h-4 w-7",md:"h-6 w-10"},cR={sm:"h-3 w-3",md:"h-5 w-5"},uR={sm:"translate-x-3",md:"translate-x-4"};function vl({checked:e,disabled:t=!1,size:r="md",className:n=""}){return s.jsx("span",{"aria-hidden":"true",className:`inline-flex shrink-0 items-center rounded-full transition ${lR[r]} ${e?"bg-primary":"bg-surface-elevated"} ${t?"opacity-50":""} ${n}`,children:s.jsx("span",{className:`mx-0.5 inline-block rounded-full bg-[var(--background)] shadow transition ${cR[r]} ${e?uR[r]:""}`})})}function ga(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var dR=typeof Symbol=="function"&&Symbol.observable||"@@observable",L5=dR,I5=()=>Math.random().toString(36).substring(7).split("").join("."),hR={INIT:`@@redux/INIT${I5()}`,REPLACE:`@@redux/REPLACE${I5()}`},E5=hR;function fR(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function $v(e,t,r){if(typeof e!="function")throw new Error(ga(2));if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(ga(0));if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(ga(1));return r($v)(e,t)}let n=e,a=t,c=new Map,l=c,d=0,f=!1;function m(){l===c&&(l=new Map,c.forEach((I,N)=>{l.set(N,I)}))}function x(){if(f)throw new Error(ga(3));return a}function y(I){if(typeof I!="function")throw new Error(ga(4));if(f)throw new Error(ga(5));let N=!0;m();const P=d++;return l.set(P,I),function(){if(N){if(f)throw new Error(ga(6));N=!1,m(),l.delete(P),c=null}}}function w(I){if(!fR(I))throw new Error(ga(7));if(typeof I.type>"u")throw new Error(ga(8));if(typeof I.type!="string")throw new Error(ga(17));if(f)throw new Error(ga(9));try{f=!0,a=n(a,I)}finally{f=!1}return(c=l).forEach(P=>{P()}),I}function v(I){if(typeof I!="function")throw new Error(ga(10));n=I,w({type:E5.REPLACE})}function T(){const I=y;return{subscribe(N){if(typeof N!="object"||N===null)throw new Error(ga(11));function P(){const Q=N;Q.next&&Q.next(x())}return P(),{unsubscribe:I(P)}},[L5](){return this}}}return w({type:E5.INIT}),{dispatch:w,subscribe:y,getState:x,replaceReducer:v,[L5]:T}}function N5(e,t){return function(...r){return t(e.apply(this,r))}}function R5(e,t){if(typeof e=="function")return N5(e,t);if(typeof e!="object"||e===null)throw new Error(ga(16));const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=N5(a,t))}return r}function Uv(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function pR(...e){return t=>(r,n)=>{const a=t(r,n);let c=()=>{throw new Error(ga(15))};const l={getState:a.getState,dispatch:(f,...m)=>c(f,...m)},d=e.map(f=>f(l));return c=Uv(...d)(a.dispatch),{...a,dispatch:c}}}var _m={exports:{}},km={};var M5;function mR(){if(M5)return km;M5=1;var e=VA();function t(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&m!==m}var r=typeof Object.is=="function"?Object.is:t,n=e.useSyncExternalStore,a=e.useRef,c=e.useEffect,l=e.useMemo,d=e.useDebugValue;return km.useSyncExternalStoreWithSelector=function(f,m,x,y,w){var v=a(null);if(v.current===null){var T={hasValue:!1,value:null};v.current=T}else T=v.current;v=l(function(){function I(U){if(!N){if(N=!0,P=U,U=y(U),w!==void 0&&T.hasValue){var Z=T.value;if(w(Z,U))return $=Z}return $=U}if(Z=$,r(P,U))return Z;var J=y(U);return w!==void 0&&w(Z,J)?(P=U,Z):(P=U,$=J)}var N=!1,P,$,Q=x===void 0?null:x;return[function(){return I(m())},Q===null?void 0:function(){return I(Q())}]},[m,x,y,w]);var S=n(f,v[0],v[1]);return c(function(){T.hasValue=!0,T.value=S},[S]),d(S),S},km}var j5;function gR(){return j5||(j5=1,_m.exports=mR()),_m.exports}gR();var xR=b.version.startsWith("19"),bR=Symbol.for(xR?"react.transitional.element":"react.element"),yR=Symbol.for("react.portal"),vR=Symbol.for("react.fragment"),wR=Symbol.for("react.strict_mode"),AR=Symbol.for("react.profiler"),TR=Symbol.for("react.consumer"),SR=Symbol.for("react.context"),zv=Symbol.for("react.forward_ref"),CR=Symbol.for("react.suspense"),_R=Symbol.for("react.suspense_list"),Rg=Symbol.for("react.memo"),kR=Symbol.for("react.lazy"),LR=zv,IR=Rg;function ER(e){if(typeof e=="object"&&e!==null){const{$$typeof:t}=e;switch(t){case bR:switch(e=e.type,e){case vR:case AR:case wR:case CR:case _R:return e;default:switch(e=e&&e.$$typeof,e){case SR:case zv:case kR:case Rg:return e;case TR:return e;default:return t}}case yR:return t}}}function NR(e){return ER(e)===Rg}function RR(e,t,r,n,{areStatesEqual:a,areOwnPropsEqual:c,areStatePropsEqual:l}){let d=!1,f,m,x,y,w;function v(P,$){return f=P,m=$,x=e(f,m),y=t(n,m),w=r(x,y,m),d=!0,w}function T(){return x=e(f,m),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function S(){return e.dependsOnOwnProps&&(x=e(f,m)),t.dependsOnOwnProps&&(y=t(n,m)),w=r(x,y,m),w}function I(){const P=e(f,m),$=!l(P,x);return x=P,$&&(w=r(x,y,m)),w}function N(P,$){const Q=!c($,m),U=!a(P,f,$,m);return f=P,m=$,Q&&U?T():Q?S():U?I():w}return function($,Q){return d?N($,Q):v($,Q)}}function MR(e,{initMapStateToProps:t,initMapDispatchToProps:r,initMergeProps:n,...a}){const c=t(e,a),l=r(e,a),d=n(e,a);return RR(c,l,d,e,a)}function jR(e,t){const r={};for(const n in e){const a=e[n];typeof a=="function"&&(r[n]=(...c)=>t(a(...c)))}return r}function P1(e){return function(r){const n=e(r);function a(){return n}return a.dependsOnOwnProps=!1,a}}function D5(e){return e.dependsOnOwnProps?!!e.dependsOnOwnProps:e.length!==1}function Hv(e,t){return function(n,{displayName:a}){const c=function(d,f){return c.dependsOnOwnProps?c.mapToProps(d,f):c.mapToProps(d,void 0)};return c.dependsOnOwnProps=!0,c.mapToProps=function(d,f){c.mapToProps=e,c.dependsOnOwnProps=D5(e);let m=c(d,f);return typeof m=="function"&&(c.mapToProps=m,c.dependsOnOwnProps=D5(m),m=c(d,f)),m},c}}function Mg(e,t){return(r,n)=>{throw new Error(`Invalid value of type ${typeof e} for ${t} argument when connecting component ${n.wrappedComponentName}.`)}}function DR(e){return e&&typeof e=="object"?P1(t=>jR(e,t)):e?typeof e=="function"?Hv(e):Mg(e,"mapDispatchToProps"):P1(t=>({dispatch:t}))}function BR(e){return e?typeof e=="function"?Hv(e):Mg(e,"mapStateToProps"):P1(()=>({}))}function QR(e,t,r){return{...r,...e,...t}}function PR(e){return function(r,{displayName:n,areMergedPropsEqual:a}){let c=!1,l;return function(f,m,x){const y=e(f,m,x);return c?a(y,l)||(l=y):(c=!0,l=y),l}}}function OR(e){return e?typeof e=="function"?PR(e):Mg(e,"mergeProps"):()=>QR}function FR(e){e()}function $R(){let e=null,t=null;return{clear(){e=null,t=null},notify(){FR(()=>{let r=e;for(;r;)r.callback(),r=r.next})},get(){const r=[];let n=e;for(;n;)r.push(n),n=n.next;return r},subscribe(r){let n=!0;const a=t={callback:r,next:null,prev:t};return a.prev?a.prev.next=a:e=a,function(){!n||e===null||(n=!1,a.next?a.next.prev=a.prev:t=a.prev,a.prev?a.prev.next=a.next:e=a.next)}}}}var B5={notify(){},get:()=>[]};function Wv(e,t){let r,n=B5,a=0,c=!1;function l(S){x();const I=n.subscribe(S);let N=!1;return()=>{N||(N=!0,I(),y())}}function d(){n.notify()}function f(){T.onStateChange&&T.onStateChange()}function m(){return c}function x(){a++,r||(r=t?t.addNestedSub(f):e.subscribe(f),n=$R())}function y(){a--,r&&a===0&&(r(),r=void 0,n.clear(),n=B5)}function w(){c||(c=!0,x())}function v(){c&&(c=!1,y())}const T={addNestedSub:l,notifyNestedSubs:d,handleChangeWrapper:f,isSubscribed:m,trySubscribe:w,tryUnsubscribe:v,getListeners:()=>n};return T}var UR=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",zR=UR(),HR=()=>typeof navigator<"u"&&navigator.product==="ReactNative",WR=HR(),GR=()=>zR||WR?b.useLayoutEffect:b.useEffect,$f=GR();function Q5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function Lm(e,t){if(Q5(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let a=0;a<r.length;a++)if(!Object.prototype.hasOwnProperty.call(t,r[a])||!Q5(e[r[a]],t[r[a]]))return!1;return!0}var VR={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},qR={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},YR={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Gv={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},ZR={[LR]:YR,[IR]:Gv};function P5(e){return NR(e)?Gv:ZR[e.$$typeof]||VR}var KR=Object.defineProperty,XR=Object.getOwnPropertyNames,O5=Object.getOwnPropertySymbols,JR=Object.getOwnPropertyDescriptor,eM=Object.getPrototypeOf,F5=Object.prototype;function O1(e,t){if(typeof t!="string"){if(F5){const c=eM(t);c&&c!==F5&&O1(e,c)}let r=XR(t);O5&&(r=r.concat(O5(t)));const n=P5(e),a=P5(t);for(let c=0;c<r.length;++c){const l=r[c];if(!qR[l]&&!(a&&a[l])&&!(n&&n[l])){const d=JR(t,l);try{KR(e,l,d)}catch{}}}}return e}var tM=Symbol.for("react-redux-context"),rM=typeof globalThis<"u"?globalThis:{};function nM(){if(!b.createContext)return{};const e=rM[tM]??=new Map;let t=e.get(b.createContext);return t||(t=b.createContext(null),e.set(b.createContext,t)),t}var Vv=nM(),sM=[null,null];function iM(e,t,r){$f(()=>e(...t),r)}function aM(e,t,r,n,a,c){e.current=n,r.current=!1,a.current&&(a.current=null,c())}function oM(e,t,r,n,a,c,l,d,f,m,x){if(!e)return()=>{};let y=!1,w=null;const v=()=>{if(y||!d.current)return;const S=t.getState();let I,N;try{I=n(S,a.current)}catch(P){N=P,w=P}N||(w=null),I===c.current?l.current||m():(c.current=I,f.current=I,l.current=!0,x())};return r.onStateChange=v,r.trySubscribe(),v(),()=>{if(y=!0,r.tryUnsubscribe(),r.onStateChange=null,w)throw w}}function lM(e,t){return e===t}function cM(e,t,r,{pure:n,areStatesEqual:a=lM,areOwnPropsEqual:c=Lm,areStatePropsEqual:l=Lm,areMergedPropsEqual:d=Lm,forwardRef:f=!1,context:m=Vv}={}){const x=m,y=BR(e),w=DR(t),v=OR(r),T=!!e;return I=>{const N=I.displayName||I.name||"Component",P=`Connect(${N})`,$={shouldHandleStateChanges:T,displayName:P,wrappedComponentName:N,WrappedComponent:I,initMapStateToProps:y,initMapDispatchToProps:w,initMergeProps:v,areStatesEqual:a,areStatePropsEqual:l,areOwnPropsEqual:c,areMergedPropsEqual:d};function Q(J){const[H,ye,oe]=b.useMemo(()=>{const{reactReduxForwardedRef:dt,...it}=J;return[J.context,dt,it]},[J]),te=b.useMemo(()=>{let dt=x;return H?.Consumer,dt},[H,x]),Ce=b.useContext(te),qe=!!J.store&&!!J.store.getState&&!!J.store.dispatch,ve=!!Ce&&!!Ce.store,Y=qe?J.store:Ce.store,st=ve?Ce.getServerState:Y.getState,he=b.useMemo(()=>MR(Y.dispatch,$),[Y]),[Qe,ie]=b.useMemo(()=>{if(!T)return sM;const dt=Wv(Y,qe?void 0:Ce.subscription),it=dt.notifyNestedSubs.bind(dt);return[dt,it]},[Y,qe,Ce]),Pe=b.useMemo(()=>qe?Ce:{...Ce,subscription:Qe},[qe,Ce,Qe]),Fe=b.useRef(void 0),ce=b.useRef(oe),Ie=b.useRef(void 0),je=b.useRef(!1),Ze=b.useRef(!1),we=b.useRef(void 0);$f(()=>(Ze.current=!0,()=>{Ze.current=!1}),[]);const le=b.useMemo(()=>()=>Ie.current&&oe===ce.current?Ie.current:he(Y.getState(),oe),[Y,oe]),Ge=b.useMemo(()=>it=>Qe?oM(T,Y,Qe,he,ce,Fe,je,Ze,Ie,ie,it):()=>{},[Qe]);iM(aM,[ce,Fe,je,oe,Ie,ie]);let He;try{He=b.useSyncExternalStore(Ge,le,st?()=>he(st(),oe):le)}catch(dt){throw we.current&&(dt.message+=`
78
78
  The error may be correlated with this previous error:
79
79
  ${we.current.stack}
80
80
 
@@ -136,7 +136,7 @@ ${we.current.stack}
136
136
  `).trim()).find(Boolean),c=typeof n=="string"&&n.trim()?n.trim():a,l=Number.isFinite(t.createdAt)&&t.createdAt>0&&Number.isFinite(new Date(t.createdAt).getTime());return{status:t.status,label:Zf[t.status]??"成员明确报告",createdAt:l?t.createdAt:null,content:r,summary:c?c.slice(0,512):"报告摘要未提供,请查看详情中的原始报告"}}function yp(e){if(e.status!=="open")return[];const t=Kf(e),r=t&&["blocked","failed"].includes(t.status)?{source:"member",label:t.label,content:t.content,summary:t.summary,createdAt:t.createdAt}:null,n=r&&(e.automationIssueSource==="member-report"||!e.summaryOnly&&!!t?.content&&e.automationIssue===t.content.slice(0,1e3)),a=r&&!t?.content&&!e.automationIssueSource,c=e.automationIssue&&!n?{source:a?"unknown":"system",label:a?"服务记录(来源待核对)":e.automationIssue.startsWith("消息投递")?"投递需要处理":e.activeAttemptId?"自动安排受阻":"执行准备受阻",content:e.automationIssue,summary:e.automationIssue}:null;return[r,c].filter(l=>!!l)}function QQ(e){return yp(e)[0]??null}function cu(e){if(e.status==="accepted")return e.completionMode==="reviewed"?"独立评审通过":"已验收";if(e.status==="closed")return"已关闭";if(e.purpose==="automation"){const l={unassigned:"后台记录待分派",awaiting_report:"后台执行等待明确报告",ack:"执行成员已确认接手",working:"成员报告进行中",blocked:"成员报告受阻",failed:"成员报告失败",complete:"执行已交付"};return e.execution?l[e.execution.status]:"后台执行记录"}if(e.decisions.some(l=>l.status==="pending"))return"需要你回答";const t=QQ(e);if(t)return t.label;if(e.workflow?.paused)return"自动安排已暂停";const r=e.attempts.find(l=>l.id===e.activeAttemptId),n=e.artifacts.filter(l=>l.kind==="plan"&&l.attemptId===e.activeAttemptId).at(-1);if(n&&n.id!==e.approvedPlanArtifactId)return"需要你确认方案";const a=e.artifacts.filter(l=>l.kind==="result"&&l.attemptId===e.activeAttemptId).at(-1),c=a&&e.events.some(l=>l.kind==="revise"&&l.attemptId===e.activeAttemptId&&l.createdAt>=a.createdAt);if(a&&!c){const l=e.artifacts.filter(d=>d.kind==="review"&&d.reviewsArtifactId===a.id).at(-1);return e.workflow&&l?.verdict!=="pass"?l?.verdict==="changes"?"评审要求修改":"等待独立评审":e.workflow?.kind==="step"?"评审通过 · 等待接续":"等待你验收"}return c?e.events.some(l=>l.kind==="revise"&&l.source==="user"&&l.attemptId===e.activeAttemptId&&l.createdAt>=a.createdAt)?"已要求跟进 · 等待新结果":"已要求修改 · 等待新结果":r?r.report?Zf[r.report.status]:["failed","expired"].includes(r.deliveryStatus??"")?"投递未成功":e.deliveries.some(l=>l.attemptId===e.activeAttemptId&&l.error)?"投递需要关注":r.deliveryStatus==="delivered"?"已写入终端 · 等待回复":"等待投递":e.scheduledAssignee?e.dependsOn.length?"依赖完成后自动分派":e.workflow?.isolated===!1?"等待分派":"准备独立执行目录":e.dependsOn.length?"等待依赖与分派":"待分派"}function Vi(e){return e.purpose!=="automation"&&e.status==="open"&&["需要你回答","需要你确认方案","等待你验收","执行准备受阻","自动安排受阻","成员报告受阻","成员报告失败","投递未成功","投递需要关注","投递需要处理"].includes(cu(e))}function gb(){return JSON.stringify(mi())}function PQ(e){const t=e instanceof Error?e.message:String(e);return(e&&typeof e=="object"&&"name"in e?String(e.name):"")==="UnexpectedEOFError"&&/^Unexpected EOF - stream closed while reading \d+\/\d+ bytes$/.test(t)||t==="Secure response ended unexpectedly"?"连接中断,待处理事项暂时无法加载;恢复后会自动重试。":t||"协作待处理事项加载失败"}const Pu=Sc(e=>{let t=0,r,n=null,a;return{tasks:[],allTasks:[],error:null,refresh:async()=>{const c=gb();if(a?.target===c)return a.promise;a?.controller.abort(),r!==c&&(r=c,n=null,e({tasks:[],allTasks:[],error:null}));const l=++t,d=new AbortController,f={owner:l,target:c,controller:d,promise:Promise.resolve()};a=f;const m=()=>a?.owner===l&&gb()===c;return f.promise=(async()=>{try{const{tasks:x}=await t3(void 0,d.signal);m()&&(n=null,e({tasks:x.filter(Vi),allTasks:x,error:null}))}catch(x){if(!m()||d.signal.aborted||x instanceof Error&&x.name==="AbortError")return;const y=x instanceof Error?x.message:String(x);n!==y&&(console.error("[CollaborationTaskInbox] refresh failed",x),n=y),e({error:PQ(x)})}finally{a?.owner===l&&(a=void 0)}})(),f.promise}}});function xb(e,t){try{localStorage.setItem(`termdock:tasks:${location.origin}:${e}:open-task`,JSON.stringify(t))}catch{}window.dispatchEvent(new CustomEvent("open-collaboration-task",{detail:{groupId:e,taskId:t}}))}function bb(e){const t=e.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);return t?{numbers:[Number(t[1]),Number(t[2]),Number(t[3])],prerelease:t[4]??null}:null}function OQ(e,t){const r=bb(e),n=bb(t);if(!r||!n)throw new Error(`Invalid version comparison: ${e} / ${t}`);for(let a=0;a<3;a+=1)if(r.numbers[a]!==n.numbers[a])return r.numbers[a]-n.numbers[a];return r.prerelease===n.prerelease?0:r.prerelease===null?1:n.prerelease===null?-1:r.prerelease.localeCompare(n.prerelease,"en",{numeric:!0})}function yb({sessionIds:e}){const t=X8(a=>e.reduce((c,l)=>c+(a.unread[l]?.length??0),0)),{locale:r}=Ur();if(!t)return null;const n=r==="zh"?`${t} 条未读进展`:`${t} unread progress updates`;return s.jsx("span",{title:n,"aria-label":n,className:"inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-primary/15 px-1 text-[10px] font-medium text-primary",children:t>99?"99+":t})}function FQ(e){if(!e.startsWith("remote:"))return null;const t=e.slice(7).split(":");if(t.length!==2)return null;try{const r=decodeURIComponent(t[0]),n=decodeURIComponent(t[1]),a=new URL(r);return!["https:","http:"].includes(a.protocol)||a.origin!==r||!n?null:{origin:r,sessionId:n}}catch{return null}}async function K6(e){const t=FQ(e);if(!t)throw new Error("远端会话标识无效");if(window.termdockDesktop?.collaborationFocus)try{if(await window.termdockDesktop.collaborationFocus(e))return}catch{}window.dispatchEvent(new CustomEvent("termdock:open-remote-session",{detail:t}))}function $Q(e,t,r){return Math.max(t,Math.min(e,r))}const vs={toVector(e,t){return e===void 0&&(e=t),Array.isArray(e)?e:[e,e]},add(e,t){return[e[0]+t[0],e[1]+t[1]]},sub(e,t){return[e[0]-t[0],e[1]-t[1]]},addTo(e,t){e[0]+=t[0],e[1]+=t[1]},subTo(e,t){e[0]-=t[0],e[1]-=t[1]}};function vb(e,t,r){return t===0||Math.abs(t)===1/0?Math.pow(e,r*5):e*t*r/(t+r*e)}function wb(e,t,r,n=.15){return n===0?$Q(e,t,r):e<t?-vb(t-e,r-t,n)+t:e>r?+vb(e-r,r-t,n)+r:e}function UQ(e,[t,r],[n,a]){const[[c,l],[d,f]]=e;return[wb(t,c,l,n),wb(r,d,f,a)]}function zQ(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function HQ(e){var t=zQ(e,"string");return typeof t=="symbol"?t:String(t)}function Hs(e,t,r){return t=HQ(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ab(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),r.push.apply(r,n)}return r}function ks(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ab(Object(r),!0).forEach(function(n){Hs(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ab(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}const X6={pointer:{start:"down",change:"move",end:"up"},mouse:{start:"down",change:"move",end:"up"},touch:{start:"start",change:"move",end:"end"},gesture:{start:"start",change:"change",end:"end"}};function Tb(e){return e?e[0].toUpperCase()+e.slice(1):""}const WQ=["enter","leave"];function GQ(e=!1,t){return e&&!WQ.includes(t)}function VQ(e,t="",r=!1){const n=X6[e],a=n&&n[t]||t;return"on"+Tb(e)+Tb(a)+(GQ(r,a)?"Capture":"")}const qQ=["gotpointercapture","lostpointercapture"];function YQ(e){let t=e.substring(2).toLowerCase();const r=!!~t.indexOf("passive");r&&(t=t.replace("passive",""));const n=qQ.includes(t)?"capturecapture":"capture",a=!!~t.indexOf(n);return a&&(t=t.replace("capture","")),{device:t,capture:a,passive:r}}function ZQ(e,t=""){const r=X6[e],n=r&&r[t]||t;return e+n}function vp(e){return"touches"in e}function J6(e){return vp(e)?"touch":"pointerType"in e?e.pointerType:"mouse"}function KQ(e){return Array.from(e.touches).filter(t=>{var r,n;return t.target===e.currentTarget||((r=e.currentTarget)===null||r===void 0||(n=r.contains)===null||n===void 0?void 0:n.call(r,t.target))})}function XQ(e){return e.type==="touchend"||e.type==="touchcancel"?e.changedTouches:e.targetTouches}function e4(e){return vp(e)?XQ(e)[0]:e}function V1(e,t){try{const r=t.clientX-e.clientX,n=t.clientY-e.clientY,a=(t.clientX+e.clientX)/2,c=(t.clientY+e.clientY)/2,l=Math.hypot(r,n);return{angle:-(Math.atan2(r,n)*180)/Math.PI,distance:l,origin:[a,c]}}catch{}return null}function JQ(e){return KQ(e).map(t=>t.identifier)}function Sb(e,t){const[r,n]=Array.from(e.touches).filter(a=>t.includes(a.identifier));return V1(r,n)}function Om(e){const t=e4(e);return vp(e)?t.identifier:t.pointerId}function ad(e){const t=e4(e);return[t.clientX,t.clientY]}const Cb=40,_b=800;function t4(e){let{deltaX:t,deltaY:r,deltaMode:n}=e;return n===1?(t*=Cb,r*=Cb):n===2&&(t*=_b,r*=_b),[t,r]}function eP(e){var t,r;const{scrollX:n,scrollY:a,scrollLeft:c,scrollTop:l}=e.currentTarget;return[(t=n??c)!==null&&t!==void 0?t:0,(r=a??l)!==null&&r!==void 0?r:0]}function tP(e){const t={};if("buttons"in e&&(t.buttons=e.buttons),"shiftKey"in e){const{shiftKey:r,altKey:n,metaKey:a,ctrlKey:c}=e;Object.assign(t,{shiftKey:r,altKey:n,metaKey:a,ctrlKey:c})}return t}function Xf(e,...t){return typeof e=="function"?e(...t):e}function rP(){}function nP(...e){return e.length===0?rP:e.length===1?e[0]:function(){let t;for(const r of e)t=r.apply(this,arguments)||t;return t}}function kb(e,t){return Object.assign({},t,e||{})}const sP=32;class r4{constructor(t,r,n){this.ctrl=t,this.args=r,this.key=n,this.state||(this.state={},this.computeValues([0,0]),this.computeInitial(),this.init&&this.init(),this.reset())}get state(){return this.ctrl.state[this.key]}set state(t){this.ctrl.state[this.key]=t}get shared(){return this.ctrl.state.shared}get eventStore(){return this.ctrl.gestureEventStores[this.key]}get timeoutStore(){return this.ctrl.gestureTimeoutStores[this.key]}get config(){return this.ctrl.config[this.key]}get sharedConfig(){return this.ctrl.config.shared}get handler(){return this.ctrl.handlers[this.key]}reset(){const{state:t,shared:r,ingKey:n,args:a}=this;r[n]=t._active=t.active=t._blocked=t._force=!1,t._step=[!1,!1],t.intentional=!1,t._movement=[0,0],t._distance=[0,0],t._direction=[0,0],t._delta=[0,0],t._bounds=[[-1/0,1/0],[-1/0,1/0]],t.args=a,t.axis=void 0,t.memo=void 0,t.elapsedTime=t.timeDelta=0,t.direction=[0,0],t.distance=[0,0],t.overflow=[0,0],t._movementBound=[!1,!1],t.velocity=[0,0],t.movement=[0,0],t.delta=[0,0],t.timeStamp=0}start(t){const r=this.state,n=this.config;r._active||(this.reset(),this.computeInitial(),r._active=!0,r.target=t.target,r.currentTarget=t.currentTarget,r.lastOffset=n.from?Xf(n.from,r):r.offset,r.offset=r.lastOffset,r.startTime=r.timeStamp=t.timeStamp)}computeValues(t){const r=this.state;r._values=t,r.values=this.config.transform(t)}computeInitial(){const t=this.state;t._initial=t._values,t.initial=t.values}compute(t){const{state:r,config:n,shared:a}=this;r.args=this.args;let c=0;if(t&&(r.event=t,n.preventDefault&&t.cancelable&&r.event.preventDefault(),r.type=t.type,a.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,a.locked=!!document.pointerLockElement,Object.assign(a,tP(t)),a.down=a.pressed=a.buttons%2===1||a.touches>0,c=t.timeStamp-r.timeStamp,r.timeStamp=t.timeStamp,r.elapsedTime=r.timeStamp-r.startTime),r._active){const Z=r._delta.map(Math.abs);vs.addTo(r._distance,Z)}this.axisIntent&&this.axisIntent(t);const[l,d]=r._movement,[f,m]=n.threshold,{_step:x,values:y}=r;if(n.hasCustomTransform?(x[0]===!1&&(x[0]=Math.abs(l)>=f&&y[0]),x[1]===!1&&(x[1]=Math.abs(d)>=m&&y[1])):(x[0]===!1&&(x[0]=Math.abs(l)>=f&&Math.sign(l)*f),x[1]===!1&&(x[1]=Math.abs(d)>=m&&Math.sign(d)*m)),r.intentional=x[0]!==!1||x[1]!==!1,!r.intentional)return;const w=[0,0];if(n.hasCustomTransform){const[Z,J]=y;w[0]=x[0]!==!1?Z-x[0]:0,w[1]=x[1]!==!1?J-x[1]:0}else w[0]=x[0]!==!1?l-x[0]:0,w[1]=x[1]!==!1?d-x[1]:0;this.restrictToAxis&&!r._blocked&&this.restrictToAxis(w);const v=r.offset,T=r._active&&!r._blocked||r.active;T&&(r.first=r._active&&!r.active,r.last=!r._active&&r.active,r.active=a[this.ingKey]=r._active,t&&(r.first&&("bounds"in n&&(r._bounds=Xf(n.bounds,r)),this.setup&&this.setup()),r.movement=w,this.computeOffset()));const[S,I]=r.offset,[[N,P],[$,Q]]=r._bounds;r.overflow=[S<N?-1:S>P?1:0,I<$?-1:I>Q?1:0],r._movementBound[0]=r.overflow[0]?r._movementBound[0]===!1?r._movement[0]:r._movementBound[0]:!1,r._movementBound[1]=r.overflow[1]?r._movementBound[1]===!1?r._movement[1]:r._movementBound[1]:!1;const U=r._active?n.rubberband||[0,0]:[0,0];if(r.offset=UQ(r._bounds,r.offset,U),r.delta=vs.sub(r.offset,v),this.computeMovement(),T&&(!r.last||c>sP)){r.delta=vs.sub(r.offset,v);const Z=r.delta.map(Math.abs);vs.addTo(r.distance,Z),r.direction=r.delta.map(Math.sign),r._direction=r._delta.map(Math.sign),!r.first&&c>0&&(r.velocity=[Z[0]/c,Z[1]/c],r.timeDelta=c)}}emit(){const t=this.state,r=this.shared,n=this.config;if(t._active||this.clean(),(t._blocked||!t.intentional)&&!t._force&&!n.triggerAllEvents)return;const a=this.handler(ks(ks(ks({},r),t),{},{[this.aliasKey]:t.values}));a!==void 0&&(t.memo=a)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function iP([e,t],r){const n=Math.abs(e),a=Math.abs(t);if(n>a&&n>r)return"x";if(a>n&&a>r)return"y"}class J0 extends r4{constructor(...t){super(...t),Hs(this,"aliasKey","xy")}reset(){super.reset(),this.state.axis=void 0}init(){this.state.offset=[0,0],this.state.lastOffset=[0,0]}computeOffset(){this.state.offset=vs.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=vs.sub(this.state.offset,this.state.lastOffset)}axisIntent(t){const r=this.state,n=this.config;if(!r.axis&&t){const a=typeof n.axisThreshold=="object"?n.axisThreshold[J6(t)]:n.axisThreshold;r.axis=iP(r._movement,a)}r._blocked=(n.lockDirection||!!n.axis)&&!r.axis||!!n.axis&&n.axis!==r.axis}restrictToAxis(t){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":t[1]=0;break;case"y":t[0]=0;break}}}const aP=e=>e,Lb=.15,n4={enabled(e=!0){return e},eventOptions(e,t,r){return ks(ks({},r.shared.eventOptions),e)},preventDefault(e=!1){return e},triggerAllEvents(e=!1){return e},rubberband(e=0){switch(e){case!0:return[Lb,Lb];case!1:return[0,0];default:return vs.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return vs.toVector(e)},transform(e,t,r){const n=e||r.shared.transform;return this.hasCustomTransform=!!n,n||aP},threshold(e){return vs.toVector(e,0)}},oP=0,uu=ks(ks({},n4),{},{axis(e,t,{axis:r}){if(this.lockDirection=r==="lock",!this.lockDirection)return r},axisThreshold(e=oP){return e},bounds(e={}){if(typeof e=="function")return c=>uu.bounds(e(c));if("current"in e)return()=>e.current;if(typeof HTMLElement=="function"&&e instanceof HTMLElement)return e;const{left:t=-1/0,right:r=1/0,top:n=-1/0,bottom:a=1/0}=e;return[[t,r],[n,a]]}}),Ib={ArrowRight:(e,t=1)=>[e*t,0],ArrowLeft:(e,t=1)=>[-1*e*t,0],ArrowUp:(e,t=1)=>[0,-1*e*t],ArrowDown:(e,t=1)=>[0,e*t]};class lP extends J0{constructor(...t){super(...t),Hs(this,"ingKey","dragging")}reset(){super.reset();const t=this.state;t._pointerId=void 0,t._pointerActive=!1,t._keyboardActive=!1,t._preventScroll=!1,t._delayed=!1,t.swipe=[0,0],t.tap=!1,t.canceled=!1,t.cancel=this.cancel.bind(this)}setup(){const t=this.state;if(t._bounds instanceof HTMLElement){const r=t._bounds.getBoundingClientRect(),n=t.currentTarget.getBoundingClientRect(),a={left:r.left-n.left+t.offset[0],right:r.right-n.right+t.offset[0],top:r.top-n.top+t.offset[1],bottom:r.bottom-n.bottom+t.offset[1]};t._bounds=uu.bounds(a)}}cancel(){const t=this.state;t.canceled||(t.canceled=!0,t._active=!1,setTimeout(()=>{this.compute(),this.emit()},0))}setActive(){this.state._active=this.state._pointerActive||this.state._keyboardActive}clean(){this.pointerClean(),this.state._pointerActive=!1,this.state._keyboardActive=!1,super.clean()}pointerDown(t){const r=this.config,n=this.state;if(t.buttons!=null&&(Array.isArray(r.pointerButtons)?!r.pointerButtons.includes(t.buttons):r.pointerButtons!==-1&&r.pointerButtons!==t.buttons))return;const a=this.ctrl.setEventIds(t);r.pointerCapture&&t.target.setPointerCapture(t.pointerId),!(a&&a.size>1&&n._pointerActive)&&(this.start(t),this.setupPointer(t),n._pointerId=Om(t),n._pointerActive=!0,this.computeValues(ad(t)),this.computeInitial(),r.preventScrollAxis&&J6(t)!=="mouse"?(n._active=!1,this.setupScrollPrevention(t)):r.delay>0?(this.setupDelayTrigger(t),r.triggerAllEvents&&(this.compute(t),this.emit())):this.startPointerDrag(t))}startPointerDrag(t){const r=this.state;r._active=!0,r._preventScroll=!0,r._delayed=!1,this.compute(t),this.emit()}pointerMove(t){const r=this.state,n=this.config;if(!r._pointerActive)return;const a=Om(t);if(r._pointerId!==void 0&&a!==r._pointerId)return;const c=ad(t);if(document.pointerLockElement===t.target?r._delta=[t.movementX,t.movementY]:(r._delta=vs.sub(c,r._values),this.computeValues(c)),vs.addTo(r._movement,r._delta),this.compute(t),r._delayed&&r.intentional){this.timeoutStore.remove("dragDelay"),r.active=!1,this.startPointerDrag(t);return}if(n.preventScrollAxis&&!r._preventScroll)if(r.axis)if(r.axis===n.preventScrollAxis||n.preventScrollAxis==="xy"){r._active=!1,this.clean();return}else{this.timeoutStore.remove("startPointerDrag"),this.startPointerDrag(t);return}else return;this.emit()}pointerUp(t){this.ctrl.setEventIds(t);try{this.config.pointerCapture&&t.target.hasPointerCapture(t.pointerId)&&t.target.releasePointerCapture(t.pointerId)}catch{}const r=this.state,n=this.config;if(!r._active||!r._pointerActive)return;const a=Om(t);if(r._pointerId!==void 0&&a!==r._pointerId)return;this.state._pointerActive=!1,this.setActive(),this.compute(t);const[c,l]=r._distance;if(r.tap=c<=n.tapsThreshold&&l<=n.tapsThreshold,r.tap&&n.filterTaps)r._force=!0;else{const[d,f]=r._delta,[m,x]=r._movement,[y,w]=n.swipe.velocity,[v,T]=n.swipe.distance,S=n.swipe.duration;if(r.elapsedTime<S){const I=Math.abs(d/r.timeDelta),N=Math.abs(f/r.timeDelta);I>y&&Math.abs(m)>v&&(r.swipe[0]=Math.sign(d)),N>w&&Math.abs(x)>T&&(r.swipe[1]=Math.sign(f))}}this.emit()}pointerClick(t){!this.state.tap&&t.detail>0&&(t.preventDefault(),t.stopPropagation())}setupPointer(t){const r=this.config,n=r.device;r.pointerLock&&t.currentTarget.requestPointerLock(),r.pointerCapture||(this.eventStore.add(this.sharedConfig.window,n,"change",this.pointerMove.bind(this)),this.eventStore.add(this.sharedConfig.window,n,"end",this.pointerUp.bind(this)),this.eventStore.add(this.sharedConfig.window,n,"cancel",this.pointerUp.bind(this)))}pointerClean(){this.config.pointerLock&&document.pointerLockElement===this.state.currentTarget&&document.exitPointerLock()}preventScroll(t){this.state._preventScroll&&t.cancelable&&t.preventDefault()}setupScrollPrevention(t){this.state._preventScroll=!1,cP(t);const r=this.eventStore.add(this.sharedConfig.window,"touch","change",this.preventScroll.bind(this),{passive:!1});this.eventStore.add(this.sharedConfig.window,"touch","end",r),this.eventStore.add(this.sharedConfig.window,"touch","cancel",r),this.timeoutStore.add("startPointerDrag",this.startPointerDrag.bind(this),this.config.preventScrollDelay,t)}setupDelayTrigger(t){this.state._delayed=!0,this.timeoutStore.add("dragDelay",()=>{this.state._step=[0,0],this.startPointerDrag(t)},this.config.delay)}keyDown(t){const r=Ib[t.key];if(r){const n=this.state,a=t.shiftKey?10:t.altKey?.1:1;this.start(t),n._delta=r(this.config.keyboardDisplacement,a),n._keyboardActive=!0,vs.addTo(n._movement,n._delta),this.compute(t),this.emit()}}keyUp(t){t.key in Ib&&(this.state._keyboardActive=!1,this.setActive(),this.compute(t),this.emit())}bind(t){const r=this.config.device;t(r,"start",this.pointerDown.bind(this)),this.config.pointerCapture&&(t(r,"change",this.pointerMove.bind(this)),t(r,"end",this.pointerUp.bind(this)),t(r,"cancel",this.pointerUp.bind(this)),t("lostPointerCapture","",this.pointerUp.bind(this))),this.config.keys&&(t("key","down",this.keyDown.bind(this)),t("key","up",this.keyUp.bind(this))),this.config.filterTaps&&t("click","",this.pointerClick.bind(this),{capture:!0,passive:!1})}}function cP(e){"persist"in e&&typeof e.persist=="function"&&e.persist()}const eh=typeof window<"u"&&window.document&&window.document.createElement;function s4(){return eh&&"ontouchstart"in window}function uP(){return s4()||eh&&window.navigator.maxTouchPoints>1}function dP(){return eh&&"onpointerdown"in window}function hP(){return eh&&"exitPointerLock"in window.document}function fP(){try{return"constructor"in GestureEvent}catch{return!1}}const Ro={isBrowser:eh,gesture:fP(),touch:s4(),touchscreen:uP(),pointer:dP(),pointerLock:hP()},pP=250,mP=180,gP=.5,xP=50,bP=250,yP=10,Eb={mouse:0,touch:0,pen:8},vP=ks(ks({},uu),{},{device(e,t,{pointer:{touch:r=!1,lock:n=!1,mouse:a=!1}={}}){return this.pointerLock=n&&Ro.pointerLock,Ro.touch&&r?"touch":this.pointerLock?"mouse":Ro.pointer&&!a?"pointer":Ro.touch?"touch":"mouse"},preventScrollAxis(e,t,{preventScroll:r}){if(this.preventScrollDelay=typeof r=="number"?r:r||r===void 0&&e?pP:void 0,!(!Ro.touchscreen||r===!1))return e||(r!==void 0?"y":void 0)},pointerCapture(e,t,{pointer:{capture:r=!0,buttons:n=1,keys:a=!0}={}}){return this.pointerButtons=n,this.keys=a,!this.pointerLock&&this.device==="pointer"&&r},threshold(e,t,{filterTaps:r=!1,tapsThreshold:n=3,axis:a=void 0}){const c=vs.toVector(e,r?n:a?1:0);return this.filterTaps=r,this.tapsThreshold=n,c},swipe({velocity:e=gP,distance:t=xP,duration:r=bP}={}){return{velocity:this.transform(vs.toVector(e)),distance:this.transform(vs.toVector(t)),duration:r}},delay(e=0){switch(e){case!0:return mP;case!1:return 0;default:return e}},axisThreshold(e){return e?ks(ks({},Eb),e):Eb},keyboardDisplacement(e=yP){return e}});function i4(e){const[t,r]=e.overflow,[n,a]=e._delta,[c,l]=e._direction;(t<0&&n>0&&c<0||t>0&&n<0&&c>0)&&(e._movement[0]=e._movementBound[0]),(r<0&&a>0&&l<0||r>0&&a<0&&l>0)&&(e._movement[1]=e._movementBound[1])}const wP=30,AP=100;class TP extends r4{constructor(...t){super(...t),Hs(this,"ingKey","pinching"),Hs(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const t=this.state;t._touchIds=[],t.canceled=!1,t.cancel=this.cancel.bind(this),t.turns=0}computeOffset(){const{type:t,movement:r,lastOffset:n}=this.state;t==="wheel"?this.state.offset=vs.add(r,n):this.state.offset=[(1+r[0])*n[0],r[1]+n[1]]}computeMovement(){const{offset:t,lastOffset:r}=this.state;this.state.movement=[t[0]/r[0],t[1]-r[1]]}axisIntent(){const t=this.state,[r,n]=t._movement;if(!t.axis){const a=Math.abs(r)*wP-Math.abs(n);a<0?t.axis="angle":a>0&&(t.axis="scale")}}restrictToAxis(t){this.config.lockDirection&&(this.state.axis==="scale"?t[1]=0:this.state.axis==="angle"&&(t[0]=0))}cancel(){const t=this.state;t.canceled||setTimeout(()=>{t.canceled=!0,t._active=!1,this.compute(),this.emit()},0)}touchStart(t){this.ctrl.setEventIds(t);const r=this.state,n=this.ctrl.touchIds;if(r._active&&r._touchIds.every(c=>n.has(c))||n.size<2)return;this.start(t),r._touchIds=Array.from(n).slice(0,2);const a=Sb(t,r._touchIds);a&&this.pinchStart(t,a)}pointerStart(t){if(t.buttons!=null&&t.buttons%2!==1)return;this.ctrl.setEventIds(t),t.target.setPointerCapture(t.pointerId);const r=this.state,n=r._pointerEvents,a=this.ctrl.pointerIds;if(r._active&&Array.from(n.keys()).every(l=>a.has(l))||(n.size<2&&n.set(t.pointerId,t),r._pointerEvents.size<2))return;this.start(t);const c=V1(...Array.from(n.values()));c&&this.pinchStart(t,c)}pinchStart(t,r){const n=this.state;n.origin=r.origin,this.computeValues([r.distance,r.angle]),this.computeInitial(),this.compute(t),this.emit()}touchMove(t){if(!this.state._active)return;const r=Sb(t,this.state._touchIds);r&&this.pinchMove(t,r)}pointerMove(t){const r=this.state._pointerEvents;if(r.has(t.pointerId)&&r.set(t.pointerId,t),!this.state._active)return;const n=V1(...Array.from(r.values()));n&&this.pinchMove(t,n)}pinchMove(t,r){const n=this.state,a=n._values[1],c=r.angle-a;let l=0;Math.abs(c)>270&&(l+=Math.sign(c)),this.computeValues([r.distance,r.angle-360*l]),n.origin=r.origin,n.turns=l,n._movement=[n._values[0]/n._initial[0]-1,n._values[1]-n._initial[1]],this.compute(t),this.emit()}touchEnd(t){this.ctrl.setEventIds(t),this.state._active&&this.state._touchIds.some(r=>!this.ctrl.touchIds.has(r))&&(this.state._active=!1,this.compute(t),this.emit())}pointerEnd(t){const r=this.state;this.ctrl.setEventIds(t);try{t.target.releasePointerCapture(t.pointerId)}catch{}r._pointerEvents.has(t.pointerId)&&r._pointerEvents.delete(t.pointerId),r._active&&r._pointerEvents.size<2&&(r._active=!1,this.compute(t),this.emit())}gestureStart(t){t.cancelable&&t.preventDefault();const r=this.state;r._active||(this.start(t),this.computeValues([t.scale,t.rotation]),r.origin=[t.clientX,t.clientY],this.compute(t),this.emit())}gestureMove(t){if(t.cancelable&&t.preventDefault(),!this.state._active)return;const r=this.state;this.computeValues([t.scale,t.rotation]),r.origin=[t.clientX,t.clientY];const n=r._movement;r._movement=[t.scale-1,t.rotation],r._delta=vs.sub(r._movement,n),this.compute(t),this.emit()}gestureEnd(t){this.state._active&&(this.state._active=!1,this.compute(t),this.emit())}wheel(t){const r=this.config.modifierKey;r&&(Array.isArray(r)?!r.find(n=>t[n]):!t[r])||(this.state._active?this.wheelChange(t):this.wheelStart(t),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(t){this.start(t),this.wheelChange(t)}wheelChange(t){"uv"in t||t.cancelable&&t.preventDefault();const n=this.state;n._delta=[-t4(t)[1]/AP*n.offset[0],0],vs.addTo(n._movement,n._delta),i4(n),this.state.origin=[t.clientX,t.clientY],this.compute(t),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){const r=this.config.device;r&&(t(r,"start",this[r+"Start"].bind(this)),t(r,"change",this[r+"Move"].bind(this)),t(r,"end",this[r+"End"].bind(this)),t(r,"cancel",this[r+"End"].bind(this)),t("lostPointerCapture","",this[r+"End"].bind(this))),this.config.pinchOnWheel&&t("wheel","",this.wheel.bind(this),{passive:!1})}}const SP=ks(ks({},n4),{},{device(e,t,{shared:r,pointer:{touch:n=!1}={}}){if(r.target&&!Ro.touch&&Ro.gesture)return"gesture";if(Ro.touch&&n)return"touch";if(Ro.touchscreen){if(Ro.pointer)return"pointer";if(Ro.touch)return"touch"}},bounds(e,t,{scaleBounds:r={},angleBounds:n={}}){const a=l=>{const d=kb(Xf(r,l),{min:-1/0,max:1/0});return[d.min,d.max]},c=l=>{const d=kb(Xf(n,l),{min:-1/0,max:1/0});return[d.min,d.max]};return typeof r!="function"&&typeof n!="function"?[a(),c()]:l=>[a(l),c(l)]},threshold(e,t,r){return this.lockDirection=r.axis==="lock",vs.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});class CP extends J0{constructor(...t){super(...t),Hs(this,"ingKey","moving")}move(t){this.config.mouseOnly&&t.pointerType!=="mouse"||(this.state._active?this.moveChange(t):this.moveStart(t),this.timeoutStore.add("moveEnd",this.moveEnd.bind(this)))}moveStart(t){this.start(t),this.computeValues(ad(t)),this.compute(t),this.computeInitial(),this.emit()}moveChange(t){if(!this.state._active)return;const r=ad(t),n=this.state;n._delta=vs.sub(r,n._values),vs.addTo(n._movement,n._delta),this.computeValues(r),this.compute(t),this.emit()}moveEnd(t){this.state._active&&(this.state._active=!1,this.compute(t),this.emit())}bind(t){t("pointer","change",this.move.bind(this)),t("pointer","leave",this.moveEnd.bind(this))}}const _P=ks(ks({},uu),{},{mouseOnly:(e=!0)=>e});class kP extends J0{constructor(...t){super(...t),Hs(this,"ingKey","scrolling")}scroll(t){this.state._active||this.start(t),this.scrollChange(t),this.timeoutStore.add("scrollEnd",this.scrollEnd.bind(this))}scrollChange(t){t.cancelable&&t.preventDefault();const r=this.state,n=eP(t);r._delta=vs.sub(n,r._values),vs.addTo(r._movement,r._delta),this.computeValues(n),this.compute(t),this.emit()}scrollEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){t("scroll","",this.scroll.bind(this))}}const LP=uu;class IP extends J0{constructor(...t){super(...t),Hs(this,"ingKey","wheeling")}wheel(t){this.state._active||this.start(t),this.wheelChange(t),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(t){const r=this.state;r._delta=t4(t),vs.addTo(r._movement,r._delta),i4(r),this.compute(t),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){t("wheel","",this.wheel.bind(this))}}const EP=uu;class NP extends J0{constructor(...t){super(...t),Hs(this,"ingKey","hovering")}enter(t){this.config.mouseOnly&&t.pointerType!=="mouse"||(this.start(t),this.computeValues(ad(t)),this.compute(t),this.emit())}leave(t){if(this.config.mouseOnly&&t.pointerType!=="mouse")return;const r=this.state;if(!r._active)return;r._active=!1;const n=ad(t);r._movement=r._delta=vs.sub(n,r._values),this.computeValues(n),this.compute(t),r.delta=r.movement,this.emit()}bind(t){t("pointer","enter",this.enter.bind(this)),t("pointer","leave",this.leave.bind(this))}}const RP=ks(ks({},uu),{},{mouseOnly:(e=!0)=>e}),tx=new Map,q1=new Map;function a4(e){tx.set(e.key,e.engine),q1.set(e.key,e.resolver)}const o4={key:"drag",engine:lP,resolver:vP},MP={key:"hover",engine:NP,resolver:RP},jP={key:"move",engine:CP,resolver:_P},DP={key:"pinch",engine:TP,resolver:SP},BP={key:"scroll",engine:kP,resolver:LP},QP={key:"wheel",engine:IP,resolver:EP};function PP(e,t){if(e==null)return{};var r={},n=Object.keys(e),a,c;for(c=0;c<n.length;c++)a=n[c],!(t.indexOf(a)>=0)&&(r[a]=e[a]);return r}function OP(e,t){if(e==null)return{};var r=PP(e,t),n,a;if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(a=0;a<c.length;a++)n=c[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}const FP={target(e){if(e)return()=>"current"in e?e.current:e},enabled(e=!0){return e},window(e=Ro.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:t=!1}={}){return{passive:e,capture:t}},transform(e){return e}},$P=["target","eventOptions","window","enabled","transform"];function xf(e={},t){const r={};for(const[n,a]of Object.entries(t))switch(typeof a){case"function":r[n]=a.call(r,e[n],n,e);break;case"object":r[n]=xf(e[n],a);break;case"boolean":a&&(r[n]=e[n]);break}return r}function UP(e,t,r={}){const n=e,{target:a,eventOptions:c,window:l,enabled:d,transform:f}=n,m=OP(n,$P);if(r.shared=xf({target:a,eventOptions:c,window:l,enabled:d,transform:f},FP),t){const x=q1.get(t);r[t]=xf(ks({shared:r.shared},m),x)}else for(const x in m){const y=q1.get(x);y&&(r[x]=xf(ks({shared:r.shared},m[x]),y))}return r}class l4{constructor(t,r){Hs(this,"_listeners",new Set),this._ctrl=t,this._gestureKey=r}add(t,r,n,a,c){const l=this._listeners,d=ZQ(r,n),f=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},m=ks(ks({},f),c);t.addEventListener(d,a,m);const x=()=>{t.removeEventListener(d,a,m),l.delete(x)};return l.add(x),x}clean(){this._listeners.forEach(t=>t()),this._listeners.clear()}}class zP{constructor(){Hs(this,"_timeouts",new Map)}add(t,r,n=140,...a){this.remove(t),this._timeouts.set(t,window.setTimeout(r,n,...a))}remove(t){const r=this._timeouts.get(t);r&&window.clearTimeout(r)}clean(){this._timeouts.forEach(t=>{window.clearTimeout(t)}),this._timeouts.clear()}}class HP{constructor(t){Hs(this,"gestures",new Set),Hs(this,"_targetEventStore",new l4(this)),Hs(this,"gestureEventStores",{}),Hs(this,"gestureTimeoutStores",{}),Hs(this,"handlers",{}),Hs(this,"config",{}),Hs(this,"pointerIds",new Set),Hs(this,"touchIds",new Set),Hs(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),WP(this,t)}setEventIds(t){if(vp(t))return this.touchIds=new Set(JQ(t)),this.touchIds;if("pointerId"in t)return t.type==="pointerup"||t.type==="pointercancel"?this.pointerIds.delete(t.pointerId):t.type==="pointerdown"&&this.pointerIds.add(t.pointerId),this.pointerIds}applyHandlers(t,r){this.handlers=t,this.nativeHandlers=r}applyConfig(t,r){this.config=UP(t,r,this.config)}clean(){this._targetEventStore.clean();for(const t of this.gestures)this.gestureEventStores[t].clean(),this.gestureTimeoutStores[t].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...t){const r=this.config.shared,n={};let a;if(!(r.target&&(a=r.target(),!a))){if(r.enabled){for(const l of this.gestures){const d=this.config[l],f=Nb(n,d.eventOptions,!!a);if(d.enabled){const m=tx.get(l);new m(this,t,l).bind(f)}}const c=Nb(n,r.eventOptions,!!a);for(const l in this.nativeHandlers)c(l,"",d=>this.nativeHandlers[l](ks(ks({},this.state.shared),{},{event:d,args:t})),void 0,!0)}for(const c in n)n[c]=nP(...n[c]);if(!a)return n;for(const c in n){const{device:l,capture:d,passive:f}=YQ(c);this._targetEventStore.add(a,l,"",n[c],{capture:d,passive:f})}}}}function Ru(e,t){e.gestures.add(t),e.gestureEventStores[t]=new l4(e,t),e.gestureTimeoutStores[t]=new zP}function WP(e,t){t.drag&&Ru(e,"drag"),t.wheel&&Ru(e,"wheel"),t.scroll&&Ru(e,"scroll"),t.move&&Ru(e,"move"),t.pinch&&Ru(e,"pinch"),t.hover&&Ru(e,"hover")}const Nb=(e,t,r)=>(n,a,c,l={},d=!1)=>{var f,m;const x=(f=l.capture)!==null&&f!==void 0?f:t.capture,y=(m=l.passive)!==null&&m!==void 0?m:t.passive;let w=d?n:VQ(n,a,x);r&&y&&(w+="Passive"),e[w]=e[w]||[],e[w].push(c)},GP=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function VP(e){const t={},r={},n=new Set;for(let a in e)GP.test(a)?(n.add(RegExp.lastMatch),r[a]=e[a]):t[a]=e[a];return[r,t,n]}function Mu(e,t,r,n,a,c){if(!e.has(r)||!tx.has(n))return;const l=r+"Start",d=r+"End",f=m=>{let x;return m.first&&l in t&&t[l](m),r in t&&(x=t[r](m)),m.last&&d in t&&t[d](m),x};a[n]=f,c[n]=c[n]||{}}function qP(e,t){const[r,n,a]=VP(e),c={};return Mu(a,r,"onDrag","drag",c,t),Mu(a,r,"onWheel","wheel",c,t),Mu(a,r,"onScroll","scroll",c,t),Mu(a,r,"onPinch","pinch",c,t),Mu(a,r,"onMove","move",c,t),Mu(a,r,"onHover","hover",c,t),{handlers:c,config:t,nativeHandlers:n}}function c4(e,t={},r,n){const a=k.useMemo(()=>new HP(e),[]);if(a.applyHandlers(e,n),a.applyConfig(t,r),k.useEffect(a.effect.bind(a)),k.useEffect(()=>a.clean.bind(a),[]),t.target===void 0)return a.bind.bind(a)}function Rb(e,t){return a4(o4),c4({drag:e},t||{},"drag")}function YP(e){return e.forEach(a4),function(r,n){const{handlers:a,nativeHandlers:c,config:l}=qP(r,n||{});return c4(a,l,void 0,c)}}function Az(e,t){return YP([o4,DP,BP,QP,jP,MP])(e,t||{})}const Mb={dampingRatio:.8,response:.3},ZP=.998;function KP(e,t,r,n){const a=2*Math.PI/Math.max(e.response,.001),c=t-n,l=r,d=e.dampingRatio;if(Math.abs(d-1)<1e-4){const v=c,T=l+a*c;return{value:S=>n+(v+T*S)*Math.exp(-a*S),velocity:S=>(T-a*(v+T*S))*Math.exp(-a*S)}}if(d<1){const v=a*Math.sqrt(1-d*d),T=c,S=(l+d*a*c)/v;return{value:I=>n+Math.exp(-d*a*I)*(T*Math.cos(v*I)+S*Math.sin(v*I)),velocity:I=>Math.exp(-d*a*I)*((S*v-d*a*T)*Math.cos(v*I)-(T*v+d*a*S)*Math.sin(v*I))}}const f=a*Math.sqrt(d*d-1),m=-d*a+f,x=-d*a-f,y=(l-x*c)/(m-x),w=c-y;return{value:v=>n+y*Math.exp(m*v)+w*Math.exp(x*v),velocity:v=>y*m*Math.exp(m*v)+w*x*Math.exp(x*v)}}function XP(e,t=ZP){return e/1e3*(t/(1-t))}function jb(e,t,r=.55){return e*t*r/(t+r*Math.abs(e))}function JP(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}const eO=.1,tO=5;function rO(e,t,r,n,a){const c=KP(e,t,r,n),l=1e3/60,d=240,f=[];for(let m=0;m<d;m++){const x=m*l/1e3,y=c.value(x),w=c.velocity(x);if(f.push(a?a(y):y),m>0&&Math.abs(y-n)<eO&&Math.abs(w)<tO)break}return f.push(a?a(n):n),{frames:f,durationMs:(f.length-1)*l,solver:c}}const nO='input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])';function sO(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.matches(nO)&&e.blur()}const iO=18,Db=8,Bb={touch:Db,pen:Db},aO=500,Fm=200,Qb=50,oO=`[${BA}]`;function $m(e,t,r){return Math.min(r,Math.max(t,e))}function Pb(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.pointerType=="string"?t.pointerType==="touch"||t.pointerType==="pen":typeof t.type=="string"&&t.type.startsWith("touch")}function Ob(e){if(!e||typeof e!="object")return!1;const t=e.target;return t instanceof Element&&!!t.closest(oO)}function Zd(...e){typeof window<"u"&&window.__SIDEBAR_DEBUG__&&console.log("[Sidebar]",...e)}const u4=k.forwardRef(function({side:t,isOpen:r,drawerWidthPx:n,onClose:a,onOpen:c,children:l,pinned:d=!1},f){const{t:m}=Ur(),x=t==="left",y=x?-n:n,w=b.useRef(null),v=b.useRef(null),T=b.useRef(r?0:y),S=b.useRef(null),I=b.useRef(null),N=b.useRef(0),P=b.useRef(null),$=b.useRef(null),Q=b.useRef(!1),U=b.useRef(null),Z=b.useRef(!1),J=b.useRef([]),H=b.useRef(null),ye=b.useRef(T.current),oe=b.useRef(r?1:0),te=b.useRef(r);te.current=r;const Ce=b.useRef(y);Ce.current=y;const qe=b.useRef(n);qe.current=n;const ve=b.useRef(x);ve.current=x;const Y=b.useRef(a);Y.current=a;const st=b.useRef(c);st.current=c;const he=b.useCallback(ae=>{w.current=ae,typeof f=="function"?f(ae):f&&(f.current=ae)},[f]),Qe=b.useCallback(()=>{I.current!==null&&(window.cancelAnimationFrame(I.current),I.current=null),S.current=null},[]),ie=b.useCallback(ae=>{const pe=qe.current;return ve.current?(ae+pe)/pe:(pe-ae)/pe},[]),Pe=b.useCallback(ae=>{const pe=v.current;pe&&(pe.style.opacity=String($m(ie(ae),0,1)))},[ie]),Fe=b.useCallback(ae=>{T.current=ae;const pe=w.current;pe&&(pe.style.transform=`translateX(${ae}px)`,Pe(ae))},[Pe]),ce=b.useCallback(ae=>{S.current=ae,I.current===null&&(I.current=window.requestAnimationFrame(()=>{I.current=null;const pe=S.current;S.current=null,pe!==null&&Fe(pe)}))},[Fe]),Ie=b.useCallback(()=>{I.current!==null&&(window.cancelAnimationFrame(I.current),I.current=null);const ae=S.current;S.current=null,ae!==null&&Fe(ae)},[Fe]),je=b.useCallback(ae=>{const pe=Ce.current;return $m(ae,Math.min(0,pe),Math.max(0,pe))},[]),Ze=b.useCallback(()=>{const ae=P.current;if(!ae)return null;P.current=null;const pe=(performance.now()-ae.startTime)/1e3,$e={value:ae.solver.value(pe),velocity:ae.solver.velocity(pe)};return ae.animations.forEach(Xe=>Xe.cancel()),$e},[]),we=b.useCallback(()=>{$.current!==null&&(window.clearTimeout($.current),$.current=null)},[]),le=b.useCallback(()=>{H.current?.(),H.current=null},[]),Ge=b.useCallback(()=>{Ie(),we();const ae=Ze();ae&&Fe(je(ae.value));const pe=w.current,$e=v.current;pe?.getAnimations().forEach(Xe=>Xe.cancel()),pe&&(pe.style.transition="none",pe.style.opacity="1"),$e?.getAnimations().forEach(Xe=>Xe.cancel()),$e&&($e.style.transition="none")},[Fe,we,je,Ie,Ze]),He=b.useCallback((ae,pe)=>{Ie(),we();const $e=w.current,Xe=v.current,wt=ae?0:Ce.current;Xe&&(Xe.style.pointerEvents=ae?"auto":"none");const Ut=Ze(),qt=Ut?je(Ut.value):T.current,Nt=pe?.velocity??Ut?.velocity??0;if(JP())return T.current=wt,$e&&($e.style.transition=`opacity ${Fm}ms ease`,$e.style.opacity=ae?"1":"0",$e.style.transform=`translateX(${wt}px)`),Xe&&(Xe.style.transition=`opacity ${Fm}ms ease`,Xe.style.opacity=ae?"1":"0"),Fm;$e&&($e.style.transition="none",$e.style.opacity="1"),Xe&&(Xe.style.transition="none");const sr=Math.abs(pe?.velocity??0)>aO,{frames:jt,durationMs:Xt,solver:Rt}=rO({dampingRatio:sr?Mb.dampingRatio:1,response:Mb.response},qt,Nt,wt,je);if(!$e||Math.abs(qt-wt)<.5&&Math.abs(Nt)<5)return Fe(wt),0;const ir=$e.animate(jt.map(Je=>({transform:`translateX(${Je}px)`})),{duration:Xt,easing:"linear",fill:"forwards"}),ge=[ir];return Xe&&ge.push(Xe.animate(jt.map(Je=>({opacity:String($m(ie(Je),0,1))})),{duration:Xt,easing:"linear",fill:"forwards"})),P.current={solver:Rt,startTime:performance.now(),target:wt,animations:ge},Zd("spring start",{startX:qt,startVelocity:Nt,targetX:wt,frames:jt.length,durationMs:Xt}),ir.onfinish=()=>{const Je=P.current;!Je||!Je.animations.includes(ir)||(P.current=null,Fe(wt),Je.animations.forEach(at=>at.cancel()),Zd("spring finish",{targetX:wt}))},Xt},[Fe,we,je,Ie,ie,Ze]),tt=b.useCallback(ae=>{Ie();const pe=ae,$e=0,Xe=Ce.current,wt=T.current+XP(pe),Ut=Math.abs(wt-$e)<=Math.abs(wt-Xe);Zd("decideSnap",{velocity:pe,currentX:T.current,projected:wt,shouldOpen:Ut});const qt=He(Ut,{velocity:pe});return Ut&&!te.current?$.current=window.setTimeout(()=>{$.current=null,st.current?.()},qt+Qb):!Ut&&te.current&&($.current=window.setTimeout(()=>{$.current=null,Y.current()},qt+Qb)),Ut},[He,Ie]),xe=b.useCallback(ae=>{const pe=Ce.current,$e=Math.min(0,pe),Xe=Math.max(0,pe),wt=qe.current;return ae<$e?$e-jb($e-ae,wt):ae>Xe?Xe+jb(ae-Xe,wt):ae},[]),dt=b.useCallback(ae=>{const pe=J.current,$e=performance.now();pe.push({t:$e,x:ae});const Xe=$e-120;for(;pe.length>0&&pe[0].t<Xe;)pe.shift()},[]),it=b.useCallback(()=>{const ae=J.current;if(ae.length<2)return 0;const pe=ae[ae.length-1];if(performance.now()-pe.t>60)return 0;const $e=ae[0],Xe=(pe.t-$e.t)/1e3;return Xe<.016?0:(pe.x-$e.x)/Xe},[]);b.useEffect(()=>{we();const ae=P.current,pe=r?0:Ce.current;ae&&ae.target===pe||He(r)},[r,He,we]),b.useEffect(()=>{Ge(),ce(te.current?0:y)},[y,Ge,ce]),b.useEffect(()=>()=>{Qe(),we(),Ze(),le()},[we,Qe,le,Ze]);const _e=Rb(({active:ae,cancel:pe,first:$e,last:Xe,movement:[wt],event:Ut})=>{if(Zd("bindPanel",{active:ae,first:$e,last:Xe,mx:wt}),!Pb(Ut)){pe();return}if($e){if(le(),Q.current=!1,U.current=null,J.current=[],Ob(Ut)){pe();return}const qt=w.current,Nt=qt?QA(Ut.target,qt):null;if(!Nt||PA()){pe();return}const sr=OA(Nt,wt,ve.current?-1:1);if(Zd("arbitrate",{owner:sr.kind,mx:wt}),sr.kind==="swiper"){H.current=FA(sr.instance),pe();return}if(sr.kind==="scroller"){const jt=$A(sr.element);if(jt)U.current=jt;else{pe();return}}U.current||(Q.current=!0,Ge(),N.current=T.current)}if(!ae){U.current=null,Q.current&&(Q.current=!1,tt(it()));return}if(U.current){UA(U.current,wt);return}if(Q.current){const qt=xe(N.current+wt);dt(qt),ce(qt)}},{axis:"x",axisThreshold:Bb,filterTaps:!0,pointer:{touch:!0}}),Ue=Rb(({active:ae,cancel:pe,first:$e,movement:[Xe],event:wt})=>{if(!Pb(wt)){pe();return}if(te.current){pe();return}if($e&&(Z.current=!0,J.current=[],Ge(),N.current=T.current),!ae){Z.current&&(Z.current=!1,tt(it())&&sO());return}if(Z.current){const Ut=xe(N.current+Xe);dt(Ut),ce(Ut)}},{axis:"x",axisThreshold:Bb,filterTaps:!0,pointer:{touch:!0}}),ke=b.useCallback(ae=>{ae.preventDefault(),ae.stopPropagation(),te.current||st.current?.()},[]);if(d)return s.jsx("aside",{ref:he,"data-sidebar":t,"data-sidebar-pinned":"true",className:"relative flex h-full min-h-0 w-full flex-col app-chrome-bg",children:l});const V=_e();return s.jsxs(s.Fragment,{children:[s.jsx("div",{...Ue(),style:{position:"fixed",top:"1.5rem",bottom:"10rem",...x?{left:0}:{right:0},width:iO,zIndex:"var(--z-chrome-hint)",touchAction:"none",pointerEvents:r?"none":"auto"},onClick:ke,"aria-label":m(x?"sidebar.openLeftSidebar":"sidebar.openRightSidebar")}),s.jsx("div",{ref:v,"data-sidebar-backdrop":t,className:"fixed inset-0 z-sidebar-backdrop bg-[var(--app-backdrop)] cursor-default",style:{opacity:oe.current,pointerEvents:r?"auto":"none",transition:"none",willChange:"opacity"},onClick:a,"aria-label":m("sidebar.closeSidebar")}),s.jsx("aside",{...V,onClickCapture:ae=>{Ob(ae)||V.onClickCapture?.(ae)},ref:he,"data-sidebar":t,className:`fixed inset-y-0 z-sidebar-panel flex flex-col chrome-glow-panel will-change-transform ${x?"border-r border-border":"border-l border-border/15"}`,style:{...x?{left:0}:{right:0},width:n,maxWidth:x?"94vw":"95vw",transform:`translateX(${ye.current}px)`,transition:"none",touchAction:"pan-y",pointerEvents:r?"auto":"none",paddingTop:"var(--safe-top-inset, env(safe-area-inset-top, 0px))",paddingBottom:"var(--safe-bottom-inset, env(safe-area-inset-bottom, 0px))",...x?{paddingLeft:"var(--safe-left-inset, env(safe-area-inset-left, 0px))"}:{paddingRight:"var(--safe-right-inset, env(safe-area-inset-right, 0px))"}},children:l})]})}),lO={activeKey:"root",items:[]},cO=()=>()=>{},uO=()=>lO;function dO(e){const t=Xo(),r=b.useSyncExternalStore(t?.subscribe??cO,t?.snapshot??uO),n=J8(),a=r.items.map(c=>c.key===n?{...c,reviewCount:e}:c).filter(c=>c.reviewCount>0);return{host:t,groups:a,currentKey:n,active:!t||r.activeKey===n,total:t?e+a.reduce((c,l)=>c+(l.key===n?0:l.reviewCount),0):e,hasOtherAttention:a.some(c=>c.key!==n)}}function hO({groups:e,currentKey:t,onClose:r}){const{t:n}=Ur(),a=b.useId(),c=b.useRef(null),l=b.useRef(null),d=b.useRef(r);d.current=r;const f=b.useRef(!0),[m,x]=b.useState(""),y=e.reduce((T,S)=>T+S.reviewCount,0);b.useEffect(()=>{const T=document.activeElement;l.current?.focus({preventScroll:!0});const S=I=>{if(I.key==="Escape"&&(I.preventDefault(),I.stopImmediatePropagation(),d.current()),I.key!=="Tab")return;const N=Array.from(c.current?.querySelectorAll("button:not(:disabled)")??[]),P=N[0],$=N[N.length-1],Q=!c.current?.contains(document.activeElement);I.shiftKey&&(document.activeElement===P||Q)?(I.preventDefault(),$?.focus()):!I.shiftKey&&(document.activeElement===$||Q)&&(I.preventDefault(),P?.focus())};return document.addEventListener("keydown",S,!0),()=>{document.removeEventListener("keydown",S,!0),f.current&&T?.isConnected&&!T.closest("[inert]")&&T.focus({preventScroll:!0})}},[]);const w=(T,S)=>{const I=Xo(),N=I?.snapshot().items.find($=>$.key===T.key);if(!N?.reviewCount||S&&!N.attentionSessions?.some($=>$.id===S)){x(n("serviceAttention.changed"));return}f.current=!1;let P=!1;S&&T.key===t?(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:S})),P=!0):S&&N.service?.targetPeerId?P=I?.focusSession(N.service.targetPeerId,S)??!1:N.service&&(P=I?.activate(N.service,!0)??!1),P?r():(f.current=!0,x(n("serviceAttention.unavailable")))},v=T=>T.phase==="offline"?n("serviceAttention.offline"):T.phase==="login"?n("serviceAttention.login"):T.phase==="connecting"||T.phase==="reconnecting"?n("connection.reconnecting"):null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button","aria-label":n("common.close"),tabIndex:-1,className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)]",onClick:r}),s.jsx("div",{className:"pointer-events-none fixed inset-0 z-modal-panel flex items-end justify-center p-3 sm:items-center sm:p-6",style:{paddingTop:"max(12px, var(--safe-top-inset, env(safe-area-inset-top, 0px)))",paddingBottom:"max(12px, var(--safe-bottom-inset, env(safe-area-inset-bottom, 0px)))"},children:s.jsxs("section",{ref:c,role:"dialog","aria-modal":"true","aria-labelledby":a,"data-sidebar-gesture-ignore":!0,onKeyDown:T=>T.stopPropagation(),className:"pointer-events-auto flex max-h-full w-full max-w-md flex-col overflow-hidden rounded-2xl border border-border bg-surface text-foreground shadow-xl",children:[s.jsxs("header",{className:"flex shrink-0 items-center gap-3 border-b border-border px-4 py-3",children:[s.jsx(wc,{size:20,className:"shrink-0 text-[color:var(--warning)]","aria-hidden":"true"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{id:a,className:"text-sm font-semibold",children:n("serviceAttention.title")}),s.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:n("serviceAttention.summary",{services:e.length,count:y})})]}),s.jsx("button",{ref:l,type:"button","aria-label":n("common.close"),onClick:r,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(jn,{size:18})})]}),s.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain p-2",children:[e.length===0&&s.jsx("p",{role:"status",className:"px-4 py-8 text-center text-sm text-muted-foreground",children:n("serviceAttention.empty")}),e.map(T=>s.jsxs("section",{className:"mb-2 last:mb-0",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 px-3 pb-1 pt-2 text-xs",children:[s.jsx("h3",{className:"min-w-0 flex-1 truncate font-medium",title:T.service?.label,children:T.service?.label||n("serviceAttention.currentService")}),T.key===t&&s.jsx("span",{className:"shrink-0 text-muted-foreground",children:n("agent.currentSession")}),s.jsx("span",{className:"shrink-0 tabular-nums text-[color:var(--warning)]",children:T.reviewCount})]}),v(T)&&s.jsx("p",{className:"px-3 pb-1 text-xs text-[color:var(--warning)]",children:v(T)}),T.attentionSessions?.length?T.attentionSessions.map(S=>s.jsxs("button",{type:"button",onClick:()=>w(T,S.id),className:"flex min-h-14 w-full items-center gap-3 rounded-xl px-3 py-2 text-left hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"line-clamp-2 break-words text-sm",title:S.label,children:S.label}),s.jsx("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:S.waiting?n("serviceAttention.waiting"):n("agent.needsReview")})]}),s.jsx(qs,{size:16,className:"shrink-0 text-muted-foreground","aria-hidden":"true"})]},S.id)):s.jsx("button",{type:"button",onClick:()=>w(T),className:"min-h-11 w-full rounded-xl px-3 py-2 text-left text-sm hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",children:n("serviceAttention.viewService")})]},T.key))]}),s.jsxs("footer",{className:"shrink-0 border-t border-border px-4 py-3 text-xs text-muted-foreground",children:[m&&s.jsx("p",{role:"alert",className:"mb-1 text-[color:var(--warning)]",children:m}),n("serviceAttention.scope")]})]})})]})}function fO(e){const t=e.icon&&e.isPlugin?`/api/terminal/agent-plugin-icon/${encodeURIComponent(e.slug)}${e.iconVersion?`?v=${Math.floor(e.iconVersion)}`:""}`:void 0,[r,n]=b.useState();if(b.useEffect(()=>{if(n(void 0),!t)return;const a=new AbortController;let c;return fetch(t,{signal:a.signal}).then(async l=>{if(!l.ok)throw new Error(`Icon request failed: ${l.status}`);const d=await l.blob();a.signal.aborted||(c=URL.createObjectURL(d),n({endpoint:t,src:c}))}).catch(()=>{}),()=>{a.abort(),c&&URL.revokeObjectURL(c)}},[t]),!!e.icon)return e.isPlugin?r?.endpoint===t?r?.src:void 0:`/icons/agents/${e.icon}.svg`}function pO(e){return e.agentStatus==="waiting"||e.agentNeedsReview===!0}function mO(e,t,r,n="next"){if(e.length===0)return null;const a=t?e.findIndex(c=>c.sessionId===t):-1;for(let c=1;c<=e.length;c+=1){const l=n==="next"?c:-c,d=(a+l+e.length)%e.length,f=e[d];if(f&&r(f))return f.sessionId}return null}function gO(e,t,r="next"){return mO(e,t,pO,r)}const ro=42,Jf=20,xO=10;function Y1(e,t,r){return Math.min(r,Math.max(t,e))}function wp(e){const t=Math.max(0,e.safeTop??0),r=Math.max(0,e.safeRight??0),n=Math.max(0,e.safeBottom??0),a=Math.max(0,e.safeLeft??0),c=Math.max(0,e.bottomClearance??72),l=a+Jf,d=Math.max(l,e.width-r-Jf-ro),f=Math.max(t+12,52),m=Math.max(f,e.height-n-c-ro);return{minX:l,maxX:d,minY:f,maxY:m}}function Fb(e,t){const r=wp(e),n=Y1(t.yRatio,0,1);return{x:t.side==="left"?r.minX:r.maxX,y:r.minY+(r.maxY-r.minY)*n}}function tu(e,t){const r=wp(e);return{x:Y1(t.x,r.minX,r.maxX),y:Y1(t.y,r.minY,r.maxY)}}function $b(e,t){const r=wp(e),n=tu(e,t),a=(r.minX+r.maxX+ro)/2,c=n.x+ro/2<a?"left":"right",l=r.maxY-r.minY;return{position:{x:c==="left"?r.minX:r.maxX,y:n.y},preference:{side:c,yRatio:l>0?(n.y-r.minY)/l:0}}}function Ub(e,t,r){const n=tu(e,t),a=ro+xO,c=m=>Math.abs(m.x-r.x)<a&&Math.abs(m.y-r.y)<a;if(!c(n))return n;const l=[{...n,y:r.y-a},{...n,y:r.y+a}].map(m=>tu(e,m)).filter(m=>!c(m)).sort((m,x)=>Math.abs(m.y-n.y)-Math.abs(x.y-n.y));if(l[0])return l[0];const d=wp(e);return[{...n,x:d.minX},{...n,x:d.maxX}].map(m=>tu(e,m)).filter(m=>!c(m)).sort((m,x)=>Math.abs(m.x-n.x)-Math.abs(x.x-n.x))[0]??n}const Um="var(--warning)",bO="var(--success)",zb="var(--tmux)",Hb="termdock:mobile-attention-position:v1",Wb="termdock:running-session-position:v1",yO={side:"right",yRatio:.68},vO={side:"right",yRatio:.54};function Gb(e,t){if(typeof window>"u")return t;try{const r=JSON.parse(window.localStorage.getItem(e)??"null");if(r&&(r.side==="left"||r.side==="right")&&typeof r.yRatio=="number"&&Number.isFinite(r.yRatio))return{side:r.side,yRatio:Math.min(1,Math.max(0,r.yRatio))}}catch{}return t}function wO(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function $h(e){if(typeof document>"u")return 0;const t=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(e));return Number.isFinite(t)?Math.max(0,t):0}function AO(e,t,r={}){if(typeof window>"u")return{width:390,height:664};const n=window.visualViewport,a=n?.width??window.innerWidth,c=n?.height??window.innerHeight,l=t?.getBoundingClientRect(),d=!!(l&&l.width>0&&l.height>0);return{width:a,height:c,safeTop:Math.max($h("--safe-top-inset"),(d?Math.max(0,l.top):0)+Math.max(0,r.top??0)),safeRight:Math.max($h("--safe-right-inset"),(d?Math.max(0,a-l.right):0)+Math.max(0,r.right??0)),safeBottom:Math.max($h("--safe-bottom-inset"),(d?Math.max(0,c-l.bottom):0)+Math.max(0,r.bottom??0)),safeLeft:Math.max($h("--safe-left-inset"),(d?Math.max(0,l.left):0)+Math.max(0,r.left??0)),bottomClearance:e?Jf:72}}function d4(){const e=Hr.getState(),t=Array.from(e.sessions.values()),r=gO(t,e.activeSessionId);if(!r)return;const n=e.activeSessionId?e.sessions.get(e.activeSessionId):void 0;n?.agentNeedsReview&&e.clearAgentNeedsReview(n.sessionId),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:r}))}function Vb(e){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e}))}function h4(e){switch(e){case"success":return"var(--success)";case"warning":return"var(--warning)";case"danger":return"var(--destructive)";case"info":case"accent":return"var(--accent)";default:return"var(--muted-foreground)"}}function TO({indicator:e,tone:t,size:r}){const n=h4(t);switch(e){case"spinner":return s.jsx(Dn,{size:r,className:"shrink-0 animate-spin",style:{color:n}});case"question":return s.jsx(_f,{size:r,className:"shrink-0 animate-bounce-y",style:{color:n}});case"badge":return s.jsx(wc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:n}});case"terminal":return s.jsx(tl,{size:r,className:"shrink-0",style:{color:n}});case"pulse":return s.jsx(pT,{size:r,className:"shrink-0 animate-pulse",style:{color:n}});case"ring":return s.jsx("span",{className:"block shrink-0 rounded-full border-2",style:{width:r,height:r,borderColor:n}});case"dot":return s.jsx("span",{className:"block shrink-0 rounded-full",style:{width:Math.max(5,r-4),height:Math.max(5,r-4),backgroundColor:n}})}}function ru({agent:e,size:t=12}){const r=t-4,n=fO(e);return n?e.iconMode==="native"?s.jsx("span",{className:"flex shrink-0 items-center justify-center rounded-[3px]",style:{width:t,height:t},title:e.displayName,children:s.jsx("img",{src:n,alt:e.displayName,style:{width:r,height:r}})}):s.jsx("span",{className:"flex shrink-0 items-center justify-center rounded-[3px]",style:{width:t,height:t,backgroundColor:e.accentColor},title:e.displayName,children:s.jsx("span",{className:"block bg-white",style:{width:r,height:r,WebkitMask:`url(${n}) center / contain no-repeat`,mask:`url(${n}) center / contain no-repeat`}})}):s.jsx("span",{className:"flex shrink-0 items-center justify-center rounded-[3px]",style:{width:t,height:t,backgroundColor:e.accentColor},title:e.displayName,children:s.jsx(G0,{size:r,className:"text-white"})})}function SO({sessionMode:e,state:t,size:r=11}){const n=t?.agent?s.jsx(ru,{agent:t.agent,size:r+1}):e==="tmux"?s.jsx(su,{size:r,className:"shrink-0"}):s.jsx(tl,{size:r,className:"shrink-0"});return t?.agentStatusDetail&&t.agentIndicator&&!(t.agentStatus==="done"&&t.agentNeedsReview)?s.jsx("span",{title:t.agentMessage??t.agentStatusDetail.label,"aria-label":t.agentStatusDetail.label,children:s.jsx(TO,{indicator:t.agentIndicator,tone:t.agentStatusDetail.tone,size:r})}):t?.agentStatus==="working"?s.jsx("span",{title:t.agentMessage??t.agent?.displayName,children:s.jsx(Dn,{size:r,className:"shrink-0 animate-spin",style:{color:bO}})}):t?.agentStatus==="waiting"?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(_f,{size:r,className:"shrink-0 animate-bounce-y",style:{color:Um}})}):t?.agentStatus==="done"&&t.agentNeedsReview?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(wc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:Um}})}):t?.agentNeedsReview?s.jsx("span",{title:t.agentMessage??void 0,children:s.jsx(wc,{size:r+1,className:"shrink-0 animate-pulse",style:{color:Um}})}):t?.inCopyMode?e==="tmux"?s.jsx(su,{size:r,className:"shrink-0 animate-pulse",style:{color:zb}}):s.jsx(tl,{size:r,className:"shrink-0 animate-pulse",style:{color:zb}}):n}function CO({status:e,detail:t,needsReview:r,inCopyMode:n}){const{t:a}=Ur();return t&&!r?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full ring-2 ring-surface animate-pulse",style:{backgroundColor:h4(t.tone)},title:t.label}):e==="working"?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-[var(--success)] ring-2 ring-surface shadow-[0_0_6px_rgb(var(--success-rgb)_/_0.50)] animate-pulse",title:a("agent.aiRunning")}):e==="waiting"||r?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-[var(--warning)] ring-2 ring-surface shadow-[0_0_0_1px_rgb(var(--warning-rgb)_/_0.24)] animate-pulse",title:a(r?"agent.finishedReview":"agent.aiWaiting")}):e==="done"&&r?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-[var(--warning)] ring-2 ring-surface shadow-[0_0_0_1px_rgb(var(--warning-rgb)_/_0.24)] animate-pulse",title:a("agent.finishedReview")}):n?s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2.5 w-2.5 rounded-[2px] bg-[var(--tmux)] ring-2 ring-surface",title:a("agent.copyMode")}):null}function f4({count:e,tone:t,title:r}){const{t:n}=Ur();if(e<=0)return null;const a=t==="running"?"inline-flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.12)] px-1.5 py-0.5 text-[10px] font-medium text-[color:var(--success)]":"inline-flex min-h-6 items-center gap-1 rounded-full bg-[rgb(var(--warning-rgb)_/_0.14)] px-2 py-0.5 text-[10px] font-semibold text-[color:var(--warning)] ring-1 ring-[rgb(var(--warning-rgb)_/_0.24)] transition hover:bg-[rgb(var(--warning-rgb)_/_0.22)] active:scale-[0.97]",c=t==="running"?"h-1.5 w-1.5 rounded-full bg-[var(--success)] animate-pulse":"h-1.5 w-1.5 rounded-full bg-[var(--warning)] animate-pulse";if(t==="review"){const l=r??n("agent.jumpToNext");return s.jsxs("button",{type:"button",className:a,title:`${l} · ${n("agent.jumpToNext")}`,"aria-label":`${l}: ${e}. ${n("agent.jumpToNext")}`,onClick:d4,children:[s.jsx(wc,{size:11,className:"shrink-0"}),s.jsx("span",{children:n("agent.needsReview")}),s.jsx("span",{className:"tabular-nums",children:e})]})}return s.jsxs("span",{className:a,title:r,children:[s.jsx("span",{className:c}),e]})}function _O({runningCount:e,reviewCount:t,className:r=""}){const n=[];return e>0&&n.push({key:"running",count:e,className:"bg-[var(--success)] text-[color:var(--success-foreground)]"}),t>0&&n.push({key:"review",count:t,className:"bg-[var(--warning)] text-[color:var(--warning-foreground)]"}),n.length===0?null:s.jsx("span",{"aria-hidden":"true",className:`pointer-events-none absolute -right-1 ${n.length>1?"top-0.5 flex flex-col gap-0.5":"-top-1"} ${r}`,children:n.map(a=>s.jsx("span",{className:`flex h-3 min-w-3 items-center justify-center rounded-full px-0.5 text-[7px] font-bold leading-3 shadow-sm ring-1 ring-background ${a.className}`,children:a.count>9?"9+":a.count},a.key))})}const kO=380,qb=10,Uh=10,zm=52,LO=104;function IO(e,t,r){const n=Math.max(0,t.safeLeft??0),a=t.width-Math.max(0,t.safeRight??0),c=Math.max(0,t.safeTop??0),l=t.height-Math.max(0,t.safeBottom??0),d=Jf,f=e.x+ro/2>=n+(a-n)/2,m=f?e.x-Uh-n-d:a-d-e.x-ro-Uh,x=Math.max(1,Math.min(Math.max(0,m),Math.max(168,r*LO))),y=f?e.x-Uh-x:e.x+ro+Uh,w=Math.min(Math.max(y,n+d),Math.max(n+d,a-d-x)),v=e.y+ro/2-zm/2,T=Math.min(Math.max(v,c+d),Math.max(c+d,l-d-zm));return{left:w,top:T,width:x,height:zm,itemWidth:x/Math.max(1,r),side:f?"left":"right"}}function Yb(e,t,r,n){return t<e.left||t>e.left+e.width||r<e.top-14||r>e.top+e.height+14?null:Math.min(n-1,Math.max(0,Math.floor((t-e.left)/e.itemWidth)))}function EO(e,t){if(e.length===0)return null;const r=t?e.findIndex(n=>n.id===t):-1;return e[(r+1)%e.length]?.id??null}function NO({reviewCount:e,runningSessions:t,activeSessionId:r,runningButtonEnabled:n,attentionButtonEnabled:a=!0,isDesktopLayout:c,containerElement:l,occlusionInsets:d}){const{t:f}=Ur(),m=Yt(_e=>_e.leftOpen),x=Yt(_e=>_e.rightOpen),{isOpen:y}=Rv({enabled:!c}),w=c||!m&&!x&&!y,v=dO(e),[T,S]=k.useState(!1);k.useEffect(()=>{(!v.active||!w)&&S(!1)},[v.active,w]);const I=a&&v.total>0&&w,N=t.length>1||t.length===1&&t[0]?.id!==r,P=n&&t.length>0&&N&&w,$=Math.max(0,d?.top??0),Q=Math.max(0,d?.right??0),U=Math.max(0,d?.bottom??0),Z=Math.max(0,d?.left??0),J=k.useCallback(()=>AO(c,l,{top:$,right:Q,bottom:U,left:Z}),[l,c,U,Z,Q,$]),H=k.useRef({attention:Gb(Hb,yO),running:Gb(Wb,vO)}),ye=k.useCallback(()=>{const _e=J(),Ue=Fb(_e,H.current.attention),ke=Fb(_e,H.current.running);return{attention:Ue,running:I&&P?Ub(_e,ke,Ue):ke}},[I,J,P]),[oe,te]=k.useState(()=>ye()),Ce=k.useRef(oe);Ce.current=oe;const[qe,ve]=k.useState(null),Y=k.useRef(null),[st,he]=k.useState("idle"),[Qe,ie]=k.useState(null),Pe=k.useRef(null),Fe=k.useRef({attention:!1,running:!1});k.useEffect(()=>()=>{const _e=Pe.current?.longPressTimer;_e!=null&&window.clearTimeout(_e)},[]),k.useEffect(()=>{if(P)return;const _e=Pe.current?.longPressTimer;_e!=null&&window.clearTimeout(_e),Pe.current=null,he("idle"),ie(null)},[P]),k.useLayoutEffect(()=>{const _e=()=>{const ke=ye();Ce.current=ke,te(ke)};_e(),window.addEventListener("resize",_e),window.addEventListener("orientationchange",_e),window.visualViewport?.addEventListener("resize",_e);const Ue=typeof ResizeObserver>"u"?null:new ResizeObserver(_e);return l&&Ue?.observe(l),()=>{window.removeEventListener("resize",_e),window.removeEventListener("orientationchange",_e),window.visualViewport?.removeEventListener("resize",_e),Ue?.disconnect()}},[l,ye]);const ce=k.useCallback(_e=>_e==="attention"?P:I,[I,P]),Ie=k.useCallback((_e,Ue)=>{if(!ce(_e))return Ue;const ke=_e==="attention"?"running":"attention";return Ub(J(),Ue,Ce.current[ke])},[J,ce]),je=k.useCallback((_e,Ue,ke,V)=>{const ae=J(),pe=Ue.moved?tu(ae,{x:Ue.startX+(ke-Ue.originX),y:Ue.startY+(V-Ue.originY)}):Ce.current[_e],$e=$b(ae,pe),Xe=Ie(_e,$e.position),wt=$b(ae,Xe);H.current[_e]=wt.preference,wO(_e==="attention"?Hb:Wb,wt.preference);const Ut={...Ce.current,[_e]:wt.position};Ce.current=Ut,te(Ut)},[Ie,J]),Ze=k.useCallback(_e=>{Fe.current[_e]=!0,window.setTimeout(()=>{Fe.current[_e]=!1},0)},[]),we=k.useCallback(_e=>{const Ue=Y.current;!Ue||Ue.kind!=="attention"||Ue.pointerId!==_e.pointerId||(Y.current=null,ve(null),je("attention",Ue,_e.clientX,_e.clientY),Ue.moved&&Ze("attention"))},[je,Ze]),le={onPointerDown:_e=>{_e.stopPropagation(),_e.currentTarget.setPointerCapture(_e.pointerId),Y.current={kind:"attention",pointerId:_e.pointerId,originX:_e.clientX,originY:_e.clientY,startX:oe.attention.x,startY:oe.attention.y,moved:!1}},onPointerMove:_e=>{const Ue=Y.current;if(!Ue||Ue.kind!=="attention"||Ue.pointerId!==_e.pointerId)return;const ke=_e.clientX-Ue.originX,V=_e.clientY-Ue.originY;if(!Ue.moved&&Math.hypot(ke,V)<5)return;Ue.moved=!0,ve("attention");const ae=J(),pe=Ie("attention",tu(ae,{x:Ue.startX+ke,y:Ue.startY+V})),$e={...Ce.current,attention:pe};Ce.current=$e,te($e)},onPointerUp:we,onPointerCancel:we},Ge=l?IO(oe.running,J(),t.length):null,He=_e=>{_e.longPressTimer!==null&&(window.clearTimeout(_e.longPressTimer),_e.longPressTimer=null)},tt={onPointerDown:_e=>{_e.stopPropagation(),_e.currentTarget.setPointerCapture(_e.pointerId);const Ue=_e.pointerId,ke={pointerId:Ue,originX:_e.clientX,originY:_e.clientY,startX:oe.running.x,startY:oe.running.y,mode:"pressing",moved:!1,selectedIndex:null,longPressTimer:null};ke.longPressTimer=window.setTimeout(()=>{const V=Pe.current;!V||V.pointerId!==Ue||V.mode!=="pressing"||(V.longPressTimer=null,V.mode="dragging",Fe.current.running=!0,he("dragging"))},kO),Pe.current=ke,he("pressing"),ie(null)},onPointerMove:_e=>{const Ue=Pe.current;if(!Ue||Ue.pointerId!==_e.pointerId)return;const ke=_e.clientX-Ue.originX,V=_e.clientY-Ue.originY;if(Ue.mode==="pressing")if(Math.abs(ke)>=qb&&Math.abs(ke)>=Math.abs(V))He(Ue),Ue.mode="selecting",Fe.current.running=!0,he("selecting");else if(Math.hypot(ke,V)>=qb){He(Ue),Ue.mode="cancelled",Fe.current.running=!0,he("idle");return}else return;if(Ue.mode==="selecting"){const Xe=Ge?Yb(Ge,_e.clientX,_e.clientY,t.length):null;Ue.selectedIndex=Xe,ie(Xe);return}if(Ue.mode!=="dragging"||!Ue.moved&&Math.hypot(ke,V)<5)return;Ue.moved=!0;const ae=J(),pe=Ie("running",tu(ae,{x:Ue.startX+ke,y:Ue.startY+V})),$e={...Ce.current,running:pe};Ce.current=$e,te($e)},onPointerUp:_e=>{const Ue=Pe.current;if(!Ue||Ue.pointerId!==_e.pointerId)return;He(Ue);const ke=Ue.mode;if(ke==="selecting"){const V=Ge?Yb(Ge,_e.clientX,_e.clientY,t.length):Ue.selectedIndex,ae=V===null?null:t[V]?.id;ae&&Vb(ae)}else ke==="dragging"&&je("running",Ue,_e.clientX,_e.clientY);Pe.current=null,he("idle"),ie(null),ke!=="pressing"&&Ze("running")},onPointerCancel:_e=>{const Ue=Pe.current;!Ue||Ue.pointerId!==_e.pointerId||(He(Ue),Pe.current=null,he("idle"),ie(null),Ze("running"))}},xe=(_e,Ue)=>s.jsx("span",{className:`pointer-events-none absolute -right-1 -top-1 z-10 flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-surface px-1 text-[9px] font-bold tabular-nums ring-2 ring-[var(--chrome-bg)] ${Ue==="attention"?"text-[color:var(--warning)]":"text-[color:var(--success)]"}`,children:_e>9?"9+":_e}),dt=()=>{const _e=v.hasOtherAttention?f("serviceAttention.title"):f("agent.jumpToNext"),Ue=oe.attention,ke=qe==="attention";return s.jsxs("button",{type:"button","data-attention-button":!0,"data-mobile-attention-button":!0,...le,onClick:V=>{V.stopPropagation(),!Fe.current.attention&&(v.hasOtherAttention?S(!0):d4())},className:`fixed z-chrome-hint inline-flex items-center justify-center rounded-full bg-[var(--warning)] text-[color:var(--warning-foreground)] shadow-[0_8px_24px_var(--app-shadow-strong)] ring-1 ring-[rgb(var(--warning-rgb)_/_0.35)] animate-fade-in ${ke?"cursor-grabbing scale-[1.04] shadow-[0_12px_30px_var(--app-shadow-strong)]":"cursor-grab transition-[left,top,transform,box-shadow] duration-200 active:scale-95"}`,style:{display:T?"none":void 0,left:Ue.x,top:Ue.y,width:ro,height:ro,touchAction:"none"},"aria-label":`${_e}: ${v.total}`,"aria-haspopup":v.hasOtherAttention?"dialog":void 0,title:_e,children:[s.jsx(wc,{size:17,className:"shrink-0"}),xe(v.total,"attention")]},"attention")},it=()=>{const _e=t.length,Ue=oe.running,ke=st==="selecting",V=st==="dragging";return s.jsxs(k.Fragment,{children:[s.jsxs("button",{type:"button","data-running-session-button":!0,"data-running-session-gesture":st,...tt,onClick:ae=>{if(ae.stopPropagation(),Fe.current.running)return;const pe=EO(t,r);pe&&Vb(pe)},className:`fixed z-chrome-hint inline-flex select-none items-center justify-center rounded-full bg-[var(--success)] text-[color:var(--success-foreground)] shadow-[0_8px_24px_var(--app-shadow-strong)] ring-1 ring-[rgb(var(--success-rgb)_/_0.35)] animate-fade-in ${V?"cursor-grabbing scale-[1.04] shadow-[0_12px_30px_var(--app-shadow-strong)]":ke?"cursor-ew-resize scale-[1.04] ring-2 ring-[rgb(var(--success-rgb)_/_0.55)]":"cursor-grab transition-[left,top,transform,box-shadow] duration-200 active:scale-95"}`,style:{left:Ue.x,top:Ue.y,width:ro,height:ro,touchAction:"none"},"aria-label":`${f("agent.jumpToNextRunning")}: ${_e}`,title:f("agent.runningSessionGestureHint"),children:[s.jsx(Dn,{size:18,className:"shrink-0 animate-spin"}),xe(_e,"running")]}),ke&&Ge&&s.jsx("div",{role:"listbox","data-running-session-rail":!0,"data-side":Ge.side,"aria-label":f("agent.selectRunningSession"),className:"pointer-events-none fixed z-popover flex overflow-hidden rounded-full border border-border/15 bg-surface/95 p-1 shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in",style:{left:Ge.left,top:Ge.top,width:Ge.width,height:Ge.height},children:t.map((ae,pe)=>{const $e=pe===Qe,Xe=ae.id===r,wt=`${ae.label}${ae.detail?` · ${ae.detail}`:""}${Xe?` · ${f("agent.currentSession")}`:""}`;return s.jsxs("div",{role:"option","aria-selected":$e,"data-running-session-option":ae.id,"data-selected":$e?"true":"false",title:wt,className:`relative flex min-w-0 flex-1 items-center justify-center gap-1.5 rounded-full px-2 transition-[background-color,color,transform] duration-100 ${$e?"scale-[1.02] bg-[var(--success)] text-[color:var(--success-foreground)]":Xe?"bg-primary/15 text-primary ring-1 ring-primary/30":"text-foreground"}`,children:[s.jsx("span",{className:`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[9px] font-bold tabular-nums ${$e?"bg-surface/25":"bg-surface-2 text-muted-foreground"}`,children:pe+1}),s.jsx("span",{className:"truncate text-[10px] font-medium",children:ae.label})]},ae.id)})})]},"running")};return!I&&!P&&!T||l===null||typeof document>"u"?null:s.jsxs(e9,{children:[I&&dt(),P&&!T&&it(),T&&v.active&&w&&s.jsx(hO,{groups:v.groups,currentKey:v.currentKey,onClose:()=>S(!1)})]})}function RO(){const{t:e}=Ur();return s.jsxs("div",{role:"status",className:"td-loading-skeleton overflow-hidden px-3 py-2",children:[s.jsx("span",{className:"sr-only",children:e("common.loading")}),s.jsx("div",{"aria-hidden":"true",children:["w-2/5","w-3/5","w-1/3","w-1/2","w-2/5","w-1/3"].map((t,r)=>s.jsxs("div",{className:"flex h-8 items-center gap-2",style:{paddingLeft:r>1&&r<5?20:0},children:[s.jsx("div",{className:"h-3 w-3 shrink-0 rounded-sm bg-surface-2"}),s.jsx("div",{className:`h-2 rounded bg-surface-2 ${t}`})]},r))})]})}const MO=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".go",".java",".c",".cpp",".h",".rb",".php",".swift",".kt",".sh",".css",".scss",".html",".json",".yaml",".yml",".toml",".md"]),Zb=120,Kb=120,jO=new Set,DO=[],BO={added:{label:"A",className:"text-[color:var(--diff-insert-strong)]",title:"Added"},modified:{label:"M",className:"text-[color:var(--diff-hunk-accent)]",title:"Modified"},deleted:{label:"D",className:"text-[color:var(--diff-delete-strong)]",title:"Deleted"},renamed:{label:"R",className:"text-muted-foreground",title:"Renamed"},copied:{label:"C",className:"text-[color:var(--diff-insert-strong)]",title:"Copied"},untracked:{label:"U",className:"text-[color:var(--diff-insert-strong)]",title:"Untracked (new file)"},conflicted:{label:"!",className:"text-destructive",title:"Conflicted"},unknown:{label:"?",className:"text-muted-foreground",title:"Unknown"}};function rx(e,t){if(t==="directory")return null;if(n9(e))return s.jsx(sT,{size:14});if(s9(e))return s.jsx(A3,{size:14});const r=e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")):"";return MO.has(r)?s.jsx(NT,{size:14}):s.jsx(f3,{size:14})}function p4({path:e}){const r=Yt(a=>a.changedFiles.get(e))?.status;if(!r)return null;const n=BO[r]??{label:"?",className:"text-muted-foreground",title:r};return s.jsx("span",{className:`w-4 shrink-0 text-center text-[10px] font-mono font-bold ${n.className}`,title:n.title,children:n.label})}function od(e){return e?"ml-1 w-6 opacity-100":"ml-1 w-6 opacity-100 sm:ml-0 sm:w-0 sm:overflow-hidden sm:opacity-0 sm:group-hover:ml-1 sm:group-hover:w-6 sm:group-hover:opacity-100 sm:group-focus-within:ml-1 sm:group-focus-within:w-6 sm:group-focus-within:overflow-visible sm:group-focus-within:opacity-100"}function nx(e){return od(e)}const QO=b.memo(function({path:t}){const{t:r}=Ur(),[n,a]=b.useState("idle"),[c,l]=b.useState(null),d=b.useCallback(async f=>{if(f.stopPropagation(),n!=="pending"){a("pending"),l(null);try{await r3(t),a("idle")}catch(m){a("error"),l(m instanceof Error?m.message:r("rightSidebar.downloadFailed"))}}},[t,n,r]);return s.jsx("button",{type:"button",disabled:n==="pending","aria-label":r("rightSidebar.downloadFile"),onClick:f=>{d(f)},className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${od(n==="pending")} ${n==="pending"?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,title:n==="error"?c??r("rightSidebar.downloadFailed"):r("rightSidebar.downloadFile"),children:n==="pending"?s.jsx(Dn,{size:12,className:"animate-spin"}):s.jsx(E0,{size:12})})});function m4(){const{t:e}=Ur(),[t,r]=b.useState({status:"idle"}),n=b.useCallback(async a=>{r({status:"pending"});try{await r3(a),r({status:"idle"})}catch(c){r({status:"error",message:c instanceof Error?c.message:e("rightSidebar.downloadFailed")})}},[e]);return{state:t,run:n}}function Z1(e){return e instanceof DOMException&&e.name==="AbortError"}function ep(){if(typeof window>"u")return!1;const e=window.getSelection();return!!(e&&!e.isCollapsed&&e.toString().trim())}function g4(e){return e.button===2||e.ctrlKey}const PO=176,OO=160,Kd=8;function Xb(e,t,r,n){const a=window.visualViewport,c=a?.offsetLeft??0,l=a?.offsetTop??0,d=c+(a?.width??window.innerWidth),f=l+(a?.height??window.innerHeight),m=c+Kd,x=l+Kd,y=Math.max(m,d-r-Kd),w=Math.max(x,f-n-Kd),v=t+n<=f-Kd?t:t-n;return{anchorX:e,anchorY:t,left:Math.min(Math.max(e,m),y),top:Math.min(Math.max(v,x),w)}}function x4(e){const[t,r]=b.useState(null),n=b.useRef(null),a=b.useCallback((c,l)=>{r(Xb(c,l,PO,OO))},[]);return b.useLayoutEffect(()=>{if(!e||!t||!n.current)return;const c=n.current.getBoundingClientRect();if(c.width<=0||c.height<=0)return;const l=Xb(t.anchorX,t.anchorY,c.width,c.height);l.left===t.left&&l.top===t.top||r(l)},[e,t]),{position:t,menuRef:n,openAt:a,clearPosition:()=>r(null)}}function b4(e,t){return t&&typeof document<"u"?Zs.createPortal(e,document.body):e}function FO(e,t){return t?`${e.name} ${e.path}`.toLowerCase().includes(t):!0}function sx(e,t,r){if(!t||FO(e,t))return!0;const n=r.get(e.path);return n?n.some(a=>sx(a,t,r)):!1}function K1(e){return e.map(t=>({name:t.name,path:t.path,type:t.type,isSymlink:t.isSymlink,modified:t.modified,expanded:!1,loaded:!1,children:t.type==="directory"?[]:void 0}))}function X1(e,t){return!e||!t.startsWith(e)?t:t.slice(e.length).replace(/^\/+/,"")||t}const $O=b.memo(function e({node:t,depth:r,onFileSelect:n,directoriesOnly:a=!1,onPathReference:c,referenceSelection:l,getReferenceText:d,onReferenceCopied:f,insertedReferenceKey:m,copiedReferenceKey:x,onDirectoryRoot:y,onSearchFromDirectory:w,onDirectoryPinToggle:v,onFilePinToggle:T,onOpenInFileBrowser:S,canOpenInFileBrowser:I,pinnedPaths:N,selectedFilePath:P,queryLower:$,onDirectoryDropFiles:Q,onFileDeleteRequest:U,deletingFilePath:Z,revealedDirectoryPath:J,gitIgnoreRoot:H}){const{t:ye}=Ur(),oe=Yt(ot=>ot.expandedPaths.has(t.path)),te=Yt(ot=>ot.directoryCache.get(t.path)),Ce=Yt(ot=>ot.showHiddenFiles),qe=Yt(ot=>ot.toggleExpanded),ve=Yt(ot=>ot.setDirectoryCache),Y=Yt(ot=>ot.fileSortModes[t.path]??"name"),st=Yt(ot=>ot.setDirectorySortMode),[he,Qe]=b.useState(!1),[ie,Pe]=b.useState(!1),{position:Fe,menuRef:ce,openAt:Ie,clearPosition:je}=x4(ie),[Ze,we]=b.useState(!1),le=b.useRef(0),Ge=b.useRef(null),He=`file-tree-reference:${b.useId()}:${t.path}`;vc(ce,ie&&!!l,()=>Pe(!1));const tt=b.useRef(null),xe=t.path===P||t.path===J,dt=t.type==="directory"&&(oe||!!$),it=t.type==="directory",_e=N.has(t.path),Ue=!it&&!!T,ke=!!(I&&S),V=`path:${t.path}`,ae=m===V||!!l?.paths.has(t.path),pe=x===V,$e=d?.(t.path)??t.path,Xe=ug(f,!!l),{state:wt,run:Ut}=m4(),qt=Z===t.path,Nt=it&&!a&&!!(y||w||v||ke),sr=b.useMemo(()=>{if(!te)return;if(!$)return te;const ot=Yt.getState().directoryCache;return te.filter(Lt=>(!a||Lt.type==="directory")&&sx(Lt,$,ot))},[te,a,$]),jt=b.useCallback(async()=>{if(!Yt.getState().directoryCache.has(t.path)&&!he){const Lt=l?He:`file-tree:${t.path}`;Ge.current?.abort(),c1(Lt);const nr=new AbortController;Ge.current=nr,Qe(!0);try{const ur=await ag(t.path,nr.signal,Ce,"expand_directory",Lt,Y,H);if(nr.signal.aborted)return;const Rr=K1(ur.entries);ve(t.path,Rr)}catch(ur){Z1(ur)}finally{Ge.current===nr&&(Ge.current=null),Qe(!1)}}},[t.path,he,ve,Ce,Y,H,!!l,He]),Xt=b.useCallback(async()=>{if(t.type!=="directory"){n(t.path);return}if(a&&y){y(t.path);return}const ot=!Yt.getState().expandedPaths.has(t.path);qe(t.path),ot&&await jt()},[a,t.path,t.type,jt,y,qe,n]);b.useEffect(()=>{t.type==="directory"&&oe&&!te&&!he&&jt()},[te,oe,jt,he,t.type]);const Rt=b.useCallback(ot=>{ot.stopPropagation(),c?.(t.path,V,ot.currentTarget)},[c,t.path,V]),ir=b.useCallback(ot=>{ot.stopPropagation(),y?.(t.path),Pe(!1)},[t.path,y]),ge=b.useCallback(ot=>{ot.stopPropagation(),w?.(t.path),Pe(!1)},[t.path,w]),Je=b.useCallback(ot=>{ot.stopPropagation(),v?.(t.path),Pe(!1)},[t.path,v]),at=b.useCallback(ot=>{ot.stopPropagation(),st(t.path,Y==="modified"?"name":"modified"),Pe(!1)},[t.path,st,Y]),Et=b.useCallback(ot=>{ot.stopPropagation(),T?.(t.path),Pe(!1)},[t.path,T]),X=b.useCallback(ot=>{ot.stopPropagation(),Pe(!1),Ut(t.path)},[t.path,Ut]),vt=b.useCallback(ot=>{ot.stopPropagation(),Pe(!1),U(t)},[t,U]),Bt=b.useCallback(ot=>{ot.stopPropagation(),S?.(t.path),Pe(!1)},[t.path,S]),Me=b.useCallback(ot=>{!it||!Q||!ot.dataTransfer.types.includes("Files")||(ot.preventDefault(),ot.stopPropagation(),le.current+=1,we(!0))},[it,Q]),Dr=b.useCallback(ot=>{!it||!Q||!ot.dataTransfer.types.includes("Files")||(ot.preventDefault(),ot.stopPropagation(),ot.dataTransfer.dropEffect="copy",we(!0))},[it,Q]),Le=b.useCallback(ot=>{!it||!Q||(ot.preventDefault(),ot.stopPropagation(),le.current-=1,le.current<=0&&(le.current=0,we(!1)))},[it,Q]),At=b.useCallback(ot=>{if(!it||!Q)return;ot.preventDefault(),ot.stopPropagation(),le.current=0,we(!1);const Lt=Array.from(ot.dataTransfer.files);Lt.length>0&&Q(t.path,Lt)},[it,t.path,Q]),Ot=b.useCallback(ot=>{ot.stopPropagation(),l?Ie(ot.clientX,ot.clientY):je(),Pe(Lt=>!Lt)},[je,Ie,!!l]),er=b.useCallback(ot=>{!Nt||!g4(ot)||(ot.preventDefault(),ot.stopPropagation(),Ie(ot.clientX,ot.clientY),Pe(!0))},[Nt,Ie]);return b.useEffect(()=>{if(!ie)return;const ot=nr=>{const ur=nr.target;ur instanceof Node&&(tt.current?.contains(ur)||ce.current?.contains(ur))||Pe(!1)},Lt=nr=>{nr.key==="Escape"&&Pe(!1)};return document.addEventListener("pointerdown",ot),document.addEventListener("keydown",Lt),()=>{document.removeEventListener("pointerdown",ot),document.removeEventListener("keydown",Lt)}},[ie,ce]),b.useEffect(()=>()=>{Ge.current?.abort()},[]),s.jsxs("div",{style:!dt&&!ie?{contentVisibility:"auto",containIntrinsicSize:"auto 32px"}:void 0,children:[s.jsxs("div",{ref:tt,className:"relative",children:[Xe.popoverNode,s.jsxs("div",{"data-file-tree-path":t.path,"data-sort-mode":Y,role:"button",tabIndex:0,onClick:()=>{ep()||Xt()},onContextMenu:er,onKeyDown:ot=>{ot.target!==ot.currentTarget||ot.key!=="Enter"&&ot.key!==" "||(ot.preventDefault(),Xt())},onDragEnter:Me,onDragOver:Dr,onDragLeave:Le,onDrop:At,className:`group relative flex w-full cursor-pointer items-center gap-1 rounded px-2 py-1 text-[13px] transition ${Ze?"scale-[1.015] bg-primary/15 text-foreground shadow-[0_0_0_1px_rgb(var(--primary-rgb)_/_0.45)]":xe?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,title:t.path,children:[r>0&&s.jsx("span",{"aria-hidden":"true",className:"shrink-0",style:{width:`${r*14-4}px`}}),Ze&&s.jsx("span",{className:"pointer-events-none absolute right-2 top-1/2 z-10 -translate-y-1/2 rounded-full bg-primary px-2 py-0.5 text-[10px] font-semibold text-primary-foreground shadow-md",children:ye("fileTree.dropToUploadHere")}),t.type==="directory"?s.jsxs(s.Fragment,{children:[dt?s.jsx(Al,{size:14,className:"shrink-0 text-muted-foreground/80"}):s.jsx(qs,{size:14,className:"shrink-0 text-muted-foreground/80"}),dt?s.jsx(qu,{size:14,className:"shrink-0 text-[color:var(--folder)]"}):s.jsx(nu,{size:14,className:"shrink-0 text-[color:var(--folder)]"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-[14px] shrink-0"}),s.jsx("span",{className:xe?"text-primary":"text-muted-foreground/80",children:rx(t.name,t.type)})]}),s.jsxs("span",{className:`flex-1 select-text whitespace-nowrap text-left leading-snug ${xe?"font-medium":""}`,children:[t.name,Y==="modified"&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-primary",title:ye("fileTree.sortedByModified"),"aria-label":ye("fileTree.sortedByModified"),children:s.jsx(I0,{size:11})}),t.isSymlink&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-muted-foreground/70",title:ye("fileTree.symbolicLink"),children:s.jsx(td,{size:11})})]}),s.jsxs("div",{className:`sticky right-0 z-20 flex shrink-0 items-center rounded pl-1 ${xe?"bg-surface-elevated":"bg-surface group-hover:bg-surface-2"}`,onClick:ot=>ot.stopPropagation(),children:[he&&s.jsx(Dn,{size:12,className:"shrink-0 animate-spin text-muted-foreground"}),s.jsx(p4,{path:t.path}),Nt&&s.jsx("button",{type:"button",onClick:Ot,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${od(ie)} ${ie?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":ye("fileTree.moreDirActions"),"aria-expanded":ie,title:ye("fileTree.moreDirActions"),children:s.jsx(Do,{size:13})}),!it&&!l&&s.jsx("button",{type:"button",onClick:Ot,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${od(ie||wt.status==="pending"||qt||_e)} ${ie?"bg-surface-elevated text-foreground":_e?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":ye("fileTree.moreFileActions"),"aria-expanded":ie,title:wt.status==="error"?wt.message??ye("rightSidebar.downloadFailed"):ye("fileTree.moreFileActions"),children:wt.status==="pending"||qt?s.jsx(Dn,{size:13,className:"animate-spin"}):s.jsx(Do,{size:13})}),c&&s.jsx("button",{type:"button",onClick:Rt,...Xe($e,V),className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-[11px] font-semibold transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${l?"ml-1 min-h-11 min-w-11":nx(ae||pe)} ${ae||pe?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":l?`${l.label}: ${t.name}`:ye(pe?"rightSidebar.copied":ae?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":l?ae:void 0,disabled:!!l?.disabled&&!ae,title:l?`${l.label}: ${t.name}`:ye(pe?"rightSidebar.copied":ae?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:pe||ae?s.jsx(oi,{size:12}):s.jsx(td,{size:12})}),Nt&&ie&&b4(s.jsxs("div",{ref:ce,className:`${Fe?l?"fixed z-popover":"fixed z-menu-panel":"absolute right-2 top-[calc(100%+2px)] z-30"} w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in`,style:Fe?{left:Fe.left,top:Fe.top}:void 0,children:[ke&&s.jsxs("button",{type:"button",onClick:Bt,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:ye("fileTree.openInFileBrowserTitle"),children:[s.jsx(qu,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye("fileTree.openInFileBrowser")})]}),y&&s.jsxs("button",{type:"button",onClick:ir,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:ye("fileTree.openDirRootTitle"),children:[s.jsx(qu,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye("fileTree.openDirRoot")})]}),w&&s.jsxs("button",{type:"button",onClick:ge,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:ye("fileTree.searchFromDirTitle"),children:[s.jsx(dg,{size:13,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye("fileTree.searchFromDir")})]}),v&&s.jsxs("button",{type:"button",onClick:Je,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${_e?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:ye(_e?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[_e?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye(_e?"fileTree.unpinDir":"fileTree.pinDir")})]}),s.jsxs("button",{type:"button",onClick:at,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",children:[Y==="modified"?s.jsx(KA,{size:13,className:"shrink-0"}):s.jsx(I0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye(Y==="modified"?"fileTree.sortByName":"fileTree.sortByModified")})]})]}),!!Fe),!it&&!l&&ie&&s.jsxs("div",{className:"absolute right-2 top-[calc(100%+2px)] z-30 w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in",children:[ke&&s.jsxs("button",{type:"button",onClick:Bt,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:ye("fileTree.openInFileBrowserTitle"),children:[s.jsx(f3,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye("fileTree.openInFileBrowser")})]}),s.jsxs("button",{type:"button",onClick:X,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:ye("rightSidebar.downloadFile"),children:[s.jsx(E0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye("rightSidebar.downloadFile")})]}),Ue&&s.jsxs("button",{type:"button",onClick:Et,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${_e?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:ye(_e?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[_e?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye(_e?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:vt,disabled:qt,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-destructive transition hover:bg-destructive/10 active:scale-[0.99] disabled:opacity-50",title:ye("fileTree.deleteFile"),children:[qt?s.jsx(Dn,{size:13,className:"shrink-0 animate-spin"}):s.jsx(Ms,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:ye("fileTree.deleteFile")})]})]})]})]})]}),dt&&sr&&sr.length>0&&s.jsx("div",{className:r===0?"mt-0.5":"",children:sr.map(ot=>s.jsx(e,{node:ot,depth:r+1,onFileSelect:n,directoriesOnly:a,onPathReference:c,referenceSelection:l,getReferenceText:d,onReferenceCopied:f,onDirectoryRoot:y,onSearchFromDirectory:w,onDirectoryPinToggle:v,onFilePinToggle:T,onOpenInFileBrowser:S,canOpenInFileBrowser:I,pinnedPaths:N,selectedFilePath:P,queryLower:$,insertedReferenceKey:m,copiedReferenceKey:x,onDirectoryDropFiles:Q,onFileDeleteRequest:U,deletingFilePath:Z,gitIgnoreRoot:H,revealedDirectoryPath:J},ot.path))})]})}),UO=b.memo(function({node:t,rootPath:r,onFileSelect:n,onPathReference:a,referenceSelection:c,getReferenceText:l,onReferenceCopied:d,insertedReferenceKey:f,copiedReferenceKey:m,onDirectoryRoot:x,onSearchFromDirectory:y,onDirectoryPinToggle:w,onFilePinToggle:v,pinnedPaths:T,selectedFilePath:S,onFileDeleteRequest:I,deletingFilePath:N}){const{t:P}=Ur(),$=t.path===S,Q=t.type==="directory",U=T.has(t.path),Z=!Q&&!!v,J=`path:${t.path}`,H=f===J||!!c?.paths.has(t.path),ye=m===J,oe=l?.(t.path)??t.path,te=ug(d,!!c),{state:Ce,run:qe}=m4(),[ve,Y]=b.useState(!1),{position:st,menuRef:he,openAt:Qe,clearPosition:ie}=x4(ve);vc(he,ve&&!!c,()=>Y(!1));const Pe=b.useRef(null),Fe=N===t.path,ce=Q&&!!(x||y||w),Ie=b.useCallback(()=>{ep()||(t.type==="directory"?x?.(t.path):n(t.path))},[t.path,t.type,x,n]),je=b.useCallback(xe=>{xe.stopPropagation(),a?.(t.path,J,xe.currentTarget)},[a,t.path,J]),Ze=b.useCallback(xe=>{xe.stopPropagation(),w?.(t.path),Y(!1)},[t.path,w]),we=b.useCallback(xe=>{xe.stopPropagation(),v?.(t.path),Y(!1)},[t.path,v]),le=b.useCallback(xe=>{xe.stopPropagation(),Y(!1),qe(t.path)},[t.path,qe]),Ge=b.useCallback(xe=>{xe.stopPropagation(),Y(!1),I(t)},[t,I]),He=b.useCallback(xe=>{xe.stopPropagation(),c?Qe(xe.clientX,xe.clientY):ie(),Y(dt=>!dt)},[ie,Qe,!!c]),tt=b.useCallback(xe=>{!ce||!g4(xe)||(xe.preventDefault(),xe.stopPropagation(),Qe(xe.clientX,xe.clientY),Y(!0))},[ce,Qe]);return b.useEffect(()=>{if(!ve)return;const xe=it=>{const _e=it.target;_e instanceof Node&&(Pe.current?.contains(_e)||he.current?.contains(_e))||Y(!1)},dt=it=>{it.key==="Escape"&&Y(!1)};return document.addEventListener("pointerdown",xe),document.addEventListener("keydown",dt),()=>{document.removeEventListener("pointerdown",xe),document.removeEventListener("keydown",dt)}},[ve,he]),s.jsxs("div",{ref:Pe,className:"relative border-b border-border/10 last:border-b-0",children:[te.popoverNode,s.jsxs("div",{role:"button",tabIndex:0,onClick:Ie,onContextMenu:tt,onKeyDown:xe=>{xe.target!==xe.currentTarget||xe.key!=="Enter"&&xe.key!==" "||(xe.preventDefault(),Ie())},className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] transition ${$?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,title:t.path,children:[t.type==="directory"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-[14px] shrink-0"}),s.jsx(nu,{size:14,className:"shrink-0 text-[color:var(--folder)]"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-[14px] shrink-0"}),s.jsx("span",{className:$?"text-primary":"text-muted-foreground/80",children:rx(t.name,t.type)})]}),s.jsxs("span",{className:"min-w-0 flex-1 select-text",children:[s.jsxs("span",{className:`block whitespace-normal break-all font-medium leading-snug ${$?"text-primary":"text-foreground"}`,children:[t.name,t.isSymlink&&s.jsx("span",{className:"ml-1 inline-flex align-middle text-muted-foreground/70",title:P("fileTree.symbolicLink"),children:s.jsx(td,{size:11})})]}),s.jsx("span",{className:"mt-0.5 block truncate font-mono text-[10px] text-muted-foreground/80",children:X1(r,t.path)})]}),s.jsx(p4,{path:t.path}),t.type==="directory"&&(w||y)&&s.jsx("button",{type:"button",onClick:He,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${od(ve)} ${ve?"bg-surface-elevated text-foreground":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":P("fileTree.moreDirActions"),"aria-expanded":ve,title:P("fileTree.moreDirActions"),children:s.jsx(Do,{size:13})}),!Q&&!c&&s.jsx("button",{type:"button",onClick:He,className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-muted-foreground transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${od(ve||Ce.status==="pending"||Fe||U)} ${ve?"bg-surface-elevated text-foreground":U?"bg-primary/15 text-primary":"bg-surface-2 hover:bg-surface-elevated hover:text-foreground"}`,"aria-label":P("fileTree.moreFileActions"),"aria-expanded":ve,title:Ce.status==="error"?Ce.message??P("rightSidebar.downloadFailed"):P("fileTree.moreFileActions"),children:Ce.status==="pending"||Fe?s.jsx(Dn,{size:13,className:"animate-spin"}):s.jsx(Do,{size:13})}),a&&s.jsx("button",{type:"button",onClick:je,...te(oe,J),className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-[11px] font-semibold transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${c?"ml-1 min-h-11 min-w-11":nx(H||ye)} ${H||ye?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":c?`${c.label}: ${t.name}`:P(ye?"rightSidebar.copied":H?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":c?H:void 0,disabled:!!c?.disabled&&!H,title:c?`${c.label}: ${t.name}`:P(ye?"rightSidebar.copied":H?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:ye||H?s.jsx(oi,{size:12}):s.jsx(td,{size:12})})]}),ce&&ve&&b4(s.jsxs("div",{ref:he,className:`${st?c?"fixed z-popover":"fixed z-menu-panel":"absolute right-2 top-[calc(100%+2px)] z-30"} w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in`,style:st?{left:st.left,top:st.top}:void 0,children:[x&&s.jsxs("button",{type:"button",onClick:xe=>{xe.stopPropagation(),x(t.path),Y(!1)},className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:P("fileTree.openDirRootTitle"),children:[s.jsx(qu,{size:13,className:"shrink-0 text-[color:var(--folder)]"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:P("fileTree.openDirRoot")})]}),y&&s.jsxs("button",{type:"button",onClick:xe=>{xe.stopPropagation(),y(t.path),Y(!1)},className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",children:[s.jsx(dg,{size:13,className:"shrink-0 text-primary"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:P("fileTree.searchFromDir")})]}),w&&s.jsxs("button",{type:"button",onClick:Ze,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${U?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:P(U?"fileTree.unpinDirTitle":"fileTree.pinDirTitle"),children:[U?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:P(U?"fileTree.unpinDir":"fileTree.pinDir")})]})]}),!!st),!Q&&!c&&ve&&s.jsxs("div",{className:"absolute right-2 top-[calc(100%+2px)] z-30 w-44 overflow-hidden rounded-xl border border-border/15 bg-surface/98 p-1 text-[12px] shadow-xl shadow-[0_18px_48px_var(--app-shadow-soft)] backdrop-blur animate-fade-in",children:[s.jsxs("button",{type:"button",onClick:le,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-foreground transition hover:bg-surface-2 active:scale-[0.99]",title:P("rightSidebar.downloadFile"),children:[s.jsx(E0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:P("rightSidebar.downloadFile")})]}),Z&&s.jsxs("button",{type:"button",onClick:we,className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium transition active:scale-[0.99] ${U?"text-primary hover:bg-primary/10":"text-foreground hover:bg-surface-2"}`,title:P(U?"fileTree.unpinFileTitle":"fileTree.pinFileTitle"),children:[U?s.jsx(R0,{size:13,className:"shrink-0"}):s.jsx(N0,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:P(U?"fileTree.unpinFile":"fileTree.pinFile")})]}),s.jsxs("button",{type:"button",onClick:Ge,disabled:Fe,className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left font-medium text-destructive transition hover:bg-destructive/10 active:scale-[0.99] disabled:opacity-50",title:P("fileTree.deleteFile"),children:[Fe?s.jsx(Dn,{size:13,className:"shrink-0 animate-spin"}):s.jsx(Ms,{size:13,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:P("fileTree.deleteFile")})]})]})]})}),zO=60,Jb=60,HO=20;function ey({count:e,loading:t,engine:r,limited:n,scope:a,content:c}){const{t:l}=Ur();return s.jsxs("div",{className:"sticky top-0 z-10 -mx-2 -mt-2 mb-2 border-b border-border/15 bg-surface/95 px-3 py-2.5 backdrop-blur",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2 text-[12px] font-semibold text-foreground",children:[s.jsx(dg,{size:14,className:"shrink-0 text-primary"}),s.jsx("span",{children:c?l("fileTree.contentMatchesCount",{count:e}):l("fileTree.searchResults",{count:e})})]}),r&&s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 rounded-full bg-surface-2 px-2 py-0.5 text-[9px] uppercase tracking-[0.12em] text-muted-foreground",children:[t&&s.jsx(Dn,{size:9,className:"animate-spin"}),r,n?" · limited":""]})]}),s.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1.5 text-[10px] text-muted-foreground",children:[s.jsx("span",{className:"shrink-0",children:l("fileTree.searchScope")}),s.jsx("span",{className:"min-w-0 truncate font-mono text-foreground/75",title:a,children:a}),t&&s.jsx("span",{className:"ml-auto shrink-0",children:l("fileTree.searching")})]})]})}function WO(e,t){if(!t)return e;const r=e.toLowerCase(),n=t.toLowerCase(),a=[];let c=0,l=r.indexOf(n,c),d=0;for(;l>=0&&n;)l>c&&a.push(e.slice(c,l)),a.push(s.jsx("mark",{className:"rounded-sm bg-[rgb(var(--warning-rgb)_/_0.30)] px-0.5 text-foreground",children:e.slice(l,l+n.length)},`m-${d++}`)),c=l+n.length,l=r.indexOf(n,c);return c<e.length&&a.push(e.slice(c)),a.length>0?a:e}const GO=b.memo(function({entry:t,rootPath:r,selectedFilePath:n,query:a,onContentMatchSelect:c,onPathReference:l,referenceSelection:d,getReferenceText:f,onReferenceCopied:m,insertedReferenceKey:x,copiedReferenceKey:y}){const{t:w}=Ur(),[v,T]=b.useState(!0),S=t.path===n,I=v?t.matches.slice(0,HO):[],N=t.matches.length-I.length,P=`path:${t.path}`,$=x===P||!!d?.paths.has(t.path),Q=y===P,U=f?.(t.path)??t.path,Z=ug(m,!!d);return s.jsxs("div",{className:"border-b border-border/10 last:border-b-0",children:[Z.popoverNode,s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{ep()||T(J=>!J)},onKeyDown:J=>{J.target!==J.currentTarget||J.key!=="Enter"&&J.key!==" "||(J.preventDefault(),T(H=>!H))},className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left text-[13px] transition ${S?"bg-surface-elevated text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,title:t.path,children:[v?s.jsx(Al,{size:14,className:"shrink-0 text-muted-foreground/80"}):s.jsx(qs,{size:14,className:"shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:S?"text-primary":"text-muted-foreground/80",children:rx(t.name,"file")}),s.jsxs("span",{className:"min-w-0 flex-1 select-text",children:[s.jsx("span",{className:"block whitespace-normal break-all font-medium leading-snug",children:t.name}),s.jsx("span",{className:"mt-0.5 block truncate font-mono text-[10px] text-muted-foreground/80",children:X1(r,t.path)})]}),s.jsx("span",{className:"shrink-0 select-none rounded-full bg-surface-2 px-1.5 py-0.5 text-[10px] text-muted-foreground",children:t.matches.length}),!d&&s.jsx(QO,{path:t.path}),l&&s.jsx("button",{type:"button",onClick:J=>{J.stopPropagation(),l(t.path,P,J.currentTarget)},...Z(U,P),className:`inline-flex h-6 shrink-0 select-none items-center justify-center rounded-md text-[11px] font-semibold transition focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary active:scale-95 ${d?"ml-1 min-h-11 min-w-11":nx($||Q)} ${$||Q?"bg-surface-elevated text-foreground":"bg-primary/10 text-primary"}`,"aria-label":d?`${d.label}: ${t.name}`:w(Q?"rightSidebar.copied":$?"rightSidebar.inserted":"fileTree.insertRefTitle"),"aria-pressed":d?$:void 0,disabled:!!d?.disabled&&!$,title:d?`${d.label}: ${t.name}`:w(Q?"rightSidebar.copied":$?"rightSidebar.inserted":"fileTree.insertRefTitle"),children:Q||$?s.jsx(oi,{size:12}):s.jsx(td,{size:12})})]}),v&&s.jsxs("div",{className:"mb-1 ml-3 border-l border-border/20 pl-1",children:[I.map((J,H)=>s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{ep()||c?.(t.path,J.line)},onKeyDown:ye=>{ye.target!==ye.currentTarget||ye.key!=="Enter"&&ye.key!==" "||(ye.preventDefault(),c?.(t.path,J.line))},className:"flex w-full cursor-pointer items-start gap-2 rounded px-2 py-1 text-left font-mono text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground",title:`${X1(r,t.path)}:${J.line}`,children:[s.jsx("span",{className:"shrink-0 select-none tabular-nums text-muted-foreground/60",children:J.line}),s.jsx("span",{className:"min-w-0 flex-1 truncate whitespace-pre select-text",children:WO(J.text,a)})]},`${J.line}-${H}`)),N>0&&s.jsx("div",{className:"px-2 py-1 text-[10px] text-muted-foreground/70",children:w("fileTree.moreMatches",{count:N})})]})]})});function VO({rootPath:e,onFileSelect:t,directoriesOnly:r=!1,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,insertedReferenceKey:d,copiedReferenceKey:f,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,onOpenInFileBrowser:v,canOpenInFileBrowser:T=!1,pinnedPaths:S=jO,selectedFilePath:I,query:N="",searchRootPath:P,searchOptions:$={},searchMode:Q="name",onContentMatchSelect:U,onDirectoryDropFiles:Z,revealDirectory:J}){const{t:H}=Ur(),ye=b.useId(),oe=a?`file-tree-reference-root:${ye}:${e}`:`file-tree-root:${e}`,te=Yt(Le=>e?Le.directoryCache.get(e):void 0),Ce=Yt(Le=>Le.setDirectoryCache),qe=Yt(Le=>Le.showHiddenFiles),ve=Yt(Le=>Le.fileSortModesHydrated),Y=Yt(Le=>Le.fileSortModes[e]??"name"),st=Yt(Le=>Le.hydrateFileSortModes),he=Yt(Le=>Le.hydrateHideGitIgnoredRoots),Qe=Yt(Le=>!!Le.hideGitIgnoredRoots[e]),ie=Yt(Le=>Le.hideGitIgnoredRootsHydrated),Pe=Yt(Le=>JSON.stringify(Le.gitIgnoreExceptions[e]??[])),Fe=Yt(Le=>Le.invalidateDirectoryCache),ce=`${e}:${Qe}:${Pe}`,[Ie,je]=b.useState("");b.useLayoutEffect(()=>{e&&Fe(e,!0),je(ce)},[e,Qe,Pe,Fe,ce]);const[Ze,we]=b.useState(!1),[le,Ge]=b.useState(null),[He,tt]=b.useState(!1),[xe,dt]=b.useState(!1),[it,_e]=b.useState(null),[Ue,ke]=b.useState(ve&&ie),V=ve&&ie||Ue;b.useEffect(()=>{let Le=!1;return Promise.all([st(),he()]).catch(()=>{}).finally(()=>{Le||ke(!0)}),()=>{Le=!0}},[st,he]);const[ae,pe]=b.useState([]),[$e,Xe]=b.useState(null),[wt,Ut]=b.useState(Zb),[qt,Nt]=b.useState([]),[sr,jt]=b.useState(null),Xt=b.useRef({busy:!1}),Rt=b.useRef(0),ir=b.useRef(e);ir.current=e,b.useEffect(()=>{const Le=()=>{Rt.current++};for(const At of["pagehide","auth:unauthorized",Fu])window.addEventListener(At,Le);return()=>{Le();for(const At of["pagehide","auth:unauthorized",Fu])window.removeEventListener(At,Le)}},[]);const ge=b.useRef(null),Je=b.useRef(0),at=N.trim().toLowerCase(),Et=Q==="content",X=P||e,vt=$.excludePatterns??DO,Bt=vt.join(`
137
137
  `);b.useEffect(()=>{const Le=J?.path;if(!Le||!Le.startsWith(`${e}/`)&&Le!==e)return;const At=Le.slice(e.length).replace(/^\/+/,""),Ot=At?At.split("/"):[],er=Ot.map((Tt,Ft)=>`${e}/${Ot.slice(0,Ft+1).join("/")}`),ot=Yt.getState(),Lt=er.filter(Tt=>!ot.expandedPaths.has(Tt));Lt.length>0&&Yt.setState(Tt=>({expandedPaths:new Set([...Tt.expandedPaths,...Lt])}));let nr=!1,ur=0;const Rr=()=>{if(nr)return;const Tt=Array.from(document.querySelectorAll("[data-file-tree-path]")).find(Ft=>Ft.dataset.fileTreePath===Le);if(Tt){Tt.scrollIntoView({block:"center",behavior:"smooth"});return}ur+=1,ur<80&&window.setTimeout(Rr,50)},Gr=window.requestAnimationFrame(Rr);return()=>{nr=!0,window.cancelAnimationFrame(Gr)}},[J?.nonce,J?.path,e]);const Me=b.useCallback(async Le=>{if(Xt.current.busy||Le.type==="directory")return;const At=Rt.current,Ot=mi(),er=Eo(),ot=e,Lt=Le.path.slice(0,Le.path.lastIndexOf("/"))||"/",nr=()=>Yt.getState().directoryCache.get(Lt)?.find(Ct=>Ct.path===Le.path),ur=Ct=>JSON.stringify([Ct.path,Ct.name,Ct.type,Ct.isSymlink,Ct.modified]),Rr=ur(Le),Gr=nr(),Tt=Gr?ur(Gr):null;let Ft=!1;const be=()=>{const Ct=nr();return At===Rt.current&&ot===ir.current&&Ot===mi()&&er===Eo()&&!er?.closed&&ur(Le)===Rr&&(Ct?ur(Ct)===(Tt??Rr):Tt===null||Ft)};await pg(Xt.current,{current:be,confirm:()=>C3({title:H("fileTree.deleteFile"),message:H("fileTree.deleteFileConfirm",{name:Le.name}),confirmLabel:H("fileTree.deleteFile"),cancelLabel:H("common.cancel")}),submit:async Ct=>{await t9(Le.path,Ct),Ft=!0},apply:()=>{Yt.getState().applyFileWatchEvents([{type:"deleted",path:Le.path}]),pe(Ct=>Ct.filter(gt=>gt.path!==Le.path)),Nt(Ct=>Ct.filter(gt=>gt.path!==Le.path)),S.has(Le.path)&&w?.(Le.path)},pending:Ct=>{At===Rt.current&&jt(Ct?Le.path:null)},failure:Ct=>d1(H("fileTree.deleteFileFailed",{message:Ct})),expiredMessage:"File deletion context changed"})},[e,w,S,H]);b.useEffect(()=>{if(!e||!V||Ie!==ce)return;if(at){we(!1);return}if(Yt.getState().directoryCache.has(e)){we(!1);return}let Le=!1;const At=new AbortController;return we(!0),Ge(null),ag(e,At.signal,qe,"load_file_tree_root",oe,Y,e).then(Ot=>{if(Le)return;const er=K1(Ot.entries);tt(!!Ot.truncated),Ce(e,er)}).catch(Ot=>{Le||Z1(Ot)||Ge(Ot instanceof Error?Ot.message:"Failed to load directory")}).finally(()=>{Le||we(!1)}),()=>{Le=!0,At.abort(),c1(oe)}},[at,te,e,Y,Ce,qe,V,Qe,Pe,oe,Ie,ce]),b.useEffect(()=>{if(!X||!at){dt(!1),_e(null),pe([]),Nt([]),Xe(null);return}let Le=!1;const At=new AbortController,Ot=new Set;dt(!0),_e(null),pe([]),Nt([]),Ut(Et?zO:Zb),Xe({truncated:!1,total:0,engine:"rg",limited:!1,done:!1});const er=`file-search:${a?ye+":":""}${X}:${++Je.current}`;return r9(X,N.trim(),ot=>{if(!Le){if(ot.engine&&Xe(Lt=>({truncated:Lt?.truncated??!1,total:Lt?.total??0,engine:ot.engine,limited:ot.limited??Lt?.limited??!1,done:Lt?.done??!1})),ot.entries?.length){const Lt=ot.entries.filter(nr=>Ot.has(nr.path)?!1:(Ot.add(nr.path),!0));Lt.length>0&&(pe(nr=>[...nr,...K1(Lt)]),Xe(nr=>nr?{...nr,total:Ot.size}:{truncated:!1,total:Ot.size,engine:"rg",limited:!1,done:!1}))}if(ot.contentEntries?.length){const Lt=ot.contentEntries.filter(nr=>Ot.has(nr.path)?!1:(Ot.add(nr.path),!0));Lt.length>0&&(Nt(nr=>[...nr,...Lt]),Xe(nr=>nr?{...nr,total:Ot.size}:{truncated:!1,total:Ot.size,engine:"rg",limited:!1,done:!1}))}ot.done&&Xe(Lt=>({truncated:!!ot.truncated,total:typeof ot.total=="number"?ot.total:Ot.size,engine:ot.engine??Lt?.engine??"rg",limited:!!ot.limited,done:!0}))}},At.signal,qe,Q,er,{excludePatterns:vt,caseSensitive:$.caseSensitive,wholeWord:$.wholeWord,regex:$.regex}).catch(ot=>{Le||Z1(ot)||(_e(ot instanceof Error?ot.message:"Failed to search files"),pe([]),Nt([]),Xe(null))}).finally(()=>{Le||dt(!1)}),()=>{Le=!0,At.abort(),c1(er)}},[X,Bt,Et,N,at,Q,$.caseSensitive,$.regex,$.wholeWord,qe,!!a,ye]),b.useEffect(()=>{if(!at)return;const Le=ge.current;if(!Le)return;const At=Et?qt.length:ae.length,Ot=Et?Jb:Kb,er=new IntersectionObserver(ot=>{ot.some(Lt=>Lt.isIntersecting)&&Ut(Lt=>Math.min(Lt+Ot,At))},{rootMargin:"160px 0px"});return er.observe(Le),()=>er.disconnect()},[at,ae.length,qt.length,Et]);const Dr=b.useMemo(()=>{if(!te)return;if(!at)return r?te.filter(At=>At.type==="directory"):te;const Le=Yt.getState().directoryCache;return te.filter(At=>(!r||At.type==="directory")&&sx(At,at,Le))},[r,at,te]);if(!e)return s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:H("fileTree.noWorkingDir")});if(Ze||!V)return s.jsx(RO,{});if(at&&Et){const Le=$e?.total??qt.length,At=qt.slice(0,wt),Ot=wt<qt.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(ey,{count:Le,loading:xe,engine:$e?.engine,limited:$e?.limited,scope:X,content:!0}),it?s.jsxs("div",{className:"mx-1 mt-3 rounded-xl border border-border/15 bg-surface-2 px-4 py-5 text-center text-sm text-muted-foreground",children:[H("fileTree.contentSearchNeedsRipgrep"),s.jsx("div",{className:"mt-1 break-words text-[11px] text-muted-foreground/70",children:it})]}):xe&&qt.length===0?s.jsx(_0,{label:H("fileTree.searching"),className:"py-8"}):qt.length===0?s.jsx("div",{className:"mx-1 mt-3 overflow-hidden rounded-xl border border-border/15 bg-surface-2 px-4 py-8 text-center text-sm text-muted-foreground",children:H("fileTree.noContentMatches")}):s.jsxs(s.Fragment,{children:[$e?.limited&&s.jsx("div",{className:"mb-2 rounded-xl bg-[rgb(var(--warning-rgb)_/_0.12)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:H("fileTree.searchTruncatedHint",{count:$e.total})}),At.map(er=>s.jsx(GO,{entry:er,rootPath:X,selectedFilePath:I,query:N.trim(),onContentMatchSelect:U,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,insertedReferenceKey:d,copiedReferenceKey:f},er.path)),s.jsx("div",{ref:ge,className:"py-2 text-center text-[11px] text-muted-foreground",children:Ot?s.jsx("button",{type:"button",onClick:()=>Ut(er=>Math.min(er+Jb,qt.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:H("fileTree.loadMoreSearchResults",{shown:At.length,total:qt.length})}):xe?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(Dn,{size:10,className:"animate-spin"}),H("fileTree.searchStillRunning")]}):At.length>0?s.jsx("span",{children:H("fileTree.showingSearchResults",{shown:At.length,total:Le})}):null})]})]})}if(at){const Le=$e?.total??ae.length,At=ae.slice(0,wt),Ot=wt<ae.length;return s.jsxs("div",{className:"termdock-native-select min-h-full space-y-px bg-surface px-2 py-2",children:[s.jsx(ey,{count:Le,loading:xe,engine:$e?.engine,limited:$e?.limited,scope:X,content:!1}),xe&&ae.length===0?s.jsx(_0,{label:H("fileTree.searching"),className:"py-8"}):it?s.jsx("div",{className:"px-4 py-4 text-sm text-destructive",children:it}):ae.length===0?s.jsx("div",{className:"mx-1 mt-3 overflow-hidden rounded-xl border border-border/15 bg-surface-2 px-4 py-8 text-center text-sm text-muted-foreground",children:H("fileTree.noMatchingFiles")}):s.jsxs(s.Fragment,{children:[$e?.limited&&s.jsx("div",{className:"mb-2 rounded-xl bg-[rgb(var(--warning-rgb)_/_0.12)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:H("fileTree.searchTruncatedHint",{count:$e.total})}),At.map(er=>s.jsx(UO,{node:er,rootPath:X,onFileSelect:t,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,pinnedPaths:S,selectedFilePath:I,insertedReferenceKey:d,copiedReferenceKey:f,onFileDeleteRequest:Me,deletingFilePath:sr},er.path)),s.jsx("div",{ref:ge,className:"py-2 text-center text-[11px] text-muted-foreground",children:Ot?s.jsx("button",{type:"button",onClick:()=>Ut(er=>Math.min(er+Kb,ae.length)),className:"rounded-full bg-surface-2 px-3 py-1 hover:bg-surface-elevated hover:text-foreground",children:H("fileTree.loadMoreSearchResults",{shown:At.length,total:ae.length})}):xe?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(Dn,{size:10,className:"animate-spin"}),H("fileTree.searchStillRunning")]}):At.length>0?s.jsx("span",{children:H("fileTree.showingSearchResults",{shown:At.length,total:Le})}):null})]})]})}return le?s.jsx("div",{role:a?"alert":void 0,className:"px-4 py-4 text-sm text-destructive",children:le}):!te||te.length===0?s.jsx("div",{className:"px-4 py-8 text-center text-sm text-muted-foreground",children:H("fileTree.emptyDir")}):!Dr||Dr.length===0?s.jsx("div",{className:"mx-3 mt-3 overflow-hidden rounded-xl border border-border/15 bg-surface-2 px-4 py-8 text-center text-sm text-muted-foreground",children:H("fileTree.noMatchingFiles")}):s.jsxs("div",{className:"termdock-native-select w-max min-w-full space-y-px px-2 py-2",children:[He&&s.jsx("div",{className:"mb-2 rounded-xl bg-[rgb(var(--warning-rgb)_/_0.12)] px-3 py-2 text-[11px] text-[color:var(--warning)]",children:H("fileTree.truncatedHint")}),Dr.map(Le=>s.jsx($O,{node:Le,gitIgnoreRoot:e,depth:0,onFileSelect:t,directoriesOnly:r,onPathReference:n,referenceSelection:a,getReferenceText:c,onReferenceCopied:l,onDirectoryRoot:m,onSearchFromDirectory:x,onDirectoryPinToggle:y,onFilePinToggle:w,onOpenInFileBrowser:v,canOpenInFileBrowser:T,pinnedPaths:S,selectedFilePath:I,queryLower:at,insertedReferenceKey:d,copiedReferenceKey:f,onDirectoryDropFiles:Z,onFileDeleteRequest:Me,deletingFilePath:sr,revealedDirectoryPath:J?.path},Le.path))]})}function J1(e){return e.trim().replace(/\/+$/,"")||"/"}function qO(e){const t=J1(e);if(t==="/")return"/";const r=t.lastIndexOf("/");return r<=0?"/":t.slice(0,r)}function Ap({open:e,initialPath:t,title:r,labels:n,onCancel:a,onConfirm:c}){const{t:l}=Ur(),d={hint:n?.hint??l("sidebar.directoryPickerHint"),cancel:n?.cancel??l("common.cancel"),confirm:n?.confirm??l("sidebar.useThisFolder"),close:n?.close??l("common.close"),parent:n?.parent??l("rightSidebar.parentFolder")},f=b.useRef(null);vc(f,e,a);const[m,x]=b.useState(()=>J1(t));return b.useEffect(()=>{e&&x(J1(t))},[t,e]),b.useEffect(()=>{if(!e)return;const y=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=y}},[e]),e?Zs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop cursor-default bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:a,"aria-label":d.cancel}),s.jsxs("section",{ref:f,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"directory-picker-title",className:"fixed bottom-[max(0.75rem,env(safe-area-inset-bottom,0px))] left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(0.75rem,env(safe-area-inset-top,0px))] z-modal-panel flex flex-col overflow-hidden rounded-2xl border border-border/15 bg-surface shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:bottom-auto sm:left-1/2 sm:right-auto sm:top-1/2 sm:h-[min(72svh,36rem)] sm:w-[min(36rem,calc(100vw-2rem))] sm:-translate-x-1/2 sm:-translate-y-1/2",children:[s.jsxs("header",{className:"flex shrink-0 items-center gap-3 border-b border-border/15 px-4 py-3",children:[s.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary",children:s.jsx(PT,{size:15})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h2",{id:"directory-picker-title",className:"text-[13px] font-semibold text-foreground",children:r}),s.jsx("p",{className:"mt-0.5 text-[10px] text-muted-foreground",children:d.hint})]}),s.jsx("button",{type:"button",onClick:a,className:"inline-flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":d.close,children:s.jsx(jn,{size:15})})]}),s.jsxs("div",{className:"flex min-h-11 shrink-0 items-center gap-2 border-b border-border/15 px-3 py-1.5",children:[s.jsx("button",{type:"button",disabled:m==="/",onClick:()=>x(qO(m)),className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground disabled:opacity-30","aria-label":d.parent,children:s.jsx(u3,{size:14})}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[10.5px] text-foreground",title:m,children:m})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain py-1",children:s.jsx(VO,{rootPath:m,directoriesOnly:!0,onFileSelect:()=>{},onDirectoryRoot:x,selectedFilePath:t||null})}),s.jsxs("footer",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/15 bg-surface-elevated px-3 py-3",children:[s.jsx("button",{type:"button",onClick:a,className:"min-h-10 rounded-lg bg-surface-2 px-4 text-[11px] font-medium text-foreground transition hover:bg-surface",children:d.cancel}),s.jsxs("button",{type:"button",onClick:()=>c(m),className:"inline-flex min-h-10 items-center gap-1.5 rounded-lg bg-primary px-4 text-[11px] font-semibold text-primary-foreground transition hover:bg-primary/90",children:[s.jsx(oi,{size:13}),d.confirm]})]})]})]}),document.body):null}const YO=Object.freeze(Object.defineProperty({__proto__:null,DirectoryPickerDialog:Ap},Symbol.toStringTag,{value:"Module"})),eg="termdock:new-session-commands:v1",gc="__saved_command__:";function zh(e){return[...new Set(Object.entries(e).filter(([t])=>t.startsWith(gc)||t==="__custom__"||t==="__terminal__").map(([,t])=>t.trim()).filter(Boolean))]}function Xd(){try{const e=JSON.parse(localStorage.getItem(eg)||"{}");return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}catch{return{}}}function ZO({directories:e,tmuxAvailable:t,options:r,agents:n,selectedAgent:a,detecting:c,resumeHistory:l,resumeHistoryLoading:d,resumeHistoryPendingId:f,resumeHistoryError:m,onRefreshAgents:x,onSelectAgent:y,onLaunchAgent:w,onResumeHistory:v,onRemoveResumeHistory:T,onClose:S,onOptionsChange:I,additionalContent:N,footerActions:P,launchPending:$=!1,launchError:Q}){const{t:U,locale:Z}=Ur(),J=b.useRef(null);vc(J,!0,S,()=>document.querySelector('[aria-controls="sidebar-launch-options"]'));const[H,ye]=b.useState(a),[oe,te]=b.useState(!1),[Ce,qe]=b.useState(!1),[ve,Y]=b.useState(Xd),[st,he]=b.useState(()=>zh(Xd())),[Qe,ie]=b.useState(null),[Pe,Fe]=b.useState("idle"),ce=Ce?"__custom__":H?.slug??"__terminal__",Ie=H?.command??"",je=Ce?ve.__custom__??ve.__terminal__??"":H?ve[ce]??Ie:"",Ze=()=>{const ke=je.trim()||Ie;if(!(Ce&&!ke))try{const V={...Xd(),[ce]:ke};if(Ce){for(const ae of zh(Xd()))V[gc+ae]=ae;V[gc+ke]=ke}localStorage.setItem(eg,JSON.stringify(V)),he(zh(V)),Ce&&ie(ke),Fe("saved")}catch{Fe("error")}},we=()=>{if(Qe)try{const ke=Xd();for(const[V,ae]of Object.entries(ke))(V.startsWith(gc)||V==="__custom__"||V==="__terminal__")&&ae.trim()===Qe&&delete ke[V];localStorage.setItem(eg,JSON.stringify(ke)),he(zh(ke)),Y(V=>({...V,__custom__:""})),ie(null),Fe("idle")}catch{Fe("error")}},le=()=>{const ke=je.trim()||Ie;$||Ce&&!ke||(Ze(),w(H,ke))},Ge=b.useMemo(()=>[...new Set(e.filter(Boolean))].slice(0,5),[e]),He=Ce?Qe?gc+Qe:"__custom__":H?.slug??"__terminal__",tt=ke=>{Fe("idle");const V=ke.startsWith(gc)?ke.slice(gc.length):null;ie(V),qe(ke==="__custom__"||V!==null),(V!==null||ke==="__custom__")&&Y(ae=>({...ae,__custom__:V??""})),ye(n.find(ae=>ae.slug===ke)??null)},xe=Ce?Qe??U("sidebar.customStartupCommand"):H?.displayName??"Terminal",dt=a?.displayName??"Terminal",it=!Ce&&(H===null?a===null:a?.slug===H.slug);b.useEffect(()=>{if(oe)return;const ke=V=>{V.target instanceof Node&&(J.current?.contains(V.target)||V.target instanceof Element&&V.target.closest("[data-sidebar-composer-popover]")?.getAttribute("data-sidebar-composer-popover")===J.current?.id||V.target instanceof Element&&V.target.closest('[aria-controls="sidebar-launch-options"]')||S())};return document.addEventListener("pointerdown",ke,!0),()=>document.removeEventListener("pointerdown",ke,!0)},[oe,S]);const _e=ke=>{I({...r,cwd:ke}),te(!1)},Ue=ke=>new Intl.DateTimeFormat(Z==="zh"?"zh-CN":"en",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(ke));return s.jsxs("section",{ref:J,tabIndex:-1,"aria-busy":$,id:"sidebar-launch-options",className:`absolute inset-x-3 bottom-3 z-30 flex flex-col overflow-hidden rounded-2xl border border-border bg-surface shadow-[0_18px_50px_var(--app-shadow-strong),0_4px_14px_var(--app-shadow-soft)] animate-slide-down ${P?"max-h-[min(70svh,42rem,calc(100%_-_4.5rem))]":"max-h-[min(56svh,36rem,calc(100%_-_4.5rem))]"}`,"aria-label":U("sidebar.newSessionComposerTitle"),children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 px-3 py-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx("span",{className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground",children:s.jsx(tl,{size:14})}),s.jsx("div",{className:"min-w-0",children:s.jsx("div",{className:"text-[12px] font-semibold text-foreground",children:U("sidebar.newSessionComposerTitle")})})]}),s.jsx("button",{type:"button",onClick:S,className:"inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":U("common.close"),children:s.jsx(jn,{size:14})})]}),s.jsxs("fieldset",{disabled:$,className:"min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain border-0 px-3 pb-1",children:[s.jsxs("div",{className:"flex min-h-11 items-center justify-between gap-3",children:[s.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:U("sidebar.sessionMode")}),s.jsx("div",{className:"grid grid-cols-2 gap-1 rounded-lg bg-surface p-0.5",children:["shell","tmux"].map(ke=>s.jsx("button",{type:"button",disabled:ke==="tmux"&&!t,onClick:()=>I({...r,mode:ke}),"aria-pressed":r.mode===ke,title:ke==="tmux"?U(t?"sidebar.tmuxKeepsRunning":"sidebar.newTmuxDisabled"):void 0,className:`min-h-9 rounded-md px-4 text-[11px] font-medium transition ${r.mode===ke?"bg-surface-2 text-foreground":"text-muted-foreground hover:text-foreground"} disabled:cursor-not-allowed disabled:opacity-40`,children:U(ke==="shell"?"sidebar.newShell":"sidebar.newTmux")},ke))})]}),s.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[s.jsx("span",{className:"text-[11px] text-muted-foreground",children:U("sidebar.startupCommand")}),s.jsx("button",{type:"button",onClick:x,disabled:c,className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition hover:bg-surface hover:text-foreground disabled:opacity-50",title:U("sidebar.detectAgents"),"aria-label":U("sidebar.detectAgents"),children:s.jsx(vn,{size:12,className:c?"animate-spin":""})})]}),s.jsxs("div",{role:"radiogroup","aria-label":U("sidebar.startupCommand"),className:"flex flex-wrap gap-1",children:[n.map(ke=>{const V=!Ce&&H?.slug===ke.slug;return s.jsxs("button",{type:"button",role:"radio","aria-checked":V,onClick:()=>tt(ke.slug),className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-medium transition ${V?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(ru,{agent:ke,size:12}),s.jsx("span",{className:"max-w-[9rem] truncate",children:ke.displayName}),a?.slug===ke.slug&&s.jsx("span",{className:"ml-0.5 text-[9px] text-muted-foreground",children:U("sidebar.defaultAgent")})]},ke.slug)}),st.map(ke=>{const V=Ce&&Qe===ke;return s.jsxs("button",{type:"button",role:"radio","aria-checked":V,onClick:()=>tt(gc+ke),title:ke,className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 transition ${V?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(qc,{size:10,className:"shrink-0"}),s.jsx("span",{className:"max-w-[9rem] truncate font-mono text-[10px]",children:ke})]},ke)}),s.jsxs("button",{type:"button",role:"radio","aria-checked":He==="__terminal__",onClick:()=>tt("__terminal__"),className:`inline-flex min-h-7 items-center gap-1 rounded-md px-2 text-[10.5px] font-medium transition ${He==="__terminal__"?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(tl,{size:11,className:"shrink-0"}),s.jsx("span",{children:"Terminal"}),a===null&&s.jsx("span",{className:"ml-0.5 text-[9px] font-normal text-muted-foreground",children:U("sidebar.defaultAgent")})]}),s.jsxs("button",{type:"button",role:"radio","aria-checked":He==="__custom__",onClick:()=>tt("__custom__"),className:`inline-flex min-h-7 items-center gap-0.5 rounded-md px-2 text-[10.5px] font-medium transition ${He==="__custom__"?"bg-surface-2 text-foreground ring-1 ring-inset ring-primary/50":"bg-surface text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(Ys,{size:10,className:"shrink-0"}),s.jsx("span",{children:U("sidebar.addStartupCommand")})]})]}),!it&&!Ce&&s.jsxs("div",{className:"mt-1 flex min-h-8 items-center justify-between gap-2 px-0.5 text-[10px]",children:[s.jsx("span",{className:"truncate text-muted-foreground",children:U("sidebar.currentDefaultAgent",{name:dt})}),s.jsx("button",{type:"button",onClick:()=>y(H),className:"relative z-10 shrink-0 rounded-md px-2 py-1.5 font-medium text-primary transition hover:bg-primary/10",children:U("sidebar.makeDefault")})]}),Pe==="error"&&s.jsx("p",{role:"alert",className:"text-[10px] text-destructive",children:U("sidebar.saveStartupCommandFailed")}),(H||Ce)&&s.jsxs("details",{open:Ce&&!Qe||void 0,className:"group/command mt-0.5",children:[s.jsxs("summary",{className:"ml-auto flex min-h-8 w-fit cursor-pointer list-none items-center gap-1 rounded-md px-1 text-[10px] text-muted-foreground transition hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50 [&::-webkit-details-marker]:hidden",children:[U(Ce&&!Qe?"sidebar.customStartupCommand":"sidebar.changeStartupCommand"),s.jsx(Al,{size:11,className:"transition-transform group-open/command:rotate-180"})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx("label",{htmlFor:"new-session-command",className:"sr-only",children:U("sidebar.startupCommand")}),H&&je!==Ie&&s.jsx("button",{type:"button",onClick:()=>{Y(ke=>({...ke,[ce]:Ie})),Fe("idle")},className:"min-h-8 rounded-md px-2 text-[10px] text-primary transition hover:bg-primary/10",children:U("sidebar.resetStartupCommand")})]}),s.jsx("input",{id:"new-session-command",value:je,onChange:ke=>{Y(V=>({...V,[ce]:ke.target.value})),Fe("idle")},placeholder:Ie||U("sidebar.startupCommandPlaceholder"),autoCapitalize:"none",autoCorrect:"off",spellCheck:!1,autoComplete:"off",className:"min-h-10 w-full rounded-lg border-0 bg-surface px-3 font-mono text-[16px] text-foreground outline-none ring-1 ring-inset ring-border transition focus:ring-primary/50 sm:text-[11px]"}),s.jsxs("div",{className:"mt-1 flex items-center justify-end gap-2","aria-live":"polite",children:[Ce&&Qe&&s.jsxs("button",{type:"button",onClick:we,className:"mr-auto inline-flex min-h-9 items-center gap-1 rounded-md px-2 text-[10px] text-muted-foreground transition hover:text-destructive","aria-label":U("sidebar.deleteStartupCommand"),children:[s.jsx(Ms,{size:11}),U("sidebar.deleteStartupCommand")]}),s.jsx("button",{type:"button",onClick:Ze,disabled:Pe==="saved"||Ce&&!je.trim(),className:"min-h-8 rounded-md px-2 text-[10px] font-medium text-primary transition hover:bg-primary/10 disabled:cursor-default disabled:opacity-50",children:U(Pe==="saved"?"sidebar.startupCommandSaved":"sidebar.saveStartupCommand")})]}),s.jsx("p",{className:"mb-2 mt-1.5 px-0.5 text-[10px] leading-relaxed text-muted-foreground",children:U(H?"sidebar.agentStartupCommandHint":"sidebar.terminalStartupCommandHint")})]},Qe??ce),s.jsx("label",{htmlFor:"new-session-directory",className:"mt-2 block text-[11px] text-muted-foreground",children:U("sidebar.workingDirectory")}),s.jsxs("button",{id:"new-session-directory",type:"button","aria-haspopup":"dialog",onClick:()=>te(!0),className:"mt-1 flex min-h-11 w-full items-center gap-2 rounded-lg border border-transparent bg-surface px-2.5 font-mono text-[11px] text-foreground outline-none transition hover:bg-surface-2 focus-visible:border-primary",children:[s.jsx(nu,{size:12,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{className:`min-w-0 flex-1 truncate text-left ${r.cwd?"":"text-muted-foreground"}`,children:r.cwd||U("sidebar.directoryPlaceholder")})]}),Ge.length>0&&s.jsx("div",{className:"mt-1.5 flex gap-1 overflow-x-auto pb-0.5","aria-label":U("sidebar.recentDirectories"),children:Ge.map(ke=>s.jsx("button",{type:"button",onClick:()=>_e(ke),title:ke,className:"min-h-8 shrink-0 rounded-md px-2 text-[10px] text-muted-foreground transition hover:bg-surface hover:text-foreground",children:ld(ke)||ke},ke))}),(l.length>0||m)&&s.jsxs("details",{className:"mt-1",children:[s.jsxs("summary",{className:"flex min-h-9 cursor-pointer list-none items-center gap-2 rounded-md px-1 text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground transition hover:text-foreground",children:[s.jsx(qc,{size:11}),s.jsx("span",{className:"flex-1",children:U("sidebar.resumeHistory")}),d&&s.jsx(Dn,{size:10,className:"animate-spin"}),l.length>0&&s.jsx("span",{className:"normal-case tracking-normal",children:U("sidebar.resumeHistoryCount",{n:l.length})}),s.jsx(Al,{size:11})]}),l.length>0&&s.jsx("div",{className:"mt-1 divide-y divide-border overflow-hidden rounded-lg border border-border bg-surface",children:l.slice(0,6).map(ke=>{const V=f===ke.id;return s.jsxs("div",{className:"group flex min-w-0 items-stretch transition hover:bg-surface-2",children:[s.jsxs("button",{type:"button",disabled:f!==null,onClick:()=>v(ke),className:"flex min-h-11 min-w-0 flex-1 items-center gap-2.5 px-2.5 py-2 text-left disabled:cursor-wait disabled:opacity-60","aria-label":U("sidebar.resumeHistoryAction",{title:ke.title}),children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:V?s.jsx(Dn,{size:13,className:"animate-spin"}):s.jsx(ru,{agent:ke.agent,size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11px] font-semibold text-foreground",children:ke.title}),s.jsxs("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[ke.agent.displayName," · ",Ue(ke.closedAt)]})]}),s.jsx(b3,{size:12,className:"shrink-0 text-muted-foreground transition group-hover:text-primary"})]}),s.jsxs("button",{type:"button",disabled:f!==null,onClick:()=>T(ke.id),className:"relative inline-flex w-11 shrink-0 items-center justify-center text-muted-foreground transition hover:text-destructive disabled:opacity-40","aria-label":U("sidebar.resumeHistoryRemove",{title:ke.title}),children:[s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 w-px bg-border opacity-30"}),s.jsx(Ms,{size:12})]})]},ke.id)})}),m&&s.jsx("div",{role:"alert",className:"mt-1.5 px-1 text-[10px] text-destructive",children:m})]}),N]}),s.jsxs("div",{className:"shrink-0 bg-surface px-3 pb-3 pt-2",children:[Q&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:Q}),s.jsxs("button",{type:"button",onClick:le,disabled:$||Ce&&!je.trim(),className:"flex min-h-11 w-full items-center justify-center gap-2 rounded-lg bg-primary px-3 text-[12px] font-semibold text-primary-foreground transition hover:brightness-110 active:scale-[0.99] disabled:cursor-not-allowed disabled:opacity-40","aria-label":U("sidebar.launchSessionWith",{name:xe}),children:[$?s.jsx(Dn,{size:14}):H?s.jsx(ru,{agent:H,size:15}):s.jsx(tl,{size:14}),s.jsx("span",{className:"truncate",children:$?U("sidebar.sessionCreating"):U("sidebar.launchSessionWith",{name:xe})})]}),P]}),s.jsx(Ap,{open:oe,initialPath:r.cwd?.trim()||Ge[0]||"/",title:U("sidebar.chooseDirectory"),onCancel:()=>te(!1),onConfirm:_e})]})}function KO({onOpenSettings:e,serverAttention:t,actions:r,compact:n=!1}){const{t:a}=Ur(),[c,l]=b.useState(!1),d=b.useRef(null),f=b.useRef(null),m=b.useRef(null),x=b.useId();return b.useLayoutEffect(()=>{if(!c)return;const y=d.current,w=m.current;if(!y||!w)return;const v=window.visualViewport,T=()=>{const I=y.getBoundingClientRect(),N=(v?.offsetLeft??0)+8,P=(v?.offsetTop??0)+8,$=(v?.width??window.innerWidth)-16,Q=(v?.offsetTop??0)+(v?.height??window.innerHeight)-8,U=Math.max(0,Math.min(256,$)),Z=Math.max(0,I.top-P-4),J=Math.max(0,Q-I.bottom-4),H=Z>=180||Z>=J;Object.assign(w.style,{width:`${U}px`,left:`${Math.max(N,Math.min(I.right-U,N+$-U))}px`,top:`${H?I.top-4:I.bottom+4}px`,maxHeight:`${H?Z:J}px`,transform:H?"translateY(-100%)":"none"})};T();const S=typeof ResizeObserver>"u"?null:new ResizeObserver(T);return S?.observe(y),window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),v?.addEventListener("resize",T),v?.addEventListener("scroll",T),()=>{S?.disconnect(),window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0),v?.removeEventListener("resize",T),v?.removeEventListener("scroll",T)}},[c]),b.useEffect(()=>{if(!c)return;m.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0});const y=w=>{w.target instanceof Node&&!d.current?.contains(w.target)&&!m.current?.contains(w.target)&&l(!1)};return document.addEventListener("pointerdown",y),()=>document.removeEventListener("pointerdown",y)},[c]),s.jsxs("div",{ref:d,role:"group","data-sidebar-gesture-ignore":!0,"aria-label":a("sidebar.moreActions"),className:n?"relative z-20 flex shrink-0 items-center":"relative z-20 mt-2 flex items-center justify-between gap-2",onKeyDown:y=>{c&&y.key==="Escape"&&(y.preventDefault(),y.stopPropagation(),l(!1),f.current?.focus({preventScroll:!0}))},children:[!n&&s.jsxs("button",{type:"button",onClick:e,title:t?a("sidebar.serverAttention"):void 0,className:"inline-flex min-h-9 items-center gap-1.5 whitespace-nowrap rounded-lg px-2 text-[11px] text-muted-foreground transition hover:bg-surface-2 hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",children:[s.jsx(y3,{size:14,className:t?"text-destructive":void 0}),s.jsx("span",{children:a("sidebar.settings")})]}),s.jsxs("button",{ref:f,"data-session-sidebar-header-action":n?"":void 0,title:a("sidebar.moreActions"),"aria-label":a("sidebar.moreActions"),type:"button","aria-haspopup":"menu","aria-expanded":c,"aria-controls":c?x:void 0,onClick:()=>l(y=>!y),onKeyDown:y=>{(y.key==="ArrowDown"||y.key==="ArrowUp")&&(y.preventDefault(),l(!0))},className:`relative inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-lg text-[11px] transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary ${n?"h-9 w-9 shrink-0":"min-h-9 px-2"} ${c?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,children:[s.jsx(Do,{size:15}),!n&&s.jsx("span",{children:a("sidebar.moreActions")}),n&&t&&s.jsx("span",{"aria-hidden":"true",className:"absolute right-0 top-0 h-1.5 w-1.5 rounded-full bg-destructive"})]}),c&&Zs.createPortal(s.jsx("div",{ref:m,id:x,role:"menu","data-sidebar-gesture-ignore":!0,"data-sidebar-composer-popover":"sidebar-launch-options","aria-label":a("sidebar.moreActions"),className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)] animate-fade-in",onKeyDown:y=>{const w=[...y.currentTarget.querySelectorAll('[role="menuitem"]')],v=w.indexOf(document.activeElement);let T;if(y.key==="ArrowDown")T=(v+1)%w.length;else if(y.key==="ArrowUp")T=(v-1+w.length)%w.length;else if(y.key==="Home")T=0;else if(y.key==="End")T=w.length-1;else if(y.key==="Tab"){l(!1);return}else return;y.preventDefault(),w[T]?.focus({preventScroll:!0})},children:r.map(({label:y,icon:w,onSelect:v,separated:T})=>s.jsxs("div",{role:"none",children:[T&&s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/40"}),s.jsxs("button",{type:"button",role:"menuitem",tabIndex:-1,onClick:()=>{l(!1),v()},className:"flex min-h-10 w-full items-center gap-2.5 whitespace-nowrap rounded-lg px-2.5 text-left text-[12px] text-foreground transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",children:[s.jsx(w,{size:15,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{children:y})]})]},y))}),document.body)]})}const Hm="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition hover:bg-primary/15 hover:text-primary active:scale-95";function XO({label:e,count:t,badge:r,actions:n,pinned:a,onTogglePinned:c,onClose:l,onOpenSettings:d,serverAttention:f}){const{t:m}=Ur(),x=b.useRef(null),y=b.useRef(null),[w,v]=b.useState(!0);return b.useLayoutEffect(()=>{const T=x.current;if(!T)return;const S=()=>{const N=getComputedStyle(T),P=T.clientWidth-parseFloat(N.paddingLeft)-parseFloat(N.paddingRight),$=T.querySelector("button"),Q=$?$.getBoundingClientRect().width:36,U=[...y.current?.children??[]],Z=U.reduce((ye,oe)=>ye+oe.scrollWidth,0)+Math.max(0,U.length-1)*6,J=n.length+(c?1:0)+(a?0:1),H=Z+J*Q+Math.max(0,J-1)*4+6;v(P<H+8)};S();const I=typeof ResizeObserver>"u"?null:new ResizeObserver(S);return I?.observe(T),window.addEventListener("resize",S),()=>{I?.disconnect(),window.removeEventListener("resize",S)}}),s.jsxs("div",{ref:x,"data-session-sidebar-header":!0,className:"relative z-20 shrink-0 px-3 py-0.5",children:[s.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-3 bottom-0 z-10 h-px bg-border opacity-40"}),s.jsxs("div",{className:"flex min-w-0 w-full items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:s.jsxs("div",{ref:y,className:"flex min-w-0 items-center gap-1.5 whitespace-nowrap",children:[s.jsx("span",{className:"min-w-0 truncate text-[12px] font-medium text-muted-foreground",children:e}),s.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:t}),r&&s.jsx("span",{className:"flex shrink-0 items-center",children:r})]})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[w?s.jsx(KO,{compact:!0,actions:n,serverAttention:f,onOpenSettings:d}):n.map(({label:T,icon:S,onSelect:I})=>s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",className:Hm,"aria-label":T,title:T,onClick:I,children:s.jsx(S,{size:16})},T)),c&&s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",className:Hm,onClick:c,"aria-label":m(a?"sidebar.unpinSidebar":"sidebar.pinSidebar"),title:m(a?"sidebar.unpinSidebar":"sidebar.pinSidebar"),"aria-pressed":a,children:a?s.jsx(R0,{size:16}):s.jsx(N0,{size:16})}),!a&&s.jsx("button",{"data-session-sidebar-header-action":!0,type:"button",className:Hm,onClick:l,"aria-label":m("common.close"),children:s.jsx(jn,{size:16})})]})]})]})}const y4="termdock:new-session-agent:v1";function JO(){if(typeof window>"u")return null;try{const e=JSON.parse(window.localStorage.getItem(y4)||"null");return!e||typeof e.slug!="string"||typeof e.command!="string"?null:{slug:e.slug,command:e.command,displayName:typeof e.displayName=="string"?e.displayName:e.slug,capabilities:Array.isArray(e.capabilities)?e.capabilities.filter(t=>typeof t=="string"):void 0,accentColor:typeof e.accentColor=="string"?e.accentColor:"var(--muted-foreground)",icon:typeof e.icon=="string"?e.icon:null,isPlugin:e.isPlugin===!0,iconMode:e.iconMode==="native"?"native":e.iconMode==="mask"?"mask":void 0,iconVersion:typeof e.iconVersion=="number"?e.iconVersion:void 0}}catch{return null}}function Wm(e){if(!(typeof window>"u"))try{window.localStorage.setItem(y4,JSON.stringify(e))}catch{}}function eF(e,t){return e?t.find(r=>r.slug===e)??null:null}function tF(){const[e,t]=b.useState(JO),[r,n]=b.useState([]),[a,c]=b.useState(!0),l=b.useCallback(async()=>{c(!0);try{const[f,m]=await Promise.all([Cc(),n3()]),x=eF(f.newSessionAgentSlug,m);n(m),t(x),Wm(x)}finally{c(!1)}},[]);b.useEffect(()=>{const f=()=>{l().catch(()=>{})};if(performance.getEntriesByName("termdock:startup:initial-viewport-presented").length>0){f();return}return window.addEventListener("termdock:initial-viewport-presented",f,{once:!0}),()=>window.removeEventListener("termdock:initial-viewport-presented",f)},[l]);const d=b.useCallback(async f=>{const m=e;t(f),Wm(f);try{await Qa({newSessionAgentSlug:f?.slug??null})}catch(x){throw t(m),Wm(m),x}},[e]);return{preference:e,agents:r,detecting:a,refresh:l,selectAgent:d}}function rF({label:e,disabled:t,onRemove:r,children:n}){const[a,c]=b.useState(null),l=b.useRef(null),d=b.useRef(null),f=(m=!1)=>{c(null),m&&l.current?.querySelector("button")?.focus({preventScroll:!0})};return b.useEffect(()=>{t&&c(null)},[t]),b.useLayoutEffect(()=>{if(!a||!d.current)return;const m=d.current.getBoundingClientRect();d.current.style.left=`${Math.max(8,Math.min(a.x,window.innerWidth-m.width-8))}px`,d.current.style.top=`${Math.max(8,Math.min(a.y,window.innerHeight-m.height-8))}px`,d.current.querySelector("button")?.focus({preventScroll:!0})},[a]),b.useEffect(()=>{if(!a)return;const m=w=>{d.current?.contains(w.target)||f()},x=w=>{w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),f(!0)):w.key==="Tab"&&f()},y=()=>f();return window.addEventListener("pointerdown",m,!0),window.addEventListener("keydown",x,!0),window.addEventListener("resize",y),window.addEventListener("scroll",y,!0),()=>{window.removeEventListener("pointerdown",m,!0),window.removeEventListener("keydown",x,!0),window.removeEventListener("resize",y),window.removeEventListener("scroll",y,!0)}},[a]),s.jsxs("span",{ref:l,className:"inline-flex max-w-full items-center gap-0.5",onContextMenu:m=>{t||(m.preventDefault(),m.stopPropagation(),c({x:m.clientX,y:m.clientY}))},onKeyDown:m=>{if(!t&&(m.key==="ContextMenu"||m.shiftKey&&m.key==="F10")){m.preventDefault(),m.stopPropagation();const x=l.current.getBoundingClientRect();c({x:x.left,y:x.bottom})}},children:[n,a&&Zs.createPortal(s.jsx("div",{ref:d,role:"menu","aria-label":`${e} 的成员操作`,style:{left:a.x,top:a.y},className:"fixed z-popover min-w-44 rounded-lg border border-border/30 bg-surface-2 p-1 shadow-xl",children:s.jsxs("button",{type:"button",role:"menuitem",className:"flex min-h-9 w-full items-center gap-2 rounded-md px-3 py-2 text-left text-xs text-destructive hover:bg-destructive/10 focus:bg-destructive/10 focus:outline-none",onClick:()=>{f(!0),r()},children:[s.jsx(Ms,{size:14}),"从协作组移除"]})}),document.body)]})}function nF({groups:e,sessions:t,busy:r,onOpen:n,onSettings:a,onCreate:c}){const[l,d]=b.useState(""),f=e.filter(m=>!l.trim()||`${m.name} ${m.sessionIds.map(x=>t.find(y=>y.sessionId===x)?.name??"").join(" ")}`.toLowerCase().includes(l.trim().toLowerCase()));return s.jsxs("section",{"aria-label":"协作组列表",className:"space-y-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsx("p",{className:"text-xs leading-6 text-muted-foreground",children:"成员消息用于日常交流;看板用于目标、交付与验收。"}),s.jsxs("button",{type:"button",disabled:r,className:"inline-flex min-h-11 shrink-0 items-center gap-1.5 rounded-lg bg-primary px-3 text-xs font-medium text-primary-foreground disabled:opacity-40",onClick:c,children:[s.jsx(Ys,{size:14}),"新建协作组"]})]}),(e.length>5||l)&&s.jsxs("label",{className:"relative block",children:[s.jsx("span",{className:"sr-only",children:"搜索协作组"}),s.jsx(Gl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{type:"search",value:l,onChange:m=>d(m.target.value),placeholder:"搜索组名或成员",className:"min-h-11 w-full rounded-lg border border-border/20 bg-surface-2 py-2 pl-9 pr-3 text-xs text-foreground outline-none focus:border-primary/60"})]}),s.jsxs("div",{className:"divide-y divide-border/15 rounded-xl border border-border/15",children:[f.map(m=>{const x=m.sessionIds.flatMap(y=>{const w=t.find(v=>v.sessionId===y);return w?[w]:[]});return s.jsxs("article",{"aria-label":m.name,className:"p-3 sm:flex sm:items-center sm:gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"break-words text-sm font-medium leading-6 text-foreground",children:m.name}),s.jsx("p",{className:"mt-1 break-words text-[11px] leading-5 text-muted-foreground",children:m.sessionIds.length?`${m.sessionIds.length} 位成员${x.length?` · ${x.slice(0,2).map(y=>$u(y,x)).join("、")}${x.length>2?"等":""}`:""}`:"尚未添加成员,可以稍后配置"})]}),s.jsxs("div",{className:"mt-2 flex shrink-0 items-center gap-1 sm:mt-0",children:[s.jsxs("button",{type:"button","aria-label":`成员消息:${m.name}`,disabled:r,className:"inline-flex min-h-11 items-center justify-center gap-1.5 rounded-lg bg-surface-2 px-3 text-xs text-foreground hover:bg-surface-elevated disabled:opacity-40",onClick:()=>n(m.id,"messages"),children:[s.jsx(cd,{size:14}),"成员消息"]}),s.jsxs("button",{type:"button","aria-label":`看板:${m.name}`,disabled:r,className:"inline-flex min-h-11 items-center justify-center gap-1.5 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 disabled:opacity-40",onClick:()=>n(m.id,"tasks"),children:[s.jsx(YT,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-label":`设置:${m.name}`,title:"组设置",disabled:r,className:"inline-flex min-h-11 min-w-11 items-center justify-center rounded-lg text-muted-foreground hover:bg-surface-2 disabled:opacity-40",onClick:y=>a(m.id,y.currentTarget),children:s.jsx(Vu,{size:14})})]})]},m.id)}),!f.length&&s.jsx("p",{className:"px-3 py-6 text-xs text-muted-foreground",children:"没有匹配的协作组,试试其他名称。"})]})]})}const Wc="min-h-11 w-full rounded-lg border border-border/20 bg-surface px-3 py-2 text-xs text-foreground outline-none focus:border-primary",Hh="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-xs disabled:opacity-40",Wh=e=>({profiles:e.launchProfiles??[],defaultId:e.defaultLaunchProfileId??"",group:e}),Gm=new Map,Jd=e=>JSON.stringify(e.profiles)!==JSON.stringify(e.group.launchProfiles??[])||e.defaultId!==(e.group.defaultLaunchProfileId??"");function sF({group:e,value:t,onChange:r,disabled:n}){if(!e.launchProfiles?.length&&!t)return null;const a=e.launchProfiles?.find(c=>c.id===t);return s.jsxs("div",{className:"mt-3 space-y-1",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["启动方案",s.jsxs("select",{"aria-label":"启动方案",className:Wc,value:t,disabled:n,onChange:c=>r(c.target.value),children:[s.jsx("option",{value:"",children:"Agent 默认命令"}),e.launchProfiles?.map(c=>s.jsx("option",{value:c.id,children:c.name},c.id))]})]}),a&&s.jsxs("p",{className:"whitespace-pre-wrap break-words text-xs leading-5 text-muted-foreground",children:[a.notes||"未填写使用备注",s.jsx("code",{className:"block break-all",children:a.command})]}),t&&!a&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"原方案已删除,请重新选择。"})]})}function iF({group:e,agents:t,busy:r,setBusy:n,refresh:a}){const c=`${window.location.origin}:${e.id}`,[l,d]=b.useState(()=>Gm.get(c)??Wh(e)),f=b.useRef(l);f.current=l;const[m,x]=b.useState(l.profiles[0]?.id??""),[y,w]=b.useState(null),[v,T]=b.useState(""),S=(U,Z=!0)=>{f.current=U,d(U),Jd(U)?Gm.set(c,U):Gm.delete(c),Z&&T("")};b.useEffect(()=>{!Jd(f.current)&&e.updatedAt>=f.current.group.updatedAt&&S(Wh(e),!1)},[e.updatedAt]);const I=l.profiles.find(U=>U.id===m),N=U=>S({...l,profiles:l.profiles.map(Z=>Z.id===m?{...Z,...U}:Z)}),P=l.profiles.every(U=>U.name.trim()&&U.agentSlug&&U.command.trim()&&!/[\x00-\x1f\x7f]/.test(U.command)),$=()=>{const U=t[0],Z={id:`profile-${crypto.randomUUID()}`,name:"",agentSlug:U?.slug??"",command:U?.command??"",notes:""};S({...l,profiles:[...l.profiles,Z]}),x(Z.id)},Q=async()=>{if(!(r||!P||!Jd(l))){n("launch-profiles"),w(null),T("");try{const{group:U}=await Wl({id:e.id,name:l.group.name,sessionIds:l.group.sessionIds,expectedUpdatedAt:l.group.updatedAt,launchProfiles:l.profiles,defaultLaunchProfileId:l.defaultId||null});S(Wh(U)),T("启动方案已保存。新会话使用所选方案,正在运行的成员保持原配置。"),await a()}catch(U){w(U instanceof Error?U.message:"保存失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-3 border-t border-border/15 pt-2",children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-xs font-medium text-foreground",children:["Agent 启动方案 · ",l.profiles.length," 个",Jd(l)?" · 未保存":""]}),s.jsxs("section",{"aria-label":"Agent 启动方案",className:"space-y-3",children:[s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"保存不同模型和参数的启动命令,填写适用场景,让协调者按备注选择。保存配置不会启动 Agent。"}),s.jsxs("fieldset",{disabled:!!r,className:"space-y-3",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["默认启动方案",s.jsxs("select",{"aria-label":"默认启动方案",className:Wc,value:l.defaultId,onChange:U=>S({...l,defaultId:U.target.value}),children:[s.jsx("option",{value:"",children:"使用 Agent 默认命令"}),l.profiles.map(U=>s.jsx("option",{value:U.id,children:U.name||"未命名方案"},U.id))]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:["编辑方案",s.jsxs("select",{"aria-label":"编辑方案",className:`${Wc} mt-1`,value:m,onChange:U=>x(U.target.value),children:[s.jsx("option",{value:"",children:"选择方案"}),l.profiles.map(U=>s.jsx("option",{value:U.id,children:U.name||"未命名方案"},U.id))]})]}),s.jsxs("button",{type:"button",className:`${Hh} self-end bg-surface text-foreground`,disabled:l.profiles.length>=20,onClick:$,children:[s.jsx(Ys,{size:14}),"新增方案"]})]}),I?s.jsxs("div",{className:"space-y-3 rounded-lg border border-border/20 p-3",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["方案名称",s.jsx("input",{className:Wc,value:I.name,maxLength:100,onChange:U=>N({name:U.target.value}),placeholder:"例如:快速排查、深度实现"})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["Agent 类型",s.jsxs("select",{"aria-label":"Agent 类型",className:Wc,value:I.agentSlug,onChange:U=>N({agentSlug:U.target.value,command:t.find(Z=>Z.slug===U.target.value)?.command??""}),children:[!t.some(U=>U.slug===I.agentSlug)&&s.jsxs("option",{value:I.agentSlug,children:[I.agentSlug||"选择 Agent","(当前不可用)"]}),t.map(U=>s.jsx("option",{value:U.slug,children:U.displayName},U.slug))]})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["启动命令",s.jsx("input",{className:`${Wc} font-mono`,value:I.command,maxLength:4096,onChange:U=>N({command:U.target.value}),placeholder:"填写完整命令,包括模型和启动参数"})]}),s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:["使用备注",s.jsx("textarea",{"aria-label":"使用备注",className:`${Wc} min-h-24 resize-y`,value:I.notes,maxLength:2e3,onChange:U=>N({notes:U.target.value}),placeholder:"适合哪些任务、何时不要使用;协调者会读取这些备注。"})]}),s.jsxs("details",{className:"text-[11px] text-muted-foreground",children:[s.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"CLI 方案标识"}),s.jsx("code",{className:"break-all",children:I.id})]}),s.jsxs("button",{type:"button",className:`${Hh} text-destructive hover:bg-destructive/10`,onClick:()=>{const U=l.profiles.filter(Z=>Z.id!==m);S({...l,profiles:U,defaultId:l.defaultId===m?"":l.defaultId}),x(U[0]?.id??"")},children:[s.jsx(Ms,{size:14}),"移除方案(保存后生效)"]})]}):s.jsx("p",{className:"text-xs text-muted-foreground",children:"尚未选择方案。新增后可填写模型、参数和备注。"})]}),y&&s.jsxs("p",{role:"alert",className:"text-xs leading-5 text-destructive",children:[y,"。草稿已保留;重新载入会放弃草稿。"]}),v&&s.jsx("p",{role:"status",className:"text-xs leading-5 text-primary",children:v}),s.jsxs("div",{className:"flex flex-wrap justify-between gap-2",children:[s.jsx("button",{type:"button",className:`${Hh} bg-surface text-muted-foreground`,disabled:!!r,onClick:()=>{S(Wh(e)),x(e.launchProfiles?.[0]?.id??""),w(null)},children:"重新载入(放弃方案草稿)"}),s.jsx("button",{type:"button",disabled:!!r||!P||!Jd(l),className:`${Hh} bg-primary text-primary-foreground`,onClick:()=>{Q()},children:r==="launch-profiles"?"保存中…":"保存启动方案"})]})]})]})}function v4(e,t=[]){const r=(t.length?t:e.children??[]).filter(S=>S.status!=="closed"),n=r.filter(S=>S.status==="accepted").length,a=cu(e),c=e.events.filter(S=>S.kind==="revise"&&S.attemptId===e.activeAttemptId).at(-1),l=e.artifacts.filter(S=>S.kind==="result"&&S.attemptId===e.activeAttemptId).at(-1),d=!!c&&(!l||c.createdAt>=l.createdAt),f=Kf(e),m=e.attempts.find(S=>S.id===e.activeAttemptId)?.report,x=S=>S?.summarySource==="explicit"||S?.summarySource!=="excerpt"&&!!S?.summary?.trim(),y=e.events.filter(S=>S.kind==="coordinate"&&S.attemptId===e.activeAttemptId&&(!c||S.sequence>c.sequence)).at(-1),w=[...f?.createdAt&&(!c||f.createdAt>c.createdAt)?[{summary:f.summary,createdAt:f.createdAt,source:"成员报告",explicit:x(m),taskId:e.id,title:e.title}]:[],...y?[{summary:y.summary||y.content,createdAt:y.createdAt,source:"协调说明",explicit:!!y.summary?.trim(),taskId:e.id,title:e.title}]:[],...d?[]:t.filter(S=>S.status!=="closed").flatMap(S=>{const I=Kf(S);return I?.createdAt?[{summary:I.summary,createdAt:I.createdAt,source:"执行报告",explicit:x(S.attempts.find(N=>N.id===S.activeAttemptId)?.report),taskId:S.id,title:S.title}]:[]})].filter(S=>S.summary.trim()&&Number.isFinite(S.createdAt)&&Number.isFinite(new Date(S.createdAt).getTime())).sort((S,I)=>I.createdAt-S.createdAt);let v=a,T="分派和报告会保存在这里;终端输出不能代替明确的任务报告。";return e.workflow?.kind==="goal"&&(e.status==="accepted"?(v="已完成 · 你已验收",T="结果与执行记录已保留;追加要求可以继续跟进。"):e.status==="closed"?T="此目标已关闭,已有报告仍保留。":Vi(e)||e.workflow.paused||l?T=a==="等待你验收"?"总结果已交付;查看结论后验收,或提出继续跟进。":a==="等待独立评审"?"总结果已提交,独立评审通过后交给你验收。":a==="需要你回答"?"回答当前问题后,成员可以继续原来的工作。":a==="需要你确认方案"?"确认这项必要决定后再继续;普通拆分不需要逐项批准。":d?"沿用原目标推进追加要求;上一版结果不代表本轮完成。":e.workflow.paused?"自动安排已暂停,恢复后才能继续安排后续工作。":"查看记录的阻塞原因,补充条件或重试;已有交付保留。":d?(v="已提出跟进 · 等待新报告",T="沿用原目标推进追加要求;旧报告保留为历史,等待本轮明确更新。"):r.length?(v=n===r.length?"执行交付已评审 · 等待总结果":"工作已拆分 · 执行与评审",T=n===r.length?"执行事项已交付评审,下一步由协调者汇总总结果,再交给你验收。":`已记录 ${r.length} 项工作,${n} 项交付已评审,${r.length-n} 项尚待交付或评审。`):f?(v=f.status==="ack"?"协调者已接手 · 等待拆分记录":a,T="尚未记录执行事项;协调者需说明工作划分、交付内容和下一步。"):T=a==="已写入终端 · 等待回复"?"目标已写入协调者终端,等待明确接手和拆分说明。":"目标已保存,等待分派、投递和协调者明确回复。"),{label:v,next:T,latest:w[0]??null,total:r.length,done:n}}function aF(e,t){const r=e.dependsOn.filter(n=>t.find(a=>a.id===n)?.status!=="accepted");return r.length?`等待依赖:${r.map(n=>t.find(a=>a.id===n)?.title??"记录尚未同步").join("、")}`:e.dependsOn.length?"依赖交付已评审,可以接续":""}function w4(e){return e.explicit?e.summary:e.source==="协调说明"?"协调者已更新工作安排。此记录未提供简短摘要,详情保留原始说明。":`「${e.title}」有新的明确报告。此记录未提供简短摘要,详情保留原文。`}function ty(e,t=!1,r=""){e=e.filter(d=>d.purpose!=="automation");const n=new Map(e.map(d=>[d.id,d])),a=d=>n.get(d.parentTaskId??d.workflow?.rootTaskId??""),c=d=>{const f=[];let m=d;for(;;){const x=f.findIndex(w=>w.id===m.id);if(x!==-1)return f.slice(x).sort((w,v)=>w.id.localeCompare(v.id))[0];f.push(m);const y=a(m);if(!y||y.status==="closed"&&m.status!=="closed")return m;m=y}},l=new Map(e.map(d=>[d.id,c(d).id]));return e.filter(d=>t||!!r.trim()||l.get(d.id)===d.id).map(d=>{const f=t||r.trim()?[]:e.filter(y=>y.id!==d.id&&l.get(y.id)===d.id&&y.status!=="closed"),m=d.status==="open"&&!Vi(d)?f.find(y=>y.decisions.some(w=>w.status==="pending"))??f.find(y=>Vi(y)||y.workflow?.paused):void 0,x=f.filter(y=>Vi(y)||y.workflow?.paused).length;return{task:d,children:f,attention:m,attentionCount:x,rootId:l.get(d.id)}})}function tg(e,t=[]){const r=cu(e),n={已验收:"已完成 · 你已验收",独立评审通过:"执行交付已评审",需要你回答:"请回答成员的问题",需要你确认方案:"请确认方案",等待你验收:"请查看结果并验收",成员报告受阻:"需要补充条件",成员报告失败:"成员报告执行失败",成员确认接手:"已接手 · 等待后续报告",成员报告进行中:"成员报告:进行中",等待独立评审:"结果已提交 · 等待评审","评审通过 · 等待接续":"交付已评审 · 等待接续","已要求跟进 · 等待新结果":"已提出跟进 · 等待新结果"};return e.status==="open"&&t.length&&!Vi(e)&&!e.artifacts.some(a=>a.kind==="result"&&a.attemptId===e.activeAttemptId)?t.every(a=>a.status==="accepted")?"执行交付已评审 · 等待总结果":"目标未完成 · 执行交付待齐":n[r]??r}function A4({task:e,children:t,onSelect:r,detail:n=!1,tasks:a=t,name:c}){const l=new Map(t.map(w=>[w.id,w])),d=(t.length?t:e.children??[]).filter(w=>w.status!=="closed");if(!d.length)return null;const f=(w,v)=>{const T=l.get(w);return T&&(Vi(T)||T.workflow?.paused)?0:v?2:1},m=[...d].sort((w,v)=>f(w.id,w.status==="accepted")-f(v.id,v.status==="accepted")||(l.get(v.id)?.updatedAt??0)-(l.get(w.id)?.updatedAt??0)),x=d.filter(w=>w.status==="accepted").length,y=w=>{const v=l.get(w.id),T=w.status==="accepted",S=v&&(Vi(v)||v.workflow?.paused),I=v?.status==="open"?aF(v,a):"",N=v?.attempts.find(Q=>Q.id===v.activeAttemptId)?.assignee??v?.scheduledAssignee??null,P=v?tg(v):T?w.completionMode==="reviewed"?"执行交付已评审":"已验收":"等待报告",$=T?L0:V0;return s.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-start gap-2 rounded-lg px-1 py-2 text-left hover:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>r(w.id),children:[s.jsx($,{size:14,className:`mt-0.5 shrink-0 ${T||S?"text-primary":"text-muted-foreground"}`}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{title:w.title,className:"line-clamp-2 break-words text-xs leading-5 text-foreground",children:w.title}),s.jsx("span",{className:`block text-[11px] leading-5 ${S?"text-primary":"text-muted-foreground"}`,children:P}),n&&v?.parentTaskId&&v.parentTaskId!==e.id&&s.jsxs("span",{className:"block text-[11px] leading-5 text-muted-foreground",children:["所属事项:",a.find(Q=>Q.id===v.parentTaskId)?.title??"父任务记录尚未同步"]}),n&&v?.acceptance&&s.jsxs("span",{className:"mt-1 line-clamp-2 text-xs leading-5 text-muted-foreground",children:["交付标准:",v.acceptance]}),I&&s.jsx("span",{className:"line-clamp-2 text-[11px] leading-5 text-muted-foreground",children:I}),n&&c&&s.jsxs("span",{className:"block text-[11px] leading-5 text-muted-foreground",children:["负责人:",N?c(v,N):"尚未分派"]})]}),s.jsx(qs,{size:12,className:"mt-1 shrink-0 text-muted-foreground"})]},w.id)};return s.jsxs("section",{"aria-label":"执行事项",className:n?"border-t border-border/15 py-2":"mx-4 border-t border-border/15 py-2",children:[!n&&s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:"执行事项"}),s.jsxs("span",{children:[x,"/",d.length," 项已完成"]})]}),(n?m.filter(w=>x===d.length||w.status!=="accepted"):m.slice(0,3)).map(y),n&&x>0&&x<d.length&&s.jsxs("details",{children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-xs text-muted-foreground",children:["查看 ",x," 项已完成的执行交付"]}),m.filter(w=>w.status==="accepted").map(y)]}),!n&&m.length>3&&s.jsxs("details",{children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-[11px] text-muted-foreground",children:["展开其余 ",m.length-3," 项"]}),m.slice(3).map(y)]})]})}function oF(e,t){const r=t.events.filter(f=>f.kind==="retry"&&!e.events.some(m=>m.id===f.id)).at(-1),n=new Set(e.deliveries.filter(f=>f.status==="delivered").map(f=>f.id)),a=new Set(e.outbox.filter(f=>!n.has(f.id)).map(f=>f.id)),c=r&&t.deliveries.some(f=>a.has(f.id)&&f.status==="delivered"&&f.deliveredAt!==null&&f.deliveredAt>=r.createdAt);let l=c?"重试请求已保存,匹配本次请求的投递已写入终端。":"重试请求已保存,服务将重新检查现有投递与协调条件。";!t.outbox.length&&!c&&(l+=" 当前没有待重试的投递记录。"),t.workflow?.paused&&(l+=" 后续自动安排仍已暂停。");const d=t.attempts.find(f=>f.id===t.activeAttemptId)?.report;return d&&["blocked","failed"].includes(d.status)&&(l+=" 成员原报告仍保留;请补齐条件并通知成员,收到新的明确回复后更新报告。"),l}function lF(e,t){const r=Math.floor(Math.max(0,t-e)/6e4);return r<1?"刚刚更新":r<60?`${r} 分钟前更新`:r<1440?`${Math.floor(r/60)} 小时前更新`:r<10080?`${Math.floor(r/1440)} 天前更新`:`${new Date(e).toLocaleDateString([],{month:"numeric",day:"numeric"})} 更新`}function ry(e){return new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}function tp({task:e,now:t,compact:r=!1}){const n=Kf(e),a=Number.isFinite(e.updatedAt)&&e.updatedAt>0&&Number.isFinite(new Date(e.updatedAt).getTime());return r&&!n?null:s.jsxs("span",{className:"mt-1 block space-y-1 text-[11px] leading-5 text-muted-foreground",children:[s.jsx("span",{className:"block break-words",children:n?s.jsxs(s.Fragment,{children:["最近明确报告:",n.label," · ",n.createdAt===null?"报告时间未提供":s.jsx("time",{dateTime:new Date(n.createdAt).toISOString(),title:new Date(n.createdAt).toLocaleString(),children:ry(n.createdAt)})]}):"暂无明确报告"}),!r&&s.jsx("span",{className:"block",children:a?s.jsxs(s.Fragment,{children:["记录更新:",s.jsx("time",{dateTime:new Date(e.updatedAt).toISOString(),title:t===void 0?new Date(e.updatedAt).toLocaleString():lF(e.updatedAt,t),children:ry(e.updatedAt)})]}):"记录更新时间未提供"})]})}function T4(e,t){const r=e.trim().split(/\n\s*\n/),n=l=>{const d=r.findIndex(m=>l.test(m.trim()));return d<0?"":r[d].trim().replace(l,"").trim()||r[d+1]?.trim()||""},a=t?.trim()||n(/^(?:#{1,6}\s*)?(?:结论|Summary|Conclusion|结果摘要)(?:[::]\s*|\s*$)/i),c=n(/^(?:#{1,6}\s*)?(?:限制与变更|限制|Limitations)(?:[::]\s*|\s*$)/i);return{summary:a||e.trim(),limitations:a?c:"",condensed:!!a&&a!==e.trim(),explicit:!!t?.trim()}}function bf({inputKey:e,paneKey:t,label:r,value:n,onChange:a,active:c=!0,disabled:l=!1,required:d,autoFocus:f,placeholder:m,className:x,onUploadChange:y}){const w=b.useId(),v=b.useRef(null),T=b.useRef(null),S=b.useRef({value:n,onChange:a,onUploadChange:y});S.current={value:n,onChange:a,onUploadChange:y};const[I,N]=b.useState(0),[P,$]=b.useState(""),Q=b.useRef(Promise.resolve());b.useEffect(()=>{const te=v.current;te&&te.setSelectionRange(te.value.length,te.value.length)},[e]);const U=()=>({value:S.current.value,start:v.current?.selectionStart??n.length,end:v.current?.selectionEnd??n.length}),Z=(te,Ce=U())=>{S.current.onChange(qe=>qe!==Ce.value?qe+(qe&&!/\s$/.test(qe)?`
138
138
  `:"")+te:qe.slice(0,Ce.start)+te+qe.slice(Ce.end))};b.useEffect(()=>{if(!c)return;const te=s3(Ce=>Z(Ce.replace(/\r\n?/g,`
139
- `)),e,!!t,t);return t||x0(e),te},[c,e,t]);const J=()=>{const te=Vc();return`${location.origin}:${te?.targetPeerId??""}:${te?.serviceOrigin??""}`},H=te=>{const Ce=U(),qe=J(),ve=S.current.onUploadChange;$(""),N(Y=>Y+1),ve?.(1),Q.current=Q.current.then(async()=>{try{if(qe!==J())throw new Error("目标服务已切换,请重新添加附件");const Y=await te();if(qe!==J())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(Y)?Z(Y.map(Ou).join(" ")+" ",Ce):Y&&Z(Y,Ce)}catch(Y){const st=Y instanceof Error?Y.message:"附件准备失败,请重试";$(st.includes("Upload did not return")?"附件上传未返回完整路径,请重试":st)}finally{N(Y=>Y-1),ve?.(-1)}})},ye=async te=>te.length===1&&te[0].type.startsWith("image/")?[await Q3(te[0])]:F3(te),oe=te=>{const Ce=te.clipboardData.files.length?Array.from(te.clipboardData.files):Array.from(te.clipboardData.items??[]).filter(Y=>Y.kind==="file").map(Y=>Y.getAsFile()).filter(Y=>Y!==null),qe=te.clipboardData.getData("text/plain"),ve=Gi();!ve?.readClipboardFiles&&!Ce.length&&qe||!ve&&!Ce.length&&typeof navigator.clipboard?.read!="function"||(te.preventDefault(),H(async()=>{const Y=J();let st;if(ve?.readClipboardFiles)try{const he=await O3();if(he.paths.length||he.files.length)return[...he.paths,...await ye(he.files)]}catch(he){if(he instanceof w0)throw he;st=he}if(Y!==J())throw new Error("目标服务已切换,请重新粘贴");if(Ce.length)return ye(Ce);if(qe)return qe;if(typeof navigator.clipboard?.read=="function"){const he=await navigator.clipboard.read(),Qe={read:async()=>he},ie=await P3(Qe);if(ie.length)return ye(ie);const Pe=await Rf(Qe);if(Pe)return ye([Pe]);for(const Fe of he)if(Fe.types.includes("text/plain"))return(await Fe.getType("text/plain")).text()}else{const he=await Rf();if(he)return ye([he])}if(st)throw st;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>x0(e),onPointerDownCapture:()=>x0(e),children:[s.jsx("label",{htmlFor:w,className:"block text-xs text-muted-foreground",children:r}),s.jsx("textarea",{ref:v,id:w,value:n,required:d,disabled:l,autoFocus:f,"aria-describedby":I||P?`${w}-status`:void 0,placeholder:m,className:x,onChange:te=>a(te.target.value),onPaste:oe,onDragOver:te=>{!l&&te.dataTransfer.types.includes("Files")&&te.preventDefault()},onDrop:te=>{const Ce=Array.from(te.dataTransfer.files);!Ce.length||l||(te.preventDefault(),te.stopPropagation(),H(()=>ye(Ce)))}}),s.jsxs("div",{className:"flex min-h-9 items-center gap-2",children:[s.jsx("input",{ref:T,type:"file",multiple:!0,hidden:!0,"aria-label":`选择附件:${r}`,onChange:te=>{const Ce=Array.from(te.target.files??[]);te.target.value="",Ce.length&&H(()=>ye(Ce))}}),s.jsxs("button",{type:"button","aria-label":`添加附件:${r}`,title:"添加附件",disabled:l,className:"inline-flex min-h-9 shrink-0 items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>T.current?.click(),children:[s.jsx(wS,{size:14}),"附件"]}),I>0?s.jsxs("span",{id:`${w}-status`,role:"status",className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s.jsx(vn,{size:12,className:"animate-spin"}),"正在准备附件…"]}):P?s.jsx("span",{id:`${w}-status`,role:"alert",className:"break-words text-xs text-destructive",children:P}):s.jsx("span",{className:"text-[11px] text-muted-foreground/70",children:"可粘贴图片、文件或拖入附件"})]})]})}function ny(e){return e.status!=="open"?"done":Vi(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Bl=[{id:"backlog",label:"待开始",icon:V0,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:kf,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:cd,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:L0,hint:"验收后的结果会保留在这里"}];function cF({tasks:e,selectedId:t,onSelect:r,name:n,storage:a,action:c,navigation:l,settings:d}){const f=b.useRef(null),m=b.useRef(null),x=b.useRef("backlog"),y=b.useRef(0),w=b.useRef(null),[v,T]=b.useState(Date.now);b.useEffect(()=>ou(()=>T(Date.now()),3e4),[]);const[S,I]=b.useState(!1);b.useEffect(()=>{const V=new ResizeObserver(ae=>{const pe=ae[0].contentRect.width;I(pe>=760),pe!==y.current&&pe<760&&m.current&&(m.current.scrollLeft=Bl.findIndex($e=>$e.id===x.current)*m.current.clientWidth),y.current=pe});return f.current&&V.observe(f.current),()=>V.disconnect()},[]);const[N]=b.useState(()=>{try{return JSON.parse(localStorage.getItem(`${a}:board`)??"null")}catch{return null}}),[P,$]=b.useState(()=>{if(Bl.some(pe=>pe.id===N?.lane))return N.lane;const ae=ty(e,N?.showSteps===!0,N?.query??"").map(pe=>pe.attention?"attention":ny(pe.task));return ae.includes("attention")?"attention":ae.includes("running")?"running":ae.includes("backlog")?"backlog":"done"});x.current=P;function Q(V,ae=!0){$(V);const pe=m.current;if(!pe||!pe.clientWidth)return;w.current=V;const $e=Bl.findIndex(wt=>wt.id===V)*pe.clientWidth,Xe=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;pe.scrollTo?pe.scrollTo({left:$e,behavior:ae&&!Xe?"smooth":"auto"}):pe.scrollLeft=$e}b.useEffect(()=>{S||Q(x.current,!1)},[S]);const[U,Z]=b.useState(typeof N?.scope=="string"?N.scope:"all"),[J,H]=b.useState(typeof N?.query=="string"?N.query:""),[ye,oe]=b.useState(N?.closed===!0),[te,Ce]=b.useState(N?.showSteps===!0),[qe,ve]=b.useState(!!N?.query),[Y,st]=b.useState(!1),[he,Qe]=b.useState(!1),ie=b.useRef(null),Pe=b.useRef(null);b.useEffect(()=>{if(!he)return;ie.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const V=pe=>{ie.current?.contains(pe.target)||Qe(!1)},ae=pe=>{pe.key==="Escape"&&(pe.preventDefault(),pe.stopPropagation(),Qe(!1),Pe.current?.focus())};return document.addEventListener("pointerdown",V),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",V),document.removeEventListener("keydown",ae)}},[he]);const Fe=b.useRef(null),ce=b.useRef(null),Ie=b.useRef(null),je=b.useRef(null);b.useEffect(()=>{qe&&Fe.current?.focus()},[qe]),b.useEffect(()=>{if(!Y)return;Ie.current?.querySelector("select")?.focus();const V=pe=>{Ie.current?.contains(pe.target)||st(!1)},ae=pe=>{pe.key==="Escape"&&(pe.preventDefault(),pe.stopPropagation(),st(!1),(S?je:Pe).current?.focus())};return document.addEventListener("pointerdown",V),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",V),document.removeEventListener("keydown",ae)}},[Y]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:P,scope:U,query:J,closed:ye,showSteps:te}))}catch{}},[a,P,U,J,ye,te]);const Ze=e.filter(V=>V.workflow?.kind==="goal"),we=ty(e,te,J),le=new Map(we.map(V=>[V.task.id,V])),Ge=V=>le.get(V.id)?.attention?"attention":ny(V),He=t?we.find(V=>V.task.id===t||V.children.some(ae=>ae.id===t)):void 0,tt=He?Ge(He.task):void 0;b.useEffect(()=>{tt&&Q(tt,!1)},[t,tt]);const xe=we.map(V=>V.task).filter(V=>(ye||V.status!=="closed")&&(U==="all"||V.id===U||le.get(V.id)?.rootId===U)&&(!J.trim()||`${V.title} ${V.spec} ${V.attempts.map(ae=>n(V,ae.assignee)).join(" ")}`.toLocaleLowerCase().includes(J.trim().toLocaleLowerCase()))),dt=+(U!=="all")+Number(ye)+Number(te),it="inline-flex min-h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",_e="flex min-h-11 w-full items-center justify-start gap-3 rounded-lg px-3 text-left text-sm font-medium text-foreground hover:bg-surface-2 active:bg-surface-elevated focus-visible:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ue=s.jsxs("div",{className:`relative flex min-w-0 items-center ${S?"flex-1 max-w-[240px]":"w-full"}`,children:[s.jsx("span",{className:"sr-only",children:"搜索任务"}),s.jsx(Gl,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:Fe,"aria-label":"搜索任务",type:"search",value:J,onChange:V=>H(V.target.value),onKeyDown:V=>{V.key==="Escape"&&(V.preventDefault(),V.stopPropagation(),J?H(""):(ve(!1),requestAnimationFrame(()=>(S?ce:Pe).current?.focus())))},placeholder:"搜索任务或负责人",className:"min-h-11 w-full rounded-lg border border-border/20 bg-transparent pl-9 pr-9 text-xs outline-none focus:border-primary"}),s.jsx("button",{type:"button","aria-label":"关闭搜索",className:"absolute right-0 flex min-h-11 w-9 items-center justify-center text-muted-foreground",onClick:()=>{H(""),ve(!1),requestAnimationFrame(()=>(S?ce:Pe).current?.focus())},children:s.jsx(jn,{size:14})})]}),ke=s.jsxs("div",{"aria-label":"任务筛选",className:"absolute right-0 top-full z-30 mt-1 w-64 space-y-3 rounded-xl border border-border/30 bg-surface p-3 shadow-xl",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:[s.jsx("span",{children:"目标范围"}),s.jsxs("select",{"aria-label":"按目标查看",value:U,onChange:V=>Z(V.target.value),className:"min-h-11 w-full rounded-lg border border-border/20 bg-surface-2 px-3 text-xs text-foreground",children:[s.jsx("option",{value:"all",children:"所有目标"}),Ze.map(V=>s.jsx("option",{value:V.id,children:V.title},V.id))]})]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:ye,onChange:V=>oe(V.target.checked)}),"含已关闭"]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:te,onChange:V=>Ce(V.target.checked)}),"显示执行子任务"]}),dt>0&&s.jsx("button",{type:"button",className:"min-h-11 w-full rounded-lg text-xs text-primary hover:bg-surface-2",onClick:()=>{Z("all"),oe(!1),Ce(!1)},children:"清除筛选"})]});return s.jsxs("div",{ref:f,className:"flex min-h-0 min-w-0 flex-1 flex-col gap-2",children:[s.jsx("div",{ref:S?void 0:Ie,"aria-label":"看板工具栏",className:"relative z-20 flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border/15 pb-2",children:S?s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"flex min-w-0 items-center mr-auto",children:l}),qe?Ue:s.jsx("button",{ref:ce,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${it} ${l?"":"ml-auto"}`,onClick:()=>ve(!0),children:s.jsx(Gl,{size:16})}),s.jsxs("div",{ref:Ie,className:"relative shrink-0",children:[s.jsxs("button",{ref:je,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务","aria-expanded":Y,className:`${it} ${dt?"text-primary":""}`,onClick:()=>st(V=>!V),children:[s.jsx(u1,{size:15}),s.jsx("span",{children:"筛选"}),dt>0&&s.jsx("span",{className:"tabular-nums text-primary",children:dt})]}),Y&&ke]}),d,c&&s.jsx("div",{className:"shrink-0",children:c})]}):s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"mr-auto flex min-w-0 items-center",children:l}),c&&s.jsx("div",{className:"shrink-0",children:c}),s.jsxs("div",{ref:ie,className:"relative shrink-0",children:[s.jsxs("button",{ref:Pe,type:"button","aria-label":"更多看板操作","aria-expanded":he,className:`${it} ${he?"bg-surface-2 text-foreground":dt||J.trim()?"text-primary":""}`,onClick:()=>{Qe(V=>!V),st(!1)},children:[s.jsx(Do,{size:18}),dt>0&&s.jsx("span",{className:"text-[10px]",children:dt})]}),he&&s.jsxs("div",{role:"group","aria-label":"看板更多操作",className:"absolute right-0 top-full z-30 mt-2 flex w-52 max-w-[calc(100vw-2rem)] flex-col gap-0.5 rounded-xl border border-border/40 bg-surface p-1.5 shadow-xl",onClick:()=>Qe(!1),children:[s.jsxs("button",{ref:ce,type:"button","aria-label":"搜索任务",className:_e,onClick:()=>ve(!0),children:[s.jsx(Gl,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:je,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务",className:_e,onClick:()=>st(!0),children:[s.jsx(u1,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",dt>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:dt})]}),d&&s.jsx("div",{className:"mt-1 border-t border-border/30 pt-1 [&>button]:min-h-11 [&>button]:w-full [&>button]:justify-start [&>button]:gap-3 [&>button]:px-3 [&>button]:text-left [&>button]:text-sm [&>button]:text-foreground [&>button:hover]:bg-surface-2 [&>button:active]:bg-surface-elevated [&>button:focus-visible]:bg-surface-2 [&>button>svg]:h-[18px] [&>button>svg]:w-[18px] [&>button>svg]:shrink-0 [&>button>svg]:text-muted-foreground [&>button>span]:not-sr-only",children:d})]})]}),qe&&Ue,Y&&ke]})}),s.jsx("nav",{hidden:S,"aria-label":"看板阶段",className:`${S?"hidden":"grid"} shrink-0 grid-cols-4 gap-1`,children:Bl.map(V=>s.jsxs("button",{type:"button","aria-pressed":P===V.id,className:`min-h-11 rounded-lg px-1 text-xs ${P===V.id?"bg-surface-2 text-foreground":"text-muted-foreground"}`,onClick:()=>Q(V.id),children:[V.label,s.jsx("span",{className:"ml-1 tabular-nums",children:xe.filter(ae=>Ge(ae)===V.id).length})]},V.id))}),s.jsxs("div",{ref:S?void 0:m,"data-kanban-scroll":!0,onPointerDown:()=>{w.current=null},onWheel:()=>{w.current=null},"aria-label":S?void 0:"可左右滑动的任务看板",onScroll:S?void 0:V=>{if(V.target!==V.currentTarget||!V.currentTarget.clientWidth)return;const ae=w.current;if(ae){const $e=Bl.findIndex(Xe=>Xe.id===ae)*V.currentTarget.clientWidth;if(Math.abs(V.currentTarget.scrollLeft-$e)>2)return;w.current=null}const pe=Math.max(0,Math.min(Bl.length-1,Math.round(V.currentTarget.scrollLeft/V.currentTarget.clientWidth)));$(Bl[pe].id)},className:S?"min-h-0 flex-1 overflow-auto pb-3":"min-h-0 flex-1 snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[S&&s.jsx("div",{"aria-label":"看板列标题",className:"sticky top-0 z-10 grid min-w-[1000px] grid-cols-4 gap-4 border-b border-border/15 bg-[var(--chrome-bg)] pb-2",children:Bl.map(V=>{const ae=V.icon;return s.jsxs("h4",{className:`flex items-center gap-2 px-3 py-2 text-[13px] font-medium ${V.id==="attention"?"text-primary":"text-muted-foreground"}`,children:[s.jsx(ae,{size:15}),V.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:xe.filter(pe=>Ge(pe)===V.id).length})]},V.id)})}),s.jsx("div",{className:S?"grid min-h-full min-w-[1000px] grid-cols-4 items-start gap-4 pt-2":"flex h-full",children:Bl.map(V=>{const ae=xe.filter(pe=>Ge(pe)===V.id).sort((pe,$e)=>$e.updatedAt-pe.updatedAt);return s.jsx("section",{"aria-label":`${V.label}任务`,"aria-hidden":!S&&P!==V.id?!0:void 0,ref:pe=>{pe&&(pe.inert=!S&&P!==V.id)},style:S?void 0:{width:"100%"},className:S?"min-w-0 px-1":"h-full min-w-0 shrink-0 snap-start snap-always overflow-y-auto overscroll-y-contain px-1 pb-3 pt-2",children:s.jsxs("div",{className:"space-y-2",children:[ae.map(pe=>{const $e=le.get(pe.id),Xe=$e.attention??pe,wt=Xe.attempts.find(Me=>Me.id===Xe.activeAttemptId),Ut=Xe.decisions.find(Me=>Me.status==="pending"),qt=cu(Xe),Nt=v4(pe,$e.children),sr=$e.attention?tg(Xe):pe.workflow?.kind==="goal"?Nt.label:tg(Xe,$e.children),jt=yp(Xe),Xt=jt[0],Rt=jt.find(Me=>Me.source==="system"),ir=jt.find(Me=>Me.source==="unknown"),ge=Rt?.content,Je=V.id==="attention",at=Ut?"回答问题":ir?"查看详情核对记录":Xt?.source==="member"&&Rt?"查看条件与异常处理":Xt?.source==="member"?"查看阻塞并补充条件":ge?"查看原因与处理":qt==="等待你验收"?"查看结果并验收":qt==="需要你确认方案"?"查看并确认方案":"查看任务并处理",Et=Xe.artifacts.filter(Me=>Me.kind==="result"&&Me.attemptId===Xe.activeAttemptId).at(-1),X=Xe.events.filter(Me=>Me.kind==="revise"&&Me.source==="user"&&Me.attemptId===Xe.activeAttemptId&&(!Et||Me.createdAt>=Et.createdAt)).at(-1),vt=Ut?Ut.question||"成员提出了一个问题,打开后可查看并回答。":Xt?.summary||X?.content||(pe.workflow?.kind==="goal"&&!$e.attention&&Nt.latest?Et?.summary||w4(Nt.latest):Et?.summary||(wt?.report?.content?T4(wt.report.content).summary:wt?.report?.summary||"")),Bt=e.find(Me=>Me.id===pe.parentTaskId);return s.jsxs("article",{"aria-label":pe.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===pe.id?"border-primary/60":ge?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":pe.id,"aria-pressed":t===pe.id,className:"block w-full rounded-xl p-4 text-left transition hover:bg-surface-2/40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>r(Xe.id),children:[Bt&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:Bt.title}),s.jsx("span",{title:pe.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:pe.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${ge&&Xt?.source!=="member"?"text-destructive":Je?"text-primary":"text-muted-foreground"}`,children:[ge&&Xt?.source!=="member"&&s.jsx(cg,{size:13,className:"shrink-0"}),sr]}),$e.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",$e.attention.title]}),$e.attention&&$e.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",$e.attentionCount," 项执行需要你处理"]}),pe.workflow?.kind==="goal"&&!$e.attention&&s.jsx("span",{className:"mt-2 block text-xs leading-5 text-muted-foreground",children:Nt.next}),vt&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:vt}),Rt&&Xt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Rt.label,":",Rt.summary]}),ir&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[ir.label,":",ir.summary]}),Je&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${ge?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[at,s.jsx(nf,{size:14})]}),!Je&&(pe.status==="accepted"||pe.artifacts.some(Me=>Me.kind==="result"&&Me.attemptId===pe.activeAttemptId))&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:[X?"查看跟进":"查看结果",s.jsx(nf,{size:14})]}),!Je&&pe.workflow?.kind==="goal"&&!Et&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:["查看拆分与进展",s.jsx(nf,{size:14})]})]}),s.jsx(A4,{task:pe,children:$e.children,onSelect:r}),s.jsxs("div",{className:"mx-4 border-t border-border/10 py-3 text-[11px] text-muted-foreground",children:[s.jsxs("span",{className:"block truncate",children:[$e.attention?"待处理任务负责人:":pe.workflow?.kind==="goal"?"协调者:":"负责人:",wt?n(Xe,wt.assignee):Xe.scheduledAssignee?n(Xe,Xe.scheduledAssignee):"未分派"]}),pe.workflow?.kind==="goal"&&!Je&&!$e.attention&&Nt.latest?s.jsxs("time",{className:"mt-1 block text-[11px]",dateTime:new Date(Nt.latest.createdAt).toISOString(),children:[Nt.latest.source," · ",new Date(Nt.latest.createdAt).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})]}):s.jsx(tp,{task:Xe,now:v,compact:!0})]})]},pe.id)}),!ae.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:J||U!=="all"?"没有匹配的任务":e.length?"暂无任务":V.hint})]})},V.id)})})]})]})}const Hl=Sc((e,t)=>({views:{},details:{},ensureDetail:(r,n)=>{const a=t().details[r];return a||(e(c=>({details:{...c.details,[r]:n}})),n)},updateDetail:(r,n,a)=>e(c=>{const l=c.details[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{details:{...c.details,[r]:{...l,[n]:d}}}}),ensure:(r,n)=>{const a=t().views[r];return a||(e(c=>({views:{...c.views,[r]:n}})),n)},update:(r,n,a)=>e(c=>{const l=c.views[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{views:{...c.views,[r]:{...l,[n]:d}}}})}));function Gh(e,t){return r=>Hl.getState().update(e,t,r)}function Vm(e,t){return r=>Hl.getState().updateDetail(e,t,r)}const uF=b.lazy(()=>Zc(()=>Promise.resolve().then(()=>YO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),dF=b.lazy(()=>Zc(()=>import("./CollaborationTaskContent-CG7g1LMH.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),xa="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-[13px] transition disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Os="w-full min-h-11 rounded-lg border border-border/30 bg-surface-2 px-3 py-2 text-sm text-foreground outline-none focus:border-primary",wl=`${xa} bg-primary text-primary-foreground`,ii=`${xa} bg-surface-2 text-foreground hover:bg-surface-2/80`,hF={created:"创建任务",assigned:"分派",report:"成员报告",respond:"答复",question:"提出问题",answer:"回答问题","submit-plan":"提交方案",review:"提交评审","request-review":"请求独立评审","approve-plan":"用户确认方案",accepted:"用户验收",revise:"要求修改",comment:"补充说明",coordinator:"协调者变更",close:"关闭",reopen:"重新打开",scheduled:"等待自动分派",coordinate:"协调说明","child-update":"子任务更新","review-passed":"独立评审通过","review-blocked":"评审受阻","automation-blocked":"自动安排受阻",pause:"暂停安排",resume:"继续安排",retry:"请求重新检查"},Xu=e=>`${e.serviceId}:${e.sessionId}`,fa=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function Lo(e,t){try{const r=JSON.parse(localStorage.getItem(e)??"null");return r===null||t!==null&&(typeof r!=typeof t||Array.isArray(r)!==Array.isArray(t))?t:r}catch{return t}}function Hi(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const p0={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]},sy="__new_coordinator__";function fF(e){const t={...p0,...Lo(e,p0)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(p0).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?p0:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function S4(e,t){const r=e.workflow?.rootTaskId?t.find(c=>c.id===e.workflow?.rootTaskId):null;if(r?.workflow?.paused)return r;const n=new Set([e.id]);let a=e.parentTaskId;for(;a&&!n.has(a);){n.add(a);const c=t.find(l=>l.id===a);if(!c)break;if(c.workflow?.kind==="goal"&&c.workflow.paused)return c;a=c.parentTaskId}return e.workflow?.paused?e:null}function pF({group:e,sessions:t,active:r,onOpenSession:n,onAttentionChange:a,onManageMembers:c,board:l=!1,boardNavigation:d,boardSettings:f,paneKey:m,agents:x=[],defaultCwd:y,onTeamReady:w}){const v=`termdock:tasks:${location.origin}:${e.id}`,[T,S]=b.useState([]),I=b.useRef(T);I.current=T;const[N,P]=b.useState(null),[$]=b.useState(()=>Hl.getState().ensure(v,{draft:fF(`${v}:draft`),selectedId:Lo(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:Q,mobileDetail:U,creating:Z,draft:J}=Hl(ne=>ne.views[v]??$),H=Gh(v,"selectedId"),ye=Gh(v,"mobileDetail"),oe=Gh(v,"creating"),te=Gh(v,"draft"),[Ce,qe]=b.useState(!1),[ve,Y]=b.useState(!1),st=b.useRef(null),he=b.useRef(null),Qe=b.useRef(!1),ie=b.useCallback(ne=>{!ne&&he.current===document.activeElement&&(Qe.current=!0),he.current=ne,ne&&Qe.current&&(Qe.current=!1,ne.focus())},[]);b.useEffect(()=>{const ne=st.current;if(!ne)return;const Ye=new ResizeObserver(St=>qe(St[0].contentRect.width>=(l?1100:760)));return Ye.observe(ne),()=>Ye.disconnect()},[l]);const[Pe,Fe]=b.useState(!1),[ce,Ie]=b.useState(null),je=i3(),[Ze,we]=b.useState(0),[le,Ge]=b.useState(null),[He,tt]=b.useState(!1),[xe,dt]=b.useState(0),it=ne=>dt(Ye=>Math.max(0,Ye+ne)),[_e,Ue]=b.useState("");b.useEffect(()=>{if(!_e)return;const ne=setTimeout(()=>Ue(""),5e3);return()=>clearTimeout(ne)},[_e]);const[ke,V]=b.useState("open"),[ae,pe]=b.useState(""),$e=b.useRef(!1),Xe=b.useRef(!0),wt=b.useRef(new Map),Ut=b.useRef(!1),qt=e.sessionIds.flatMap(ne=>{const Ye=t.find(St=>St.sessionId===ne);return Ye?[Ye]:[]}),Nt=qt.map(ne=>({...ne,name:$u(ne,qt)})),sr=J.coordinator===sy,jt=J.coordinator||Lo(`${v}:lead`,""),Xt=Nt.find(ne=>ne.sessionId===J.coordinator&&ne.agent),Rt=!!J.coordinator&&!sr&&!Xt,ir=sr||Rt?"":Xt?.sessionId||Nt.find(ne=>ne.sessionId===jt&&ne.agent)?.sessionId||Nt.find(ne=>ne.agent)?.sessionId||"",ge=Nt.filter(ne=>ne.sessionId!==ir&&ne.agent).map(ne=>ne.sessionId),[Je,at]=b.useState(!1),[Et,X]=b.useState(!1),[vt,Bt]=b.useState(()=>Lo(`${v}:agent`,"")),[Me,Dr]=b.useState(()=>Lo(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Le=e.launchProfiles?.find(ne=>ne.id===Me),At=Nt.flatMap(ne=>ne.agent&&x.some(Ye=>Ye.slug===ne.agent.slug)?[ne.agent.slug]:[]),Ot=[...new Set(At)].sort((ne,Ye)=>At.filter(St=>St===Ye).length-At.filter(St=>St===ne).length)[0],er=x.find(ne=>ne.slug===Xt?.agent?.slug)?.slug??Ot??x[0]?.slug??"",ot=Le?.agentSlug??(vt||er),[Lt,nr]=b.useState(()=>Lo(`${v}:cwd`,Nt[0]?.cwd??y??"")),ur=!Nt.find(ne=>ne.sessionId===ir)?.agent||!ge.length,[Rr,Gr]=b.useState(null),Tt=!!J.spec.trim()&&(!!Rr||!Rt&&(!ur||!e.federated&&(!Me||!!Le)&&!!x.find(ne=>ne.slug===ot)&&!!Lt.trim())),Ft=T.find(ne=>ne.id===Q)??null,be=N?.id===Q?N:null;b.useEffect(()=>(Xe.current=!0,()=>{Xe.current=!1}),[]),b.useEffect(()=>{Hi(`${v}:draft`,J)},[v,J]),b.useEffect(()=>{Hi(`${v}:selected`,Q)},[v,Q]),b.useEffect(()=>{const ne=St=>{const Jt=St.detail;Jt?.groupId===e.id&&(Hi(`${v}:open-task`,null),H(Jt.taskId),ye(!0),oe(!1),V("all"),Ct())};window.addEventListener("open-collaboration-task",ne);const Ye=Lo(`${v}:open-task`,null);return Ye&&(H(Ye),ye(!0),V("all"),Hi(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",ne)},[e.id]),b.useEffect(()=>{if(!r||!Ft||N?.id===Ft.id&&N.revision===Ft.revision)return;let ne=!1;return i9(Ft.id).then(Ye=>{ne||(P(Ye.task),Ie(null))}).catch(Ye=>{ne||Ie(Ye instanceof Error?Ye.message:"任务详情加载失败")}),()=>{ne=!0}},[r,Ft?.id,Ft?.revision,N?.id,N?.revision,Ze]);const Ct=async()=>{if(!Ut.current){Ut.current=!0;try{const ne=await t3(e.id);Xe.current&&(S(ne.tasks),Fe(!0),Ie(null),we(Ye=>Ye+1))}catch(ne){Xe.current&&Ie(ne instanceof Error?ne.message:"任务加载失败")}finally{Ut.current=!1}}};b.useEffect(()=>{if(r)return ou(()=>{navigator.onLine!==!1&&Ct()},2500,[k0,"pageshow"])},[r,e.id]);const gt=ne=>{const Ye=JSON.stringify(ne),St=Lo(`${v}:request`,null);let Jt=wt.current.get(Ye)??(St?.fingerprint===Ye?St.key:void 0);return Jt||(Jt=crypto.randomUUID(),wt.current.set(Ye,Jt)),Hi(`${v}:request`,{fingerprint:Ye,key:Jt}),Jt},rt=ne=>{wt.current.delete(JSON.stringify(ne)),Hi(`${v}:request`,null)},cn=async(ne,Ye)=>{if(He||$e.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};$e.current=!0,tt(!0),Ge(null),Ue("");let St={...Ye,expectedRevision:ne.revision};if(["comment","revise"].includes(Ye.kind)){const Jt=Lo(`${v}:request`,null);try{const[Or,un]=JSON.parse(Jt?.fingerprint??"null"),{expectedRevision:Jr,...en}=un;Or===ne.id&&JSON.stringify(en)===JSON.stringify(Ye)&&(St=un)}catch{}}try{const Jt=await l9(ne.id,{...St,idempotencyKey:gt([ne.id,St])});if(rt([ne.id,St]),Pu.getState().refresh(),Xe.current){const Or=I.current.find(mr=>mr.id===Jt.task.id),un=Or&&Or.revision>Jt.task.revision?Or:Jt.task;S(mr=>mr.map(tn=>tn.id===Jt.task.id&&tn.revision<=Jt.task.revision?Jt.task:tn)),P(mr=>mr?.id===Jt.task.id&&mr.revision>Jt.task.revision?mr:Jt.task);const Jr=S4(un,I.current),en=`${Ye.kind==="answer"?"回答已保存":"方案确认已保存"},${Jr?Jr.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;Ue(["comment","revise"].includes(Ye.kind)?"":Ye.kind==="retry"?oF(ne,Jt.task):["answer","approve-plan"].includes(Ye.kind)?en:Ye.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(Jt){const Or=Jt instanceof Error?Jt.message:"操作失败";return Or.includes("任务已更新")&&rt([ne.id,St]),Xe.current&&(Ge(["comment","revise"].includes(Ye.kind)?null:Or),Ct()),{ok:!1,error:Or}}finally{$e.current=!1,Xe.current&&tt(!1)}},Kr=async ne=>{if(ne.preventDefault(),He||xe>0||(J.mode==="goal"?!Tt:!J.title.trim()||!J.spec.trim())||$e.current)return;$e.current=!0,tt(!0),Ge(null);const Ye=J.mode==="goal",St={groupId:e.id,title:J.title.trim()||J.spec.trim().split(`
139
+ `)),e,!!t,t);return t||x0(e),te},[c,e,t]);const J=()=>{const te=Vc();return`${location.origin}:${te?.targetPeerId??""}:${te?.serviceOrigin??""}`},H=te=>{const Ce=U(),qe=J(),ve=S.current.onUploadChange;$(""),N(Y=>Y+1),ve?.(1),Q.current=Q.current.then(async()=>{try{if(qe!==J())throw new Error("目标服务已切换,请重新添加附件");const Y=await te();if(qe!==J())throw new Error("目标服务已切换,请重新添加附件");Array.isArray(Y)?Z(Y.map(Ou).join(" ")+" ",Ce):Y&&Z(Y,Ce)}catch(Y){const st=Y instanceof Error?Y.message:"附件准备失败,请重试";$(st.includes("Upload did not return")?"附件上传未返回完整路径,请重试":st)}finally{N(Y=>Y-1),ve?.(-1)}})},ye=async te=>te.length===1&&te[0].type.startsWith("image/")?[await Q3(te[0])]:F3(te),oe=te=>{const Ce=te.clipboardData.files.length?Array.from(te.clipboardData.files):Array.from(te.clipboardData.items??[]).filter(Y=>Y.kind==="file").map(Y=>Y.getAsFile()).filter(Y=>Y!==null),qe=te.clipboardData.getData("text/plain"),ve=Gi();!ve?.readClipboardFiles&&!Ce.length&&qe||!ve&&!Ce.length&&typeof navigator.clipboard?.read!="function"||(te.preventDefault(),H(async()=>{const Y=J();let st;if(ve?.readClipboardFiles)try{const he=await O3();if(he.paths.length||he.files.length)return[...he.paths,...await ye(he.files)]}catch(he){if(he instanceof w0)throw he;st=he}if(Y!==J())throw new Error("目标服务已切换,请重新粘贴");if(Ce.length)return ye(Ce);if(qe)return qe;if(typeof navigator.clipboard?.read=="function"){const he=await navigator.clipboard.read(),Qe={read:async()=>he},ie=await P3(Qe);if(ie.length)return ye(ie);const Pe=await Rf(Qe);if(Pe)return ye([Pe]);for(const Fe of he)if(Fe.types.includes("text/plain"))return(await Fe.getType("text/plain")).text()}else{const he=await Rf();if(he)return ye([he])}if(st)throw st;return null}))};return s.jsxs("div",{className:"space-y-1.5",onFocusCapture:()=>x0(e),onPointerDownCapture:()=>x0(e),children:[s.jsx("label",{htmlFor:w,className:"block text-xs text-muted-foreground",children:r}),s.jsx("textarea",{ref:v,id:w,value:n,required:d,disabled:l,autoFocus:f,"aria-describedby":I||P?`${w}-status`:void 0,placeholder:m,className:x,onChange:te=>a(te.target.value),onPaste:oe,onDragOver:te=>{!l&&te.dataTransfer.types.includes("Files")&&te.preventDefault()},onDrop:te=>{const Ce=Array.from(te.dataTransfer.files);!Ce.length||l||(te.preventDefault(),te.stopPropagation(),H(()=>ye(Ce)))}}),s.jsxs("div",{className:"flex min-h-9 items-center gap-2",children:[s.jsx("input",{ref:T,type:"file",multiple:!0,hidden:!0,"aria-label":`选择附件:${r}`,onChange:te=>{const Ce=Array.from(te.target.files??[]);te.target.value="",Ce.length&&H(()=>ye(Ce))}}),s.jsxs("button",{type:"button","aria-label":`添加附件:${r}`,title:"添加附件",disabled:l,className:"inline-flex min-h-9 shrink-0 items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>T.current?.click(),children:[s.jsx(wS,{size:14}),"附件"]}),I>0?s.jsxs("span",{id:`${w}-status`,role:"status",className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s.jsx(vn,{size:12,className:"animate-spin"}),"正在准备附件…"]}):P?s.jsx("span",{id:`${w}-status`,role:"alert",className:"break-words text-xs text-destructive",children:P}):s.jsx("span",{className:"text-[11px] text-muted-foreground/70",children:"可粘贴图片、文件或拖入附件"})]})]})}function ny(e){return e.status!=="open"?"done":Vi(e)||e.workflow?.paused?"attention":e.activeAttemptId?"running":"backlog"}const Bl=[{id:"backlog",label:"待开始",icon:V0,hint:"等待分派或依赖完成"},{id:"running",label:"执行中",icon:kf,hint:"分派后的任务会出现在这里"},{id:"attention",label:"需要你",icon:cd,hint:"问题、方案与验收都在这里"},{id:"done",label:"已完成",icon:L0,hint:"验收后的结果会保留在这里"}];function cF({tasks:e,selectedId:t,onSelect:r,name:n,storage:a,action:c,navigation:l,settings:d}){const f=b.useRef(null),m=b.useRef(null),x=b.useRef("backlog"),y=b.useRef(0),w=b.useRef(null),[v,T]=b.useState(Date.now);b.useEffect(()=>ou(()=>T(Date.now()),3e4),[]);const[S,I]=b.useState(!1);b.useEffect(()=>{const V=new ResizeObserver(ae=>{const pe=ae[0].contentRect.width;I(pe>=760),pe!==y.current&&pe<760&&m.current&&(m.current.scrollLeft=Bl.findIndex($e=>$e.id===x.current)*m.current.clientWidth),y.current=pe});return f.current&&V.observe(f.current),()=>V.disconnect()},[]);const[N]=b.useState(()=>{try{return JSON.parse(localStorage.getItem(`${a}:board`)??"null")}catch{return null}}),[P,$]=b.useState(()=>{if(Bl.some(pe=>pe.id===N?.lane))return N.lane;const ae=ty(e,N?.showSteps===!0,N?.query??"").map(pe=>pe.attention?"attention":ny(pe.task));return ae.includes("attention")?"attention":ae.includes("running")?"running":ae.includes("backlog")?"backlog":"done"});x.current=P;function Q(V,ae=!0){$(V);const pe=m.current;if(!pe||!pe.clientWidth)return;w.current=V;const $e=Bl.findIndex(wt=>wt.id===V)*pe.clientWidth,Xe=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;pe.scrollTo?pe.scrollTo({left:$e,behavior:ae&&!Xe?"smooth":"auto"}):pe.scrollLeft=$e}b.useEffect(()=>{S||Q(x.current,!1)},[S]);const[U,Z]=b.useState(typeof N?.scope=="string"?N.scope:"all"),[J,H]=b.useState(typeof N?.query=="string"?N.query:""),[ye,oe]=b.useState(N?.closed===!0),[te,Ce]=b.useState(N?.showSteps===!0),[qe,ve]=b.useState(!!N?.query),[Y,st]=b.useState(!1),[he,Qe]=b.useState(!1),ie=b.useRef(null),Pe=b.useRef(null);b.useEffect(()=>{if(!he)return;ie.current?.querySelector('[aria-label="看板更多操作"] button')?.focus();const V=pe=>{ie.current?.contains(pe.target)||Qe(!1)},ae=pe=>{pe.key==="Escape"&&(pe.preventDefault(),pe.stopPropagation(),Qe(!1),Pe.current?.focus())};return document.addEventListener("pointerdown",V),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",V),document.removeEventListener("keydown",ae)}},[he]);const Fe=b.useRef(null),ce=b.useRef(null),Ie=b.useRef(null),je=b.useRef(null);b.useEffect(()=>{qe&&Fe.current?.focus()},[qe]),b.useEffect(()=>{if(!Y)return;Ie.current?.querySelector("select")?.focus();const V=pe=>{Ie.current?.contains(pe.target)||st(!1)},ae=pe=>{pe.key==="Escape"&&(pe.preventDefault(),pe.stopPropagation(),st(!1),(S?je:Pe).current?.focus())};return document.addEventListener("pointerdown",V),document.addEventListener("keydown",ae),()=>{document.removeEventListener("pointerdown",V),document.removeEventListener("keydown",ae)}},[Y]),b.useEffect(()=>{try{localStorage.setItem(`${a}:board`,JSON.stringify({lane:P,scope:U,query:J,closed:ye,showSteps:te}))}catch{}},[a,P,U,J,ye,te]);const Ze=e.filter(V=>V.workflow?.kind==="goal"),we=ty(e,te,J),le=new Map(we.map(V=>[V.task.id,V])),Ge=V=>le.get(V.id)?.attention?"attention":ny(V),He=t?we.find(V=>V.task.id===t||V.children.some(ae=>ae.id===t)):void 0,tt=He?Ge(He.task):void 0;b.useEffect(()=>{tt&&Q(tt,!1)},[t,tt]);const xe=we.map(V=>V.task).filter(V=>(ye||V.status!=="closed")&&(U==="all"||V.id===U||le.get(V.id)?.rootId===U)&&(!J.trim()||`${V.title} ${V.spec} ${V.attempts.map(ae=>n(V,ae.assignee)).join(" ")}`.toLocaleLowerCase().includes(J.trim().toLocaleLowerCase()))),dt=+(U!=="all")+Number(ye)+Number(te),it="inline-flex min-h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",_e="flex min-h-11 w-full items-center justify-start gap-3 rounded-lg px-3 text-left text-sm font-medium text-foreground hover:bg-surface-2 active:bg-surface-elevated focus-visible:bg-surface-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Ue=s.jsxs("div",{className:`relative flex min-w-0 items-center ${S?"flex-1 max-w-[240px]":"w-full"}`,children:[s.jsx("span",{className:"sr-only",children:"搜索任务"}),s.jsx(Gl,{"aria-hidden":"true",size:15,className:"pointer-events-none absolute left-3 text-muted-foreground"}),s.jsx("input",{ref:Fe,"aria-label":"搜索任务",type:"search",value:J,onChange:V=>H(V.target.value),onKeyDown:V=>{V.key==="Escape"&&(V.preventDefault(),V.stopPropagation(),J?H(""):(ve(!1),requestAnimationFrame(()=>(S?ce:Pe).current?.focus())))},placeholder:"搜索任务或负责人",className:"min-h-11 w-full rounded-lg border border-border/20 bg-transparent pl-9 pr-9 text-xs outline-none focus:border-primary"}),s.jsx("button",{type:"button","aria-label":"关闭搜索",className:"absolute right-0 flex min-h-11 w-9 items-center justify-center text-muted-foreground",onClick:()=>{H(""),ve(!1),requestAnimationFrame(()=>(S?ce:Pe).current?.focus())},children:s.jsx(jn,{size:14})})]}),ke=s.jsxs("div",{"aria-label":"任务筛选",className:"absolute right-0 top-full z-30 mt-1 w-64 space-y-3 rounded-xl border border-border/30 bg-surface p-3 shadow-xl",children:[s.jsxs("label",{className:"block space-y-1 text-xs text-muted-foreground",children:[s.jsx("span",{children:"目标范围"}),s.jsxs("select",{"aria-label":"按目标查看",value:U,onChange:V=>Z(V.target.value),className:"min-h-11 w-full rounded-lg border border-border/20 bg-surface-2 px-3 text-xs text-foreground",children:[s.jsx("option",{value:"all",children:"所有目标"}),Ze.map(V=>s.jsx("option",{value:V.id,children:V.title},V.id))]})]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:ye,onChange:V=>oe(V.target.checked)}),"含已关闭"]}),s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-muted-foreground",children:[s.jsx("input",{type:"checkbox",checked:te,onChange:V=>Ce(V.target.checked)}),"显示执行子任务"]}),dt>0&&s.jsx("button",{type:"button",className:"min-h-11 w-full rounded-lg text-xs text-primary hover:bg-surface-2",onClick:()=>{Z("all"),oe(!1),Ce(!1)},children:"清除筛选"})]});return s.jsxs("div",{ref:f,className:"flex min-h-0 min-w-0 flex-1 flex-col gap-2",children:[s.jsx("div",{ref:S?void 0:Ie,"aria-label":"看板工具栏",className:"relative z-20 flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border/15 pb-2",children:S?s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"flex min-w-0 items-center mr-auto",children:l}),qe?Ue:s.jsx("button",{ref:ce,type:"button","aria-label":"搜索任务",title:"搜索任务",className:`${it} ${l?"":"ml-auto"}`,onClick:()=>ve(!0),children:s.jsx(Gl,{size:16})}),s.jsxs("div",{ref:Ie,className:"relative shrink-0",children:[s.jsxs("button",{ref:je,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务","aria-expanded":Y,className:`${it} ${dt?"text-primary":""}`,onClick:()=>st(V=>!V),children:[s.jsx(u1,{size:15}),s.jsx("span",{children:"筛选"}),dt>0&&s.jsx("span",{className:"tabular-nums text-primary",children:dt})]}),Y&&ke]}),d,c&&s.jsx("div",{className:"shrink-0",children:c})]}):s.jsxs(s.Fragment,{children:[l&&s.jsx("div",{className:"mr-auto flex min-w-0 items-center",children:l}),c&&s.jsx("div",{className:"shrink-0",children:c}),s.jsxs("div",{ref:ie,className:"relative shrink-0",children:[s.jsxs("button",{ref:Pe,type:"button","aria-label":"更多看板操作","aria-expanded":he,className:`${it} ${he?"bg-surface-2 text-foreground":dt||J.trim()?"text-primary":""}`,onClick:()=>{Qe(V=>!V),st(!1)},children:[s.jsx(Do,{size:18}),dt>0&&s.jsx("span",{className:"text-[10px]",children:dt})]}),he&&s.jsxs("div",{role:"group","aria-label":"看板更多操作",className:"absolute right-0 top-full z-30 mt-2 flex w-52 max-w-[calc(100vw-2rem)] flex-col gap-0.5 rounded-xl border border-border/40 bg-surface p-1.5 shadow-xl",onClick:()=>Qe(!1),children:[s.jsxs("button",{ref:ce,type:"button","aria-label":"搜索任务",className:_e,onClick:()=>ve(!0),children:[s.jsx(Gl,{size:18,className:"shrink-0 text-muted-foreground"}),"搜索任务"]}),s.jsxs("button",{ref:je,type:"button","aria-label":dt?`筛选任务,${dt} 项已启用`:"筛选任务",className:_e,onClick:()=>st(!0),children:[s.jsx(u1,{size:18,className:"shrink-0 text-muted-foreground"}),"筛选任务",dt>0&&s.jsx("span",{className:"ml-auto rounded bg-primary/10 px-1.5 text-xs tabular-nums text-primary",children:dt})]}),d&&s.jsx("div",{className:"mt-1 border-t border-border/30 pt-1 [&>button]:min-h-11 [&>button]:w-full [&>button]:justify-start [&>button]:gap-3 [&>button]:px-3 [&>button]:text-left [&>button]:text-sm [&>button]:text-foreground [&>button:hover]:bg-surface-2 [&>button:active]:bg-surface-elevated [&>button:focus-visible]:bg-surface-2 [&>button>svg]:h-[18px] [&>button>svg]:w-[18px] [&>button>svg]:shrink-0 [&>button>svg]:text-muted-foreground [&>button>span]:not-sr-only",children:d})]})]}),qe&&Ue,Y&&ke]})}),s.jsx("nav",{hidden:S,"aria-label":"看板阶段",className:`${S?"hidden":"grid"} shrink-0 grid-cols-4 gap-1`,children:Bl.map(V=>s.jsxs("button",{type:"button","aria-pressed":P===V.id,className:`min-h-11 rounded-lg px-1 text-xs ${P===V.id?"bg-surface-2 text-foreground":"text-muted-foreground"}`,onClick:()=>Q(V.id),children:[V.label,s.jsx("span",{className:"ml-1 tabular-nums",children:xe.filter(ae=>Ge(ae)===V.id).length})]},V.id))}),s.jsxs("div",{ref:S?void 0:m,"data-kanban-scroll":!0,onPointerDown:()=>{w.current=null},onWheel:()=>{w.current=null},"aria-label":S?void 0:"可左右滑动的任务看板",onScroll:S?void 0:V=>{if(V.target!==V.currentTarget||!V.currentTarget.clientWidth)return;const ae=w.current;if(ae){const $e=Bl.findIndex(Xe=>Xe.id===ae)*V.currentTarget.clientWidth;if(Math.abs(V.currentTarget.scrollLeft-$e)>2)return;w.current=null}const pe=Math.max(0,Math.min(Bl.length-1,Math.round(V.currentTarget.scrollLeft/V.currentTarget.clientWidth)));$(Bl[pe].id)},className:S?"min-h-0 flex-1 overflow-auto pb-3":"min-h-0 flex-1 snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[S&&s.jsx("div",{"aria-label":"看板列标题",className:"sticky top-0 z-10 grid min-w-[1000px] grid-cols-4 gap-4 border-b border-border/15 bg-[var(--chrome-bg)] pb-2",children:Bl.map(V=>{const ae=V.icon;return s.jsxs("h4",{className:`flex items-center gap-2 px-3 py-2 text-[13px] font-medium ${V.id==="attention"?"text-primary":"text-muted-foreground"}`,children:[s.jsx(ae,{size:15}),V.label,s.jsx("span",{className:"ml-auto tabular-nums text-xs",children:xe.filter(pe=>Ge(pe)===V.id).length})]},V.id)})}),s.jsx("div",{className:S?"grid min-h-full min-w-[1000px] grid-cols-4 items-start gap-4 pt-2":"flex h-full",children:Bl.map(V=>{const ae=xe.filter(pe=>Ge(pe)===V.id).sort((pe,$e)=>$e.updatedAt-pe.updatedAt);return s.jsx("section",{"aria-label":`${V.label}任务`,"aria-hidden":!S&&P!==V.id?!0:void 0,ref:pe=>{pe&&(pe.inert=!S&&P!==V.id)},style:S?void 0:{width:"100%"},className:S?"min-w-0 px-1":"h-full min-w-0 shrink-0 snap-start snap-always overflow-y-auto overscroll-y-contain px-1 pb-3 pt-2",children:s.jsxs("div",{className:"space-y-2",children:[ae.map(pe=>{const $e=le.get(pe.id),Xe=$e.attention??pe,wt=Xe.attempts.find(Me=>Me.id===Xe.activeAttemptId),Ut=Xe.decisions.find(Me=>Me.status==="pending"),qt=cu(Xe),Nt=v4(pe,$e.children),sr=$e.attention?tg(Xe):pe.workflow?.kind==="goal"?Nt.label:tg(Xe,$e.children),jt=yp(Xe),Xt=jt[0],Rt=jt.find(Me=>Me.source==="system"),ir=jt.find(Me=>Me.source==="unknown"),ge=Rt?.content,Je=V.id==="attention",at=Ut?"回答问题":ir?"查看详情核对记录":Xt?.source==="member"&&Rt?"查看条件与异常处理":Xt?.source==="member"?"查看阻塞并补充条件":ge?"查看原因与处理":qt==="等待你验收"?"查看结果并验收":qt==="需要你确认方案"?"查看并确认方案":"查看任务并处理",Et=Xe.artifacts.filter(Me=>Me.kind==="result"&&Me.attemptId===Xe.activeAttemptId).at(-1),X=Xe.events.filter(Me=>Me.kind==="revise"&&Me.source==="user"&&Me.attemptId===Xe.activeAttemptId&&(!Et||Me.createdAt>=Et.createdAt)).at(-1),vt=Ut?Ut.question||"成员提出了一个问题,打开后可查看并回答。":Xt?.summary||X?.content||(pe.workflow?.kind==="goal"&&!$e.attention&&Nt.latest?Et?.summary||w4(Nt.latest):Et?.summary||(wt?.report?.content?T4(wt.report.content).summary:wt?.report?.summary||"")),Bt=e.find(Me=>Me.id===pe.parentTaskId);return s.jsxs("article",{"aria-label":pe.title,className:`overflow-hidden rounded-xl border bg-surface text-left shadow-sm ${t===pe.id?"border-primary/60":ge?"border-destructive/35":"border-border/20"}`,children:[s.jsxs("button",{type:"button","data-task-id":pe.id,"aria-pressed":t===pe.id,className:"block w-full rounded-xl p-4 text-left transition hover:bg-surface-2/40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onClick:()=>r(Xe.id),children:[Bt&&s.jsx("span",{className:"mb-2 block truncate text-[10px] text-muted-foreground",children:Bt.title}),s.jsx("span",{title:pe.title,className:"block line-clamp-3 break-words text-sm font-medium leading-6 text-foreground",children:pe.title}),s.jsxs("span",{className:`mt-3 flex items-center gap-1.5 text-xs ${ge&&Xt?.source!=="member"?"text-destructive":Je?"text-primary":"text-muted-foreground"}`,children:[ge&&Xt?.source!=="member"&&s.jsx(cg,{size:13,className:"shrink-0"}),sr]}),$e.attention&&s.jsxs("span",{className:"mt-2 block truncate text-[11px] text-muted-foreground",children:["来自执行任务:",$e.attention.title]}),$e.attention&&$e.attentionCount>1&&s.jsxs("span",{className:"mt-1 block text-[11px] text-primary",children:["共 ",$e.attentionCount," 项执行需要你处理"]}),pe.workflow?.kind==="goal"&&!$e.attention&&s.jsx("span",{className:"mt-2 block text-xs leading-5 text-muted-foreground",children:Nt.next}),vt&&s.jsx("span",{className:"mt-2 line-clamp-3 break-words text-xs leading-5 text-foreground/80",children:vt}),Rt&&Xt?.source==="member"&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-destructive",children:[Rt.label,":",Rt.summary]}),ir&&s.jsxs("span",{className:"mt-2 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:[ir.label,":",ir.summary]}),Je&&s.jsxs("span",{className:`mt-4 flex min-h-9 items-center justify-between rounded-lg px-2.5 text-xs font-medium ${ge?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"}`,children:[at,s.jsx(nf,{size:14})]}),!Je&&(pe.status==="accepted"||pe.artifacts.some(Me=>Me.kind==="result"&&Me.attemptId===pe.activeAttemptId))&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:[X?"查看跟进":"查看结果",s.jsx(nf,{size:14})]}),!Je&&pe.workflow?.kind==="goal"&&!Et&&s.jsxs("span",{className:"mt-3 flex min-h-9 items-center justify-between text-xs font-medium text-primary",children:["查看拆分与进展",s.jsx(nf,{size:14})]})]}),s.jsx(A4,{task:pe,children:$e.children,onSelect:r}),s.jsxs("div",{className:"mx-4 border-t border-border/10 py-3 text-[11px] text-muted-foreground",children:[s.jsxs("span",{className:"block truncate",children:[$e.attention?"待处理任务负责人:":pe.workflow?.kind==="goal"?"协调者:":"负责人:",wt?n(Xe,wt.assignee):Xe.scheduledAssignee?n(Xe,Xe.scheduledAssignee):"未分派"]}),pe.workflow?.kind==="goal"&&!Je&&!$e.attention&&Nt.latest?s.jsxs("time",{className:"mt-1 block text-[11px]",dateTime:new Date(Nt.latest.createdAt).toISOString(),children:[Nt.latest.source," · ",new Date(Nt.latest.createdAt).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})]}):s.jsx(tp,{task:Xe,now:v,compact:!0})]})]},pe.id)}),!ae.length&&s.jsx("p",{className:"px-2 py-3 text-xs leading-6 text-muted-foreground/70",children:J||U!=="all"?"没有匹配的任务":e.length?"暂无任务":V.hint})]})},V.id)})})]})]})}const Hl=Sc((e,t)=>({views:{},details:{},ensureDetail:(r,n)=>{const a=t().details[r];return a||(e(c=>({details:{...c.details,[r]:n}})),n)},updateDetail:(r,n,a)=>e(c=>{const l=c.details[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{details:{...c.details,[r]:{...l,[n]:d}}}}),ensure:(r,n)=>{const a=t().views[r];return a||(e(c=>({views:{...c.views,[r]:n}})),n)},update:(r,n,a)=>e(c=>{const l=c.views[r];if(!l)return c;const d=typeof a=="function"?a(l[n]):a;return Object.is(l[n],d)?c:{views:{...c.views,[r]:{...l,[n]:d}}}})}));function Gh(e,t){return r=>Hl.getState().update(e,t,r)}function Vm(e,t){return r=>Hl.getState().updateDetail(e,t,r)}const uF=b.lazy(()=>Zc(()=>Promise.resolve().then(()=>YO),void 0).then(e=>({default:e.DirectoryPickerDialog}))),dF=b.lazy(()=>Zc(()=>import("./CollaborationTaskContent-Ce6gFw26.js"),__vite__mapDeps([6,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17]))),xa="inline-flex min-h-11 items-center justify-center gap-2 rounded-lg px-3 text-[13px] transition disabled:cursor-not-allowed disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",Os="w-full min-h-11 rounded-lg border border-border/30 bg-surface-2 px-3 py-2 text-sm text-foreground outline-none focus:border-primary",wl=`${xa} bg-primary text-primary-foreground`,ii=`${xa} bg-surface-2 text-foreground hover:bg-surface-2/80`,hF={created:"创建任务",assigned:"分派",report:"成员报告",respond:"答复",question:"提出问题",answer:"回答问题","submit-plan":"提交方案",review:"提交评审","request-review":"请求独立评审","approve-plan":"用户确认方案",accepted:"用户验收",revise:"要求修改",comment:"补充说明",coordinator:"协调者变更",close:"关闭",reopen:"重新打开",scheduled:"等待自动分派",coordinate:"协调说明","child-update":"子任务更新","review-passed":"独立评审通过","review-blocked":"评审受阻","automation-blocked":"自动安排受阻",pause:"暂停安排",resume:"继续安排",retry:"请求重新检查"},Xu=e=>`${e.serviceId}:${e.sessionId}`,fa=e=>new Date(e).toLocaleString([],{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"});function Lo(e,t){try{const r=JSON.parse(localStorage.getItem(e)??"null");return r===null||t!==null&&(typeof r!=typeof t||Array.isArray(r)!==Array.isArray(t))?t:r}catch{return t}}function Hi(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}const p0={mode:"goal",isolated:!0,title:"",spec:"",constraints:"",acceptance:"",assignee:"",coordinator:"",parent:"",dependencies:[]},sy="__new_coordinator__";function fF(e){const t={...p0,...Lo(e,p0)};return!t||!Array.isArray(t.dependencies)||t.dependencies.some(r=>typeof r!="string")||Object.keys(p0).some(r=>!["dependencies","isolated"].includes(r)&&typeof t[r]!="string")?p0:{...t,mode:t.mode==="task"?"task":"goal",isolated:t.isolated!==!1}}function S4(e,t){const r=e.workflow?.rootTaskId?t.find(c=>c.id===e.workflow?.rootTaskId):null;if(r?.workflow?.paused)return r;const n=new Set([e.id]);let a=e.parentTaskId;for(;a&&!n.has(a);){n.add(a);const c=t.find(l=>l.id===a);if(!c)break;if(c.workflow?.kind==="goal"&&c.workflow.paused)return c;a=c.parentTaskId}return e.workflow?.paused?e:null}function pF({group:e,sessions:t,active:r,onOpenSession:n,onAttentionChange:a,onManageMembers:c,board:l=!1,boardNavigation:d,boardSettings:f,paneKey:m,agents:x=[],defaultCwd:y,onTeamReady:w}){const v=`termdock:tasks:${location.origin}:${e.id}`,[T,S]=b.useState([]),I=b.useRef(T);I.current=T;const[N,P]=b.useState(null),[$]=b.useState(()=>Hl.getState().ensure(v,{draft:fF(`${v}:draft`),selectedId:Lo(`${v}:selected`,null),creating:!1,mobileDetail:!1})),{selectedId:Q,mobileDetail:U,creating:Z,draft:J}=Hl(ne=>ne.views[v]??$),H=Gh(v,"selectedId"),ye=Gh(v,"mobileDetail"),oe=Gh(v,"creating"),te=Gh(v,"draft"),[Ce,qe]=b.useState(!1),[ve,Y]=b.useState(!1),st=b.useRef(null),he=b.useRef(null),Qe=b.useRef(!1),ie=b.useCallback(ne=>{!ne&&he.current===document.activeElement&&(Qe.current=!0),he.current=ne,ne&&Qe.current&&(Qe.current=!1,ne.focus())},[]);b.useEffect(()=>{const ne=st.current;if(!ne)return;const Ye=new ResizeObserver(St=>qe(St[0].contentRect.width>=(l?1100:760)));return Ye.observe(ne),()=>Ye.disconnect()},[l]);const[Pe,Fe]=b.useState(!1),[ce,Ie]=b.useState(null),je=i3(),[Ze,we]=b.useState(0),[le,Ge]=b.useState(null),[He,tt]=b.useState(!1),[xe,dt]=b.useState(0),it=ne=>dt(Ye=>Math.max(0,Ye+ne)),[_e,Ue]=b.useState("");b.useEffect(()=>{if(!_e)return;const ne=setTimeout(()=>Ue(""),5e3);return()=>clearTimeout(ne)},[_e]);const[ke,V]=b.useState("open"),[ae,pe]=b.useState(""),$e=b.useRef(!1),Xe=b.useRef(!0),wt=b.useRef(new Map),Ut=b.useRef(!1),qt=e.sessionIds.flatMap(ne=>{const Ye=t.find(St=>St.sessionId===ne);return Ye?[Ye]:[]}),Nt=qt.map(ne=>({...ne,name:$u(ne,qt)})),sr=J.coordinator===sy,jt=J.coordinator||Lo(`${v}:lead`,""),Xt=Nt.find(ne=>ne.sessionId===J.coordinator&&ne.agent),Rt=!!J.coordinator&&!sr&&!Xt,ir=sr||Rt?"":Xt?.sessionId||Nt.find(ne=>ne.sessionId===jt&&ne.agent)?.sessionId||Nt.find(ne=>ne.agent)?.sessionId||"",ge=Nt.filter(ne=>ne.sessionId!==ir&&ne.agent).map(ne=>ne.sessionId),[Je,at]=b.useState(!1),[Et,X]=b.useState(!1),[vt,Bt]=b.useState(()=>Lo(`${v}:agent`,"")),[Me,Dr]=b.useState(()=>Lo(`${v}:launch-profile`,e.defaultLaunchProfileId??"")),Le=e.launchProfiles?.find(ne=>ne.id===Me),At=Nt.flatMap(ne=>ne.agent&&x.some(Ye=>Ye.slug===ne.agent.slug)?[ne.agent.slug]:[]),Ot=[...new Set(At)].sort((ne,Ye)=>At.filter(St=>St===Ye).length-At.filter(St=>St===ne).length)[0],er=x.find(ne=>ne.slug===Xt?.agent?.slug)?.slug??Ot??x[0]?.slug??"",ot=Le?.agentSlug??(vt||er),[Lt,nr]=b.useState(()=>Lo(`${v}:cwd`,Nt[0]?.cwd??y??"")),ur=!Nt.find(ne=>ne.sessionId===ir)?.agent||!ge.length,[Rr,Gr]=b.useState(null),Tt=!!J.spec.trim()&&(!!Rr||!Rt&&(!ur||!e.federated&&(!Me||!!Le)&&!!x.find(ne=>ne.slug===ot)&&!!Lt.trim())),Ft=T.find(ne=>ne.id===Q)??null,be=N?.id===Q?N:null;b.useEffect(()=>(Xe.current=!0,()=>{Xe.current=!1}),[]),b.useEffect(()=>{Hi(`${v}:draft`,J)},[v,J]),b.useEffect(()=>{Hi(`${v}:selected`,Q)},[v,Q]),b.useEffect(()=>{const ne=St=>{const Jt=St.detail;Jt?.groupId===e.id&&(Hi(`${v}:open-task`,null),H(Jt.taskId),ye(!0),oe(!1),V("all"),Ct())};window.addEventListener("open-collaboration-task",ne);const Ye=Lo(`${v}:open-task`,null);return Ye&&(H(Ye),ye(!0),V("all"),Hi(`${v}:open-task`,null)),()=>window.removeEventListener("open-collaboration-task",ne)},[e.id]),b.useEffect(()=>{if(!r||!Ft||N?.id===Ft.id&&N.revision===Ft.revision)return;let ne=!1;return i9(Ft.id).then(Ye=>{ne||(P(Ye.task),Ie(null))}).catch(Ye=>{ne||Ie(Ye instanceof Error?Ye.message:"任务详情加载失败")}),()=>{ne=!0}},[r,Ft?.id,Ft?.revision,N?.id,N?.revision,Ze]);const Ct=async()=>{if(!Ut.current){Ut.current=!0;try{const ne=await t3(e.id);Xe.current&&(S(ne.tasks),Fe(!0),Ie(null),we(Ye=>Ye+1))}catch(ne){Xe.current&&Ie(ne instanceof Error?ne.message:"任务加载失败")}finally{Ut.current=!1}}};b.useEffect(()=>{if(r)return ou(()=>{navigator.onLine!==!1&&Ct()},2500,[k0,"pageshow"])},[r,e.id]);const gt=ne=>{const Ye=JSON.stringify(ne),St=Lo(`${v}:request`,null);let Jt=wt.current.get(Ye)??(St?.fingerprint===Ye?St.key:void 0);return Jt||(Jt=crypto.randomUUID(),wt.current.set(Ye,Jt)),Hi(`${v}:request`,{fingerprint:Ye,key:Jt}),Jt},rt=ne=>{wt.current.delete(JSON.stringify(ne)),Hi(`${v}:request`,null)},cn=async(ne,Ye)=>{if(He||$e.current)return{ok:!1,error:"已有操作正在提交,请稍候。"};$e.current=!0,tt(!0),Ge(null),Ue("");let St={...Ye,expectedRevision:ne.revision};if(["comment","revise"].includes(Ye.kind)){const Jt=Lo(`${v}:request`,null);try{const[Or,un]=JSON.parse(Jt?.fingerprint??"null"),{expectedRevision:Jr,...en}=un;Or===ne.id&&JSON.stringify(en)===JSON.stringify(Ye)&&(St=un)}catch{}}try{const Jt=await l9(ne.id,{...St,idempotencyKey:gt([ne.id,St])});if(rt([ne.id,St]),Pu.getState().refresh(),Xe.current){const Or=I.current.find(mr=>mr.id===Jt.task.id),un=Or&&Or.revision>Jt.task.revision?Or:Jt.task;S(mr=>mr.map(tn=>tn.id===Jt.task.id&&tn.revision<=Jt.task.revision?Jt.task:tn)),P(mr=>mr?.id===Jt.task.id&&mr.revision>Jt.task.revision?mr:Jt.task);const Jr=S4(un,I.current),en=`${Ye.kind==="answer"?"回答已保存":"方案确认已保存"},${Jr?Jr.workflow?.kind==="goal"?"目标仍暂停;恢复目标后才能投递。":"任务仍暂停;继续安排后才能投递。":"投递状态请查看任务记录。"}`;Ue(["comment","revise"].includes(Ye.kind)?"":Ye.kind==="retry"?oF(ne,Jt.task):["answer","approve-plan"].includes(Ye.kind)?en:Ye.kind==="accept"?"已验收此版本结果。":"记录已保存。")}return{ok:!0}}catch(Jt){const Or=Jt instanceof Error?Jt.message:"操作失败";return Or.includes("任务已更新")&&rt([ne.id,St]),Xe.current&&(Ge(["comment","revise"].includes(Ye.kind)?null:Or),Ct()),{ok:!1,error:Or}}finally{$e.current=!1,Xe.current&&tt(!1)}},Kr=async ne=>{if(ne.preventDefault(),He||xe>0||(J.mode==="goal"?!Tt:!J.title.trim()||!J.spec.trim())||$e.current)return;$e.current=!0,tt(!0),Ge(null);const Ye=J.mode==="goal",St={groupId:e.id,title:J.title.trim()||J.spec.trim().split(`
140
140
  `)[0].slice(0,100),spec:J.spec,constraints:J.constraints,acceptance:J.acceptance,assigneeSessionId:Ye?void 0:J.assignee||void 0,coordinatorSessionId:Ye?ir:J.coordinator||void 0,parentTaskId:Ye?void 0:J.parent||void 0,dependsOn:Ye?[]:J.dependencies,managed:Ye,isolated:J.isolated,reviewerSessionIds:Ye?ge:void 0};try{if(Ye&&(ur||Rr)){X(!0);const Or=sr?Lo(`${v}:team-request`,"")||crypto.randomUUID():void 0;Or&&Hi(`${v}:team-request`,Or);const un=Rr??await a9(e.id,{agentSlug:ot,...Me?{launchProfileId:Me}:e.launchProfiles?.length?{launchProfileId:""}:{},cwd:Lt.trim(),...sr?{coordinatorSessionId:null,coordinatorCreationKey:Or}:ir?{coordinatorSessionId:ir}:{}});X(!1),Gr(un),St.coordinatorSessionId=un.coordinatorSessionId,St.reviewerSessionIds=un.reviewerSessionIds,Hi(`${v}:agent`,vt),Hi(`${v}:cwd`,Lt.trim()),Hi(`${v}:launch-profile`,Me)}const{task:Jt}=await o9({...St,idempotencyKey:gt(St)});rt(St),Xe.current&&(S(Or=>[Jt,...Or.filter(un=>un.id!==Jt.id)]),H(Jt.id),ye(!0),P(Jt),Ye&&Hi(`${v}:lead`,St.coordinatorSessionId),Hi(`${v}:team-request`,null),Gr(null),w?.(),te(p0),oe(!1),V("open"),pe(""),Ue(Ye?"目标已提交,协调者收到后开始拆分与分派。后续评审和依赖由服务接续。":"任务已保存。分派后由服务端持续投递。"))}catch(Jt){Xe.current&&Ge(Jt instanceof Error?Jt.message:"创建失败")}finally{$e.current=!1,Xe.current&&(tt(!1),X(!1))}},wn=(ne,Ye)=>{if(!Ye)return"用户";const St=ne.memberSessions[Xu(Ye)];return Nt.find(Jt=>Jt.sessionId===St)?.name??t.find(Jt=>Jt.sessionId===St)?.name??"暂不可用的成员"},Oe=T.filter(ne=>(ke==="all"?!0:ke==="archive"?ne.status!=="open":ne.status==="open")&&(ke==="all"||ke==="attention"||ne.workflow?.kind!=="step")&&(ke!=="attention"||Vi(ne))&&(!ae.trim()||`${ne.title} ${ne.spec} ${ne.attempts.map(Ye=>wn(ne,Ye.assignee)).join(" ")}`.toLowerCase().includes(ae.trim().toLowerCase()))),ft=T.filter(Vi).length;b.useEffect(()=>{a?.(ft)},[ft,a]);const ht=!!Ft&&(l?U:Ce||U),Cr=()=>{oe(!1),requestAnimationFrame(()=>he.current?.focus())},Ht=ne=>{Hl.getState().updateDetail(`${v}:${ne}`,"view","overview"),H(ne),ye(!0),Ue("")},yr=T.filter(Vi).filter(ne=>!ae.trim()||`${ne.title} ${ne.spec} ${ne.attempts.map(Ye=>wn(ne,Ye.assignee)).join(" ")}`.toLowerCase().includes(ae.trim().toLowerCase())),Xr=(ne,Ye=!1)=>{const St=ne.attempts.find(mr=>mr.id===ne.activeAttemptId),Jt=ne.children?.filter(mr=>mr.status==="accepted").length??0,Or=ne.children?.filter(mr=>mr.status!=="closed").length??0,un=yp(ne),Jr=un.length>1?un.find(mr=>mr.source!=="member"):null,en=(Ye?ne.decisions.find(mr=>mr.status==="pending")?.question:"")||un[0]?.summary||St?.report?.summary||St?.report?.content;return s.jsxs("button",{type:"button","aria-pressed":Q===ne.id,className:`group flex min-h-11 w-full items-start gap-3 rounded-xl p-3 text-left transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary ${Q===ne.id?"bg-surface-2":"hover:bg-surface-2/70"}`,onClick:()=>Ht(ne.id),children:[s.jsx("span",{className:`mt-0.5 shrink-0 ${Ye||ne.status==="accepted"?"text-primary":"text-muted-foreground"}`,children:Ye?s.jsx(cd,{size:16}):ne.status==="accepted"?s.jsx(L0,{size:16}):s.jsx(V0,{size:16})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block break-words text-sm font-medium leading-5 text-foreground",children:ne.title}),s.jsx("span",{className:`mt-1 block text-xs leading-5 ${Ye?"text-primary":"text-muted-foreground"}`,children:cu(ne)}),en&&s.jsx("span",{className:"mt-1 block line-clamp-2 break-words text-xs leading-5 text-muted-foreground",children:en}),Jr&&s.jsxs("span",{className:`mt-1 block line-clamp-2 break-words text-xs leading-5 ${Jr.source==="system"?"text-destructive":"text-muted-foreground"}`,children:[Jr.label,":",Jr.summary]}),Or>0&&s.jsxs("span",{className:"mt-2 flex items-center gap-2 text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"flex gap-1","aria-hidden":"true",children:(ne.children??[]).filter(mr=>mr.status!=="closed").slice(0,8).map(mr=>s.jsx("span",{className:`h-1.5 w-3 rounded-full ${mr.status==="accepted"?"bg-primary":"bg-border/30"}`},mr.id))}),Jt,"/",Or," 子任务已验收"]}),s.jsxs("span",{className:"mt-2 block text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"block truncate",children:St?wn(ne,St.assignee):"尚未分派"}),s.jsx(tp,{task:ne})]})]}),s.jsx(qs,{size:14,className:"mt-1 shrink-0 text-muted-foreground/60"})]},ne.id)},Bn=[],mn=new Set([Q]);let hn=Ft?.parentTaskId;for(;hn&&!mn.has(hn);){mn.add(hn);const ne=T.find(Ye=>Ye.id===hn);if(!ne)break;Bn.unshift(ne),hn=ne.parentTaskId}const gn=()=>{const ne=Array.from(st.current?.querySelectorAll("button[data-task-id]")??[]).find(Ye=>Ye.dataset.taskId===Q);ye(!1),requestAnimationFrame(()=>{ne&&!ne.closest("[hidden]")?ne.focus():he.current?.focus()})},an=Z||!l&&Pe&&T.length===0;return s.jsxs("section",{ref:st,"aria-label":"协作任务",className:l?"relative flex h-full min-h-0 min-w-0 flex-col gap-2":"space-y-5",children:[l&&(an||!Pe)&&d&&s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/15 pb-2",children:[d,s.jsx("div",{className:"ml-auto",children:f})]}),(le||ce&&je==="ready"&&!Sf(ce))&&s.jsxs("div",{role:"alert",className:"flex items-center gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive",children:[s.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[le||ce,!le&&Pe?" · 显示最近保存的记录":""]}),s.jsxs("button",{type:"button",className:xa,onClick:()=>le?Ge(null):void Ct(),children:[s.jsx(vn,{size:14}),le?"关闭提示":"重试"]})]}),ce&&Sf(ce)&&!l&&s.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"正在恢复任务同步,现有记录和草稿已保留"}),_e&&s.jsx("p",{role:"status",className:"rounded-lg bg-primary/10 px-3 py-2 text-xs leading-5 text-primary",children:_e}),an?s.jsxs("form",{onSubmit:ne=>{Kr(ne)},className:`mx-auto w-full max-w-xl space-y-4 ${l?"overflow-auto px-1 py-5":""}`,onKeyDown:ne=>{ne.key==="Escape"&&Z&&!ne.defaultPrevented&&!ne.nativeEvent.isComposing&&op(ne.currentTarget)&&(ne.preventDefault(),ne.stopPropagation(),He||Cr())},children:[s.jsxs("header",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"text-lg font-semibold text-foreground",children:J.mode==="goal"?"一起完成什么?":"新建手动任务"}),s.jsx("p",{className:"mt-1 text-xs leading-5 text-muted-foreground",children:J.mode==="goal"?"交给协调者拆分,你在这里看交付、回答问题。":"选择负责人,保留分派和验收记录。"})]}),(T.length>0||l)&&s.jsx("button",{type:"button","aria-label":"取消创建,保留草稿",className:`${xa} shrink-0 px-2 text-muted-foreground hover:bg-surface-2`,disabled:He,onClick:Cr,children:s.jsx(jn,{size:16})})]}),J.mode==="task"&&s.jsx(Ja,{label:"任务标题",children:s.jsx("input",{className:Os,required:!0,maxLength:200,value:J.title,onChange:ne=>te(Ye=>({...Ye,title:ne.target.value})),placeholder:"要完成什么?"})}),s.jsx(bf,{paneKey:m,inputKey:`${v}:spec`,active:r&&an,label:J.mode==="goal"?"协作目标":"目标与交付要求",className:`${Os} ${ur&&J.mode==="goal"?"min-h-24":"min-h-32"} resize-y text-sm leading-6`,autoFocus:Z,required:!0,disabled:He,value:J.spec,onUploadChange:it,onChange:ne=>te(Ye=>({...Ye,spec:typeof ne=="function"?ne(Ye.spec):ne})),placeholder:"例如:完善附件预览体验,交付实现和评审结果,保留现有快捷键。"}),J.mode==="goal"&&Rr&&s.jsxs("section",{role:"status","aria-label":"目标提交阶段",className:"space-y-2 rounded-lg bg-primary/10 px-3 py-2 text-xs leading-5",children:[s.jsx("p",{className:"text-primary",children:"成员已准备,目标尚未提交。重试会复用这些成员。"}),s.jsx("p",{className:"text-muted-foreground",children:"Agent 和工作目录已用于准备成员,因此暂时锁定;目标正文仍可修改。"}),c&&s.jsx("button",{type:"button",className:ii,disabled:He,onClick:()=>{w?.(),c()},children:"查看已准备的成员"})]}),J.mode==="goal"&&s.jsxs(Ja,{label:"协调者",children:[s.jsxs("select",{"aria-label":"协调者",className:Os,disabled:He||!!Rr,value:J.coordinator,onChange:ne=>{Hi(`${v}:team-request`,null),te(Ye=>({...Ye,coordinator:ne.target.value}))},children:[s.jsx("option",{value:"",children:"自动选择(优先复用组内 Agent)"}),s.jsx("option",{value:sy,disabled:!!e.federated,children:"新建协调者"}),Rt&&s.jsx("option",{value:J.coordinator,disabled:!0,children:"原协调者已不可用,请重新选择"}),Nt.map(ne=>s.jsxs("option",{value:ne.sessionId,disabled:!ne.agent,children:[ne.name,ne.agent?` · ${ne.agent.displayName}`:"(需要启动 Agent)"]},ne.sessionId))]}),Rt&&!Rr&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"所选协调者已离组或未运行 Agent,请重新选择。"})]}),J.mode==="goal"&&(ur||Rr)?s.jsxs("fieldset",{disabled:He||!!Rr,className:"space-y-3",children:[s.jsx("legend",{className:"mb-2 text-xs text-muted-foreground",children:Rr?"已用于准备成员的配置":"首次开始时配置 Agent"}),(!!e.launchProfiles?.length||!!Me)&&s.jsxs(Ja,{label:"启动方案",children:[s.jsxs("select",{"aria-label":"协作启动方案",className:Os,value:Me,onChange:ne=>Dr(ne.target.value),children:[s.jsx("option",{value:"",children:"Agent 默认命令"}),e.launchProfiles?.map(ne=>s.jsxs("option",{value:ne.id,children:[ne.name," · ",x.find(Ye=>Ye.slug===ne.agentSlug)?.displayName??ne.agentSlug]},ne.id))]}),Le&&s.jsxs("details",{className:"text-xs leading-5 text-muted-foreground",children:[s.jsx("summary",{className:"min-h-11 cursor-pointer py-2",children:s.jsx("span",{className:"line-clamp-2 break-words",children:Le.notes||"查看启动命令与使用备注"})}),s.jsx("p",{"aria-label":"完整使用备注",className:"whitespace-pre-wrap break-words",children:Le.notes}),s.jsx("code",{className:"mt-1 block break-all",children:Le.command})]}),Me&&!Le&&s.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"原方案已删除,请重新选择。"})]}),!Le&&s.jsx(Ja,{label:"Agent",children:s.jsxs("select",{"aria-label":"协作 Agent",className:Os,disabled:!!Le,value:ot,onChange:ne=>Bt(ne.target.value),children:[s.jsx("option",{value:"",disabled:!0,children:"选择已安装的 Agent"}),x.map(ne=>s.jsx("option",{value:ne.slug,children:ne.displayName},ne.slug))]})}),s.jsxs(Ja,{label:"工作目录",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{"aria-label":"工作目录",className:`${Os} min-w-0 flex-1`,value:Lt,onChange:ne=>nr(ne.target.value),placeholder:"选择项目所在的目录"}),s.jsx("button",{type:"button",className:ii,onClick:()=>at(!0),children:"浏览目录"})]}),Je&&s.jsx(b.Suspense,{fallback:s.jsx("p",{className:"text-xs",children:"正在打开目录…"}),children:s.jsx(uF,{open:!0,initialPath:Lt.trim()||y||"/",title:"选择协作项目目录",onCancel:()=>at(!1),onConfirm:ne=>{nr(ne),at(!1)}})})]}),!Rr&&s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:sr?"开始时新建协调者,并补齐执行/评审成员。":"保留所选协调者,开始时补齐执行/评审成员;自动选择会优先复用组内 Agent。"}),e.federated&&s.jsxs("p",{role:"alert",className:"text-xs text-muted-foreground",children:["跨服务组请从成员设置添加 Agent。",c&&s.jsx("button",{type:"button",className:ii,onClick:c,children:"管理成员"})]}),!x.length&&s.jsxs("p",{role:"alert",className:"text-xs text-muted-foreground",children:["尚未检测到可启动的 Agent。安装后刷新,或从成员设置复用现有 Agent。",c&&s.jsx("button",{type:"button",className:ii,onClick:c,children:"管理成员"})]})]}):J.mode==="task"&&s.jsx(Ja,{label:"分派给",children:s.jsxs("select",{className:Os,value:J.assignee,onChange:ne=>te(Ye=>({...Ye,assignee:ne.target.value})),children:[s.jsx("option",{value:"",children:"先保存,稍后分派"}),Nt.map(ne=>s.jsx("option",{value:ne.sessionId,children:ne.name},ne.sessionId))]})}),s.jsxs("details",{className:"border-y border-border/15",children:[s.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:["验收标准与更多设置",(J.acceptance||J.constraints)&&s.jsx("span",{className:"text-primary",children:"已补充"})]}),s.jsxs("div",{className:"space-y-3 pb-4",children:[J.mode==="goal"&&s.jsxs(Ja,{label:"目标名称(选填)",children:[s.jsx("input",{"aria-label":"目标名称",className:Os,maxLength:100,value:J.title,onChange:ne=>te(Ye=>({...Ye,title:ne.target.value})),placeholder:"用成果命名,例如:交付可安装的 Preview 客户端"}),s.jsx("p",{className:"text-xs leading-5 text-muted-foreground",children:"看板用这个名称辨认目标;未填写时使用正文第一行。"})]}),s.jsx(Ja,{label:"验收标准(选填)",children:s.jsx("textarea",{className:`${Os} min-h-20 resize-y`,value:J.acceptance,onChange:ne=>te(Ye=>({...Ye,acceptance:ne.target.value})),placeholder:"什么结果满足要求?"})}),s.jsx(Ja,{label:"约束(选填)",children:s.jsx("textarea",{className:`${Os} min-h-20 resize-y`,value:J.constraints,onChange:ne=>te(Ye=>({...Ye,constraints:ne.target.value})),placeholder:"必须保留什么?哪些操作需要先问你?"})}),J.mode==="goal"?s.jsxs("label",{className:"flex min-h-11 items-start gap-2 text-xs leading-5 text-muted-foreground",children:[s.jsx("input",{type:"checkbox",className:"mt-1",checked:J.isolated,onChange:ne=>te(Ye=>({...Ye,isolated:ne.target.checked}))}),s.jsxs("span",{children:["代码任务使用独立目录",s.jsx("br",{}),s.jsx("span",{className:"text-[11px]",children:"协调者自动区分查询与代码任务;查询复用成员会话,只有代码需要目录与集成。"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Ja,{label:"协调者",children:s.jsxs("select",{className:Os,value:J.coordinator,onChange:ne=>te(Ye=>({...Ye,coordinator:ne.target.value})),children:[s.jsx("option",{value:"",children:"由用户协调"}),Nt.map(ne=>s.jsx("option",{value:ne.sessionId,children:ne.name},ne.sessionId))]})}),s.jsx(Ja,{label:"父任务",children:s.jsxs("select",{className:Os,value:J.parent,onChange:ne=>te(Ye=>({...Ye,parent:ne.target.value})),children:[s.jsx("option",{value:"",children:"独立任务"}),T.filter(ne=>!ne.workflow).map(ne=>s.jsx("option",{value:ne.id,children:ne.title},ne.id))]})}),s.jsxs("fieldset",{className:"space-y-1",children:[s.jsx("legend",{className:"text-xs text-muted-foreground",children:"需先验收的依赖任务"}),T.filter(ne=>ne.status!=="closed").map(ne=>s.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-xs text-foreground",children:[s.jsx("input",{type:"checkbox",checked:J.dependencies.includes(ne.id),onChange:Ye=>te(St=>({...St,dependencies:Ye.target.checked?[...St.dependencies,ne.id]:St.dependencies.filter(Jt=>Jt!==ne.id)}))}),ne.title]},ne.id))]})]}),s.jsx("button",{type:"button",className:`${xa} text-muted-foreground hover:bg-surface-2`,onClick:()=>te(ne=>({...ne,mode:ne.mode==="goal"?"task":"goal"})),children:J.mode==="goal"?"改为手动分派任务":"改为自动协作目标"})]})]}),s.jsxs("button",{className:`${wl} w-full`,disabled:He||xe>0||(J.mode==="goal"?!Tt:!J.title.trim()||!J.spec.trim()),children:[He?s.jsx(vn,{size:14,className:"animate-spin"}):s.jsx(b0,{size:14}),He?Et?"正在准备成员…":"提交中…":J.mode==="goal"?Rr?"重试提交目标":"开始协作":J.assignee?"创建并分派":"保存任务"]}),s.jsx("p",{className:"text-center text-[11px] leading-5 text-muted-foreground",children:J.mode==="goal"?"拆分任务 → 执行与独立评审 → 你验收结果":"草稿自动保存,分派后保留投递与回复记录。"})]}):l&&Pe?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"sr-only",children:"任务看板"}),s.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 gap-5",children:[s.jsx("div",{hidden:ht,className:`${ht?"hidden":"flex"} min-h-0 min-w-0 flex-1`,children:s.jsx(cF,{navigation:d,settings:f,action:s.jsxs("button",{ref:ie,type:"button",className:wl,disabled:He,onClick:()=>oe(!0),children:[s.jsx(Ys,{size:14}),"新目标"]}),storage:v,tasks:T,selectedId:ht?Q:null,name:wn,onSelect:Ht})}),ht&&s.jsxs("aside",{"aria-label":"任务详情",className:"mx-auto flex min-h-0 min-w-0 w-full max-w-[1040px] flex-col",children:[s.jsx("nav",{"aria-label":"任务位置",className:"mb-2 shrink-0",children:s.jsxs("ol",{className:"flex min-w-0 items-center gap-1 text-xs text-muted-foreground",children:[s.jsx("li",{className:"shrink-0",children:s.jsx("button",{type:"button","aria-label":"返回看板",title:"查看此协作组的任务看板",className:`${xa} px-2 hover:bg-surface-2`,onClick:gn,children:"看板"})}),Bn.map(ne=>s.jsxs("li",{className:"flex min-w-0 flex-1 items-center gap-1 sm:max-w-xs sm:flex-none",children:[s.jsx(qs,{"aria-hidden":"true",size:12,className:"shrink-0"}),s.jsx("button",{type:"button","aria-label":`查看${ne.workflow?.kind==="goal"?"目标":"父任务"}:${ne.title}`,title:`查看${ne.workflow?.kind==="goal"?"目标":"父任务"}:${ne.title}`,className:`${xa} min-w-0 px-2 hover:bg-surface-2`,onClick:()=>Ht(ne.id),children:s.jsxs("span",{className:"truncate",children:[ne.workflow?.kind==="goal"?"目标":"父任务",":",ne.title]})})]},ne.id)),s.jsxs("li",{"aria-current":"page",className:"flex shrink-0 items-center gap-1",children:[s.jsx(qs,{"aria-hidden":"true",size:12}),s.jsx("span",{className:"px-2",children:Ft?.parentTaskId?"子任务详情":Ft?.workflow?.kind==="goal"?"目标详情":"任务详情"})]})]})}),s.jsx("div",{className:"min-h-0 flex-1",children:be?s.jsx(iy,{reader:!0,paneKey:m,active:r,task:be,tasks:T,members:Nt,busy:He,name:ne=>wn(be,ne),act:ne=>cn(be,ne),storage:v,onSelectTask:Ht,onOpenSession:async ne=>{const Ye=t.find(St=>St.sessionId===be.memberSessions[Xu(ne)]);if(!Ye){Ge("成员会话暂不可用,任务历史已保留。");return}try{await n(Ye)}catch(St){Ge(St instanceof Error?St.message:"无法打开终端")}}},be.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})})]})]})]}):!Pe&&!T.length?s.jsxs("div",{role:"status",className:"space-y-3 py-8",children:[s.jsx("p",{className:"text-center text-xs text-muted-foreground",children:ce?"任务暂时无法加载,请重试。":"正在加载目标…"}),!ce&&[0,1,2].map(ne=>s.jsx("div",{className:"h-14 animate-pulse rounded-lg bg-surface-2"},ne))]}):s.jsxs(s.Fragment,{children:[(!ht||Ce)&&s.jsxs("header",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-base font-semibold text-foreground",children:"协作目标"}),s.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:[T.filter(ne=>ne.status==="open"&&ne.workflow?.kind!=="step").length," 个进行中 · ",T.filter(ne=>ne.status==="accepted"&&ne.workflow?.kind!=="step").length," 个已验收"]})]}),s.jsxs("button",{ref:ie,type:"button",className:wl,disabled:He,onClick:()=>oe(!0),children:[s.jsx(Ys,{size:14}),"新目标"]})]}),s.jsxs("div",{className:Ce&&ht?"grid items-start gap-6 grid-cols-[260px_minmax(0,1fr)]":"",children:[(!ht||Ce)&&s.jsxs("div",{className:"min-w-0 space-y-5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("select",{"aria-label":"任务筛选",className:`${Os} min-w-0 flex-1 border-transparent bg-transparent`,value:ke,onChange:ne=>V(ne.target.value),children:[s.jsx("option",{value:"open",children:"进行中的目标"}),s.jsxs("option",{value:"attention",children:["需要你处理(",ft,")"]}),s.jsx("option",{value:"archive",children:"已归档"}),s.jsx("option",{value:"all",children:"全部任务"})]}),s.jsx("button",{type:"button","aria-label":"搜索任务","aria-expanded":ve,className:`${xa} shrink-0 px-3 text-muted-foreground hover:bg-surface-2`,onClick:()=>{Y(ne=>!ne),pe("")},children:s.jsx(Gl,{size:16})})]}),ve&&s.jsx("input",{"aria-label":"搜索任务或负责人",autoFocus:!0,className:Os,value:ae,onChange:ne=>pe(ne.target.value),placeholder:"搜索目标、内容或负责人"}),ke==="open"&&yr.length>0&&s.jsxs("section",{"aria-label":"需要你处理",className:"rounded-xl bg-surface-2/40 p-1",children:[s.jsxs("h4",{className:"flex items-center justify-between px-3 pb-1 pt-3 text-xs font-medium text-primary",children:["需要你处理",s.jsx("span",{className:"rounded-md bg-primary/15 px-2 py-0.5",children:yr.length})]}),yr.map(ne=>Xr(ne,!0))]}),(ke!=="open"||Oe.some(ne=>!Vi(ne))||Oe.length===0)&&s.jsxs("section",{className:"space-y-1",children:[s.jsx("h4",{className:"px-3 text-[11px] font-medium text-muted-foreground",children:ke==="attention"?"需要你处理":ke==="archive"?"已归档":ke==="all"?"全部任务":"当前目标"}),Oe.filter(ne=>ke!=="open"||!Vi(ne)).map(ne=>Xr(ne,ke==="attention")),!Oe.length&&s.jsxs("div",{className:"px-3 py-6 text-center text-xs leading-5 text-muted-foreground",children:[ae.trim()?"没有匹配的任务。":ke==="attention"?"目前没有需要你处理的任务。":ke==="archive"?"还没有归档任务。":"当前没有进行中的目标。",(ke!=="all"||ae)&&s.jsx("button",{type:"button",className:`${xa} mt-2 text-primary`,onClick:()=>{V("all"),pe("")},children:"查看全部任务"})]})]})]}),ht&&s.jsxs("div",{className:"min-w-0",children:[!Ce&&s.jsxs("button",{type:"button",className:`${xa} mb-4 -ml-2 text-muted-foreground hover:bg-surface-2`,onClick:()=>ye(!1),children:[s.jsx(a3,{size:14}),"全部目标"]}),be?s.jsx(iy,{paneKey:m,active:r,task:be,tasks:T,members:Nt,busy:He,name:ne=>wn(be,ne),act:ne=>cn(be,ne),storage:v,onSelectTask:Ht,onOpenSession:async ne=>{const Ye=t.find(St=>St.sessionId===be.memberSessions[Xu(ne)]);if(!Ye){Ge("成员会话暂不可用,任务历史已保留。");return}try{await n(Ye)}catch(St){Ge(St instanceof Error?St.message:"无法打开终端")}}},be.id):s.jsx("p",{role:"status",className:"py-8 text-center text-xs text-muted-foreground",children:"正在加载任务详情…"})]})]})]})]})}function Ja({label:e,children:t}){return s.jsxs("label",{className:"block space-y-1.5",children:[s.jsx("span",{className:"text-xs text-muted-foreground",children:e}),t]})}function iy({reader:e=!1,active:t,paneKey:r,task:n,tasks:a,members:c,name:l,busy:d,act:f,storage:m,onOpenSession:x,onSelectTask:y}){const[w,v]=b.useState(""),[T,S]=b.useState(""),[I,N]=b.useState(""),[P,$]=b.useState(!1),[Q,U]=b.useState(null),Z=b.useRef(!1),J=b.useRef(!0);b.useEffect(()=>(J.current=!0,()=>{J.current=!1}),[]);const H=b.useRef(null),ye=b.useRef(null);b.useEffect(()=>{!e&&Q&&Q.state!=="pending"&&t&&requestAnimationFrame(()=>ye.current?.scrollIntoView({block:"nearest"}))},[Q]);const oe=b.useRef(null),[te,Ce]=b.useState(0),qe=X=>Ce(vt=>Math.max(0,vt+X)),ve=b.useRef(null);b.useEffect(()=>{ve.current?.focus()},[]);const Y=`${m}:${n.id}`,[st]=b.useState(()=>Hl.getState().ensureDetail(Y,{feedback:Lo(`${Y}:feedback`,""),answers:Lo(`${Y}:answers`,{}),view:"overview"})),{feedback:he,answers:Qe,view:ie}=Hl(X=>X.details[Y]??st),Pe=Vm(Y,"feedback"),Fe=Vm(Y,"answers"),ce=Vm(Y,"view");b.useEffect(()=>{oe.current&&(oe.current.scrollTop=0)},[ie]),b.useEffect(()=>Hi(`${m}:${n.id}:answers`,Qe),[m,n.id,Qe]),b.useEffect(()=>Hi(`${m}:${n.id}:feedback`,he),[m,n.id,he]);const Ie=n.attempts.find(X=>X.id===n.activeAttemptId),je=n.status==="open",Ze=S4(n,a),we=n.artifacts.filter(X=>X.kind==="result"&&X.attemptId===n.activeAttemptId).at(-1);b.useEffect(()=>{Q?.state==="saved"&&we?.id!==Q.resultId&&U(null)},[we?.id,Q]);const le=n.artifacts.filter(X=>X.kind==="plan"&&X.attemptId===n.activeAttemptId).at(-1),Ge=n.events.filter(X=>X.kind==="revise"&&X.source==="user"&&X.attemptId===n.activeAttemptId).at(-1),He=we&&n.events.some(X=>X.kind==="revise"&&X.attemptId===n.activeAttemptId&&X.createdAt>=we.createdAt),tt=e&&je&&!!He,xe=Q?.state==="saved"&&Q.kind==="revise"&&Q.resultId===we?.id,dt=n.decisions.filter(X=>X.status==="pending"&&X.attemptId===n.activeAttemptId),it=n.dependsOn.some(X=>a.find(vt=>vt.id===X)?.status!=="accepted"),_e=!n.workflow||n.artifacts.filter(X=>X.kind==="review"&&X.reviewsArtifactId===we?.id).at(-1)?.verdict==="pass",Ue=n.children??[],ke=n.workflow?.kind==="goal"&&Ue.some(X=>!["accepted","closed"].includes(X.status)),V=`任务:${n.title}
141
141
  任务 ID:${n.id}
142
142
  ${n.spec}
@@ -159,7 +159,7 @@ ${dt.map(X=>`待回答:${X.question}`).join(`
159
159
  `))},Ct,be)},[w,e,n,y,rt?.id,be,Ct,ve,Nt]),b.useEffect(()=>{const K=Ft.current;if(!w||!K)return;const De=Mt=>oe(String(Mt.detail));return K.addEventListener("termdock:file-drop-error",De),()=>K.removeEventListener("termdock:file-drop-error",De)},[w,rt?.id,oe]);const hn=async K=>{const De=rt?.id;oe(null),wn(Mt=>Mt+1);try{const Mt=await W0("/tmp",K);if(Mt.files.length!==K.length||Mt.files.some(Dt=>!Dt.path))throw new Error("文件路径准备失败,请重试");const vr=Mt.files.map(Dt=>Ou(Dt.path)).join(" ")+" ";if(ht.current===De)wt(Dt=>Dt+(Dt&&!/\s$/.test(Dt)?`
160
160
  `:"")+vr);else if(De){const Dt=Oe.current.get(De)??{content:"",targets:null},Br={...Dt,content:Dt.content+`
161
161
  `+vr};Oe.current.set(De,Br),mn({drafts:{[De]:Br}})}}catch(Mt){oe(Mt instanceof Error?Mt.message:"文件上传失败")}finally{wn(Mt=>Mt-1)}},gn=new Set(S.filter(qm).map(K=>K.sessionId)),an=ce.size,ne=[...ce].filter(K=>!gn.has(K)),Ye=_F(rt,S),St=je.trim().toLocaleLowerCase(),Jt=S.filter(K=>!St||[$u(K,S),K.name,K.serviceLabel??"",K.cwd,Zm(K.currentTask)].some(De=>De.toLocaleLowerCase().includes(St))),Or=cy(Jt),un=cy(Ye),Jr=K=>!St&&we.has(K),en=K=>le(De=>{const Mt=new Set(De);return Mt.has(K)?Mt.delete(K):Mt.add(K),Mt});b.useEffect(()=>{qt(!1),Rt.current!==rt?.id&&sr(!1),Rt.current=null,he(!1),Le(!1),He(!1),Me({}),Et(new Set(rt?.sessionIds??[])),ot(rt?.defaultLaunchProfileId??"")},[rt?.id]),b.useEffect(()=>{!At&&I[0]&&Ot(I[0].slug)},[I,At]),b.useEffect(()=>{it([]),V(null)},[rt?.id]),b.useEffect(()=>{if(!P||!n||w&&!y||!rt){Ue(!1);return}Ue(!0);let K=!1,De=0,Mt=!1;const Dt=ou(()=>{if(K||Mt||document.hidden||navigator.onLine===!1)return;Mt=!0;const Br=++De;Bx(rt.id).then(Pr=>{!K&&Br===De&&(it(Pr.messages),V(null))}).catch(Pr=>{!K&&Br===De&&V(Pr instanceof Error?Pr.message:"消息加载失败")}).finally(()=>{Mt=!1,!K&&Br===De&&Ue(!1)})},3e3,[k0,"pageshow"]);return()=>{K=!0,Dt()}},[rt?.id,n,w,y]),b.useEffect(()=>{!P||rt?.id!==P||gt.current||(gt.current=!0,ve==="messages"&&Ft.current?.scrollIntoView?.({block:"nearest"}))},[P,rt?.id]);const mr=async()=>{ye("create-group"),oe(null),te(null);try{if(ne.length)throw new Error("所选会话已变化,请先清除不可用选择");const K=await Wl({name:Pe,sessionIds:[...ce]});Fe(""),Ze(""),x(K.group.id),await Ce(),te(`“${K.group.name}”已创建。`),r?await r(K.group.id,"messages"):U&&await U(K.group.id)}catch(K){oe(K instanceof Error?K.message:"创建失败")}finally{ye(null)}},tn=rt?.sessionIds.filter(K=>pe===null||pe.includes(K))??[],Sn=async()=>{if(!rt||H||Kr||!Xe.trim()||!tn.length)return;const K=Xe,De=rt.id;ye("send-message"),oe(null),te(null);try{const Mt=await c9(rt.id,{fromSessionId:null,toSessionIds:pe===null?void 0:tn,kind:"message",content:Xe});if(ht.current===De){const Pr=yr.current,xn=Pr===K?"":Pr.startsWith(K)?Pr.slice(K.length).replace(/^\n/,""):Pr;wt(xn),mn({drafts:{[De]:{content:xn,targets:Ht.current}}})}else{const Pr=Oe.current.get(De);if(Pr){const xn={...Pr,content:Pr.content===K?"":Pr.content.startsWith(K)?Pr.content.slice(K.length).replace(/^\n/,""):Pr.content};Oe.current.set(De,xn),mn({drafts:{[De]:xn}})}}const vr=await Bx(De).catch(()=>null);vr&&ht.current===De&&it(vr.messages);const Dt=Mt.deliveries?.filter(Pr=>Pr.serviceUnavailable).length??0,Br=Mt.deliveries?.filter(Pr=>Pr.pending>0).length??0;te(Dt>0?`已保存消息;${Dt} 个接收成员的服务不可达,尚未送达,等待重连`:Br>0?`已保存消息;${Br} 个成员等待投递确认`:`消息已送达 ${Mt.messages.length} 个会话`)}catch(Mt){oe(Mt instanceof Error?Mt.message:"发送失败")}finally{ye(null)}},Zr=async()=>{if(!rt)return;ye(`delete:${rt.id}`),oe(null),te(null);const K=rt.name;try{await o3(rt.id,tt),x(null),He(!1),await Ce(),te(`“${K}”已删除`)}catch(De){oe(De instanceof Error?De.message:"删除失败")}finally{ye(null)}},Qr=async()=>{if(!rt)return;const K=[...at];ye("save-members"),oe(null),te(null);try{const De=await Wl({id:rt.id,name:rt.name,sessionIds:K,expectedUpdatedAt:X});x(De.group.id),qt(!1),await Ce(),te(`“${rt.name}”成员已更新,共 ${K.length} 个会话`)}catch(De){oe(De instanceof Error?De.message:"成员更新失败")}finally{ye(null)}},lr=async K=>{if(!rt||!rt.sessionIds.includes(K)){Je(null);return}const De=S.find(vr=>vr.sessionId===K)?.name??K,Mt=rt.name;ye(`remove-member:${K}`),oe(null),te(null);try{await Wl({id:rt.id,name:Mt,sessionIds:rt.sessionIds.filter(vr=>vr!==K),expectedUpdatedAt:rt.updatedAt}),Je(null),$e(vr=>vr?.filter(Dt=>Dt!==K)??null),Et(vr=>new Set([...vr].filter(Dt=>Dt!==K))),Me(vr=>Object.fromEntries(Object.entries(vr).filter(([Dt])=>Dt!==K))),await Ce(),te(`已把“${De}”移出“${Mt}”`)}catch(vr){oe(vr instanceof Error?vr.message:"移出成员失败")}finally{ye(null)}},fn=async K=>{if(!rt)return;const De=Bt[K]??"";ye(`role:${K}`),oe(null),te(null);try{await f9(rt.id,K,De.trim()||null),await Ce(),te(De.trim()?"定位已保存,该成员每次收到消息都会看到":"定位已清除")}catch(Mt){oe(Mt instanceof Error?Mt.message:"定位保存失败")}finally{ye(null)}},Ss=()=>{ot(rt?.defaultLaunchProfileId??"");const K=S.find(De=>De.sessionId===N)?.cwd??S.find(De=>rt?.sessionIds.includes(De.sessionId))?.cwd??"";Rr(K),nr(""),Tt(""),Le(!0),qt(!1)},Ar=async()=>{if(!(!rt||!At||er&&!rt.launchProfiles?.some(K=>K.id===er))){ye("spawn-agent"),oe(null),te(null);try{const K=await u9(rt.id,{agentSlug:rt.launchProfiles?.find(De=>De.id===er)?.agentSlug??At,...er||rt.launchProfiles?.length?{launchProfileId:er}:{},name:Lt.trim()||void 0,cwd:ur.trim()||void 0,task:Gr.trim()||void 0,mode:J});Le(!1),await Ce(),te(`“${K.session.name}”已创建并加入“${K.group.name}”`)}catch(K){oe(K instanceof Error?K.message:"Agent Session 创建失败")}finally{ye(null)}}},En=NF(dt,S),qr=K=>s.jsxs("label",{className:"flex cursor-pointer items-start gap-3 px-2 py-2.5 transition hover:bg-surface-2",children:[s.jsx("input",{className:"mt-0.5",type:"checkbox",disabled:!qm(K),checked:ce.has(K.sessionId),onChange:()=>Ie(De=>{const Mt=new Set(De);return Mt.has(K.sessionId)?Mt.delete(K.sessionId):Mt.add(K.sessionId),Mt})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"truncate text-[12px] text-foreground",children:$u(K,S)}),s.jsx(Ym,{session:K}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground",children:wf(K)})]}),s.jsx("span",{className:"mt-0.5 block truncate text-[10px] text-muted-foreground",children:K.currentTask?`${Zm(K.currentTask)} · ${K.cwd}`:K.cwd||K.capability||"终端会话"})]})]},K.sessionId),Lr=K=>{const De=Bt[K.sessionId]??"",Mt=rt?.roles?.[K.sessionId]??"";return s.jsxs("div",{className:"px-2 py-2 transition hover:bg-surface-2",children:[s.jsxs("label",{className:"flex cursor-pointer items-center gap-3",children:[s.jsx("input",{type:"checkbox",disabled:!rt?.sessionIds.includes(K.sessionId)&&!qm(K),checked:at.has(K.sessionId),onChange:()=>Et(vr=>{const Dt=new Set(vr);return Dt.has(K.sessionId)?Dt.delete(K.sessionId):Dt.add(K.sessionId),Dt})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11px] text-foreground",children:K.name}),s.jsx(Ym,{session:K}),s.jsxs("span",{className:"block truncate text-[9px] text-muted-foreground",children:[wf(K)," · ",K.cwd]})]})]}),s.jsxs("div",{className:"mt-2 flex items-center gap-2 pl-7",children:[s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground",children:"定位"}),s.jsx("input",{"aria-label":`${K.name} 的定位`,className:`${Gs} min-h-8 py-1 text-[10px]`,value:De,maxLength:200,placeholder:"成员收到的定位;清空后保存可移除",onChange:vr=>Me(Dt=>({...Dt,[K.sessionId]:vr.target.value}))}),s.jsx("button",{"aria-label":`保存 ${K.name} 的定位`,title:De.trim()===Mt?"定位未变化":"保存此成员的定位",disabled:H!==null||De.trim()===Mt,className:`${Sr} min-h-8 shrink-0 px-2 text-muted-foreground`,onClick:()=>{fn(K.sessionId)},children:H===`role:${K.sessionId}`?s.jsx(vn,{size:12,className:"animate-spin"}):s.jsx(oi,{size:12})})]})]},K.sessionId)},On=s.jsx("nav",{"aria-label":"协作工作区",className:"flex shrink-0 items-center gap-1",children:[["tasks",e||qe?"看板":"目标"],["messages","成员与消息"]].map(([K,De])=>s.jsxs("button",{type:"button","aria-label":De,"aria-pressed":ve===K,className:`${Sr} min-h-11 ${ve===K?"bg-surface-2 text-foreground":"text-muted-foreground hover:bg-surface-2"}`,onClick:Mt=>{if(qe&&K==="tasks"){U?.(rt.id).catch(Br=>oe(Br instanceof Error?Br.message:"无法打开看板"));return}const vr=Mt.currentTarget.closest("[data-collaboration-views]"),Dt=Mt.currentTarget;Y(K),requestAnimationFrame(()=>{const Br=document.activeElement;Br!==Dt&&Br!==document.body&&Br?.isConnected&&!Br.closest("[hidden]")||Array.from(vr?.querySelectorAll('nav[aria-label="协作工作区"] button')??[]).find(Pr=>Pr.getAttribute("aria-pressed")==="true"&&!Pr.closest("[hidden]"))?.focus()})},children:[e&&K==="messages"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"sm:hidden",children:"成员"}),s.jsx("span",{className:"hidden sm:inline",children:De})]}):De,!e&&K==="tasks"&&Qe>0&&s.jsxs("span",{className:"rounded bg-primary/15 px-1.5 text-[11px] text-primary",children:[Qe," 待处理"]})]},K))}),tr=s.jsxs("button",{type:"button","aria-label":"组设置",title:"组设置","aria-expanded":Nt,className:`${Sr} min-h-11 shrink-0 text-muted-foreground hover:bg-surface-2`,onClick:K=>{Xt.current=K.currentTarget,sr(De=>!De),oe(null),te(null)},children:[s.jsx(Vu,{size:14}),e&&s.jsx("span",{className:"sm:sr-only",children:"组设置"})]});return s.jsxs("div",{ref:jt,className:e?"flex min-h-0 flex-1 flex-col gap-3":qe?void 0:"space-y-3",children:[ke&&ae==="ready"&&!Sf(ke)&&s.jsxs("p",{role:"alert",className:"rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["消息同步暂时失败,正在自动重试:",ke]}),ke&&Sf(ke)&&!e&&s.jsx("p",{role:"status",className:"text-[11px] text-muted-foreground",children:"正在恢复消息同步,现有记录已保留"}),s.jsxs("div",{className:e?Nt?"min-h-0 flex-1 overflow-auto":"contents":void 0,children:[!P&&m!=="new"&&T.length>0&&s.jsx("div",{hidden:Nt,children:s.jsx(nF,{groups:T,sessions:S,busy:H!==null,onOpen:(K,De)=>{r?.(K,De)},onSettings:(K,De)=>{Rt.current=K,x(K),Xt.current=De,sr(!0),oe(null),te(null)},onCreate:()=>{x("new"),He(!1),te(null)}})}),!P&&(m==="new"||Nt)&&T.length>0&&s.jsx("button",{type:"button",className:`${Sr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{Nt?ir():x(T[0].id)},children:"返回协作组"}),Nt&&rt&&s.jsx(AF,{group:rt,agents:I,activeSessionId:N,sessions:S,busy:H,setBusy:ye,setError:oe,setNotice:te,refresh:Ce,onClose:ir},rt.id),!P&&v!=="loaded"&&!T.length&&s.jsx("p",{role:"status",className:"py-5 text-xs text-muted-foreground",children:v==="loading"?"正在加载协作组与会话…":"会话加载失败,请重试"}),!rt&&(P||m==="new"||v==="loaded")&&s.jsxs("section",{className:"border-y border-border/15 py-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-[12px] font-medium text-foreground",children:"创建协作组"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"先给协作组命名。成员可以现在选择,也可以以后添加;消息和看板都能独立使用。"})]}),s.jsxs("span",{className:`shrink-0 text-[10px] ${an>=2?"text-primary":"text-muted-foreground"}`,children:["已选 ",an," 个"]})]}),s.jsxs("label",{className:"mt-4 block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{className:Gs,value:Pe,onChange:K=>Fe(K.target.value),placeholder:"例如:发布准备"})]}),s.jsxs("details",{className:"mt-3",children:[s.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-xs text-muted-foreground",children:["复用已有会话(选填) · 已选 ",an," 个"]}),S.length>5&&s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"筛选会话"}),s.jsx(Gl,{size:13,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{className:`${Gs} pl-8`,value:je,onChange:K=>Ze(K.target.value),placeholder:"按名称、目录或当前任务筛选"})]}),s.jsxs("div",{className:"mt-3 max-h-64 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:[Or.length<=1?Jt.map(qr):Or.map(K=>{const De=Jr(K.key);return s.jsxs("div",{children:[s.jsx(uy,{label:K.label,count:K.sessions.length,collapsed:De,onToggle:()=>en(K.key)}),!De&&s.jsx("div",{className:"divide-y divide-border/10",children:K.sessions.map(qr)})]},K.key)}),S.length===0&&s.jsx("p",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:v==="loading"?"正在加载会话…":v==="error"?"会话加载失败,请重试":"没有现有会话也可以创建,开始目标时会启动 Agent"}),S.length>0&&Jt.length===0&&s.jsx("p",{className:"px-3 py-6 text-center text-[11px] text-muted-foreground",children:"没有符合筛选条件的会话"})]})]}),ne.length>0&&s.jsxs("div",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:["有 ",ne.length," 个所选会话暂不可用。",s.jsx("button",{className:Sr,onClick:()=>Ie(K=>new Set([...K].filter(De=>gn.has(De)))),children:"清除不可用选择"})]}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-center",children:[s.jsx("p",{className:`min-w-0 flex-1 text-[10px] ${an<2?"text-muted-foreground":"text-primary"}`,children:Pe.trim()?"创建后进入成员消息,看板可随时使用":"请填写协作组名称"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[T.length>0&&s.jsx("button",{className:`${Sr} bg-surface-2 text-foreground`,onClick:()=>x(T[0]?.id??null),children:"取消"}),s.jsxs("button",{disabled:H!==null||!Pe.trim()||ne.length>0,className:`${Sr} bg-primary text-primary-foreground`,onClick:()=>{mr()},children:[H==="create-group"?s.jsx(vn,{size:13,className:"animate-spin"}):s.jsx(Ys,{size:13}),"创建协作组"]})]})]})]})]}),rt&&P&&s.jsxs("div",{"data-collaboration-views":!0,hidden:Nt,className:e?`${Nt?"hidden":"flex"} min-h-0 flex-1 flex-col gap-3`:qe?void 0:"space-y-3",children:[!qe&&(!e||ve==="messages")&&s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-border/15 pb-2",children:[On,s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e&&ve==="messages"&&s.jsxs("button",{type:"button","aria-label":"放到终端旁",title:Z?"在当前终端分屏中使用成员与消息":"先打开一个终端,再嵌入消息面板",disabled:!Z||H!==null,className:`${Sr} min-h-11 text-muted-foreground hover:bg-surface-2`,onClick:()=>{ye("dock-messages"),oe(null),Z?.().catch(K=>oe(K instanceof Error?K.message:"消息面板打开失败,草稿已保留")).finally(()=>ye(null))},children:[s.jsx(Kc,{size:14}),s.jsx("span",{className:"hidden sm:inline",children:"放到终端旁"})]}),tr]})]}),!qe&&ve==="messages"&&s.jsx("div",{className:"flex gap-1 overflow-x-auto","aria-label":"工作组终端",children:cn.map(K=>s.jsx("button",{type:"button","aria-pressed":K.sessionId===N,title:`${K.name} · ${K.cwd||"终端会话"}`,className:`${Sr} min-h-9 shrink-0 ${K.sessionId===N?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2"}`,onClick:()=>{Q(K).catch(De=>oe(De instanceof Error?De.message:"无法打开终端"))},children:$u(K,cn)},K.sessionId))}),!qe&&s.jsx("div",{hidden:ve!=="tasks",className:e?`${ve==="tasks"?"flex":"hidden"} min-h-0 flex-1 flex-col`:void 0,children:s.jsx(pF,{paneKey:d?Ct:void 0,boardNavigation:e?On:void 0,boardSettings:e?tr:void 0,board:e,group:rt,sessions:S,agents:I,defaultCwd:S.find(K=>K.sessionId===N)?.cwd??void 0,onTeamReady:Ce,active:n&&!Nt&&ve==="tasks"&&(!w||y),onAttentionChange:ie,onManageMembers:()=>Y("messages"),onOpenSession:Q},rt.id)}),s.jsxs("div",{hidden:ve!=="messages",className:e?"min-h-0 flex-1 overflow-auto":void 0,children:[s.jsxs("section",{onFocusCapture:()=>x0(Ct),onPointerDownCapture:()=>x0(Ct),"data-termdock-terminal-dropzone":w?N??"collaboration-composer":void 0,onDragOver:K=>{w&&K.preventDefault()},onDrop:K=>{if(!w)return;const De=Array.from(K.dataTransfer.files);if(!(De.length&&Gi()))if(K.preventDefault(),K.stopPropagation(),De.length)hn(De);else{const Mt=K.dataTransfer.getData("text/plain")||K.dataTransfer.getData("text/uri-list");Mt&&wt(vr=>vr+(vr?`
162
- `:"")+Mt)}},ref:Ft,className:w?"":"rounded-xl border border-primary/20 bg-primary/5 px-3 py-3",children:[!w&&s.jsxs("h4",{className:"truncate text-[12px] font-medium text-foreground",children:[rt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[qe&&s.jsxs("div",{className:"relative z-20 flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["发送给 ",s.jsx("span",{className:"text-[9px]",children:"· 可多选"})]}),s.jsxs("details",{className:"relative",onKeyDown:K=>{K.key==="Escape"&&(K.currentTarget.removeAttribute("open"),K.currentTarget.querySelector("summary")?.focus(),K.stopPropagation())},children:[s.jsx("summary",{"aria-label":"更多协作操作",className:"flex min-h-11 min-w-11 cursor-pointer list-none items-center justify-center rounded text-muted-foreground hover:bg-surface-2 sm:min-h-8 sm:min-w-8 [&::-webkit-details-marker]:hidden",children:s.jsx(Do,{size:16})}),s.jsxs("div",{className:"absolute right-0 top-full z-30 w-44 rounded-lg border border-border/20 bg-surface-2 p-1 shadow-lg",children:[s.jsxs("button",{type:"button",className:`${Sr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),U?.(rt.id).catch(De=>oe(De instanceof Error?De.message:"无法打开看板"))},children:[s.jsx(Kc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":st,className:`${Sr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),he(De=>!De)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":Nt,className:`${Sr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),Xt.current=K.currentTarget,sr(!0),oe(null),te(null)},children:[s.jsx(Vu,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:qe?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...rt.sessionIds.map(K=>({id:K,label:(()=>{const De=cn.find(Mt=>Mt.sessionId===K);return De?$u(De,cn):void 0})()??`${K.slice(0,8)}(离线)`}))].map(({id:K,label:De})=>{const Mt=K==="*"?pe===null:pe?.includes(K)??!1,vr=S.find(Dt=>Dt.sessionId===K);return s.jsxs(rF,{label:De,disabled:K==="*"||H!==null,onRemove:()=>{lr(K)},children:[s.jsxs("button",{type:"button","aria-pressed":Mt,onClick:()=>$e(Dt=>K==="*"?null:Dt?.includes(K)?Dt.filter(Br=>Br!==K):[...Dt??[],K]),className:`${rg} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Mt?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Mt&&s.jsx(oi,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:De})]}),vr&&s.jsx("button",{type:"button","aria-label":`打开 ${De} 的终端`,title:`打开 ${De} 的终端`,className:"inline-flex h-9 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-surface-2 hover:text-primary sm:h-7 sm:w-6",onClick:()=>{$(vr).catch(Dt=>oe(Dt instanceof Error?Dt.message:"无法打开会话"))},children:s.jsx(Kc,{size:12})})]},`${rt.id}:${K}`)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:qe?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:K=>{K.key==="Enter"&&(K.metaKey||K.ctrlKey)&&!K.nativeEvent.isComposing&&K.keyCode!==229&&(K.preventDefault(),Sn())},onPaste:K=>{const De=Array.from(K.clipboardData.files);De.length&&(K.preventDefault(),hn(De))},className:`${Gs} min-h-16 max-h-48 resize-y`,value:Xe,onChange:K=>wt(K.target.value),placeholder:"输入消息,可粘贴引用或文件…"})]}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsx("p",{role:"status","aria-live":"polite",title:w&&a?a:void 0,className:`min-w-0 flex-1 text-[9px] leading-relaxed ${w?"truncate":""} ${w&&a?"text-primary":"text-muted-foreground"}`,children:Kr>0?"正在准备文件路径…":w&&a?a:rt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:H!==null||Kr>0||!Xe.trim()||!tn.length,className:`${Sr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{Sn()},children:[H==="send-message"?s.jsx(vn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:qe&&!st,open:qe?st:void 0,onToggle:K=>{qe&&he(K.currentTarget.open)},className:"mt-4 rounded-xl border border-border/15",children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-3 text-[11px] font-medium text-foreground",children:["管理成员、角色与删除 · ",rt.sessionIds.length," 个成员"]}),s.jsxs("section",{className:"border-t border-border/15 p-3",children:[s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h4",{className:"text-[13px] font-medium text-foreground",children:rt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[rt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:_4(rt.id)})]})]}),Ge?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${Sr} bg-surface-2 px-2 text-foreground`,onClick:()=>He(!1),children:"取消"}),s.jsxs("button",{disabled:H!==null,className:`${Sr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{Zr()},children:[H===`delete:${rt.id}`?s.jsx(vn,{size:13,className:"animate-spin"}):null,"确认删除"]})]}):s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsxs("button",{className:`${Sr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{Et(new Set(rt.sessionIds)),vt(rt.updatedAt);const K=!Ut;qt(K),K&&Me(Object.fromEntries(rt.sessionIds.map(De=>[De,rt.roles?.[De]??""]))),Le(!1)},children:[s.jsx(Vu,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${Sr} px-2 text-primary hover:bg-primary/10`,onClick:Ss,children:[s.jsx(Ys,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${rt.name}`,title:"删除协作组",disabled:H!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{xe(rt.updatedAt),He(!0)},children:s.jsx(Ms,{size:14})})]})]}),Ge&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",rt.name,"”协作组及其协作记录,",rt.sessionIds.length," 个成员的终端会话会保留。"]}),s.jsx("div",{className:"mt-3 grid divide-y divide-border/10 border-y border-border/10 sm:grid-cols-2 sm:divide-x sm:divide-y-0",children:rt.sessionIds.map(K=>{const De=S.find(Dt=>Dt.sessionId===K),Mt=rt.roles?.[K],vr=De?.name??K;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${ge===K?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!De,onClick:()=>De&&void $(De).catch(Dt=>oe(Dt instanceof Error?Dt.message:"无法打开会话")),className:"min-w-0 flex-1 px-3 py-2.5 text-left disabled:cursor-default",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${De&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(De.status)&&De.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:vr}),De&&s.jsx(Ym,{session:De}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:De?wf(De):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Mt?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Mt]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,De?s.jsx("span",{className:"min-w-0 truncate",children:Zm(De.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${vr} 移出协作组`,"aria-expanded":ge===K,title:"移出协作组",disabled:H!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${ge===K?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>Je(ge===K?null:K),children:s.jsx(Ms,{size:13})})]},K)})}),ge&&rt.sessionIds.includes(ge)&&(()=>{const K=S.find(Mt=>Mt.sessionId===ge)?.name??ge,De=H===`remove-member:${ge}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${K}`,className:"flex flex-wrap items-center gap-x-3 gap-y-2 border-y border-destructive/25 bg-destructive/5 px-3 py-2.5",children:[s.jsx("p",{className:"min-w-0 flex-1 text-[10px] leading-relaxed text-destructive",children:`把“${K}”移出“${rt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${Sr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>Je(null),children:"取消"}),s.jsxs("button",{disabled:H!==null,className:`${Sr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{lr(ge)},children:[De?s.jsx(vn,{size:12,className:"animate-spin"}):s.jsx(Ms,{size:12}),"移出"]})]})]})})(),Ut&&s.jsxs("div",{className:"mt-4 border-t border-border/15 pt-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"管理成员"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"暂不可用的原成员会保留,只有取消勾选才会移出;定位(角色)在每行独立保存,成员收到消息时会看到自己的定位。"})]}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["已选 ",at.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:un.length<=1?Ye.map(Lr):un.map(K=>{const De=Jr(K.key);return s.jsxs("div",{children:[s.jsx(uy,{label:K.label,count:K.sessions.length,collapsed:De,onToggle:()=>en(K.key)}),!De&&s.jsx("div",{className:"divide-y divide-border/10",children:K.sessions.map(Lr)})]},K.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Sr} bg-surface-2 text-foreground`,onClick:()=>{qt(!1),Me({})},children:"取消"}),s.jsxs("button",{disabled:H!==null||v!=="loaded",className:`${Sr} bg-primary text-primary-foreground`,onClick:()=>{Qr()},children:[H==="save-members"?s.jsx(vn,{size:13,className:"animate-spin"}):s.jsx(oi,{size:13}),"保存成员"]})]})]}),Dr&&s.jsxs("div",{className:"mt-4 border-t border-primary/20 pt-4",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"创建 Agent Session"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"新会话启动后自动加入本组,并收到初始任务和成员信息。"})]}),s.jsx(sF,{group:rt,value:er,onChange:ot,disabled:H!==null}),s.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["Agent / Plugin",s.jsx("select",{"aria-label":"新 Agent 类型",className:Gs,disabled:!!er,value:rt.launchProfiles?.find(K=>K.id===er)?.agentSlug??At,onChange:K=>Ot(K.target.value),children:I.map(K=>s.jsxs("option",{value:K.slug,children:[K.displayName,K.isPlugin?" · Plugin":""]},K.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:Gs,value:Lt,onChange:K=>nr(K.target.value),placeholder:"留空则自动命名"})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["工作目录",s.jsx("input",{"aria-label":"新 Agent 工作目录",className:Gs,value:ur,onChange:K=>Rr(K.target.value),placeholder:"默认继承当前会话"})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["初始任务",s.jsx("textarea",{"aria-label":"新 Agent 初始任务",className:`${Gs} min-h-16 resize-y`,value:Gr,onChange:K=>Tt(K.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Sr} bg-surface-2 text-foreground`,onClick:()=>Le(!1),children:"取消"}),s.jsxs("button",{disabled:H!==null||!At||!!er&&!rt.launchProfiles?.some(K=>K.id===er),className:`${Sr} bg-primary text-primary-foreground`,onClick:()=>{Ar()},children:[H==="spawn-agent"?s.jsx(vn,{size:13,className:"animate-spin"}):s.jsx(G0,{size:13}),"创建并加入"]})]})]})]})]},rt.id),s.jsxs("section",{className:"mt-4",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[11px] font-medium text-foreground",children:"协作记录"}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:[En.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[En.map(K=>s.jsxs("div",{className:"px-2 py-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-primary",children:K.responseKind==="ack"?"收到确认":K.responseKind==="progress"?"进展":K.responseKind==="result"?"结果":EF(K.kind)}),s.jsx("span",{children:K.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:K.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(K.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:K.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:K.status==="pending"?"已入队 · 等待投递":K.status==="failed"?"投递失败":K.status==="expired"?"消息已过期,未继续投递":K.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),K.deliveryErrors.map(De=>s.jsx("p",{role:"status",className:"mt-1 text-[10px] text-destructive",children:De==="TMUX_PANE_CHANGED"?"目标会话绑定已变化,投递暂停。原消息已保留,请确认目标会话后继续。":`投递暂停:${De}。原消息已保留,请检查目标会话。`},De)),(K.task||K.failureReason)&&s.jsxs("details",{className:"mt-2 text-[10px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:"任务详情与证据"}),s.jsx("pre",{className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(K.task??{failure_reason:K.failureReason},null,2)})]})]},K.key)),En.length===0&&s.jsx(OF,{text:_e?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function AF({group:e,agents:t,activeSessionId:r,sessions:n,busy:a,setBusy:c,setError:l,setNotice:d,refresh:f,onClose:m}){const x=n.filter(ve=>e.sessionIds.includes(ve.sessionId)&&!ed(ve.sessionId)),[y,w]=b.useState(()=>gF(e,r&&x.some(ve=>ve.sessionId===r)?r:"")),v=b.useRef(y),[T,S]=b.useState(null),I=ve=>{const Y={...v.current,...ve};v.current=Y,xF(e.id,Y),w(Y)},{name:N,rules:P,savedName:$,savedRules:Q,rulesVersion:U,rulesMemberId:Z}=y,J=np(y),H=new TextEncoder().encode(P).length,ye=x.some(ve=>ve.sessionId===Z),oe=async()=>{if(!(a||!N.trim())){c("group-name"),l(null),d(null);try{const ve=await Wl({id:e.id,name:N.trim(),sessionIds:y.sessionIds??e.sessionIds,expectedUpdatedAt:y.updatedAt});S(null),I({savedName:ve.group.name,name:ve.group.name,updatedAt:ve.group.updatedAt,sessionIds:ve.group.sessionIds,...P===Q?{rules:ve.group.instructions?.text??"",savedRules:ve.group.instructions?.text??"",rulesVersion:ve.group.instructions?.version??""}:{}}),await f(),d("协作组名称已更新")}catch(ve){S(null),l(ve instanceof g0&&ve.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":ve instanceof Error?ve.message:"改名失败")}finally{c(null)}}},te=async()=>{if(!(a||!ye||H>8192)){c("group-rules"),l(null),d(null);try{const ve=await h9(e.id,{sessionId:Z,text:P,expectedVersion:U});S(null),I({savedName:ve.group.name,...N===$?{name:ve.group.name}:{},updatedAt:ve.group.updatedAt,sessionIds:ve.group.sessionIds,rules:ve.group.instructions?.text??"",savedRules:ve.group.instructions?.text??"",rulesVersion:ve.group.instructions?.version??""}),await f(),d(P.trim()?"群规已保存,变更通知已入队":"群规已清空,变更通知已入队")}catch(ve){S(null),l(ve instanceof g0&&ve.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":ve instanceof Error?ve.message:"群规保存失败")}finally{c(null)}}},Ce=()=>{I(ix(e,Z)),S(null),l(null)},qe=async()=>{if(!a){c("group-latest"),l(null),d(null),S(null);try{const Y=(await lg()).groups.find(st=>st.id===e.id);if(!Y)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");S(Y)}catch(ve){l(ve instanceof Error?ve.message:"最新状态读取失败;草稿仍保留,请重试。")}finally{c(null)}}};return s.jsxs("section",{"aria-label":"协作组设置",onKeyDown:ve=>{ve.key!=="Escape"||ve.defaultPrevented||ve.nativeEvent.isComposing||(ve.preventDefault(),ve.stopPropagation(),a||m())},className:"mt-3 rounded-xl border border-border/20 bg-surface-2 p-3",children:[s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[12px] font-medium text-foreground",children:"组设置"}),s.jsx("button",{type:"button",disabled:!!a,"aria-label":"关闭组设置",className:"rounded-lg p-2 text-muted-foreground hover:bg-surface-elevated",onClick:m,children:s.jsx(jn,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:Gs,value:N,maxLength:240,disabled:!!a,onChange:ve=>I({name:ve.target.value})})]}),s.jsx("div",{className:"mt-2 flex justify-end",children:s.jsx("button",{type:"button",disabled:!!a||!!T||!N.trim()||N.trim()===$,className:`${Sr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{oe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(iF,{group:e,agents:t,busy:a,setBusy:c,refresh:f}),s.jsxs("div",{className:"mt-3 space-y-2 border-t border-border/15 pt-3",children:[s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["由本组成员发布群规变更",s.jsxs("select",{className:Gs,value:Z,disabled:!!a||!x.length,onChange:ve=>I({rulesMemberId:ve.target.value}),children:[s.jsx("option",{value:"",children:"选择当前服务的一个成员"}),!x.some(ve=>ve.sessionId===Z)&&Z&&s.jsx("option",{value:Z,children:"原成员已不在组内,请重新选择"}),x.map(ve=>s.jsx("option",{value:ve.sessionId,children:ve.name},ve.sessionId))]})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["群规与协作约定",s.jsx("textarea",{className:`${Gs} min-h-24 resize-y`,value:P,maxLength:8192,disabled:!!a,onChange:ve=>I({rules:ve.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!ye&&s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x.length?"选择发布变更的成员后即可保存,不需要关闭工作台。":"当前服务没有本组成员,请先添加成员或切换到成员所在的服务。已有群规可在此查看。"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[s.jsx("p",{className:`text-[9px] ${H>8192?"text-destructive":"text-muted-foreground"}`,children:H>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!T||!ye||H>8192||P===Q,className:`${Sr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{te()},children:a==="group-rules"?"保存中…":P.trim()?"保存群规":"清空群规"})]}),J&&s.jsx("p",{role:"status",className:"mt-3 text-[11px] leading-5 text-muted-foreground",children:"有未保存修改。关闭、Escape 或切换组后,草稿仍保留在本标签页;名称与群规需分别保存。"}),J&&s.jsx("button",{type:"button",disabled:!!a,className:`${Sr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{qe()},children:a==="group-latest"?"读取中…":"查看最新状态并保留草稿"}),T&&s.jsxs("section",{"aria-label":"最新组设置",className:"mt-3 space-y-2 rounded-lg bg-surface p-3 text-[11px] leading-5",children:[s.jsx("p",{className:"font-medium text-foreground",children:"确认最新状态后,再分别保存草稿"}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前名称:",T.name]}),s.jsxs("p",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:["当前群规:",T.instructions?.text||"未设置"]}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前成员(",T.sessionIds.length,"):",T.sessionIds.map(ve=>n.find(Y=>Y.sessionId===ve)?.name??_4(ve)).join("、")||"暂无成员"]}),s.jsx("p",{className:"text-muted-foreground",children:"保留你的未保存内容;名称保存将保留以上成员,群规保存会通知当前成员。再次发生修改时仍会检查冲突。"}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",disabled:!!a,className:`${Sr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{I(mF(v.current,T)),S(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${Sr} min-h-11 text-muted-foreground`,onClick:()=>S(null),children:"取消确认"})]})]}),s.jsxs("div",{className:"mt-3 flex justify-between gap-2 border-t border-border/15 pt-2",children:[s.jsxs("button",{type:"button",disabled:!!a,className:`${Sr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:Ce,children:[s.jsx(vn,{size:12}),"重新载入",J&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${Sr} min-h-9 bg-surface text-foreground`,onClick:m,children:J?"关闭并保留草稿":"关闭"})]})]})}function TF({peers:e,currentGroupId:t,busy:r,setBusy:n,setError:a,setNotice:c,onSelectGroup:l}){const[d,f]=b.useState(null),[m,x]=b.useState(!1),y=e.services??[],w=e.removedServices??[],v=y.filter(I=>!I.connected),T=v.some(I=>I.groups?.some(N=>N.id===t)),S=async(I,N)=>{if(!r){n(`peer:${I}`),a(null),c(null);try{N?await b9(I):await y9(I),f(null),x(!1),c(N?"协作连接已恢复,正在连接服务":"协作连接已移除,不会再自动重连;已有会话和消息保留")}catch(P){a(P instanceof Error?P.message:N?"重新连接失败":"移除连接失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-4 shrink-0 rounded-lg border border-border/15",open:T||void 0,children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-2.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-foreground",children:"协作连接与管理"}),s.jsx("span",{className:"ml-2",children:e.state==="loading"?"正在加载…":`${y.length-v.length} 个已连接${v.length?` · ${v.length} 个离线`:""}`})]}),s.jsxs("div",{className:"max-h-64 overflow-y-auto border-t border-border/15 px-3 py-2",children:[y.length>0&&s.jsx("p",{className:"mb-1 text-[10px] leading-relaxed text-muted-foreground",children:"与以下服务进行跨服务协作,名称与服务切换器一致。"}),v.length>0&&s.jsx("p",{className:"mb-2 text-[10px] leading-relaxed text-muted-foreground",children:T?"当前协作组的部分服务不可达,消息会保留并等待重连。":"其他服务暂时离线;当前服务内的协作可以继续。不再使用的连接可移除。"}),e.error&&s.jsx("p",{role:"status",className:"mb-2 break-words text-[10px] text-destructive",children:e.error}),e.state==="unsupported"&&s.jsx("p",{className:"mb-2 text-[10px] text-muted-foreground",children:"请更新客户端以管理跨服务连接。"}),s.jsx("div",{className:"divide-y divide-border/10",children:y.map(I=>s.jsxs("div",{className:"py-2.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[Ac({serviceLabel:I.label,serviceOrigin:I.origin}),s.jsx("span",{className:`ml-2 text-[9px] ${I.connected?"text-[var(--success)]":"text-muted-foreground"}`,children:I.connected?"已连接":I.error==="CONNECTING"?"连接中":"暂时离线"})]}),s.jsx(SF,{service:I})]}),I.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${I.origin}`,className:`${Sr} min-h-9 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,onClick:()=>f(d===I.serviceId?null:I.serviceId),children:[s.jsx(Ms,{size:12}),"移除"]})]}),!!I.groups?.length&&s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{children:"用于"}),I.groups.map(N=>s.jsx("button",{type:"button",className:"rounded px-1.5 py-1 text-primary hover:bg-primary/10",onClick:()=>l(N.id),children:N.name},N.id))]}),!I.connected&&I.error&&I.error!=="CONNECTING"&&s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:RF(I.error)}),s.jsx("p",{className:"mt-1 select-text break-words",children:I.error})]}),d===I.serviceId&&s.jsxs("div",{role:"group","aria-label":"确认移除协作连接",className:"mt-2 rounded-lg bg-surface-2 p-2.5",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-foreground",children:I.groups?.length?"请先处理上方协作组的成员,再移除这条连接。":"移除后停止与该服务协作,保留已有会话和消息;以后可重新连接。"}),s.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:!!r,className:`${Sr} min-h-9 text-muted-foreground`,onClick:()=>f(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!I.groups?.length,className:`${Sr} min-h-9 bg-destructive text-destructive-foreground`,onClick:()=>{S(I.serviceId,!1)},children:r===`peer:${I.serviceId}`?"正在移除…":"确认移除"})]})]})]},I.serviceId||I.origin))}),y.length===0&&e.state==="ready"&&s.jsx("p",{className:"py-2 text-[10px] text-muted-foreground",children:"当前没有其他协作服务,当前服务内仍可创建协作组。"}),v.length>0&&s.jsxs("button",{type:"button",className:`${Sr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:x9,children:[s.jsx(vn,{size:12}),"重试连接"]}),w.length>0&&s.jsxs("div",{className:"mt-2 border-t border-border/15 pt-1",children:[s.jsx("button",{type:"button","aria-expanded":m,className:`${Sr} min-h-9 text-muted-foreground hover:bg-surface-2`,onClick:()=>x(I=>!I),children:m?"收起恢复列表":"恢复已移除连接"}),m&&s.jsxs("section",{"aria-label":"恢复已移除连接",className:"mt-1 rounded-lg bg-surface-2 px-2.5 py-2",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-muted-foreground",children:"以下是恢复记录,连接已停用,不会自动重连。点击恢复后才会重新启用协作。"}),s.jsx("div",{className:"mt-1 divide-y divide-border/10",children:w.map(I=>s.jsxs("div",{className:"flex items-start gap-2 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"break-words text-[10px] text-foreground",children:[Ac({serviceLabel:I.label,serviceOrigin:I.origin}),s.jsx("span",{className:"ml-2 text-[9px] text-muted-foreground",children:"已停用"})]}),s.jsx("p",{className:"mt-0.5 select-text break-all text-[9px] text-muted-foreground",children:I.accessUrl||I.origin})]}),s.jsx("button",{type:"button",disabled:!!r||!I.serviceId,className:`${Sr} min-h-9 shrink-0 text-primary hover:bg-primary/10`,onClick:()=>{S(I.serviceId,!0)},children:r===`peer:${I.serviceId}`?"恢复中…":"恢复连接"})]},I.serviceId||I.origin))})]})]})]})]},T?"affected":"other")}function SF({service:e}){let t=!1;try{t=["localhost","127.0.0.1","[::1]"].includes(new URL(e.origin).hostname)}catch{}const r=e.accessUrl||(t?"":e.origin);return s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"w-fit cursor-pointer py-1",children:"连接详情"}),s.jsxs("dl",{className:"mt-1 space-y-1 select-text break-all",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务地址:"}),s.jsx("dd",{className:"inline",children:r||"暂未获取,请在服务切换器中查看"})]}),e.serviceId&&s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务身份:"}),s.jsx("dd",{className:"inline",children:e.serviceId})]})]})]})}function qm(e){return!ed(e.sessionId)||e.serviceConnected!==!1}function CF(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:ed(e.sessionId)?.origin??""}function cy(e){const t=new Map;for(const r of e){const n=CF(r),a=t.get(n)??{key:n,label:n?Ac(r):"本机服务",sessions:[]};n&&a.label==="远端服务"&&(a.label=Ac(r)),a.sessions.push(r),t.set(n,a)}return[...t.values()].sort((r,n)=>(r.key?1:0)-(n.key?1:0)||r.label.localeCompare(n.label))}function uy({label:e,count:t,collapsed:r,onToggle:n}){return s.jsxs("button",{type:"button","aria-expanded":!r,onClick:n,className:"flex w-full items-center gap-1.5 bg-surface-2/50 px-2 py-1.5 text-left text-muted-foreground transition hover:bg-surface-elevated",children:[s.jsx(Al,{size:12,className:`shrink-0 transition-transform ${r?"-rotate-90":""}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[10px] font-semibold uppercase tracking-wide",children:e}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground/70",children:t})]})}function _F(e,t){const r=new Map(t.map(n=>[n.sessionId,n]));for(const n of e?.sessionIds??[]){if(r.has(n))continue;const a=e?.remoteSessions?.find(c=>c.sessionId===n);r.set(n,a?{...a,status:"offline",serviceConnected:!1}:{sessionId:n,name:n,backendSessionId:null,cwd:"",agent:null,status:"offline",capability:"",currentTask:"暂不可用,保留成员身份",updatedAt:0,...ed(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function Ym({session:e}){return!e.serviceOrigin||e.serviceOrigin===window.location.origin?null:s.jsxs("span",{className:"inline-flex max-w-28 shrink-0 items-center gap-1 rounded border border-border/20 px-1 py-0.5 text-[9px] text-muted-foreground",children:[s.jsx(Kc,{size:9}),s.jsx("span",{className:"truncate",children:Ac(e)})]})}function wf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":IF(e.status)}function kF(e,t=[]){if(!e)return;const r=t.some(a=>a.sessionId!==e.sessionId&&a.name.trim()===e.name.trim()),n=e.sessionId.startsWith("remote:")?Ac(e):"本机服务";return r?`${e.name} · ${n}`:e.name}async function LF(e){e.sessionId.startsWith("remote:")?await K6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function IF(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function Zm(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return sp(t.prompt)||"暂无任务摘要"}catch{}return sp(e)||"暂无任务摘要"}function EF(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function NF(e,t){const r=new Map(t.map(a=>[a.sessionId,kF(a,t)])),n=new Map;for(const a of e){const c=`${a.threadId}:${a.createdAt}:${a.fromSessionId??a.integrationOrigin?.integrationId??"user"}:${a.kind}:${a.responseKind??""}:${JSON.stringify(a.task??null)}:${a.content}`,l=n.get(c),d=a.toPrincipalId?`后台接入 ${a.toPrincipalId}`:r.get(a.toSessionId)??a.toSessionId.slice(0,8);if(l){l.toNames.push(d),a.delivery?.stage==="blocked"&&a.delivery.error&&!l.deliveryErrors.includes(a.delivery.error)&&l.deliveryErrors.push(a.delivery.error);const f={failed:-2,expired:-1,pending:0,delivered:1,read:2,stored:3};f[a.status]<f[l.status]&&(l.status=a.status);continue}n.set(c,{key:c,kind:a.kind,content:a.content,createdAt:a.createdAt,fromName:a.fromSessionId?r.get(a.fromSessionId)??a.fromSessionId.slice(0,8):a.integrationOrigin?`后台接入 ${a.integrationOrigin.integrationId}`:"你",toNames:[d],status:a.status,responseKind:a.responseKind,task:a.task,failureReason:a.failureReason,deliveryErrors:a.delivery?.stage==="blocked"&&a.delivery.error?[a.delivery.error]:[]})}return[...n.values()].sort((a,c)=>c.createdAt-a.createdAt)}function RF(e){return/timeout|timed out|超时|operation was aborted/i.test(e)?"连接超时,暂时无法访问该服务。请确认远端服务已启动,并检查网络或 VPN 连接。":/ECONNREFUSED|connection refused/i.test(e)?"远端拒绝连接,请确认服务已启动且端口正确。":/ENOTFOUND|EHOSTUNREACH|ENETUNREACH/i.test(e)?"无法访问远端地址,请检查地址和网络连接。":/certificate|fingerprint|TLS|证书/i.test(e)?"远端证书校验失败,请检查服务连接授权。":"服务连接暂时不可用,可查看连接详情并重试。"}function Km({value:e,query:t}){const r=t.trim().toLocaleLowerCase();if(!r)return s.jsx(s.Fragment,{children:e});const n=e.toLocaleLowerCase(),a=[];let c=0,l;for(;(l=n.indexOf(r,c))>=0;)a.push(e.slice(c,l)),a.push(s.jsx("mark",{className:"rounded bg-primary/15 text-primary",children:e.slice(l,l+r.length)},l)),c=l+r.length;return a.push(e.slice(c)),s.jsx(s.Fragment,{children:a})}function MF({active:e,onClose:t,onNewSession:r,setError:n}){const[a,c]=b.useState(""),[l,d]=b.useState([]),[f,m]=b.useState(0),[x,y]=b.useState(),[w,v]=b.useState(50),[T,S]=b.useState(0),[I,N]=b.useState(!1),[P,$]=b.useState(null),[Q,U]=b.useState(null),Z=b.useRef(null),J=b.useRef(0);b.useEffect(()=>{e&&Z.current?.focus({preventScroll:!0})},[e]),b.useEffect(()=>{if(!e)return;const oe=++J.current,te=new AbortController;let Ce;$(null),N(!0);const qe=async()=>{try{const ve=await v9(a.trim(),w,te.signal);if(oe!==J.current)return;d(ve.results),m(ve.total??ve.results.length),y(ve.index),ve.index?.building&&(Ce=window.setTimeout(()=>{qe()},2500))}catch(ve){oe===J.current&&!te.signal.aborted&&$(ve instanceof Error?ve.message:"搜索失败")}finally{oe===J.current&&N(!1)}};return Ce=window.setTimeout(()=>{qe()},a.trim()?250:0),()=>{window.clearTimeout(Ce),te.abort(),++J.current}},[e,a,w,T]);const H=oe=>{n(null),c(oe),d([]),m(0),v(50)},ye=async oe=>{if(!Q){if(oe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:oe.sessionId})),t();return}if(!(!oe.nativeKey&&!oe.resumeHistoryId)){U(oe.sessionId),n(null);try{const te=oe.nativeKey?await w9(oe.nativeKey):await c3(oe.resumeHistoryId);if("sessionId"in te&&te.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:te.sessionId}));else if(te.command)r({mode:"shell",cwd:te.cwd,command:te.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(te){n(te instanceof Error?te.message:"恢复失败")}finally{U(null)}}}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky -top-4 z-20 -mx-4 -mt-4 border-b border-border/15 bg-surface px-4 py-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:"历史会话搜索"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"搜索当前服务的 Codex、Claude 历史对话和 Termdock 终端记录,未启动的会话也能找到并恢复。"})]}),s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"搜索历史会话"}),s.jsx(Gl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:Z,maxLength:512,className:`${Gs} pl-9 pr-9`,value:a,onChange:oe=>H(oe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),I?s.jsx(vn,{size:13,className:"absolute right-3 top-1/2 -translate-y-1/2 animate-spin text-muted-foreground"}):a&&s.jsx("button",{type:"button","aria-label":"清空搜索",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-muted-foreground hover:bg-surface-2 hover:text-foreground",onClick:()=>H(""),children:s.jsx(jn,{size:13})})]}),x?.building&&s.jsxs("div",{role:"status",className:"mt-2 text-[10px] text-muted-foreground",children:["正在建立历史索引:",x.indexed,"/",x.total," 个会话。可以先搜名称和目录,对话结果会自动补齐。"]}),x?.warning&&s.jsx("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:x.warning}),!!x?.failed&&s.jsxs("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:[x.failed," 个会话暂未完成索引,其余结果可正常使用。请稍后刷新重试。"]})]}),s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[a.trim()?`找到 ${f} 个会话`:"最近的会话",f>l.length?` · 显示 ${l.length} 个`:""]}),s.jsxs("button",{type:"button",disabled:I,className:`${Sr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>S(oe=>oe+1),children:[s.jsx(vn,{size:12}),"刷新"]})]}),!a.trim()&&s.jsx("p",{className:"text-[10px] text-muted-foreground",children:"记得之前讨论过什么?输入一句话中的关键词,就能找到对应会话。历史对话与索引保存在当前服务机器上。"}),s.jsx("div",{className:"divide-y divide-border/10 border-y border-border/10",children:l.map(oe=>{const te=oe.live||!!(oe.nativeKey||oe.resumeHistoryId),Ce=Q===oe.sessionId?"正在恢复…":oe.live?"打开会话":te?"恢复会话":"仅供查阅",qe=oe.source==="codex"||oe.source==="claude"?oe.snippet:jF(oe),ve=oe.source==="codex"?"Codex 历史":oe.source==="claude"?"Claude 历史":"终端记录",Y=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"break-words text-[12px] font-medium text-foreground",children:s.jsx(Km,{value:oe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(Km,{value:oe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${oe.live?"text-[var(--success)]":te?"text-primary":"text-muted-foreground"}`,children:Ce})]}),qe&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(Km,{value:qe,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[ve," · ",ip(oe.updatedAt),a.trim()?` · ${oe.matchCount>=999?"999+":oe.matchCount} 处匹配`:"",te?"":" · 没有可恢复记录"]}),oe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:oe.agentNativeSessionId})]});return te?s.jsx("button",{disabled:!!Q,onClick:()=>{ye(oe)},className:"block w-full px-2 py-3 text-left transition hover:bg-surface-2 focus-visible:bg-surface-2 focus-visible:outline-none",children:Y},oe.nativeKey||oe.sessionId):s.jsx("article",{className:"px-2 py-3",children:Y},oe.sessionId)})}),f>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:I,className:`${Sr} w-full bg-surface-2 text-foreground`,onClick:()=>v(oe=>oe+50),children:I?"正在加载…":"加载更多会话"}),P&&s.jsxs("div",{role:"alert",className:"rounded-lg bg-destructive/10 p-3 text-[11px] text-destructive",children:["搜索失败:",P,s.jsx("button",{type:"button",className:`${Sr} ml-2`,onClick:()=>S(oe=>oe+1),children:"重试"})]}),!I&&!P&&l.length===0&&s.jsxs("div",{className:"border-y border-border/15 py-8 text-center",children:[s.jsx("p",{className:"text-[12px] text-foreground",children:x?.building?"历史对话仍在索引,请稍候":x?.warning||x?.failed?"暂未找到结果,部分历史记录尚不可搜索":a.trim()?`没有找到“${a.trim()}”`:"当前服务还没有可搜索的历史会话"}),s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x?.building?"新结果会自动显示,也可以先搜会话名称或目录。":"可尝试更短的关键词、项目目录或 session ID;其他机器的历史需切换到对应服务搜索。"}),a.trim()&&s.jsx("button",{className:`${Sr} mt-3 bg-surface-2 text-foreground`,onClick:()=>H(""),children:"查看最近会话"})]})]})}function sp(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g," ").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g," ").replace(/\(B/g," ").replace(/<[^>]{1,120}>/g," ").replace(/[─━│┃┄┅┆┇┈┉┊┋┌┐└┘├┤┬┴┼╭╮╯╰═║╔╗╚╝╠╣╦╩╬]+/g," ").replace(/([^\p{L}\p{N}\s])\1{3,}/gu," ").replace(/([A-Za-z])\1{12,}/g," ").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g," ").replace(/\s+/g," ").trim().slice(0,280)}function jF(e){let t=sp(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return sp(t)}function DF(e){if(e.schedule.kind==="interval")return e.schedule.everyMinutes===60?"每小时":e.schedule.everyMinutes===1440?"每天":`每 ${e.schedule.everyMinutes} 分钟`;const t=["日","一","二","三","四","五","六"];return`${e.schedule.weekdays.length===7?"每天":e.schedule.weekdays.map(n=>`周${t[n]}`).join("、")} ${e.schedule.time}`}function BF(e,t=Date.now(),r=t){if(e.kind==="interval"){const c=e.everyMinutes*6e4,l=Math.max(0,t-r);return r+(Math.floor(l/c)+1)*c}const[n,a]=e.time.split(":").map(Number);for(let c=0;c<=7;c+=1){const l=new Date(t);if(l.setDate(l.getDate()+c),l.setHours(n,a,0,0),l.getTime()>t&&e.weekdays.includes(l.getDay()))return l.getTime()}return t}function ip(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function QF(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function PF(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function OF({text:e}){return s.jsx("div",{className:"rounded-xl border border-dashed border-border/20 px-4 py-8 text-center text-[11px] text-muted-foreground",children:e})}const e0=64,dy=10,FF=120;function $F({children:e,open:t,onOpenChange:r,onClose:n,closeLabel:a,closeTitle:c,compact:l}){const d=b.useRef(null),f=b.useRef(null),m=b.useRef(0),[x,y]=b.useState(null),w=x??(t?e0:0);return b.useEffect(()=>{if(!t)return;const v=T=>{T.target instanceof Node&&!d.current?.contains(T.target)&&r(!1)};return document.addEventListener("pointerdown",v,!0),()=>document.removeEventListener("pointerdown",v,!0)},[t,r]),s.jsxs("div",{ref:d,"data-sidebar-gesture-ignore":!0,"data-session-swipe":!0,className:`relative flex min-w-0 flex-1 items-center ${l?"":"gap-1"}`,style:{touchAction:"pan-y"},onPointerDown:v=>{if(m.current=0,!(v.pointerType!=="touch"&&v.pointerType!=="pen")){if(v.isPrimary===!1){f.current=null,y(null);return}!(v.target instanceof Element)||!v.target.closest(".sidebar-session-primary")||(f.current={pointerId:v.pointerId,x:v.clientX,y:v.clientY,startedAt:Date.now(),initialOffset:t?e0:0,offset:t?e0:0,horizontal:!1})}},onPointerMove:v=>{const T=f.current;if(!T||T.pointerId!==v.pointerId)return;const S=v.clientX-T.x,I=v.clientY-T.y;if(!T.horizontal){if(v.defaultPrevented||Date.now()-T.startedAt>=FF||Math.abs(I)>dy){f.current=null;return}if(Math.abs(S)<=dy)return;if(Math.abs(S)<Math.abs(I)*1.5||!t&&S<0){f.current=null;return}T.horizontal=!0,v.currentTarget.setPointerCapture?.(v.pointerId)}v.preventDefault(),T.offset=Math.max(0,Math.min(e0,T.initialOffset+S)),y(T.offset)},onPointerUp:v=>{const T=f.current;!T||T.pointerId!==v.pointerId||(f.current=null,T.horizontal&&(m.current=Date.now()+600,r(T.offset>=e0/2),y(null)))},onPointerCancel:()=>{f.current?.horizontal&&(m.current=Date.now()+600),f.current=null,y(null)},onClickCapture:v=>{if(Date.now()<m.current){m.current=0,v.preventDefault(),v.stopPropagation();return}t&&v.target instanceof Element&&v.target.closest(".sidebar-session-primary")&&(r(!1),v.preventDefault(),v.stopPropagation())},onKeyDown:v=>{t&&v.key==="Escape"&&(v.stopPropagation(),r(!1))},children:[s.jsx("div",{className:"shrink-0 overflow-hidden rounded-md transition-[width] duration-150 ease-out motion-reduce:transition-none",style:{width:w,transition:x===null?void 0:"none"},children:w>0&&s.jsxs("button",{type:"button",tabIndex:t?0:-1,"aria-hidden":!t,"aria-label":c,className:"flex min-h-8 w-16 flex-col items-center justify-center gap-0.5 bg-destructive py-1 text-[10px] text-destructive-foreground",onClick:v=>{v.stopPropagation(),r(!1),n(v)},children:[s.jsx(Ms,{size:14}),a]})}),e]})}const hy="recoverable-tmux";function UF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=Ur(),d=Yt(N=>N.collapsedGroups.has(hy)),f=Yt(N=>N.toggleGroupCollapsed),[m,x]=b.useState(null),[y,w]=b.useState(null),[v,T]=b.useState(null),S=b.useRef(!1),I=async N=>{if(!(!c||S.current)){S.current=!0,w(N),T(null);try{await c(N),x(null)}catch(P){T(P instanceof Error?P.message:l("sidebar.closeRecoverableSessionFailed"))}finally{S.current=!1,w(null)}}};return e.length===0?null:s.jsxs("section",{className:"mb-2 shrink-0 rounded-lg bg-[rgb(var(--tmux-rgb)_/_0.07)] p-1","aria-label":l("sidebar.recoverableSessions"),children:[s.jsxs("div",{className:"flex items-center gap-1 text-[10.5px] font-semibold text-[color:var(--tmux)]",children:[s.jsxs("button",{type:"button","aria-expanded":!d,onClick:()=>f(hy),className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left hover:bg-surface-elevated md:min-h-8",children:[s.jsx(qs,{size:12,className:`shrink-0 ${d?"":"rotate-90"}`}),s.jsx(qc,{size:12,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:l("sidebar.recoverableSessions")}),s.jsx("span",{className:"text-muted-foreground",children:e.length})]}),n&&s.jsx("button",{type:"button",onClick:n,disabled:t||y!==null,className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.refreshRecoverableSessions"),title:l("sidebar.refreshRecoverableSessions"),children:s.jsx(vn,{size:11,className:t?"animate-spin":""})})]}),!d&&s.jsx("div",{className:"space-y-0.5",children:e.map(N=>{const P=N.friendlyName?.trim()||N.label?.trim()||N.name,$=ld(N.cwd??null),Q=r===N.name,U=m===N.name;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex min-w-0 items-center",children:[s.jsxs("button",{type:"button",disabled:r!==null||y!==null||U,onClick:()=>a(N),className:"group flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-60 md:min-h-10","aria-label":l("sidebar.restoreRecoverableSession",{name:P}),title:N.cwd||N.name,children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--tmux-rgb)_/_0.11)] text-[color:var(--tmux)]",children:Q?s.jsx(Dn,{size:12,className:"animate-spin"}):s.jsx(su,{size:12})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11.5px] font-semibold text-foreground",children:P}),s.jsx("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[N.program,$].filter(Boolean).join(" · ")||`tmux:${N.name}`})]}),s.jsx("span",{className:"shrink-0 text-[10px] font-medium text-[color:var(--tmux)] group-hover:text-foreground",children:l(Q?"sidebar.restoringRecoverableSession":"sidebar.restore")})]}),c&&s.jsx("button",{type:"button",disabled:r!==null||y!==null,onClick:()=>{x(N.name),T(null)},className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-destructive/15 hover:text-destructive disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.closeSession",{name:P}),title:l("sidebar.closeSession",{name:P}),children:s.jsx(jn,{size:12})})]}),U&&s.jsxs("div",{role:"group","aria-label":l("sidebar.closeSession",{name:P}),className:"space-y-2 rounded-md bg-surface px-2 py-2",children:[s.jsx("p",{className:"text-[11px] text-foreground",children:l("sidebar.confirmCloseRecoverableSession",{name:P})}),v&&s.jsx("p",{role:"alert",className:"text-[11px] text-destructive",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{x(null),T(null)},className:"min-h-11 rounded-md px-2 text-[11px] text-muted-foreground hover:bg-surface-elevated disabled:opacity-50 md:min-h-8",children:l("common.cancel")}),s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{I(N.name)},className:"min-h-11 rounded-md bg-destructive/15 px-2 text-[11px] text-destructive hover:bg-destructive/25 disabled:opacity-50 md:min-h-8",children:y===N.name?l("common.loading"):l("sidebar.endRecoverableSession")})]})]})]},N.name)})})]})}const ju="flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-xs transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",fy="min-h-11 rounded-lg px-4 text-xs transition disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary";function zF({group:e,collapsed:t,onOpen:r,onMessages:n,onToggleCollapsed:a,onChanged:c,children:l}){const[d,f]=b.useState(null),[m,x]=b.useState(null),[y,w]=b.useState(""),[v,T]=b.useState(!1),S=b.useRef(!1),[I,N]=b.useState(""),P=b.useRef(null),$=b.useRef(null),Q=b.useRef(null),U=b.useRef(null),Z=b.useRef(null),J=b.useId(),H=ex(),ye=()=>Z.current?.isConnected?Z.current:$.current,oe=()=>{S.current||(x(null),N(""))};vc(Q,!!d,()=>f(null),ye),vc(U,!!m,oe,ye);const te=Y=>{Z.current=document.activeElement instanceof HTMLElement&&P.current?.contains(document.activeElement)?document.activeElement:$.current;const st=$.current?.getBoundingClientRect();f(Y??{x:st?.left??8,y:st?.bottom??8})};b.useEffect(()=>{d&&Q.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0})},[d]),b.useEffect(()=>{if(!d)return;const Y=he=>{he.target instanceof Node&&!Q.current?.contains(he.target)&&!P.current?.contains(he.target)&&f(null)},st=he=>{he.target instanceof Node&&Q.current?.contains(he.target)||f(null)};return document.addEventListener("pointerdown",Y),window.addEventListener("resize",st),window.addEventListener("scroll",st,!0),()=>{document.removeEventListener("pointerdown",Y),window.removeEventListener("resize",st),window.removeEventListener("scroll",st,!0)}},[d]),b.useLayoutEffect(()=>{if(!d||!Q.current)return;const Y=window.visualViewport,st=(Y?.offsetLeft??0)+8,he=(Y?.offsetTop??0)+8,Qe=Math.min(240,(Y?.width??innerWidth)-16),ie=he+(Y?.height??innerHeight)-16;Object.assign(Q.current.style,{width:`${Qe}px`,maxHeight:`${ie-he}px`,left:`${Math.max(st,Math.min(d.x,st+(Y?.width??innerWidth)-16-Qe))}px`,top:`${Math.max(he,Math.min(d.y,ie-Q.current.offsetHeight))}px`})},[d]);const Ce=Y=>{f(null),Y()},qe=Y=>{N(""),w(e.name),x({kind:Y,group:e})},ve=async()=>{if(!(!m||S.current||m.kind==="rename"&&!y.trim())){S.current=!0,T(!0),N("");try{const Y=m.group,st=m.kind==="delete"?(await o3(Y.id,Y.updatedAt),null):m.kind==="archive"||m.kind==="unarchive"?await T9(Y,m.kind==="archive"):(await Wl({id:Y.id,name:y.trim(),sessionIds:Y.sessionIds,expectedUpdatedAt:Y.updatedAt})).group;x(null),c(st)}catch(Y){const st=Y instanceof Error?Y.message:"操作失败,请重试";N(st.includes("协作组已变化")?"协作组刚刚发生变化,请取消后重新打开操作。":st)}finally{S.current=!1,T(!1)}}};return s.jsxs("div",{ref:P,className:"flex min-w-0 items-center","data-sidebar-gesture-ignore":!0,...H(()=>te()),onContextMenu:Y=>{Y.preventDefault(),Y.stopPropagation(),te({x:Y.clientX,y:Y.clientY})},onKeyDown:Y=>{(Y.key==="ContextMenu"||Y.shiftKey&&Y.key==="F10")&&(Y.preventDefault(),Y.stopPropagation(),te())},children:[l,s.jsx("button",{ref:$,type:"button","aria-label":`协作组操作:${e.name}`,title:"协作组操作","aria-haspopup":"menu","aria-expanded":!!d,"aria-controls":d?`${J}-menu`:void 0,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:Y=>{Y.stopPropagation(),d?f(null):te()},children:s.jsx(Do,{size:14})}),d&&Zs.createPortal(s.jsxs("div",{ref:Q,id:`${J}-menu`,role:"menu",tabIndex:-1,"aria-label":`协作组操作:${e.name}`,"data-sidebar-gesture-ignore":!0,className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)]",onKeyDown:Y=>{const st=Array.from(Y.currentTarget.querySelectorAll('[role="menuitem"]:not(:disabled)')),he=st.indexOf(document.activeElement),Qe=Y.key==="ArrowDown"?(he+1)%st.length:Y.key==="ArrowUp"?(he-1+st.length)%st.length:Y.key==="Home"?0:Y.key==="End"?st.length-1:null;Qe!==null&&(Y.preventDefault(),Y.stopPropagation(),st[Qe]?.focus({preventScroll:!0})),Y.key==="Tab"&&(Y.preventDefault(),f(null))},children:[s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(r),children:[s.jsx(su,{size:15}),"打开看板"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,disabled:!n,className:`${ju} disabled:opacity-40`,onClick:()=>Ce(()=>n?.()),children:[s.jsx(cd,{size:15}),"成员与消息"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(a),children:[s.jsx(qs,{size:15,className:t?"":"rotate-90"}),t?"展开成员会话":"收起成员会话"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(()=>qe("rename")),children:[s.jsx(Vu,{size:15}),"重命名协作组"]}),!e.federated&&s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(()=>qe(e.archivedAt===void 0?"archive":"unarchive")),children:[s.jsx(Cf,{size:15}),e.archivedAt===void 0?"归档协作组":"恢复显示"]}),s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/30"}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:`${ju} text-destructive`,onClick:()=>Ce(()=>qe("delete")),children:[s.jsx(Ms,{size:15}),"删除协作组"]})]}),document.body),m&&Zs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-modal-backdrop bg-black/50 backdrop-blur-sm",onClick:oe}),s.jsxs("section",{ref:U,role:"dialog","aria-modal":"true","aria-labelledby":`${J}-title`,"aria-describedby":`${J}-description`,tabIndex:-1,className:"fixed left-1/2 top-1/2 z-modal-panel max-h-[calc(100dvh-2rem)] w-[min(24rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 text-foreground shadow-[0_28px_70px_var(--app-shadow-strong)]",children:[s.jsxs("header",{className:"flex items-center gap-2",children:[s.jsx("h2",{id:`${J}-title`,className:"min-w-0 flex-1 text-sm font-semibold",children:m.kind==="delete"?"删除协作组":m.kind==="archive"?"归档协作组":m.kind==="unarchive"?"恢复协作组显示":"重命名协作组"}),s.jsx("button",{type:"button","aria-label":"关闭协作组操作",disabled:v,className:"flex h-11 w-11 items-center justify-center rounded-lg hover:bg-surface-2",onClick:oe,children:s.jsx(jn,{size:16})})]}),s.jsx("p",{id:`${J}-description`,className:"my-3 break-words text-xs leading-6 text-muted-foreground",children:m.kind==="delete"?s.jsxs(s.Fragment,{children:["确定删除“",m.group.name,"”?协作组及组内消息会被移除,成员终端会保留。此操作无法撤销。",m.group.federated&&"删除会同步到其他服务。"]}):m.kind==="archive"?s.jsxs(s.Fragment,{children:["归档“",m.group.name,"”后,它会从默认侧栏隐藏。组、成员、消息和历史都会保留,之后可以恢复显示。"]}):m.kind==="unarchive"?s.jsxs(s.Fragment,{children:["恢复“",m.group.name,"”的显示后,它会重新出现在侧栏;不会自动恢复已关闭的会话。"]}):"修改协作组的名称。"}),s.jsxs("form",{onSubmit:Y=>{Y.preventDefault(),ve()},children:[m.kind==="rename"&&s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,required:!0,maxLength:256,disabled:v,className:"mt-2 min-h-11 w-full rounded-lg border border-border/30 bg-surface-2 px-3 text-sm text-foreground outline-none focus:border-primary",value:y,onChange:Y=>w(Y.target.value)})]}),I&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs leading-5 text-destructive",children:I}),s.jsxs("footer",{className:"mt-4 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:v,className:`${fy} bg-surface-2`,onClick:oe,children:"取消"}),s.jsxs("button",{type:"submit",disabled:v||m.kind==="rename"&&!y.trim(),className:`${fy} inline-flex items-center gap-2 ${m.kind==="delete"?"bg-destructive text-destructive-foreground":"bg-primary text-primary-foreground"}`,children:[v&&s.jsx(vn,{size:14,className:"animate-spin"}),v?m.kind==="delete"?"正在删除…":"正在保存…":m.kind==="delete"?"确认删除":m.kind==="archive"?"归档并隐藏":m.kind==="unarchive"?"恢复显示":"保存名称"]})]})]})]})]}),document.body)]})}function HF(e,t){return fg(e.filter(r=>r.archivedAt===void 0),t)}function t0(e,t){const r=new Set(e),n=t.filter(c=>c.sessionIds.length>=2&&c.sessionIds.every(l=>r.has(l))),a=new Set;return e.flatMap(c=>{const l=n.find(d=>d.sessionIds.includes(c));return l?a.has(l.id)?[]:(a.add(l.id),[{sessionIds:l.sessionIds,workspace:l}]):[{sessionIds:[c]}]})}function r0(e,t,r,n=[]){const a=new Map,c=new Map,l=new Set(e.map(x=>x.id));for(const x of n){const y=x.sessionIds.filter(v=>l.has(v));if(!y.length)continue;const w=y.length===x.sessionIds.length?x:{...x,sessionIds:y};y.forEach(v=>a.set(v,w))}for(const x of t)if(!(x.sessionIds.length<2||!x.sessionIds.every(y=>l.has(y)))&&!x.sessionIds.some(y=>a.has(y)))for(const y of x.sessionIds)c.set(y,x);const d=new Set,f=new Set,m=[];for(const x of e){const y=a.get(x.id);if(y){if(d.has(y.id))continue;d.add(y.id);const T=y.sessionIds.flatMap(S=>{const I=r.get(S);return I?[I]:[]});m.push({kind:"collaboration",id:`collaboration:${y.id}`,group:y,members:T,sessionIds:y.sessionIds});continue}const w=c.get(x.id);if(!w){m.push({kind:"session",id:`session:${x.id}`,session:x,sessionIds:[x.id]});continue}if(f.has(w.id))continue;f.add(w.id);const v=w.sessionIds.flatMap(T=>{const S=r.get(T);return S?[S]:[]});m.push({kind:"workspace",id:`workspace:${w.id}`,workspace:w,members:v,sessionIds:w.sessionIds})}return m}function py(e,t,r){const n=Math.min(e.length,Math.max(0,r)),a=e.slice(0,n).flatMap(l=>l.sessionIds.filter(d=>d!==t)),c=e.slice(n).flatMap(l=>l.sessionIds.filter(d=>d!==t));return[...a,t,...c]}function WF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(CO,{status:e,detail:t,needsReview:r,inCopyMode:n})}function my({isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,sessions:a,activeSessionId:c,sessionStates:l,onJumpToNextAttention:d,onNewSession:f,onCloseSession:m,onSplitSession:x,onCloseSplit:y,onRemoveFromSplit:w,splitWorkspaces:v,onSetSplitLayout:T,onReorderSplitWorkspace:S,onCombineSplitSessions:I,onReorderSessions:N,onSessionMenu:P,onOpenSettings:$,onOpenQuota:Q,updateState:U,updateActionPending:Z=!1,onConfirmUpdateRestart:J,onRetryUpdate:H,serverHealthState:ye,tmuxAvailable:oe=!0,defaultSessionMode:te="shell",push:Ce,pinned:qe,onTogglePinned:ve,recoverableTmuxSessions:Y=[],recoverableTmuxSessionsLoading:st=!1,onRefreshRecoverableTmuxSessions:he,onCloseRecoverableTmuxSession:Qe}){const{t:ie}=Ur(),[,Pe]=b.useState(0),[Fe,ce]=b.useState(null),[Ie,je]=b.useState(!1),[Ze,we]=b.useState(!1),[le,Ge]=b.useState(null),He=b.useRef(!1),tt=b.useRef(0),xe=b.useCallback(W=>{W||(tt.current+=1),je(W)},[]),[dt,it]=b.useState(!1),_e=Bi(W=>W.groupId),[Ue,ke]=b.useState({}),V=dt||Object.keys(Ue).length>0,ae=b.useRef(!1),pe=b.useRef(!1),[$e,Xe]=b.useState(null);b.useEffect(()=>{let W=!1;return Cc().then(Re=>{W||ae.current||ke(Object.fromEntries(M3(Re.collaborationPanels?.[lp()]).map(Ke=>[Ke,!0])))}).catch(()=>{}),()=>{W=!0}},[]);const wt=async(W,Re)=>{ae.current=!0,await eo({floatingGroupId:Re},W),ke(Ke=>({...Ke,[W]:Re!==null}))},[Ut,qt]=b.useState([]),[Nt,sr]=b.useState(!1),[jt,Xt]=b.useState(null),[Rt,ir]=b.useState(null),[ge,Je]=b.useState(null),[at,Et]=b.useState(null),X=Pu(W=>W.tasks),vt=Pu(W=>W.allTasks),[Bt,Me]=b.useState(0),[Dr,Le]=b.useState(null),At=b.useRef(!1),[Ot,er]=b.useState({}),ot=Pu(W=>W.error),[Lt,nr]=b.useState(!1),[ur,Rr]=b.useState(!1);b.useEffect(()=>ou(()=>{Pu.getState().refresh()},5e3,[k0]),[]);const Gr=async W=>(xe(!1),ae.current=!0,W?(Bi.getState().open(W),tr(),!0):(it(!0),tr(),!0)),Tt=Ef(W=>W.collaborationGroups),Ft=Ef(W=>W.setCollaborationGroups),[be,Ct]=b.useState({mode:te}),{preference:gt,agents:rt,detecting:cn,refresh:Kr,selectAgent:wn}=tF(),Oe=b.useRef(null);let ft=!1;if(U?.latestVersion)try{ft=OQ(U.latestVersion,U.currentVersion)>0}catch{}const ht=!!(ft&&U&&["checking","installing","ready","restarting","error"].includes(U.status)),Cr=!!ye?.attention,Ht=[ie("sidebar.moreActions"),ht&&U?.latestVersion?ie("sidebar.updateAvailable",{version:U.latestVersion}):null].filter(Boolean).join(": "),yr=Yt(W=>W.groupByFolder),Xr=Yt(W=>W.collapsedGroups),Bn=Yt(W=>W.toggleGroupCollapsed),mn=b.useRef(null),hn=b.useRef(null),gn=b.useRef(null),an=b.useRef(0),ne=b.useRef(!1),Ye=b.useRef(null),St=b.useRef(null),[Jt,Or]=b.useState(!1),un=b.useRef([]),Jr=b.useRef(null),en=b.useRef(null),mr=b.useRef(new Set),tn=b.useRef(null),Sn=b.useMemo(()=>new Set(v.flatMap(W=>W.sessionIds)),[v]),Zr=b.useMemo(()=>new Map(a.map(W=>[W.id,W])),[a]),Qr=b.useMemo(()=>HF(Tt,new Set(Zr.keys())),[Tt,Zr]),lr=b.useMemo(()=>fg(Tt.filter(W=>W.archivedAt!==void 0),new Set(Zr.keys())),[Tt,Zr]),fn=b.useCallback(async()=>{const W=++an.current;try{const Re=await lg();if(W!==an.current)return;Ft(Array.isArray(Re.groups)?Re.groups:[])}catch{if(W!==an.current)return;Ft(Re=>Re.map(Ke=>({...Ke,remoteSessions:Ke.remoteSessions?.map(lt=>({...lt,status:"offline",serviceConnected:!1}))})))}},[]);b.useEffect(()=>l3(W=>Ft(W.groups)),[]),b.useEffect(()=>{const W=ou(()=>{fn()},1e4,["focus",k0]);return()=>{an.current+=1,W()}},[fn]),b.useEffect(()=>{(e||!V)&&fn()},[V,e,fn]);const Ss=b.useCallback(()=>{un.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(W=>{const Re=W.dataset.collaborationMember??"",Ke=W.hasAttribute("data-collaboration-background"),lt=W.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Re&&!Ke||!lt)return[];const ut=[];for(let It=W.parentElement;It;It=It.parentElement)ut.push({element:It,top:It.scrollTop,left:It.scrollLeft});return[{element:W,sessionId:Re,groupId:lt,background:Ke,rect:W.getBoundingClientRect(),scrollParents:ut}]})},[]),Ar=b.useCallback((W,Re)=>{if(!ne.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(q=>q.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(q=>q.removeAttribute("data-drop-active"));const lt=document.elementsFromPoint(W,Re).map(q=>q.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(lt?.dataset.collaborationGroup){lt.dataset.dropActive="true",en.current={kind:"collaboration",groupId:lt.dataset.collaborationGroup,background:!0};return}const ut=un.current.find(q=>{if(q.sessionId===St.current||!q.element.isConnected)return!1;const se=q.scrollParents.reduce((We,mt)=>We+mt.element.scrollLeft-mt.left,0),Ee=q.scrollParents.reduce((We,mt)=>We+mt.element.scrollTop-mt.top,0);return W>=q.rect.left-se&&W<=q.rect.right-se&&Re>=q.rect.top-Ee+q.rect.height*.25&&Re<=q.rect.bottom-Ee-q.rect.height*.25});if(ut?.background){ut.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),en.current={kind:"collaboration",groupId:ut.groupId,background:!0};return}if(ut&&!v.find(se=>se.sessionIds.includes(ut.sessionId))?.sessionIds.includes(St.current??"")){ut.element.dataset.dropActive="true",en.current={kind:"split",sessionId:ut.sessionId,groupId:ut.groupId};return}const It=document.elementsFromPoint(W,Re).filter(q=>{const se=q.closest("[data-rfd-draggable-id]");return!se||!["session:","split-member:","collaboration-member:"].some(Ee=>se.dataset.rfdDraggableId===`${Ee}${St.current}`)}),_t=It.map(q=>q.closest("[data-collaboration-group]")).find(q=>q?.dataset.collaborationGroup);if(_t?.dataset.collaborationGroup){const q=_t.dataset.collaborationGroup,se=It.map(et=>et.closest("[data-collaboration-split]")).find(Boolean),Ee=It.map(et=>et.closest("[data-collaboration-member]")).find(Boolean),We=Ee?.dataset.collaborationMember??se?.dataset.splitAnchor,mt=q===Ye.current&&v.some(et=>et.sessionIds.includes(We??"")&&et.sessionIds.includes(St.current??""));if(We&&!mt&&(q!==Ye.current||!Ee&&se)){_t.dataset.dropActive="true";const et=Ee??se;et&&(et.dataset.dropActive="true"),en.current={kind:"split",sessionId:We,groupId:q}}else{const et=It.some(dr=>dr.closest("[data-collaboration-background]"));(q!==Ye.current||et)&&(_t.dataset.dropActive="true"),en.current={kind:"collaboration",groupId:q,background:et}}return}const xt=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(q=>q.dataset.sidebarEntityListId===Jr.current).find(q=>{const se=q.getBoundingClientRect();return W>=se.left&&W<=se.right&&Re>=se.top-8&&Re<=se.bottom+8});if(!xt){en.current=null;return}const Pt=Array.from(xt.children).filter(q=>q instanceof HTMLElement&&q.hasAttribute("data-sidebar-entity-index")),z=Pt.findIndex(q=>{const se=q.getBoundingClientRect();return Re<se.top+se.height/2}),R=z<0?Pt.length:z;en.current={kind:"list",listId:xt.dataset.sidebarEntityListId??"",index:R};const F=Array.from(xt.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(q=>q.dataset.splitExitDropIndex===String(R));F instanceof HTMLElement&&(F.dataset.active="true")},[v]);b.useEffect(()=>{const W=Ke=>Ar(Ke.clientX,Ke.clientY),Re=Ke=>{const lt=Ke.touches[0];lt&&Ar(lt.clientX,lt.clientY)};return window.addEventListener("pointermove",W),window.addEventListener("touchmove",Re,{passive:!0}),()=>{window.removeEventListener("pointermove",W),window.removeEventListener("touchmove",Re)}},[Ar]);const En=b.useCallback((W,Re)=>{try{W(Re)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach(Ke=>{delete Ke.dataset.sidebarDragging}),ne.current=!1,un.current=[],Or(!1),Ye.current=null,St.current=null,Jr.current=null,en.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ke=>Ke.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ke=>Ke.removeAttribute("data-drop-active"))}},[]),qr=b.useMemo(()=>a.filter(W=>!Sn.has(W.id)),[a,Sn]),Lr=b.useMemo(()=>{let W=0;for(const Re of a)l.get(Re.id)?.agentStatus==="working"&&(W+=1);return W},[a,l]);b.useLayoutEffect(()=>{const W=mn.current,Re=hn.current;if(!e||!W||!Re){gn.current=null;return}const Ke=Re.getBoundingClientRect(),lt=W.getBoundingClientRect(),ut={item:W,top:Math.round(lt.top-Ke.top+Re.scrollTop),height:Math.round(lt.height),viewportHeight:Re.clientHeight},It=gn.current;if(gn.current=ut,It?.item===ut.item&&It.top===ut.top&&It.height===ut.height&&It.viewportHeight===ut.viewportHeight||ne.current||Re.clientHeight===0)return;const _t=8,Qt=lt.top-Ke.top,xt=lt.bottom-Ke.top;Qt<_t?Re.scrollTop+=Qt-_t:xt>Re.clientHeight-_t&&(Re.scrollTop+=xt-Re.clientHeight+_t)});const On=b.useMemo(()=>{if(!yr||!c)return null;const W=l.get(c)?.cwd??null;return gC(W)},[yr,c,l]);b.useEffect(()=>{if(!yr){tn.current=null,mr.current.clear();return}if(!c){tn.current=null;return}const W=Yt.getState(),Re=mr.current,Ke=tn.current,lt=On;Ke!==null&&Ke!==lt&&Re.has(Ke)&&(W.collapsedGroups.has(Ke)||W.toggleGroupCollapsed(Ke),Re.delete(Ke)),lt!==null&&lt!==""&&W.collapsedGroups.has(lt)&&(W.toggleGroupCollapsed(lt),Re.add(lt)),tn.current=lt},[yr,c,On]),b.useEffect(()=>{e||xe(!1)},[e]),b.useEffect(()=>{Ct(W=>({...W,command:gt?.command}))},[gt]),b.useEffect(()=>{if(!Ie)return;let W=!1;return sr(!0),ir(null),Qx().then(Re=>{W||qt(Re)}).catch(()=>{W||ir(ie("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{W||sr(!1)}),()=>{W=!0}},[Ie,ie]),b.useEffect(()=>{if(!Fe)return;const W=Re=>{Re instanceof KeyboardEvent&&Re.key!=="Escape"||Re instanceof PointerEvent&&Re.target instanceof Node&&Oe.current?.contains(Re.target)||ce(null)};return window.addEventListener("pointerdown",W),window.addEventListener("keydown",W),()=>{window.removeEventListener("pointerdown",W),window.removeEventListener("keydown",W)}},[Fe]);const tr=()=>{!Ce&&!qe&&r()};b.useEffect(()=>{const W=Re=>{xe(!1);const{groupId:Ke,dock:lt}=Re.detail;ae.current=!0,os.getState().setDock(Ke,{...lt,preferredWidth:360}),ke(ut=>({...ut,[Ke]:!0})),Bi.getState().terminal(),tr()};return window.addEventListener("termdock:open-collaboration-messages",W),()=>window.removeEventListener("termdock:open-collaboration-messages",W)},[tr]);const K=te==="tmux"&&!oe?"shell":te,De=(W,Re=!1)=>{if(He.current)return;He.current=!0,we(!0),Ge(null);const Ke=tt.current;f({...W,shouldActivate:()=>Ke===tt.current&&(W.shouldActivate?.()??!0),onResult:lt=>{if(He.current=!1,we(!1),!lt.ok){Ge(lt.error);return}Ke===tt.current&&(Re&&xe(!1),tr())}})},Mt=()=>{De({mode:K})},vr=()=>{gt&&De({mode:K,command:gt.command})},Dt=W=>{xe(!1),Je(W.name),f({mode:"tmux",tmuxSessionName:W.name,cwd:W.cwd??void 0}),tr()};b.useEffect(()=>{ge&&(Y.some(W=>W.name===ge)||Je(null))},[ge,Y]);const Br=(W,Re)=>{De({...be,cwd:be.cwd?.trim()||void 0,command:Re??W?.command},!0)},Pr=async W=>{Xt(W.id),ir(null);try{const Re=await c3(W.id);De({mode:"shell",cwd:Re.cwd,command:Re.command},!0)}catch(Re){const Ke=Re&&typeof Re=="object"&&"code"in Re?String(Re.code??""):"";ir(ie(Ke==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Xt(null)}},xn=async W=>{qt(Re=>Re.filter(Ke=>Ke.id!==W));try{await M9(W)}catch{ir(ie("sidebar.resumeHistoryRemoveFailed")),Qx().then(qt).catch(()=>{})}},Kn=()=>{if(Ie){xe(!1);return}He.current||(tt.current+=1,He.current||Ge(null),Ct({mode:te==="tmux"&&!oe?"shell":te,cwd:c?l.get(c)?.cwd??void 0:void 0,command:gt?.command}),xe(!0))},Cs=b.useCallback(W=>!_e&&W===c?"sidebar-session-selected text-foreground":"text-muted-foreground hover:bg-surface-2",[c,_e]),ws=ex(),[Wr,Qn]=b.useState(null);b.useEffect(()=>{e||Qn(null)},[e]);const Pn=b.useCallback((W,Re,Ke,lt,ut)=>{const It=!_e&&W.id===c,_t=Sn.has(W.id),Qt=!!(Ke&&_t),xt=l.get(W.id),Pt=ld(xt?.cwd??null),z=xt?.shellTitle??S9(W.id),R=z===xt?.cwd||z===Pt?null:z,F=C9(W,xt?.activeProgram??null,null,_9,R,xt?.promptState??null),q=!!(xt?.tuiProgress&&xt.tuiProgress.state!=="remove");return s.jsxs($F,{open:Wr===W.id,onOpenChange:se=>Qn(Ee=>se?W.id:Ee===W.id?null:Ee),onClose:se=>m(W.id,se,{skipConfirmation:!0}),closeLabel:ie("common.close"),closeTitle:ie("sidebar.closeSession",{name:F}),compact:Ke,children:[s.jsxs("button",{ref:It?mn:null,"aria-current":It?"page":void 0,type:"button",...Re??{},onContextMenu:se=>{P&&(se.preventDefault(),P(W.id,{x:se.clientX,y:se.clientY}))},onClick:()=>{xe(!1),Bi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:W.id})),tr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Re?"cursor-grab active:cursor-grabbing ":""}${Ke?"min-h-7 gap-1.5 py-0.5 pl-2 pr-0.5":"min-h-[30px] gap-1.5 py-1 pl-2 pr-1"}`,title:xt?.cwd??W.name,children:[It&&s.jsx("span",{"aria-hidden":"true",className:"absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-primary"}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${Ke?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${It?W.mode==="tmux"?"bg-[rgb(var(--tmux-rgb)_/_0.15)] text-[color:var(--tmux)]":"bg-primary/15 text-primary":W.mode==="tmux"?"bg-surface text-[rgb(var(--tmux-rgb)_/_0.80)]":"bg-surface text-muted-foreground"}`,children:[xt?.isConnecting||q&&!xt?.agentStatus?s.jsx(Dn,{size:Ke?10:11,className:"animate-spin"}):xt?.agent??Px(W.id)?s.jsx(ru,{agent:xt?.agent??Px(W.id),size:Ke?13:15}):W.mode==="tmux"?s.jsx(su,{size:Ke?10:11}):s.jsx(tl,{size:Ke?10:11}),s.jsx(WF,{status:xt?.agentStatus??null,detail:xt?.agentStatusDetail,needsReview:xt?.agentNeedsReview,inCopyMode:xt?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${Ke?"text-[11px]":"text-[12px]"} ${It?"font-medium text-foreground":""} ${xt?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:F}),s.jsx(yb,{sessionIds:[W.id]})]}),lt,s.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),Qt?w(W.id):_t?y(W.id):x(W.id)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md transition hover:bg-primary/15 hover:text-primary active:scale-95 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"} text-muted-foreground`,"aria-label":`${ie(Qt?"tab.splitRemovePane":_t?"tab.splitClose":"tab.split")} ${F}`,title:ie(Qt?"tab.splitRemovePane":_t?"tab.splitClose":"tab.split"),children:Qt?s.jsx(nC,{size:11}):s.jsx($l,{size:12})}),ut??s.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),m(W.id,se)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md text-muted-foreground/70 transition hover:bg-destructive/15 hover:text-destructive active:scale-95 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":ie("sidebar.closeSession",{name:F}),title:ie("common.close"),children:s.jsx(jn,{size:Ke?11:12})})]})},[c,_e,Sn,l,m,x,y,w,P,ie,Wr]),jr=b.useMemo(()=>Lf(a,W=>l.get(W.id)?.cwd??null,yr,ie("sidebar.ungrouped"),v,Qr).groups,[Qr,yr,a,l,v,ie]),ds=b.useMemo(()=>r0(a,v,Zr,Qr),[Qr,a,Zr,v]),Tr=b.useCallback(W=>{Or(W.draggableId.startsWith("collaboration:")||W.draggableId.startsWith("workspace:"));const Re=W.draggableId.replace(/^split-member:/,"");St.current=W.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const Ke=W.type==="split-member"?v.find(Qt=>Qt.sessionIds.includes(Re)):null,lt=W.type==="collaboration-member"?W.source.droppableId.replace(/^collaboration-members:/,""):null,ut=lt?Qr.find(Qt=>Qt.id===lt):null;ne.current=!!(Ke||ut||W.type==="session"&&W.draggableId.startsWith("session:")),ne.current&&document.querySelectorAll("[data-collaboration-group]").forEach(Qt=>{Qt.dataset.sidebarDragging="true"}),Ye.current=ut?.id??null;const It=Ke?.sessionIds??ut?.sessionIds??[],_t=It.length>0?jr.find(Qt=>It.every(xt=>Qt.sessions.some(Pt=>Pt.id===xt))):null;Jr.current=yr?_t?`group-sessions:${_t.key}`:null:It.length>0?"sidebar-entities":null,en.current=null},[Qr,jr,yr,v]),bn=b.useCallback((W,Re,Ke)=>{if(Re===Ke)return;const lt=Re?Tt.find(xt=>xt.id===Re):null,ut=Ke?Tt.find(xt=>xt.id===Ke):null;if(Ke&&!ut)return;if(ut){const xt=a.map(z=>z.id).filter(z=>z!==W);let Pt=-1;xt.forEach((z,R)=>{ut.sessionIds.includes(z)&&(Pt=R)}),Pt>=0&&(xt.splice(Pt+1,0,W),N(xt))}const It=lt?.sessionIds.filter(xt=>xt!==W)??[],_t=ut?[...ut.sessionIds.filter(xt=>xt!==W),W]:[];Ft(xt=>xt.flatMap(Pt=>Pt.id===Re?[{...Pt,sessionIds:It}]:Pt.id===Ke?[{...Pt,sessionIds:_t}]:[Pt])),Et(null),(lt&&ut?k9({sourceGroupId:lt.id,targetGroupId:ut.id,sessionId:W,expectedSourceUpdatedAt:lt.updatedAt,expectedTargetUpdatedAt:ut.updatedAt}):lt?Wl({id:lt.id,name:lt.name,sessionIds:It,expectedUpdatedAt:lt.updatedAt}):ut?Wl({id:ut.id,name:ut.name,sessionIds:_t,expectedUpdatedAt:ut.updatedAt}):Promise.resolve()).then(()=>fn(),xt=>(Et(xt instanceof Error?xt.message:"协作成员移动失败"),fn()))},[Tt,fn,a,N]),An=b.useCallback((W,Re,Ke,lt=!1)=>{const ut=Tt.find(se=>se.id===W);if(!ut||Re===Ke)return;const It=ut.sessionIds.filter(se=>!se.startsWith("remote:")),_t=t0(It,v).flatMap(se=>se.sessionIds),Qt=mb(vt,ut.id),xt=lt&&!Ot[ut.id]?_t.filter(se=>!Qt.has(se)||se===c||Sn.has(se)):_t.slice(),Pt=new Set(xt),[z]=xt.splice(Re,1);if(!z)return;xt.splice(Ke,0,z);let R=0;const F=_t.map(se=>Pt.has(se)?xt[R++]:se),q=v.find(se=>se.sessionIds.includes(z));if(q&&q.sessionIds.every(se=>ut.sessionIds.includes(se))){const se=F.filter(Ee=>q.sessionIds.includes(Ee));S(q.id,se)}F.push(...ut.sessionIds.filter(se=>se.startsWith("remote:"))),Ft(se=>se.map(Ee=>Ee.id===W?{...Ee,sessionIds:F}:Ee)),Et(null),Wl({id:ut.id,name:ut.name,sessionIds:F,expectedUpdatedAt:ut.updatedAt}).then(()=>fn(),se=>(Et(se instanceof Error?se.message:"成员排序失败"),fn()))},[Tt,fn,v,S,vt,Ot,c,Sn]);b.useEffect(()=>{const W=Re=>{const{sourceId:Ke,targetId:lt}=Re.detail;if(!Ke||!lt||Ke===lt)return;const ut=Lf(a,We=>l.get(We.id)?.cwd??null,yr,"",v,Qr).arranged.map(We=>We.id),It=ut.indexOf(Ke),_t=ut.indexOf(lt);if(It<0||_t<0)return;const Qt=Qr.find(We=>We.sessionIds.includes(Ke));if(Qt?.sessionIds.includes(lt)){const We=t0(Qt.sessionIds,v).flatMap(mt=>mt.sessionIds);An(Qt.id,We.indexOf(Ke),We.indexOf(lt));return}const xt=v.filter(We=>We.sessionIds.length>=2&&We.sessionIds.every(mt=>Zr.has(mt))&&!Qr.some(mt=>We.sessionIds.some(et=>mt.sessionIds.includes(et)))),Pt=xt.find(We=>We.sessionIds.includes(Ke));if(Pt?.sessionIds.includes(lt)){const We=[...Pt.sessionIds];We.splice(We.indexOf(Ke),1),We.splice(Pt.sessionIds.indexOf(lt),0,Ke),S(Pt.id,We);return}const z=We=>Qr.find(mt=>mt.sessionIds.includes(We))?.sessionIds??xt.find(mt=>mt.sessionIds.includes(We))?.sessionIds??[We],R=new Set(z(Ke)),F=new Set(z(lt)),q=ut.filter(We=>!R.has(We)),se=q.flatMap((We,mt)=>F.has(We)?[mt]:[]),Ee=It<_t?Math.max(...se)+1:Math.min(...se);q.splice(Ee,0,...ut.filter(We=>R.has(We))),N(q)};return window.addEventListener("reorder-navigation-session",W),()=>window.removeEventListener("reorder-navigation-session",W)},[a,l,yr,v,Qr,Zr,An,S,N]);const rr=b.useCallback(W=>{if(W.type!=="collaboration-member")return!1;if(W.reason==="CANCEL")return!0;const Re=W.source.droppableId.replace(/^collaboration-members:/,""),Ke=W.draggableId.replace(/^collaboration-member:/,""),lt=en.current;if(lt?.kind==="split")return bn(Ke,Re,lt.groupId),I(lt.sessionId,Ke),!0;if(lt?.kind==="collaboration"&&lt.groupId!==Re)return bn(Ke,Re,lt.groupId),!0;if(lt?.kind==="collaboration"&&lt.background)return Sn.has(Ke)&&w(Ke),!0;if(W.destination&&W.destination.droppableId!==W.source.droppableId){const ut=W.destination.droppableId.replace(/^collaboration-members:/,"");if(Qr.some(It=>It.id===ut))return bn(Ke,Re,ut),!0}if(W.combine){const ut=W.combine.droppableId.replace(/^collaboration-members:/,"");ut!==Re&&bn(Ke,Re,ut);const It=W.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(Qt=>Qt.sessionIds.includes(Ke))?.sessionIds.includes(It)){const Qt=Qr.find(Pt=>Pt.id===Re),xt=Qt?t0(Qt.sessionIds,v).flatMap(Pt=>Pt.sessionIds).indexOf(It):-1;xt>=0&&Qt&&An(Re,t0(Qt.sessionIds,v).flatMap(Pt=>Pt.sessionIds).indexOf(Ke),xt)}else Zr.has(It)&&I(It,Ke);return!0}if(W.destination?.droppableId===W.source.droppableId)return An(Re,W.source.index,W.destination.index,!0),!0;if(lt?.kind!=="list")return!0;if(lt?.kind==="list"){const ut=jr.find(_t=>`group-sessions:${_t.key}`===lt.listId),It=lt.listId==="sidebar-entities"?ds:ut?r0(ut.sessions,v,Zr,Qr):null;if(It){const _t=py(It,Ke,lt.index);lt.listId==="sidebar-entities"?N(_t):ut&&N(jr.flatMap(Qt=>Qt.key===ut.key?_t:Qt.sessions.map(xt=>xt.id)))}}return bn(Ke,Re,null),!0},[Qr,ds,jr,bn,N,An,Zr,v,Sn,w,I]),kn=b.useCallback(W=>{if(W.type!=="split-member")return!1;if(W.reason==="CANCEL")return!0;const Re=W.draggableId.replace(/^split-member:/,""),Ke=v.find(xt=>xt.sessionIds.includes(Re));if(!Ke?.sessionIds.includes(Re))return!0;const lt=Ke.id,ut=en.current;if(ut?.kind==="split")return bn(Re,null,ut.groupId),I(ut.sessionId,Re),!0;if(ut?.kind==="collaboration")return bn(Re,null,ut.groupId),!0;if(!W.destination&&ut?.kind==="list"){const xt=jr.find(R=>`group-sessions:${R.key}`===ut.listId),Pt=ut.listId==="sidebar-entities"?ds:xt?r0(xt.sessions,v,Zr,Qr):null;if(!Pt)return!0;const z=py(Pt,Re,ut.index);return w(Re),ut.listId==="sidebar-entities"?N(z):xt&&N(jr.flatMap(R=>R.key===xt.key?z:R.sessions.map(F=>F.id))),!0}if(!W.destination)return!0;const It=W.destination.droppableId.replace(/^split-members:/,"");if(It!==lt){const Pt=v.find(z=>z.id===It)?.sessionIds[0];return Pt&&I(Pt,Re),!0}if(W.source.index===W.destination.index)return!0;const _t=[...Ke.sessionIds],[Qt]=_t.splice(W.source.index,1);return Qt&&(_t.splice(W.destination.index,0,Qt),S(lt,_t)),!0},[Qr,ds,jr,bn,I,w,N,S,Zr,v]),Cn=(W,Re="top")=>s.jsx("div",{"data-split-exit-drop-index":W,className:`group/split-exit pointer-events-none absolute inset-x-0 z-10 h-2 ${Re==="top"?"-top-1":"-bottom-1"}`,children:s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-1 top-1/2 h-px -translate-y-1/2 rounded-full bg-transparent transition-colors group-data-[active=true]/split-exit:bg-primary"})}),wr=b.useCallback((W,Re,Ke)=>{if(rr(W)||kn(W)||W.reason==="CANCEL")return;const lt=Re.find(xt=>xt.id===W.draggableId);if(!lt)return;const ut=en.current;if(ut?.kind==="split"&&lt.kind==="session"){bn(lt.session.id,null,ut.groupId),I(ut.sessionId,lt.session.id);return}if(ut?.kind==="collaboration"&&lt.kind==="session"){bn(lt.session.id,null,ut.groupId);return}if(W.combine&&lt.kind!=="session"){const xt=Re.findIndex(Pt=>Pt.id===W.combine?.draggableId);if(xt<0)return;W={...W,combine:null,destination:{...W.source,index:xt}}}if(W.combine){const xt=Re.find(q=>q.id===W.combine?.draggableId);if(!xt)return;const Pt=xt.kind==="workspace"?xt:lt.kind==="workspace"?lt:xt,z=Pt===lt?xt:lt,R=Pt.sessionIds[0],F=z.sessionIds[0];R&&F&&R!==F&&I(R,F);return}if(!W.destination||W.source.index===W.destination.index)return;const It=[...Re],[_t]=It.splice(W.source.index,1);if(!_t)return;It.splice(W.destination.index,0,_t);const Qt=It.flatMap(xt=>xt.sessionIds);if(Ke===void 0){N(Qt);return}N(jr.flatMap(xt=>xt.key===Ke?Qt:xt.sessions.map(Pt=>Pt.id)))},[jr,rr,kn,bn,I,N]),ps=b.useCallback(W=>{if(W.reason==="CANCEL"||rr(W)||kn(W))return;if(W.type==="group"){if(!W.destination||W.source.index===W.destination.index)return;N(S3(jr,W.source.index,W.destination.index));return}const Re=W.source.droppableId.replace(/^group-sessions:/,""),Ke=jr.find(ut=>ut.key===Re);if(!Ke)return;const lt=r0(Ke.sessions,v,Zr,Qr);if(W.combine||en.current?.kind==="collaboration"||en.current?.kind==="split"){wr(W,lt,Re);return}!W.destination||W.destination.droppableId!==W.source.droppableId||wr(W,lt,Re)},[Qr,jr,Zr,v,rr,wr,kn,N]),Ks=(W,Re)=>{const Ke=Fe===W.id,lt=[{layout:"horizontal",label:ie("tab.splitHorizontal"),icon:$l},{layout:"vertical",label:ie("tab.splitVertical"),icon:zx},...W.sessionIds.length>=3||W.layout==="grid"?[{layout:"grid",label:ie("tab.splitGrid"),icon:Ux}]:[]],ut=W.layout==="vertical"?zx:W.layout==="grid"?Ux:$l,It=lt.find(_t=>_t.layout===W.layout)?.label??ie("tab.splitHorizontal");return s.jsxs("div",{ref:Ke?Oe:void 0,className:"relative shrink-0",onPointerDown:_t=>_t.stopPropagation(),children:[s.jsx("button",{...Re??{},type:"button",className:`sidebar-session-action inline-flex h-6 w-6 items-center justify-center rounded-md transition active:scale-95 ${Ke?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${ie("tab.splitLayout")}: ${It}`,"aria-haspopup":"menu","aria-expanded":Ke,title:Re?`${ie("tab.splitLayout")} · 按住拖动分屏组`:ie("tab.splitLayout"),onClick:_t=>{_t.stopPropagation(),ce(Qt=>Qt===W.id?null:W.id)},children:s.jsx(ut,{size:12})}),Ke&&s.jsx("div",{role:"menu","aria-label":ie("tab.splitLayout"),className:"absolute right-0 top-full z-30 mt-1 flex gap-0.5 rounded-md border border-border bg-surface-elevated p-1 shadow-lg",children:lt.map(_t=>{const Qt=_t.icon,xt=_t.layout===W.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":xt,"aria-label":_t.label,title:_t.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${xt?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:Pt=>{Pt.stopPropagation(),T(W.sessionIds[0],_t.layout),ce(null)},children:s.jsx(Qt,{size:13})},_t.layout)})})]})},rs=(W,Re,Ke=!1,lt=!1,ut)=>{if(Re.length<2)return null;const It=W.name?.trim()||`${ie("tab.splitWorkspace")} ${v.findIndex(Qt=>Qt.id===W.id)+1}`,_t=Fe===W.id;return s.jsx("section",{"data-split-workspace":W.id,"aria-label":It,className:`group/split relative rounded-md my-1 p-0.5 before:opacity-40 before:pointer-events-none before:absolute before:inset-0 before:rounded-md before:border before:border-border transition-colors ${lt?"bg-primary/15 ring-1 ring-primary/40":Ke?"bg-surface-elevated opacity-90 shadow-lg":"bg-[var(--chrome-bg)]"}`,children:s.jsx(Fl,{droppableId:`split-members:${W.id}`,type:"split-member",direction:"vertical",children:(Qt,xt)=>s.jsxs("div",{ref:Qt.innerRef,...Qt.droppableProps,"data-split-members":!0,className:xt.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Re.map((Pt,z)=>s.jsx(Ol,{draggableId:`split-member:${Pt.id}`,index:z,disableInteractiveElementBlocking:!0,children:(R,F)=>s.jsx("div",{ref:R.innerRef,...R.draggableProps,...P?ws(()=>P(Pt.id)):{},className:`sidebar-session-row ${z===0&&_t?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${F.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Cs(Pt.id)}`,children:Pn(Pt,R.dragHandleProps,!0,z===0?Ks(W,ut):void 0)})},Pt.id)),Qt.placeholder]})})})},on=(W,Re)=>{const Ke=c??Re;pe.current||!Ke||(xe(!1),pe.current=!0,Xe(W),Et(null),PC(W,Ke).catch(lt=>Et(lt instanceof Error?lt.message:"消息面板打开失败,请重试")).finally(()=>{pe.current=!1,Xe(null)}))},Hn=(W,Re)=>{an.current+=1,Ft(Ke=>Re?Ke.map(lt=>lt.id===W?Re:lt):Ke.filter(lt=>lt.id!==W)),Re||(Bi.getState().groupId===W&&Bi.getState().terminal(),os.getState().setDock(W,null),ke(Ke=>{const lt={...Ke};return delete lt[W],lt}),requestAnimationFrame(()=>mn.current?.focus({preventScroll:!0})),eo({floatingGroupId:null},W).catch(()=>Et("协作组已删除,面板布局保存失败,请刷新后检查。"))),fn()},Fr=(W,Re,Ke,lt=!1,ut=!1)=>{const It=`collaboration:${W.id}`,_t=Xr.has(It),Qt=`collaboration-members-${W.id}`,xt=mb(vt,W.id),Pt=W.sessionIds.filter(Ee=>xt.has(Ee)&&Ee!==c&&!Sn.has(Ee)),z=Ot[W.id]===!0,R=z?W.sessionIds:W.sessionIds.filter(Ee=>!Pt.includes(Ee)),F=t0(R,v),q=F.flatMap(Ee=>Ee.sessionIds),se=F.length===1?F[0]?.workspace:void 0;return s.jsxs("section",{"data-collaboration-group":W.id,"data-collaboration-group-name":W.name,"aria-label":`Agent 工作组:${W.name}`,className:`group/collaboration relative my-1 rounded-lg p-1 before:pointer-events-none before:absolute before:inset-0 before:rounded-lg before:border before:border-border/60 transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${ut?"bg-primary/15 ring-1 ring-primary/40":lt?"bg-surface-elevated opacity-90 shadow-lg":"bg-[var(--chrome-bg)]"}`,children:[s.jsx("div",{className:"rounded-md bg-surface",children:s.jsxs(zF,{group:Tt.find(Ee=>Ee.id===W.id)??W,collapsed:_t,onOpen:()=>{Gr(W.id)},onMessages:$e===null&&(c||Re.length)?()=>on(W.id,Re[0]?.id):void 0,onToggleCollapsed:()=>Bn(It),onChanged:Ee=>Hn(W.id,Ee),children:[s.jsx("button",{type:"button","aria-label":`${_t?"展开":"收起"} ${W.name} 的成员会话`,"aria-expanded":!_t,"aria-controls":Qt,title:`${_t?"展开":"收起"}成员会话`,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-5",onClick:Ee=>{Ee.stopPropagation(),Bn(It)},children:s.jsx(qs,{size:14,className:_t?"":"rotate-90"})}),s.jsxs("button",{...Ke??{},type:"button",className:"flex min-h-11 min-w-0 flex-1 cursor-grab items-center gap-1.5 rounded-sm px-1 text-left text-xs font-medium text-foreground transition hover:text-primary active:cursor-grabbing md:min-h-[30px]",title:`打开 ${W.name} 的协作工作区 · 按住标题拖动排序`,"aria-label":`打开协作工作区:${W.name}`,"aria-current":_e===W.id?"page":void 0,onClick:Ee=>{Ee.stopPropagation(),Gr(W.id)},children:[s.jsx(Wp,{size:14,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:W.name}),X.some(Ee=>Ee.groupId===W.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[X.filter(Ee=>Ee.groupId===W.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${W.name}`,title:"在终端旁打开成员与消息",disabled:$e!==null||!c&&!Re.length,"aria-busy":$e===W.id,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-primary disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:Ee=>{Ee.stopPropagation(),on(W.id,Re[0]?.id)},children:$e===W.id?s.jsx(vn,{size:14,className:"animate-spin"}):s.jsx(cd,{size:14})})]})}),s.jsx("div",{id:Qt,className:_t?void 0:"px-0.5 pt-1",children:!_t&&s.jsxs(s.Fragment,{children:[Pt.length>0&&s.jsxs("button",{type:"button","aria-expanded":z,className:"flex min-h-11 w-full items-center gap-2 rounded-sm px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-elevated md:min-h-8",title:"展开后可查看或归档执行会话,任务结果保留。",onClick:()=>er(Ee=>({...Ee,[W.id]:!z})),children:[s.jsx(qs,{size:12,className:z?"rotate-90":""}),"已完成的执行会话 · ",Pt.length]}),s.jsx(Fl,{droppableId:`collaboration-members:${W.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(Ee,We)=>s.jsxs("div",{ref:Ee.innerRef,...Ee.droppableProps,"data-collaboration-members":!0,className:`${We.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[F.map(mt=>s.jsx("div",{"data-collaboration-split":mt.workspace?.id,"data-split-anchor":mt.workspace?.sessionIds[0],role:mt.workspace?"region":void 0,"aria-label":mt.workspace?`${ie("tab.splitWorkspace")} · ${mt.sessionIds.length}`:void 0,className:mt.workspace&&!se?`relative my-0.5 rounded-sm before:pointer-events-none before:absolute before:inset-0 before:rounded-sm before:border before:border-border data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${mt.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:mt.sessionIds.map(et=>{const dr=Zr.get(et);return dr?s.jsx(Ol,{draggableId:`collaboration-member:${dr.id}`,index:q.indexOf(dr.id),disableInteractiveElementBlocking:!0,children:(Wn,Gt)=>s.jsxs("div",{ref:Wn.innerRef,...Wn.draggableProps,"data-collaboration-member":dr.id,"data-split-member":Sn.has(dr.id)?"true":void 0,...P?ws(()=>P(dr.id)):{},className:`${mt.workspace&&et===mt.sessionIds[0]&&Fe===mt.workspace.id?"z-20 ":""}sidebar-session-row relative flex items-center rounded-sm pr-0.5 transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${Gt.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":Gt.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Cs(dr.id)}`,children:[Pn(dr,Wn.dragHandleProps,!0,mt.workspace&&et===mt.sessionIds[0]?Ks(mt.workspace):void 0,xt.has(et)?s.jsxs("button",{type:"button","aria-label":`归档 ${dr.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:Dr!==null,className:"sidebar-session-action inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1 rounded-md px-2 text-muted-foreground hover:bg-primary/15 hover:text-primary disabled:opacity-40 md:h-6 md:min-w-6 md:px-1",onClick:zr=>{zr.stopPropagation(),!At.current&&(At.current=!0,Le(et),Et(null),N9(et).then(async()=>{Me(_r=>_r+1),await fn()}).catch(_r=>Et(_r instanceof Error?_r.message:"归档失败,终端已保留")).finally(()=>{At.current=!1,Le(null)}))},children:[Dr===et?s.jsx(vn,{size:13,className:"animate-spin"}):s.jsx(Cf,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!mt.workspace&&Sn.has(dr.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(zr=>zr.sessionIds.includes(dr.id))?.sessionIds.filter(zr=>zr!==dr.id).map(zr=>Zr.get(zr)?.name??zr).join("、")} 分屏`,"aria-label":`查看 ${dr.name} 的跨组分屏`,onClick:()=>{xe(!1),Bi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:dr.id})),tr()},children:s.jsx($l,{size:10})})]})},dr.id):null})},mt.workspace?.id??mt.sessionIds[0])),Ee.placeholder]})}),s.jsx(BQ,{groupId:W.id,version:Bt,onRestore:async Ee=>{xe(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:Ee.cwd,preferredFrontendSessionId:Ee.sessionId,requireExisting:!0}})),await fn(),Bi.getState().terminal(),tr()}}),W.remoteSessions?.map(Ee=>{const We=R9(Ee),mt=We==="connected",et=We==="unknown"?"连接状态未知":"连接已断开";return s.jsxs("button",{type:"button",title:`${Ac(Ee)} · ${mt?"服务已连接":et}`,className:"flex w-full min-w-0 items-center gap-1.5 rounded-sm px-2 py-1 text-left text-[11px] text-muted-foreground hover:bg-surface-2",onClick:()=>{xe(!1),K6(Ee.sessionId).catch(()=>{Gr(W.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${mt?"bg-primary":"bg-muted-foreground"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Ee.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:Ac(Ee)}),!mt&&s.jsx("span",{className:"shrink-0 text-[9px]",children:et})]},Ee.sessionId)})]})}),s.jsx("div",{"data-collaboration-background":!0,className:_t?"absolute inset-0 pointer-events-none":"h-1.5"})]})},$r=(W,Re,Ke)=>s.jsx(Gu,{onBeforeCapture:Ss,onDragStart:Tr,onDragEnd:lt=>En(ut=>wr(ut,W,Ke),lt),children:s.jsx(Fl,{droppableId:Re,direction:"vertical",isCombineEnabled:!Jt,children:lt=>s.jsxs("div",{ref:lt.innerRef,...lt.droppableProps,"data-sidebar-entity-list-id":Re,className:"flex-1 space-y-0.5",children:[W.map((ut,It)=>s.jsx(Ol,{draggableId:ut.id,index:It,disableInteractiveElementBlocking:!0,children:(_t,Qt)=>s.jsxs("div",{ref:_t.innerRef,..._t.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":It,className:"relative",children:[Cn(It),It===W.length-1&&Cn(W.length,"bottom"),ut.kind==="workspace"?rs(ut.workspace,ut.members,Qt.isDragging,!!Qt.combineTargetFor,_t.dragHandleProps):ut.kind==="collaboration"?Fr(ut.group,ut.members,_t.dragHandleProps,Qt.isDragging,!!Qt.combineTargetFor):s.jsx("div",{...P?ws(()=>P(ut.session.id)):{},className:`sidebar-session-row group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Qt.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Qt.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Cs(ut.session.id)} cursor-grab active:cursor-grabbing`,children:Pn(ut.session,_t.dragHandleProps)})]})},ut.id)),lt.placeholder]})})}),pn=s.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[s.jsx(XO,{label:ie("sidebar.sessions"),count:a.length,badge:Lr>0?s.jsx(f4,{count:Lr,tone:"running",title:ie("agent.aiRunning")}):null,pinned:!!qe,onClose:r,onTogglePinned:ve?()=>{xe(!1),ve()}:void 0,serverAttention:Cr,onOpenSettings:()=>{xe(!1),$()},actions:[...Q?[{label:ie("sidebar.subscriptionQuota"),icon:hT,onSelect:()=>{xe(!1),Q()}}]:[],{label:"Agent 工作台",icon:Wp,onSelect:()=>{xe(!1),Gr(null)}},{label:"服务与设备",icon:L9,onSelect:()=>{xe(!1),I9()}},{label:ie("sidebar.settings"),icon:y3,onSelect:()=>{xe(!1),$()}}]}),at&&s.jsxs("div",{role:"alert",className:"mx-2 mt-2 flex items-start gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:[s.jsx("span",{className:"min-w-0 flex-1",children:at}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>Et(null),children:s.jsx(jn,{size:14})})]}),s.jsxs("div",{ref:hn,className:"relative z-10 flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-1.5 pt-0.5 pb-1.5",children:[X.length>0&&s.jsxs("section",{className:"mb-2 rounded-lg border border-primary/20 bg-primary/5","aria-label":"协作待处理事项",children:[X.length>0&&s.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center gap-2 px-3 text-left text-xs text-primary","aria-expanded":Lt,onClick:()=>nr(W=>!W),children:[s.jsx(Wp,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:X.length}),s.jsx(qs,{size:12,className:Lt?"rotate-90":""})]}),(Lt||X.length===0)&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[ot&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[ot,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{Pu.getState().refresh()},children:"重试"})]}),X.map(W=>s.jsxs("button",{type:"button",className:"min-h-11 w-full rounded-md px-2 py-2 text-left hover:bg-surface-2",onClick:()=>{xb(W.groupId,W.id),Gr(W.groupId).then(Re=>{Re&&xb(W.groupId,W.id)})},children:[s.jsx("span",{className:"block truncate text-xs text-foreground",children:W.title}),s.jsxs("span",{className:"mt-1 block truncate text-[10px] text-muted-foreground",children:[Tt.find(Re=>Re.id===W.groupId)?.name??"协作组"," · ",cu(W)]})]},W.id))]})]}),s.jsx(UF,{sessions:Y,loading:st,attachingName:ge,onRefresh:he,onRestore:Dt,onClose:Qe}),lr.length>0&&s.jsxs("section",{className:"mb-1","aria-label":"已归档协作组",children:[s.jsxs("button",{type:"button",className:"flex min-h-10 w-full items-center gap-2 rounded-md px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-2","aria-expanded":ur,onClick:()=>Rr(W=>!W),children:[s.jsx(Cf,{size:13}),s.jsx("span",{className:"flex-1",children:"已归档协作组"}),s.jsx("span",{children:lr.length}),s.jsx(qs,{size:12,className:ur?"rotate-90":""})]}),ur&&s.jsx("div",{className:"space-y-1",children:lr.map(W=>s.jsx(Gu,{onDragEnd:()=>{},children:Fr(W,W.sessionIds.flatMap(Re=>Zr.get(Re)??[]))},W.id))})]}),Qr.filter(W=>!W.sessionIds.length).map(W=>s.jsx(Gu,{onDragEnd:()=>{},children:Fr(W,[])},W.id)),a.length===0?s.jsxs("div",{className:"rounded-xl bg-surface-2/60 px-4 py-8 text-center",children:[s.jsx(tl,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:ie("sidebar.noSessions")})]}):qr.length===0&&v.length===0?s.jsx("div",{className:"rounded-xl bg-surface-2/60 px-4 py-6 text-center",children:s.jsx("p",{className:"text-[12px] text-muted-foreground",children:ie("sidebar.noMatchingSessions")})}):yr?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(Gu,{onBeforeCapture:Ss,onDragStart:Tr,onDragEnd:W=>En(ps,W),children:s.jsx(Fl,{droppableId:"sidebar-groups",type:"group",direction:"vertical",children:W=>s.jsxs("div",{ref:W.innerRef,...W.droppableProps,className:"flex flex-1 flex-col space-y-1.5",children:[jr.map((Re,Ke)=>{const lt=Xr.has(Re.key),ut=!lt&&Ke===jr.length-1,It=r0(Re.sessions,v,Zr,Qr);let _t=0,Qt=0;for(const Pt of Re.sessions){const z=l.get(Pt.id);z?.agentStatus==="working"&&(_t+=1),(z?.agentStatus==="waiting"||z?.agentNeedsReview)&&(Qt+=1)}const xt=Re.key==="";return s.jsx(Ol,{draggableId:`sidebar-group:${Re.key||"__ungrouped__"}`,index:Ke,isDragDisabled:xt,disableInteractiveElementBlocking:!0,children:(Pt,z)=>s.jsxs("div",{ref:Pt.innerRef,...Pt.draggableProps,className:`shrink-0 rounded-md transition-colors ${ut?"flex flex-1 flex-col ":""}${z.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...xt?{}:Pt.dragHandleProps,onClick:()=>{Bn(Re.key),mr.current.delete(Re.key)},className:`flex w-full shrink-0 items-center gap-1.5 rounded-md px-1.5 pb-1 pt-2.5 text-left text-muted-foreground transition hover:bg-surface-2 ${xt?"":"cursor-grab active:cursor-grabbing"}`,title:Re.key||Re.label,children:[s.jsx(qs,{size:13,className:`shrink-0 transition-transform ${lt?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[10.5px] font-semibold uppercase tracking-[0.08em]",children:Re.label}),_t>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),Qt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx(yb,{sessionIds:Re.sessions.map(R=>R.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Re.sessions.length})]}),!lt&&s.jsx("div",{className:`mt-0.5 pl-2 ${ut?"flex flex-1 flex-col":""}`,children:s.jsx(Fl,{droppableId:`group-sessions:${Re.key}`,type:"session",direction:"vertical",isCombineEnabled:!Jt,children:R=>s.jsxs("div",{ref:R.innerRef,...R.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Re.key}`,className:`${ut?"flex-1 ":""}space-y-0.5`,children:[It.map((F,q)=>s.jsx(Ol,{draggableId:F.id,index:q,disableInteractiveElementBlocking:!0,children:(se,Ee)=>s.jsxs("div",{ref:se.innerRef,...se.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":q,className:"relative",children:[Cn(q),q===It.length-1&&Cn(It.length,"bottom"),F.kind==="workspace"?rs(F.workspace,F.members,Ee.isDragging,!!Ee.combineTargetFor,se.dragHandleProps):F.kind==="collaboration"?Fr(F.group,F.members,se.dragHandleProps,Ee.isDragging,!!Ee.combineTargetFor):s.jsx("div",{...P?ws(()=>P(F.session.id)):{},className:`sidebar-session-row group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Ee.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Ee.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Cs(F.session.id)} cursor-grab active:cursor-grabbing`,children:Pn(F.session,se.dragHandleProps)})]})},F.id)),R.placeholder]})})})]})},Re.key||"__ungrouped__")}),W.placeholder]})})})}):$r(ds,"sidebar-entities")]}),s.jsx(E9,{onReselect:()=>{d&&(gn.current=null,Pe(W=>W+1),d())}}),Ie&&s.jsx(ZO,{directories:a.flatMap(W=>{const Re=l.get(W.id)?.cwd;return Re?[Re]:[]}),tmuxAvailable:oe,options:be,launchPending:Ze,launchError:le?ie(h1(le)):null,agents:rt,selectedAgent:gt,detecting:cn,resumeHistory:Ut,resumeHistoryLoading:Nt,resumeHistoryPendingId:jt,resumeHistoryError:Rt,onRefreshAgents:()=>{Kr().catch(()=>{})},onSelectAgent:W=>{wn(W).catch(()=>{})},onLaunchAgent:Br,onResumeHistory:W=>{Pr(W)},onRemoveResumeHistory:W=>{xn(W)},onClose:()=>xe(!1),onOptionsChange:Ct,additionalContent:ht&&U?.latestVersion&&s.jsxs("div",{className:"mb-1 rounded-lg bg-[rgb(var(--warning-rgb)_/_0.10)] px-2.5 py-2.5 text-foreground",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]",children:s.jsx(vn,{size:13,className:U.status==="checking"||U.status==="installing"||U.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:ie("sidebar.updateAvailable",{version:U.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:U.status==="checking"?ie("settings.updateChecking"):U.status==="installing"?ie("sidebar.updateInstalling"):U.status==="ready"?ie("sidebar.updateReady"):U.status==="restarting"?ie("sidebar.updateRestarting"):U.error||ie("sidebar.updateFailed")})]})]}),U.status==="ready"&&J&&s.jsx("button",{type:"button",disabled:Z,onClick:J,className:"mt-2 flex w-full items-center justify-center rounded-md bg-[var(--warning)] px-2 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:ie("sidebar.updateRestart")}),U.status==="error"&&H&&s.jsx("button",{type:"button",disabled:Z,onClick:H,className:"mt-2 flex w-full items-center justify-center rounded-md bg-surface-elevated px-2 py-1.5 text-[11px] font-semibold text-foreground transition hover:bg-surface-2 disabled:cursor-wait disabled:opacity-60",children:ie("sidebar.updateRetry")})]})}),dt&&s.jsx(ay,{onEnterGroup:async W=>{if(!await Gr(W))throw new Error("协作组已保存,打开工作区失败,请重试");it(!1)},onFloatingChange:async W=>{if(W){if(!await Gr(W))throw new Error("打开协作工作区失败");it(!1)}},activeSessionId:c,defaultSessionMode:te,onClose:()=>it(!1),onNewSession:W=>f(W)}),Object.entries(Ue).map(([W,Re])=>s.jsx(ay,{activeSessionId:c,initialCollaborationGroupId:W,initialFloating:Re,visible:!_e,onEnterGroup:async Ke=>{if(Ke===W){await Gr(Ke);return}if(!await Gr(Ke))throw new Error("协作组已保存,打开工作区失败,请重试");await eo({floatingGroupId:null},W),ke(lt=>{const ut={...lt};return delete ut[W],ut})},onFloatingChange:Ke=>wt(W,Ke),defaultSessionMode:te,onClose:()=>{ae.current=!0,ke(Ke=>{const lt={...Ke};return delete lt[W],lt})},onNewSession:Ke=>f(Ke)},W)),!Ie&&s.jsxs("div",{className:"relative z-10 shrink-0 bg-[var(--chrome-bg)] px-3 pb-3 pt-1 md:border-t md:border-border md:p-2",children:[le&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:ie(h1(le))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${gt?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:Mt,disabled:Ze,"aria-busy":Ze,className:`flex min-w-0 items-center justify-center gap-2 rounded-lg px-2 py-2.5 text-[12px] font-semibold transition active:scale-[0.99] ${gt?"bg-surface-elevated text-foreground ring-1 ring-border/30 hover:bg-surface-2":"bg-primary text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90"}`,title:ie("sidebar.newSession"),"aria-label":ie("sidebar.newSession"),children:[s.jsx(tl,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Ze?ie("sidebar.sessionCreating"):"Terminal"})]}),gt&&s.jsxs("button",{type:"button",onClick:vr,disabled:Ze,"aria-busy":Ze,className:"flex min-w-0 items-center justify-center gap-2 rounded-lg bg-primary px-2 py-2.5 text-[12px] font-semibold text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 transition hover:bg-primary/90 active:scale-[0.99]",title:ie("sidebar.newSessionWithAgent",{agent:gt.displayName}),"aria-label":ie("sidebar.newSessionWithAgent",{agent:gt.displayName}),children:[s.jsx(ru,{agent:gt,size:15}),s.jsx("span",{className:"truncate",children:gt.displayName})]}),s.jsxs("button",{type:"button",onClick:Kn,disabled:Ze,className:"relative inline-flex w-10 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-[0.97]",title:Ht,"aria-label":Ht,"aria-expanded":Ie,"aria-controls":"sidebar-launch-options",children:[s.jsx(Do,{size:15}),ht&&s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)]","aria-hidden":"true"})]})]})]})]});return qe?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:pn}):s.jsx(u4,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:Ce,children:pn})}function GF(e,t,r,n,a){let c=t,l=null,d=!1;const f=e.style.width,m=document.body.style.cursor,x=document.body.style.userSelect,y=()=>n(r+c-t),w=()=>{l=null,e.style.width=`${y()}px`},v=N=>{c=N.clientX,l===null&&(l=requestAnimationFrame(w))},T=N=>{d||(d=!0,window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",S),window.removeEventListener("blur",I),l!==null&&cancelAnimationFrame(l),l=null,document.body.style.cursor=m,document.body.style.userSelect=x,N?(w(),y()!==r&&a(y())):e.style.width=f)},S=N=>{c=N.clientX,T(!0)},I=()=>T(!0);return document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",v),window.addEventListener("mouseup",S),window.addEventListener("blur",I),()=>T(!1)}function VF(){const{t:e}=Ur();return s.jsxs("div",{role:"status","aria-label":e("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[s.jsx("span",{className:"sr-only",children:e("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",className:"shrink-0 border-b border-border/15 px-3 py-2",children:[s.jsxs("div",{className:"mb-2 flex h-5 items-center gap-1",children:[s.jsx("div",{className:"h-4 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-7 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-12 rounded bg-surface-2"})]}),s.jsxs("div",{className:"flex h-[15px] items-center justify-between",children:[s.jsx("div",{className:"h-2 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-6 rounded bg-surface-2"})]}),s.jsxs("div",{className:"mt-2 flex h-7 items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-12 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-7 w-16 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-3 w-24 max-w-[30%] rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-4 rounded-full bg-surface-2"})]})]}),s.jsxs("div",{"aria-hidden":"true",className:"overflow-hidden px-3 py-2",children:[s.jsxs("div",{className:"flex h-8 items-center gap-2",children:[s.jsx("div",{className:"h-3 w-3 rounded-sm bg-surface-2"}),s.jsx("div",{className:"h-2 w-32 max-w-[55%] rounded bg-surface-2"})]}),["w-3/5","w-2/5","w-1/2","w-1/3"].map((t,r)=>s.jsxs("div",{className:"flex h-9 items-center gap-2 pl-5",style:{opacity:1-r*.15},children:[s.jsx("div",{className:"h-3 w-3 shrink-0 rounded-sm bg-surface-2"}),s.jsx("div",{className:`h-2 rounded bg-surface-2 ${t}`})]},t))]})]})}function qF({slow:e=!1}){const{t}=Ur();return s.jsxs("div",{role:"status","aria-label":t("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton relative h-full min-h-0 overflow-hidden bg-surface px-3",children:[s.jsx("span",{className:"sr-only",children:t("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",children:[s.jsxs("div",{className:"flex h-[76px] items-center gap-2 border-b border-border/40 px-2",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-12 rounded bg-surface-2"})]})]}),s.jsxs("div",{className:"flex h-11 items-center gap-2 px-1 pt-3",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-12 rounded-full bg-surface-2"})]}),[!1,!0].map(r=>s.jsxs("div",{className:"border-b border-border/40 px-1 py-4",children:[s.jsxs("div",{className:"mb-2 flex h-8 items-center justify-between",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),r&&s.jsx("div",{className:"h-2 w-28 rounded bg-surface-2"})]}),s.jsx("div",{className:"h-8 w-12 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]},String(r))),s.jsx("div",{className:"flex h-[69px] items-center border-b border-border/40 px-2",children:s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"})}),s.jsxs("div",{className:"space-y-2 px-1 py-4",children:[s.jsxs("div",{className:"flex h-8 items-center justify-between",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-8 w-28 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-7 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]})]}),e&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 rounded-md bg-surface-elevated px-3 py-2 text-xs text-muted-foreground",children:t("rightSidebar.loadingGitChangesSlow")})]})}const k4=()=>Zc(()=>import("./RightSidebar-DiECnX5D.js").then(e=>e.R),__vite__mapDeps([7,1,2,3,4,5,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.RightSidebar})),YF=b.lazy(k4);function gy(e){const t=b.useRef(!1);b.useEffect(()=>{const f=navigator.connection;if(!(f?.saveData||/2g|3g/.test(f?.effectiveType??"")))return gg(()=>{k4().catch(()=>{})},3e3)},[]);const{t:r}=Ur(),n=Yt(f=>f.rootPath),a=Yt(f=>f.rightTab),c=Yt(f=>f.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(u4,{side:"right",isOpen:e.isOpen,drawerWidthPx:e.drawerWidthPx,onClose:e.onClose,onOpen:e.onOpen,pinned:e.pinned,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[s.jsxs("div",{className:"shrink-0 border-b border-border/15 bg-surface px-2 pt-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1 px-1",children:s.jsx("div",{className:"flex min-h-[1.25rem] items-baseline gap-1.5",children:s.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",children:l})})}),s.jsx("div",{"aria-hidden":"true",className:"flex items-center gap-1.5",children:[Gl,kS,Do].map((f,m)=>s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-surface-2 text-muted-foreground",children:s.jsx(f,{size:14})},m))}),s.jsx("button",{type:"button",onClick:e.onClose,"aria-label":r("common.close"),className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:s.jsx(jn,{size:14})})]}),s.jsx("div",{className:"mt-2 grid grid-cols-5 gap-0.5 rounded-md bg-surface-2 p-0.5",children:[["git",GA,"rightSidebar.tabGit"],["diff",qA,"rightSidebar.tabChanges"],["files",nu,"rightSidebar.tabFiles"],["architecture",hS,"architecture.tab"],["computer",j9,"rightSidebar.tabComputer"]].map(([f,m,x])=>s.jsxs("button",{type:"button",onClick:()=>c(f),className:`flex items-center justify-center gap-1 rounded px-2 py-1.5 text-[11px] font-medium ${a===f?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:[s.jsx(m,{size:12}),r(x)]},f))}),s.jsx("div",{className:"h-2"})]}),s.jsx("div",{className:"min-h-0 flex-1 bg-surface",children:a==="architecture"?s.jsx("div",{role:"status",className:"p-3 text-xs text-muted-foreground",children:r("architecture.loading")}):a==="computer"?s.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:r("computer.loading")}):a==="git"?s.jsx(qF,{}):s.jsx(VF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(YF,{...e})}):d}const xy=Sc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function ZF(e){let t=1,r="terminal";for(;;){let n=!1;for(const a of e.values())if(a.name===r){n=!0;break}if(!n)break;r=`terminal-${t}`,t++}return r}const KF=Sc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=j3(),a=Date.now(),c=t().sessions,l=ZF(c),d={id:n,cwd:r,sessionId:null,name:l,customName:!1,createdAt:a,lastActivity:a};return e(f=>{const m=new Map(f.sessions);return m.set(n,d),{sessions:m,activeSessionId:f.activeSessionId??n,nextSessionNumber:f.nextSessionNumber+1}}),n},closeSession:r=>{e(n=>{const a=new Map(n.sessions),c=n.activeSessionId===r;a.delete(r);let l=n.activeSessionId;if(c){const d=Array.from(a.keys());l=d.length>0?d[0]:null}return{sessions:a,activeSessionId:l}})},switchSession:r=>{e(n=>n.sessions.has(r)?{activeSessionId:r}:n)},updateSession:(r,n)=>{e(a=>{const c=a.sessions.get(r);if(!c)return a;const l=new Map(a.sessions);return l.set(r,{...c,...n,lastActivity:Date.now()}),{sessions:l}})},setTerminalSession:(r,n)=>{t().updateSession(r,{sessionId:n.sessionId})},getActiveSession:()=>{const r=t();if(r.activeSessionId)return r.sessions.get(r.activeSessionId)},getSessionCount:()=>t().sessions.size,clearAllSessions:()=>{e({sessions:new Map,activeSessionId:null,nextSessionNumber:1})}})),XF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class JF{level=6;badSince=null;goodSince=null;connectedAt=0;lastSample=-1/0;lastChange=-1/0;lastUpgrade=-1/0;upgradeAfter=0;failedProbes=0;baselineRtt=1/0;get quality(){return XF[this.level]}connected(t){this.connectedAt=t,this.badSince=this.goodSince=null,this.lastSample=-1/0}sample(t,r,n=1600){if(r-this.lastSample>2500&&(this.badSince=this.goodSince=null),this.lastSample=r,t.rttMs!==null&&(this.baselineRtt=Math.min(this.baselineRtt,t.rttMs)),r-this.connectedAt<3e3)return null;const a=t.rttMs!==null&&t.rttMs>this.baselineRtt+150,c=t.deliveryDelayMs>250||t.decodeQueue>=4||a&&t.frames>0&&t.deliveryDelayMs>100,l=t.deliveryDelayMs>800||t.decodeQueue>=8,d=t.rttMs!==null&&t.rttMs<this.baselineRtt+100&&t.deliveryDelayMs<80&&t.decodeQueue<=1;this.badSince=c?this.badSince??r:null,this.goodSince=d?this.goodSince??r:null;const f=n<=1080?7:n<=1600?9:11;if(this.badSince!==null&&r-this.badSince>=(l?1e3:2e3)&&r-this.lastChange>=(l?2e3:3e3)&&this.level>0){this.level=Math.max(0,this.level-(l?2:1));const m=r-this.lastUpgrade<2e4;this.failedProbes=m?this.failedProbes+1:0,this.upgradeAfter=r+(m?Math.min(3e4,8e3*2**(this.failedProbes-1)):5e3),this.lastUpgrade=-1/0}else if(this.goodSince!==null&&r-this.goodSince>=3e3&&r-this.lastChange>=4e3&&r>=this.upgradeAfter&&this.level<f)this.level++,this.lastUpgrade=r;else return null;return this.lastChange=r,this.badSince=this.goodSince=null,this.quality}}function e$(e,t){const r=new Map,n=a=>a.serial===t?0:a.state!=="device"?5:a.isNetwork?a.serial.startsWith("[")?3:2:1;for(const a of e){const c=a.physicalId?`physical:${a.physicalId}`:`serial:${a.serial}`,l=r.get(c);(!l||n(a)<n(l))&&r.set(c,a)}return[...r.values()]}async function du(e,t){const r=await fetch(e,{...t,headers:{"Content-Type":"application/json",Accept:"application/json",...t?.headers??{}}}),n=await r.json().catch(()=>null);if(!r.ok||!n){const a=n?.error||n?.code||`ANDROID_REQUEST_FAILED_${r.status}`;throw new Error(a)}return n}async function t$(){return du("/api/android/devices")}async function r$(e){return du("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const ap=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],H0=ap[1];function ng(e){if(!e||typeof e!="object")return H0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=ap.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return H0;const n=typeof t.maxSize=="number"?Math.max(360,Math.min(2160,Math.round(t.maxSize))):1080,a=typeof t.bitRate=="number"?Math.max(3e5,Math.min(3e7,Math.round(t.bitRate))):4e6,c=typeof t.maxFps=="number"?Math.max(0,Math.min(60,Math.round(t.maxFps))):30;return{id:"custom",maxSize:n,bitRate:a,maxFps:c}}function n$(e,t){if(e.length>128||!/^(?:[0-9a-zA-Z_.:\-]+|\[[0-9a-fA-F:.]+\]:\d{1,5})$/.test(e))throw new Error("INVALID_SERIAL");const r=new URLSearchParams;t&&(r.set("max_size",String(t.maxSize)),r.set("bit_rate",String(t.bitRate)),t.maxFps>0&&r.set("max_fps",String(t.maxFps)));const n=r.toString();return`/api/android/${e}/ws${n?`?${n}`:""}`}function Vh(e){const t={ADB_UNAVAILABLE:"本机没有可用的 adb,请先安装 Android platform-tools。",ADB_NOT_FOUND:"找不到 adb 可执行文件,可用 TERMDOCK_ADB_BIN 指定路径。",SCRCPY_NOT_FOUND:"本机没有 scrcpy,请先安装(含 scrcpy-server)。",SCRCPY_SERVER_NOT_FOUND:"找不到 scrcpy-server,可用 TERMDOCK_SCRCPY_SERVER 指定路径。",SCRCPY_VERSION_UNKNOWN:"无法读取 scrcpy 版本,请确认 scrcpy --version 可执行。",SCRCPY_CONNECT_TIMEOUT:"设备连接超时,请确认已授权 USB 调试并保持解锁。",SCRCPY_UNSUPPORTED_CODEC:"设备返回了不支持的视频编码。",INVALID_ADDRESS:"地址格式不正确,应为 ip:port。",API_NOT_ALLOWED:"当前设备权限不足:投屏需要全权服务授权。"};for(const[r,n]of Object.entries(t))if(e.includes(r))return n;return e}function s$(e){return du(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function i$(e){return du("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function a$(e){return du(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function o$(e,t){return du(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function l$(e){return du(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const c$=0,u$=1,d$=2,h$=3,f$=4,p$=5,m$=7,g$=10,x$=11,b$=16,by=17,yy=0,Xm=1,y$=2,vy=3,Jm=0,wy=1,Ay=1,Du=0xffffffffffffffffn,qh=0xfffffffffffffffen,n0={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function L4(e,t,r){e.setUint32(t,Math.max(0,Math.round(r.x))&4294967295),e.setUint32(t+4,Math.max(0,Math.round(r.y))&4294967295),e.setUint16(t+8,Math.min(65535,Math.round(r.screenWidth))),e.setUint16(t+10,Math.min(65535,Math.round(r.screenHeight)))}function v$(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,d$),d.setUint8(1,e),d.setBigUint64(2,t),L4(d,10,r),d.setUint16(22,Math.max(0,Math.min(65535,Math.round(n*65536)))),d.setUint32(24,a>>>0),d.setUint32(28,c>>>0),l}function e1(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,c$),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function w$(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,h$),L4(c,1,e);const l=d=>Math.max(-32768,Math.min(32767,Math.round(Math.max(-1,Math.min(1,d/16))*32768)));return c.setInt16(13,l(t)),c.setInt16(15,l(r)),c.setUint32(17,n>>>0),a}function A$(e){const t=new TextEncoder().encode(e);if(!t.length)return null;const r=t.subarray(0,300),n=new Uint8Array(5+r.length),a=new DataView(n.buffer);return a.setUint8(0,u$),a.setUint32(1,r.length),n.set(r,5),n}function T$(e){const t=new TextEncoder().encode(e);if(!t.length||t.length>255)return null;const r=new Uint8Array(2+t.length);return r[0]=b$,r[1]=t.length,r.set(t,2),r}function s0(e){return new Uint8Array([e])}function Ty(e){return new Uint8Array([f$,e])}function S$(e){return new Uint8Array([g$,e?1:0])}function C$(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function _$(e){const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function t1(e){return e.toString(16).padStart(2,"0")}function I4(e,t,r){for(let n=0;n+4<e.length;n++){const a=e[n]===0&&e[n+1]===0&&e[n+2]===1,l=e[n]===0&&e[n+1]===0&&e[n+2]===0&&e[n+3]===1?n+4:a?n+3:-1;if(l<0||l>=e.length)continue;if((r?e[l]>>1&63:e[l]&31)!==t){n=l-1;continue}let f=l+1;for(;f+2<e.length&&!(e[f]===0&&e[f+1]===0&&(e[f+2]===1||e[f+2]===0&&e[f+3]===1));)f++;return e.subarray(l,Math.min(e.length,f))}return null}function k$(e){const t=e?I4(e,7,!1):null;return t&&t.length>=4?`avc1.${t1(t[1])}${t1(t[2])}${t1(t[3])}`:"avc1.42e01e"}function L$(e){const t=e?I4(e,32,!0):null;if(t&&t.length>=13){const r=t[1]>>6&3,n=t[1]&31,a=t[12];return`hev1.${r}.${n}.L${a}.B0`}return"hev1.1.6.L120.B0"}class I${constructor(t,r){this.canvas=t,this.callbacks=r}canvas;callbacks;liveBitrate=!1;bitrateFailureDetail;get lastBitrateFailure(){return this.bitrateFailureDetail}bitrateRequestId=0;bitratePending=null;get supportsLiveBitrate(){return this.liveBitrate}get canSetBitrate(){return this.liveBitrate&&!this.bitratePending&&this.socket?.readyState===1}setBitrate(t){return!this.canSetBitrate||!Number.isInteger(t)||t<3e5||t>3e7?Promise.resolve(!1):new Promise(r=>{const n=++this.bitrateRequestId,a=setTimeout(()=>this.finishBitrate(!1,`BITRATE_CLIENT_TIMEOUT: requested=${t} bps; no server confirmation within 4000ms`),4e3);this.bitratePending={id:n,value:t,resolve:r,timer:a},this.send({type:"bitrate",requestId:n,bitRate:t})})}finishBitrate(t,r){const n=this.bitratePending;n&&(this.bitratePending=null,clearTimeout(n.timer),t||(this.liveBitrate=!1,this.bitrateFailureDetail=r??this.bitrateFailureDetail??"BITRATE_REASON_UNAVAILABLE: server rejected adjustment without a diagnostic",this.closedByUser||this.callbacks.onBitrateSupport?.(!1,this.bitrateFailureDetail)),n.resolve(t))}socket=null;decoder=null;configured=!1;configData=null;header=null;closedByUser=!1;failureReason=null;lastMessageAt=0;lastFrameAt=0;lastResetAt=0;heartbeat=null;statsTimer=null;stallTimer=null;pendingConfig=null;needsKeyframe=!1;frameCount=0;receivedFrames=0;decodedFrames=0;controlsSent=0;lastSeq=0;lastType="";bytesSinceSample=0;warnedUnsupported=!1;lastSampleAt=0;serial="";autoQuality=!1;pingAt=null;rttMs=null;rttAt=0;minimumFrameOffset=1/0;deliveryDelayMs=0;peakDecodeQueue=0;sampleFrames=0;get currentHeader(){return this.header}connect(t,r){this.liveBitrate=!1,this.bitrateFailureDetail=void 0,this.serial=t,this.autoQuality=r?.id==="auto",this.closedByUser=!1,this.failureReason=null,this.callbacks.onState("connecting");let n;try{n=D9(n$(t,r))}catch(a){this.reportError(a instanceof Error?a.message:"ANDROID_STREAM_FAILED");return}this.socket=n,n.onopen=()=>{this.lastMessageAt=Date.now()},n.onmessage=a=>{this.closedByUser||this.handleMessage(a.data)},n.onerror=()=>{!this.closedByUser&&!this.failureReason&&this.reportError("SCRCPY_CONNECTION_LOST")},n.onclose=a=>{if(this.finishBitrate(!1,"BITRATE_CONNECTION_CLOSED: preview connection closed"),this.liveBitrate=!1,this.teardownTimers(),this.closedByUser)this.callbacks.onState("idle");else{const c=`WebSocket close code=${a.code}${a.reason?`: ${a.reason}`:""}`;this.reportError(`${this.failureReason||"SCRCPY_CONNECTION_CLOSED"}
162
+ `:"")+Mt)}},ref:Ft,className:w?"":"rounded-xl border border-primary/20 bg-primary/5 px-3 py-3",children:[!w&&s.jsxs("h4",{className:"truncate text-[12px] font-medium text-foreground",children:[rt.name," · 发送给成员"]}),s.jsxs("div",{className:w?"space-y-2":"mt-2 space-y-2",children:[qe&&s.jsxs("div",{className:"relative z-20 flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["发送给 ",s.jsx("span",{className:"text-[9px]",children:"· 可多选"})]}),s.jsxs("details",{className:"relative",onKeyDown:K=>{K.key==="Escape"&&(K.currentTarget.removeAttribute("open"),K.currentTarget.querySelector("summary")?.focus(),K.stopPropagation())},children:[s.jsx("summary",{"aria-label":"更多协作操作",className:"flex min-h-11 min-w-11 cursor-pointer list-none items-center justify-center rounded text-muted-foreground hover:bg-surface-2 sm:min-h-8 sm:min-w-8 [&::-webkit-details-marker]:hidden",children:s.jsx(Do,{size:16})}),s.jsxs("div",{className:"absolute right-0 top-full z-30 w-44 rounded-lg border border-border/20 bg-surface-2 p-1 shadow-lg",children:[s.jsxs("button",{type:"button",className:`${Sr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),U?.(rt.id).catch(De=>oe(De instanceof Error?De.message:"无法打开看板"))},children:[s.jsx(Kc,{size:14}),"看板"]}),s.jsx("button",{type:"button","aria-expanded":st,className:`${Sr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),he(De=>!De)},children:"成员管理"}),s.jsxs("button",{type:"button","aria-label":"组设置","aria-expanded":Nt,className:`${Sr} min-h-11 w-full justify-start text-foreground hover:bg-surface-elevated`,onClick:K=>{K.currentTarget.closest("details")?.removeAttribute("open"),Xt.current=K.currentTarget,sr(!0),oe(null),te(null)},children:[s.jsx(Vu,{size:14}),"组设置"]})]})]})]}),s.jsxs("fieldset",{className:"min-w-0",children:[s.jsx("legend",{className:qe?"sr-only":"mb-1 text-[10px] text-muted-foreground",children:"接收人(可多选)"}),s.jsx("div",{className:"flex flex-wrap gap-1",children:[{id:"*",label:"全组成员"},...rt.sessionIds.map(K=>({id:K,label:(()=>{const De=cn.find(Mt=>Mt.sessionId===K);return De?$u(De,cn):void 0})()??`${K.slice(0,8)}(离线)`}))].map(({id:K,label:De})=>{const Mt=K==="*"?pe===null:pe?.includes(K)??!1,vr=S.find(Dt=>Dt.sessionId===K);return s.jsxs(rF,{label:De,disabled:K==="*"||H!==null,onRemove:()=>{lr(K)},children:[s.jsxs("button",{type:"button","aria-pressed":Mt,onClick:()=>$e(Dt=>K==="*"?null:Dt?.includes(K)?Dt.filter(Br=>Br!==K):[...Dt??[],K]),className:`${rg} min-h-9 min-w-0 gap-1 sm:min-h-7 ${Mt?"border-primary/40 bg-primary/15 text-primary":"border-border/20 bg-surface-2 text-muted-foreground hover:text-foreground"}`,children:[Mt&&s.jsx(oi,{size:12,"aria-hidden":"true",className:"shrink-0"}),s.jsx("span",{className:"break-words text-left",children:De})]}),vr&&s.jsx("button",{type:"button","aria-label":`打开 ${De} 的终端`,title:`打开 ${De} 的终端`,className:"inline-flex h-9 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-surface-2 hover:text-primary sm:h-7 sm:w-6",onClick:()=>{$(vr).catch(Dt=>oe(Dt instanceof Error?Dt.message:"无法打开会话"))},children:s.jsx(Kc,{size:12})})]},`${rt.id}:${K}`)})})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:qe?"sr-only":void 0,children:"内容"}),s.jsx("textarea",{onKeyDown:K=>{K.key==="Enter"&&(K.metaKey||K.ctrlKey)&&!K.nativeEvent.isComposing&&K.keyCode!==229&&(K.preventDefault(),Sn())},onPaste:K=>{const De=Array.from(K.clipboardData.files);De.length&&(K.preventDefault(),hn(De))},className:`${Gs} min-h-16 max-h-48 resize-y`,value:Xe,onChange:K=>wt(K.target.value),placeholder:"输入消息,可粘贴引用或文件…"})]}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3",children:[s.jsx("p",{role:"status","aria-live":"polite",title:w&&a?a:void 0,className:`min-w-0 flex-1 text-[9px] leading-relaxed ${w?"truncate":""} ${w&&a?"text-primary":"text-muted-foreground"}`,children:Kr>0?"正在准备文件路径…":w&&a?a:rt.federated?"消息由服务端后台投递,可查看送达结果;无需保持客户端在线。":"在线成员立即入队;离线成员上线后送达。"}),s.jsxs("button",{disabled:H!==null||Kr>0||!Xe.trim()||!tn.length,className:`${Sr} shrink-0 bg-primary text-primary-foreground`,title:"发送(⌘ / Ctrl + Enter)",onClick:()=>{Sn()},children:[H==="send-message"?s.jsx(vn,{size:13,className:"animate-spin"}):null,"发送"]})]})]}),s.jsxs("div",{children:[s.jsxs("details",{hidden:qe&&!st,open:qe?st:void 0,onToggle:K=>{qe&&he(K.currentTarget.open)},className:"mt-4 rounded-xl border border-border/15",children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-3 text-[11px] font-medium text-foreground",children:["管理成员、角色与删除 · ",rt.sessionIds.length," 个成员"]}),s.jsxs("section",{className:"border-t border-border/15 p-3",children:[s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h4",{className:"text-[13px] font-medium text-foreground",children:rt.name}),s.jsxs("p",{className:"mt-1 text-[10px] text-muted-foreground",children:[rt.sessionIds.length," 个成员 · 组 ID:",s.jsx("span",{className:"break-all font-mono",children:_4(rt.id)})]})]}),Ge?s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsx("button",{className:`${Sr} bg-surface-2 px-2 text-foreground`,onClick:()=>He(!1),children:"取消"}),s.jsxs("button",{disabled:H!==null,className:`${Sr} bg-destructive px-2 text-destructive-foreground`,onClick:()=>{Zr()},children:[H===`delete:${rt.id}`?s.jsx(vn,{size:13,className:"animate-spin"}):null,"确认删除"]})]}):s.jsxs("div",{className:"flex flex-wrap items-center gap-1 sm:justify-end",children:[s.jsxs("button",{className:`${Sr} px-2 text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>{Et(new Set(rt.sessionIds)),vt(rt.updatedAt);const K=!Ut;qt(K),K&&Me(Object.fromEntries(rt.sessionIds.map(De=>[De,rt.roles?.[De]??""]))),Le(!1)},children:[s.jsx(Vu,{size:13}),"管理成员"]}),s.jsxs("button",{className:`${Sr} px-2 text-primary hover:bg-primary/10`,onClick:Ss,children:[s.jsx(Ys,{size:13}),"新建 Agent"]}),s.jsx("button",{"aria-label":`删除协作组 ${rt.name}`,title:"删除协作组",disabled:H!==null,className:"rounded-lg p-2 text-muted-foreground transition hover:bg-destructive/10 hover:text-destructive",onClick:()=>{xe(rt.updatedAt),He(!0)},children:s.jsx(Ms,{size:14})})]})]}),Ge&&s.jsxs("p",{role:"alert",className:"mt-2 rounded-lg bg-destructive/10 px-3 py-2 text-[10px] leading-relaxed text-destructive",children:["将删除“",rt.name,"”协作组及其协作记录,",rt.sessionIds.length," 个成员的终端会话会保留。"]}),s.jsx("div",{className:"mt-3 grid divide-y divide-border/10 border-y border-border/10 sm:grid-cols-2 sm:divide-x sm:divide-y-0",children:rt.sessionIds.map(K=>{const De=S.find(Dt=>Dt.sessionId===K),Mt=rt.roles?.[K],vr=De?.name??K;return s.jsxs("div",{className:`flex min-w-0 items-stretch transition ${ge===K?"bg-destructive/5":"hover:bg-surface-2"}`,children:[s.jsxs("button",{disabled:!De,onClick:()=>De&&void $(De).catch(Dt=>oe(Dt instanceof Error?Dt.message:"无法打开会话")),className:"min-w-0 flex-1 px-3 py-2.5 text-left disabled:cursor-default",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${De&&["ready","shell","terminal-connected","service-reachable","working","idle","done"].includes(De.status)&&De.serviceConnected!==!1?"bg-[var(--success)]":"bg-muted-foreground"}`}),s.jsx("span",{className:"truncate text-[11px] text-foreground",children:vr}),De&&s.jsx(Ym,{session:De}),s.jsx("span",{className:"ml-auto shrink-0 text-[9px] text-muted-foreground",children:De?wf(De):"已离线"})]}),s.jsxs("span",{className:"mt-1 flex min-w-0 items-center gap-1 text-[9px] text-muted-foreground",children:[Mt?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"min-w-0 truncate font-medium text-primary/80",children:["定位:",Mt]}),s.jsx("span",{className:"shrink-0 text-muted-foreground/50",children:"·"})]}):null,De?s.jsx("span",{className:"min-w-0 truncate",children:Zm(De.currentTask)}):s.jsx("span",{className:"shrink-0",children:"重新上线后可继续接收消息"})]})]}),s.jsx("button",{"aria-label":`把 ${vr} 移出协作组`,"aria-expanded":ge===K,title:"移出协作组",disabled:H!==null,className:`mr-1 shrink-0 self-center rounded-lg p-2 transition ${ge===K?"text-destructive":"text-muted-foreground hover:bg-destructive/10 hover:text-destructive"}`,onClick:()=>Je(ge===K?null:K),children:s.jsx(Ms,{size:13})})]},K)})}),ge&&rt.sessionIds.includes(ge)&&(()=>{const K=S.find(Mt=>Mt.sessionId===ge)?.name??ge,De=H===`remove-member:${ge}`;return s.jsxs("div",{role:"group","aria-label":`确认移除成员 ${K}`,className:"flex flex-wrap items-center gap-x-3 gap-y-2 border-y border-destructive/25 bg-destructive/5 px-3 py-2.5",children:[s.jsx("p",{className:"min-w-0 flex-1 text-[10px] leading-relaxed text-destructive",children:`把“${K}”移出“${rt.name}”?移出后它不再收到这个组的消息,可以随时重新加入`}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{className:`${Sr} min-h-8 bg-surface-2 px-2 text-[10px] text-foreground`,onClick:()=>Je(null),children:"取消"}),s.jsxs("button",{disabled:H!==null,className:`${Sr} min-h-8 px-2 text-[10px] bg-destructive text-destructive-foreground`,onClick:()=>{lr(ge)},children:[De?s.jsx(vn,{size:12,className:"animate-spin"}):s.jsx(Ms,{size:12}),"移出"]})]})]})})(),Ut&&s.jsxs("div",{className:"mt-4 border-t border-border/15 pt-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"管理成员"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"暂不可用的原成员会保留,只有取消勾选才会移出;定位(角色)在每行独立保存,成员收到消息时会看到自己的定位。"})]}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["已选 ",at.size]})]}),s.jsx("div",{className:"mt-3 max-h-72 divide-y divide-border/10 overflow-y-auto border-y border-border/10",children:un.length<=1?Ye.map(Lr):un.map(K=>{const De=Jr(K.key);return s.jsxs("div",{children:[s.jsx(uy,{label:K.label,count:K.sessions.length,collapsed:De,onToggle:()=>en(K.key)}),!De&&s.jsx("div",{className:"divide-y divide-border/10",children:K.sessions.map(Lr)})]},K.key)})}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Sr} bg-surface-2 text-foreground`,onClick:()=>{qt(!1),Me({})},children:"取消"}),s.jsxs("button",{disabled:H!==null||v!=="loaded",className:`${Sr} bg-primary text-primary-foreground`,onClick:()=>{Qr()},children:[H==="save-members"?s.jsx(vn,{size:13,className:"animate-spin"}):s.jsx(oi,{size:13}),"保存成员"]})]})]}),Dr&&s.jsxs("div",{className:"mt-4 border-t border-primary/20 pt-4",children:[s.jsxs("div",{children:[s.jsx("h5",{className:"text-[11px] font-medium text-foreground",children:"创建 Agent Session"}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:"新会话启动后自动加入本组,并收到初始任务和成员信息。"})]}),s.jsx(sF,{group:rt,value:er,onChange:ot,disabled:H!==null}),s.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["Agent / Plugin",s.jsx("select",{"aria-label":"新 Agent 类型",className:Gs,disabled:!!er,value:rt.launchProfiles?.find(K=>K.id===er)?.agentSlug??At,onChange:K=>Ot(K.target.value),children:I.map(K=>s.jsxs("option",{value:K.slug,children:[K.displayName,K.isPlugin?" · Plugin":""]},K.slug))})]}),s.jsxs("label",{className:"space-y-1 text-[9px] text-muted-foreground",children:["会话名称",s.jsx("input",{"aria-label":"新 Agent 会话名称",className:Gs,value:Lt,onChange:K=>nr(K.target.value),placeholder:"留空则自动命名"})]})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["工作目录",s.jsx("input",{"aria-label":"新 Agent 工作目录",className:Gs,value:ur,onChange:K=>Rr(K.target.value),placeholder:"默认继承当前会话"})]}),s.jsxs("label",{className:"mt-2 block space-y-1 text-[9px] text-muted-foreground",children:["初始任务",s.jsx("textarea",{"aria-label":"新 Agent 初始任务",className:`${Gs} min-h-16 resize-y`,value:Gr,onChange:K=>Tt(K.target.value),placeholder:"说明它加入后要先完成什么"})]}),s.jsxs("div",{className:"mt-3 flex justify-end gap-2",children:[s.jsx("button",{className:`${Sr} bg-surface-2 text-foreground`,onClick:()=>Le(!1),children:"取消"}),s.jsxs("button",{disabled:H!==null||!At||!!er&&!rt.launchProfiles?.some(K=>K.id===er),className:`${Sr} bg-primary text-primary-foreground`,onClick:()=>{Ar()},children:[H==="spawn-agent"?s.jsx(vn,{size:13,className:"animate-spin"}):s.jsx(G0,{size:13}),"创建并加入"]})]})]})]})]},rt.id),s.jsxs("section",{className:"mt-4",children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[11px] font-medium text-foreground",children:"协作记录"}),s.jsxs("span",{className:"text-[9px] text-muted-foreground",children:[En.length," 条"]})]}),s.jsxs("div",{className:"divide-y divide-border/10 border-y border-border/10 [overflow-wrap:anywhere]",children:[En.map(K=>s.jsxs("div",{className:"px-2 py-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[9px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-primary",children:K.responseKind==="ack"?"收到确认":K.responseKind==="progress"?"进展":K.responseKind==="result"?"结果":EF(K.kind)}),s.jsx("span",{children:K.fromName}),s.jsx("span",{children:"→"}),s.jsx("span",{className:"truncate",children:K.toNames.join("、")}),s.jsx("span",{className:"ml-auto shrink-0",children:new Date(K.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),s.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-foreground",children:K.content}),s.jsx("p",{className:"mt-1 text-[9px] text-muted-foreground",children:K.status==="pending"?"已入队 · 等待投递":K.status==="failed"?"投递失败":K.status==="expired"?"消息已过期,未继续投递":K.status==="stored"?"答复已持久保存 · 供后台接收":"已写入接收方终端 · 等待接手确认"}),K.deliveryErrors.map(De=>s.jsx("p",{role:"status",className:"mt-1 text-[10px] text-destructive",children:De==="TMUX_PANE_CHANGED"?"目标会话绑定已变化,投递暂停。原消息已保留,请确认目标会话后继续。":`投递暂停:${De}。原消息已保留,请检查目标会话。`},De)),(K.task||K.failureReason)&&s.jsxs("details",{className:"mt-2 text-[10px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:"任务详情与证据"}),s.jsx("pre",{className:"mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(K.task??{failure_reason:K.failureReason},null,2)})]})]},K.key)),En.length===0&&s.jsx(OF,{text:_e?"正在加载协作记录…":"还没有消息。可以直接给成员发送说明或问题。"})]})]})]})]})]})]})}function AF({group:e,agents:t,activeSessionId:r,sessions:n,busy:a,setBusy:c,setError:l,setNotice:d,refresh:f,onClose:m}){const x=n.filter(ve=>e.sessionIds.includes(ve.sessionId)&&!ed(ve.sessionId)),[y,w]=b.useState(()=>gF(e,r&&x.some(ve=>ve.sessionId===r)?r:"")),v=b.useRef(y),[T,S]=b.useState(null),I=ve=>{const Y={...v.current,...ve};v.current=Y,xF(e.id,Y),w(Y)},{name:N,rules:P,savedName:$,savedRules:Q,rulesVersion:U,rulesMemberId:Z}=y,J=np(y),H=new TextEncoder().encode(P).length,ye=x.some(ve=>ve.sessionId===Z),oe=async()=>{if(!(a||!N.trim())){c("group-name"),l(null),d(null);try{const ve=await Wl({id:e.id,name:N.trim(),sessionIds:y.sessionIds??e.sessionIds,expectedUpdatedAt:y.updatedAt});S(null),I({savedName:ve.group.name,name:ve.group.name,updatedAt:ve.group.updatedAt,sessionIds:ve.group.sessionIds,...P===Q?{rules:ve.group.instructions?.text??"",savedRules:ve.group.instructions?.text??"",rulesVersion:ve.group.instructions?.version??""}:{}}),await f(),d("协作组名称已更新")}catch(ve){S(null),l(ve instanceof g0&&ve.status===409?"组设置已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":ve instanceof Error?ve.message:"改名失败")}finally{c(null)}}},te=async()=>{if(!(a||!ye||H>8192)){c("group-rules"),l(null),d(null);try{const ve=await h9(e.id,{sessionId:Z,text:P,expectedVersion:U});S(null),I({savedName:ve.group.name,...N===$?{name:ve.group.name}:{},updatedAt:ve.group.updatedAt,sessionIds:ve.group.sessionIds,rules:ve.group.instructions?.text??"",savedRules:ve.group.instructions?.text??"",rulesVersion:ve.group.instructions?.version??""}),await f(),d(P.trim()?"群规已保存,变更通知已入队":"群规已清空,变更通知已入队")}catch(ve){S(null),l(ve instanceof g0&&ve.status===409?"群规已被其他人修改。请查看最新状态并确认,名称与群规草稿仍保留。":ve instanceof Error?ve.message:"群规保存失败")}finally{c(null)}}},Ce=()=>{I(ix(e,Z)),S(null),l(null)},qe=async()=>{if(!a){c("group-latest"),l(null),d(null),S(null);try{const Y=(await lg()).groups.find(st=>st.id===e.id);if(!Y)throw new Error("协作组已删除;草稿仍保留,请返回看板查看。");S(Y)}catch(ve){l(ve instanceof Error?ve.message:"最新状态读取失败;草稿仍保留,请重试。")}finally{c(null)}}};return s.jsxs("section",{"aria-label":"协作组设置",onKeyDown:ve=>{ve.key!=="Escape"||ve.defaultPrevented||ve.nativeEvent.isComposing||(ve.preventDefault(),ve.stopPropagation(),a||m())},className:"mt-3 rounded-xl border border-border/20 bg-surface-2 p-3",children:[s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[s.jsx("h4",{className:"text-[12px] font-medium text-foreground",children:"组设置"}),s.jsx("button",{type:"button",disabled:!!a,"aria-label":"关闭组设置",className:"rounded-lg p-2 text-muted-foreground hover:bg-surface-elevated",onClick:m,children:s.jsx(jn,{size:14})})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,className:Gs,value:N,maxLength:240,disabled:!!a,onChange:ve=>I({name:ve.target.value})})]}),s.jsx("div",{className:"mt-2 flex justify-end",children:s.jsx("button",{type:"button",disabled:!!a||!!T||!N.trim()||N.trim()===$,className:`${Sr} min-h-9 bg-primary text-primary-foreground`,onClick:()=>{oe()},children:a==="group-name"?"保存中…":"保存名称"})}),s.jsx(iF,{group:e,agents:t,busy:a,setBusy:c,refresh:f}),s.jsxs("div",{className:"mt-3 space-y-2 border-t border-border/15 pt-3",children:[s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["由本组成员发布群规变更",s.jsxs("select",{className:Gs,value:Z,disabled:!!a||!x.length,onChange:ve=>I({rulesMemberId:ve.target.value}),children:[s.jsx("option",{value:"",children:"选择当前服务的一个成员"}),!x.some(ve=>ve.sessionId===Z)&&Z&&s.jsx("option",{value:Z,children:"原成员已不在组内,请重新选择"}),x.map(ve=>s.jsx("option",{value:ve.sessionId,children:ve.name},ve.sessionId))]})]}),s.jsxs("label",{className:"block space-y-1 text-[10px] text-muted-foreground",children:["群规与协作约定",s.jsx("textarea",{className:`${Gs} min-h-24 resize-y`,value:P,maxLength:8192,disabled:!!a,onChange:ve=>I({rules:ve.target.value}),placeholder:"例如:说明分工、交接要求和结果格式。清空后保存可移除群规。"})]})]}),!ye&&s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x.length?"选择发布变更的成员后即可保存,不需要关闭工作台。":"当前服务没有本组成员,请先添加成员或切换到成员所在的服务。已有群规可在此查看。"}),s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[s.jsx("p",{className:`text-[9px] ${H>8192?"text-destructive":"text-muted-foreground"}`,children:H>8192?"内容过长,请缩短群规":"保存或清空群规会通知本组其他成员"}),s.jsx("button",{type:"button",disabled:!!a||!!T||!ye||H>8192||P===Q,className:`${Sr} min-h-9 shrink-0 bg-primary text-primary-foreground`,onClick:()=>{te()},children:a==="group-rules"?"保存中…":P.trim()?"保存群规":"清空群规"})]}),J&&s.jsx("p",{role:"status",className:"mt-3 text-[11px] leading-5 text-muted-foreground",children:"有未保存修改。关闭、Escape 或切换组后,草稿仍保留在本标签页;名称与群规需分别保存。"}),J&&s.jsx("button",{type:"button",disabled:!!a,className:`${Sr} mt-2 min-h-11 text-primary hover:bg-surface-elevated`,onClick:()=>{qe()},children:a==="group-latest"?"读取中…":"查看最新状态并保留草稿"}),T&&s.jsxs("section",{"aria-label":"最新组设置",className:"mt-3 space-y-2 rounded-lg bg-surface p-3 text-[11px] leading-5",children:[s.jsx("p",{className:"font-medium text-foreground",children:"确认最新状态后,再分别保存草稿"}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前名称:",T.name]}),s.jsxs("p",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:["当前群规:",T.instructions?.text||"未设置"]}),s.jsxs("p",{className:"break-words text-muted-foreground",children:["当前成员(",T.sessionIds.length,"):",T.sessionIds.map(ve=>n.find(Y=>Y.sessionId===ve)?.name??_4(ve)).join("、")||"暂无成员"]}),s.jsx("p",{className:"text-muted-foreground",children:"保留你的未保存内容;名称保存将保留以上成员,群规保存会通知当前成员。再次发生修改时仍会检查冲突。"}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",disabled:!!a,className:`${Sr} min-h-11 bg-primary text-primary-foreground`,onClick:()=>{I(mF(v.current,T)),S(null),l(null),d("已确认最新状态,草稿仍保留;请分别保存名称与群规。")},children:"确认最新状态,保留草稿"}),s.jsx("button",{type:"button",className:`${Sr} min-h-11 text-muted-foreground`,onClick:()=>S(null),children:"取消确认"})]})]}),s.jsxs("div",{className:"mt-3 flex justify-between gap-2 border-t border-border/15 pt-2",children:[s.jsxs("button",{type:"button",disabled:!!a,className:`${Sr} min-h-9 text-muted-foreground hover:bg-surface-elevated`,onClick:Ce,children:[s.jsx(vn,{size:12}),"重新载入",J&&"(放弃草稿)"]}),s.jsx("button",{type:"button",disabled:!!a,className:`${Sr} min-h-9 bg-surface text-foreground`,onClick:m,children:J?"关闭并保留草稿":"关闭"})]})]})}function TF({peers:e,currentGroupId:t,busy:r,setBusy:n,setError:a,setNotice:c,onSelectGroup:l}){const[d,f]=b.useState(null),[m,x]=b.useState(!1),y=e.services??[],w=e.removedServices??[],v=y.filter(I=>!I.connected),T=v.some(I=>I.groups?.some(N=>N.id===t)),S=async(I,N)=>{if(!r){n(`peer:${I}`),a(null),c(null);try{N?await b9(I):await y9(I),f(null),x(!1),c(N?"协作连接已恢复,正在连接服务":"协作连接已移除,不会再自动重连;已有会话和消息保留")}catch(P){a(P instanceof Error?P.message:N?"重新连接失败":"移除连接失败")}finally{n(null)}}};return s.jsxs("details",{className:"mt-4 shrink-0 rounded-lg border border-border/15",open:T||void 0,children:[s.jsxs("summary",{className:"cursor-pointer px-3 py-2.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{className:"font-medium text-foreground",children:"协作连接与管理"}),s.jsx("span",{className:"ml-2",children:e.state==="loading"?"正在加载…":`${y.length-v.length} 个已连接${v.length?` · ${v.length} 个离线`:""}`})]}),s.jsxs("div",{className:"max-h-64 overflow-y-auto border-t border-border/15 px-3 py-2",children:[y.length>0&&s.jsx("p",{className:"mb-1 text-[10px] leading-relaxed text-muted-foreground",children:"与以下服务进行跨服务协作,名称与服务切换器一致。"}),v.length>0&&s.jsx("p",{className:"mb-2 text-[10px] leading-relaxed text-muted-foreground",children:T?"当前协作组的部分服务不可达,消息会保留并等待重连。":"其他服务暂时离线;当前服务内的协作可以继续。不再使用的连接可移除。"}),e.error&&s.jsx("p",{role:"status",className:"mb-2 break-words text-[10px] text-destructive",children:e.error}),e.state==="unsupported"&&s.jsx("p",{className:"mb-2 text-[10px] text-muted-foreground",children:"请更新客户端以管理跨服务连接。"}),s.jsx("div",{className:"divide-y divide-border/10",children:y.map(I=>s.jsxs("div",{className:"py-2.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[Ac({serviceLabel:I.label,serviceOrigin:I.origin}),s.jsx("span",{className:`ml-2 text-[9px] ${I.connected?"text-[var(--success)]":"text-muted-foreground"}`,children:I.connected?"已连接":I.error==="CONNECTING"?"连接中":"暂时离线"})]}),s.jsx(SF,{service:I})]}),I.serviceId&&s.jsxs("button",{type:"button",disabled:!!r,"aria-label":`移除协作连接 ${I.origin}`,className:`${Sr} min-h-9 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,onClick:()=>f(d===I.serviceId?null:I.serviceId),children:[s.jsx(Ms,{size:12}),"移除"]})]}),!!I.groups?.length&&s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 text-[9px] text-muted-foreground",children:[s.jsx("span",{children:"用于"}),I.groups.map(N=>s.jsx("button",{type:"button",className:"rounded px-1.5 py-1 text-primary hover:bg-primary/10",onClick:()=>l(N.id),children:N.name},N.id))]}),!I.connected&&I.error&&I.error!=="CONNECTING"&&s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"cursor-pointer",children:RF(I.error)}),s.jsx("p",{className:"mt-1 select-text break-words",children:I.error})]}),d===I.serviceId&&s.jsxs("div",{role:"group","aria-label":"确认移除协作连接",className:"mt-2 rounded-lg bg-surface-2 p-2.5",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-foreground",children:I.groups?.length?"请先处理上方协作组的成员,再移除这条连接。":"移除后停止与该服务协作,保留已有会话和消息;以后可重新连接。"}),s.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:!!r,className:`${Sr} min-h-9 text-muted-foreground`,onClick:()=>f(null),children:"取消"}),s.jsx("button",{type:"button",disabled:!!r||!!I.groups?.length,className:`${Sr} min-h-9 bg-destructive text-destructive-foreground`,onClick:()=>{S(I.serviceId,!1)},children:r===`peer:${I.serviceId}`?"正在移除…":"确认移除"})]})]})]},I.serviceId||I.origin))}),y.length===0&&e.state==="ready"&&s.jsx("p",{className:"py-2 text-[10px] text-muted-foreground",children:"当前没有其他协作服务,当前服务内仍可创建协作组。"}),v.length>0&&s.jsxs("button",{type:"button",className:`${Sr} mt-1 min-h-9 text-primary hover:bg-primary/10`,onClick:x9,children:[s.jsx(vn,{size:12}),"重试连接"]}),w.length>0&&s.jsxs("div",{className:"mt-2 border-t border-border/15 pt-1",children:[s.jsx("button",{type:"button","aria-expanded":m,className:`${Sr} min-h-9 text-muted-foreground hover:bg-surface-2`,onClick:()=>x(I=>!I),children:m?"收起恢复列表":"恢复已移除连接"}),m&&s.jsxs("section",{"aria-label":"恢复已移除连接",className:"mt-1 rounded-lg bg-surface-2 px-2.5 py-2",children:[s.jsx("p",{className:"text-[10px] leading-relaxed text-muted-foreground",children:"以下是恢复记录,连接已停用,不会自动重连。点击恢复后才会重新启用协作。"}),s.jsx("div",{className:"mt-1 divide-y divide-border/10",children:w.map(I=>s.jsxs("div",{className:"flex items-start gap-2 py-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"break-words text-[10px] text-foreground",children:[Ac({serviceLabel:I.label,serviceOrigin:I.origin}),s.jsx("span",{className:"ml-2 text-[9px] text-muted-foreground",children:"已停用"})]}),s.jsx("p",{className:"mt-0.5 select-text break-all text-[9px] text-muted-foreground",children:I.accessUrl||I.origin})]}),s.jsx("button",{type:"button",disabled:!!r||!I.serviceId,className:`${Sr} min-h-9 shrink-0 text-primary hover:bg-primary/10`,onClick:()=>{S(I.serviceId,!0)},children:r===`peer:${I.serviceId}`?"恢复中…":"恢复连接"})]},I.serviceId||I.origin))})]})]})]})]},T?"affected":"other")}function SF({service:e}){let t=!1;try{t=["localhost","127.0.0.1","[::1]"].includes(new URL(e.origin).hostname)}catch{}const r=e.accessUrl||(t?"":e.origin);return s.jsxs("details",{className:"mt-1 text-[9px] text-muted-foreground",children:[s.jsx("summary",{className:"w-fit cursor-pointer py-1",children:"连接详情"}),s.jsxs("dl",{className:"mt-1 space-y-1 select-text break-all",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务地址:"}),s.jsx("dd",{className:"inline",children:r||"暂未获取,请在服务切换器中查看"})]}),e.serviceId&&s.jsxs("div",{children:[s.jsx("dt",{className:"inline",children:"服务身份:"}),s.jsx("dd",{className:"inline",children:e.serviceId})]})]})]})}function qm(e){return!ed(e.sessionId)||e.serviceConnected!==!1}function CF(e){return e.serviceOrigin?e.serviceOrigin===window.location.origin?"":e.serviceOrigin:ed(e.sessionId)?.origin??""}function cy(e){const t=new Map;for(const r of e){const n=CF(r),a=t.get(n)??{key:n,label:n?Ac(r):"本机服务",sessions:[]};n&&a.label==="远端服务"&&(a.label=Ac(r)),a.sessions.push(r),t.set(n,a)}return[...t.values()].sort((r,n)=>(r.key?1:0)-(n.key?1:0)||r.label.localeCompare(n.label))}function uy({label:e,count:t,collapsed:r,onToggle:n}){return s.jsxs("button",{type:"button","aria-expanded":!r,onClick:n,className:"flex w-full items-center gap-1.5 bg-surface-2/50 px-2 py-1.5 text-left text-muted-foreground transition hover:bg-surface-elevated",children:[s.jsx(Al,{size:12,className:`shrink-0 transition-transform ${r?"-rotate-90":""}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[10px] font-semibold uppercase tracking-wide",children:e}),s.jsx("span",{className:"shrink-0 text-[9px] text-muted-foreground/70",children:t})]})}function _F(e,t){const r=new Map(t.map(n=>[n.sessionId,n]));for(const n of e?.sessionIds??[]){if(r.has(n))continue;const a=e?.remoteSessions?.find(c=>c.sessionId===n);r.set(n,a?{...a,status:"offline",serviceConnected:!1}:{sessionId:n,name:n,backendSessionId:null,cwd:"",agent:null,status:"offline",capability:"",currentTask:"暂不可用,保留成员身份",updatedAt:0,...ed(n)?{serviceConnected:!1}:{}})}return[...r.values()]}function Ym({session:e}){return!e.serviceOrigin||e.serviceOrigin===window.location.origin?null:s.jsxs("span",{className:"inline-flex max-w-28 shrink-0 items-center gap-1 rounded border border-border/20 px-1 py-0.5 text-[9px] text-muted-foreground",children:[s.jsx(Kc,{size:9}),s.jsx("span",{className:"truncate",children:Ac(e)})]})}function wf(e){return e.serviceConnected===!1?"服务不可达":e.status==="recovering"&&e.route_error==="ROUTE_NOT_CHECKED"?"投递目标未检查":IF(e.status)}function kF(e,t=[]){if(!e)return;const r=t.some(a=>a.sessionId!==e.sessionId&&a.name.trim()===e.name.trim()),n=e.sessionId.startsWith("remote:")?Ac(e):"本机服务";return r?`${e.name} · ${n}`:e.name}async function LF(e){e.sessionId.startsWith("remote:")?await K6(e.sessionId):window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:e.sessionId}))}function IF(e){return{ready:"终端可达",shell:"Shell 终端",recovering:"正在检查投递目标",unchecked:"投递目标未检查","terminal-connected":"终端已连接",detached:"终端未连接","agent-exited":"Agent 已退出",offline:"已离线",ambiguous:"需确认目标终端","identity-mismatch":"终端身份已变化",unavailable:"终端暂不可达","service-reachable":"服务可达","service-unreachable":"服务不可达"}[e]??"在线"}function Zm(e){if(!e)return"暂无任务摘要";try{const t=JSON.parse(e);if(typeof t.prompt=="string")return sp(t.prompt)||"暂无任务摘要"}catch{}return sp(e)||"暂无任务摘要"}function EF(e){return{message:"消息",ask:"问题",reply:"回复",task:"任务",handoff:"交接",done:"完成"}[e]}function NF(e,t){const r=new Map(t.map(a=>[a.sessionId,kF(a,t)])),n=new Map;for(const a of e){const c=`${a.threadId}:${a.createdAt}:${a.fromSessionId??a.integrationOrigin?.integrationId??"user"}:${a.kind}:${a.responseKind??""}:${JSON.stringify(a.task??null)}:${a.content}`,l=n.get(c),d=a.toPrincipalId?`后台接入 ${a.toPrincipalId}`:r.get(a.toSessionId)??a.toSessionId.slice(0,8);if(l){l.toNames.push(d),a.delivery?.stage==="blocked"&&a.delivery.error&&!l.deliveryErrors.includes(a.delivery.error)&&l.deliveryErrors.push(a.delivery.error);const f={failed:-2,expired:-1,pending:0,delivered:1,read:2,stored:3};f[a.status]<f[l.status]&&(l.status=a.status);continue}n.set(c,{key:c,kind:a.kind,content:a.content,createdAt:a.createdAt,fromName:a.fromSessionId?r.get(a.fromSessionId)??a.fromSessionId.slice(0,8):a.integrationOrigin?`后台接入 ${a.integrationOrigin.integrationId}`:"你",toNames:[d],status:a.status,responseKind:a.responseKind,task:a.task,failureReason:a.failureReason,deliveryErrors:a.delivery?.stage==="blocked"&&a.delivery.error?[a.delivery.error]:[]})}return[...n.values()].sort((a,c)=>c.createdAt-a.createdAt)}function RF(e){return/timeout|timed out|超时|operation was aborted/i.test(e)?"连接超时,暂时无法访问该服务。请确认远端服务已启动,并检查网络或 VPN 连接。":/ECONNREFUSED|connection refused/i.test(e)?"远端拒绝连接,请确认服务已启动且端口正确。":/ENOTFOUND|EHOSTUNREACH|ENETUNREACH/i.test(e)?"无法访问远端地址,请检查地址和网络连接。":/certificate|fingerprint|TLS|证书/i.test(e)?"远端证书校验失败,请检查服务连接授权。":"服务连接暂时不可用,可查看连接详情并重试。"}function Km({value:e,query:t}){const r=t.trim().toLocaleLowerCase();if(!r)return s.jsx(s.Fragment,{children:e});const n=e.toLocaleLowerCase(),a=[];let c=0,l;for(;(l=n.indexOf(r,c))>=0;)a.push(e.slice(c,l)),a.push(s.jsx("mark",{className:"rounded bg-primary/15 text-primary",children:e.slice(l,l+r.length)},l)),c=l+r.length;return a.push(e.slice(c)),s.jsx(s.Fragment,{children:a})}function MF({active:e,onClose:t,onNewSession:r,setError:n}){const[a,c]=b.useState(""),[l,d]=b.useState([]),[f,m]=b.useState(0),[x,y]=b.useState(),[w,v]=b.useState(50),[T,S]=b.useState(0),[I,N]=b.useState(!1),[P,$]=b.useState(null),[Q,U]=b.useState(null),Z=b.useRef(null),J=b.useRef(0);b.useEffect(()=>{e&&Z.current?.focus({preventScroll:!0})},[e]),b.useEffect(()=>{if(!e)return;const oe=++J.current,te=new AbortController;let Ce;$(null),N(!0);const qe=async()=>{try{const ve=await v9(a.trim(),w,te.signal);if(oe!==J.current)return;d(ve.results),m(ve.total??ve.results.length),y(ve.index),ve.index?.building&&(Ce=window.setTimeout(()=>{qe()},2500))}catch(ve){oe===J.current&&!te.signal.aborted&&$(ve instanceof Error?ve.message:"搜索失败")}finally{oe===J.current&&N(!1)}};return Ce=window.setTimeout(()=>{qe()},a.trim()?250:0),()=>{window.clearTimeout(Ce),te.abort(),++J.current}},[e,a,w,T]);const H=oe=>{n(null),c(oe),d([]),m(0),v(50)},ye=async oe=>{if(!Q){if(oe.live){window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:oe.sessionId})),t();return}if(!(!oe.nativeKey&&!oe.resumeHistoryId)){U(oe.sessionId),n(null);try{const te=oe.nativeKey?await w9(oe.nativeKey):await c3(oe.resumeHistoryId);if("sessionId"in te&&te.sessionId)window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:te.sessionId}));else if(te.command)r({mode:"shell",cwd:te.cwd,command:te.command});else throw new Error("这条会话暂时无法恢复,请重新搜索");t()}catch(te){n(te instanceof Error?te.message:"恢复失败")}finally{U(null)}}}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky -top-4 z-20 -mx-4 -mt-4 border-b border-border/15 bg-surface px-4 py-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-[13px] font-medium text-foreground",children:"历史会话搜索"}),s.jsx("p",{className:"mt-1 text-[10px] leading-relaxed text-muted-foreground",children:"搜索当前服务的 Codex、Claude 历史对话和 Termdock 终端记录,未启动的会话也能找到并恢复。"})]}),s.jsxs("label",{className:"relative mt-3 block",children:[s.jsx("span",{className:"sr-only",children:"搜索历史会话"}),s.jsx(Gl,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:Z,maxLength:512,className:`${Gs} pl-9 pr-9`,value:a,onChange:oe=>H(oe.target.value),placeholder:"搜索会话名称、对话关键词、目录或 session ID"}),I?s.jsx(vn,{size:13,className:"absolute right-3 top-1/2 -translate-y-1/2 animate-spin text-muted-foreground"}):a&&s.jsx("button",{type:"button","aria-label":"清空搜索",className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded-md p-1.5 text-muted-foreground hover:bg-surface-2 hover:text-foreground",onClick:()=>H(""),children:s.jsx(jn,{size:13})})]}),x?.building&&s.jsxs("div",{role:"status",className:"mt-2 text-[10px] text-muted-foreground",children:["正在建立历史索引:",x.indexed,"/",x.total," 个会话。可以先搜名称和目录,对话结果会自动补齐。"]}),x?.warning&&s.jsx("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:x.warning}),!!x?.failed&&s.jsxs("p",{role:"status",className:"mt-2 text-[10px] text-destructive",children:[x.failed," 个会话暂未完成索引,其余结果可正常使用。请稍后刷新重试。"]})]}),s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("p",{className:"text-[11px] text-foreground",children:[a.trim()?`找到 ${f} 个会话`:"最近的会话",f>l.length?` · 显示 ${l.length} 个`:""]}),s.jsxs("button",{type:"button",disabled:I,className:`${Sr} text-muted-foreground hover:bg-surface-2 hover:text-foreground`,onClick:()=>S(oe=>oe+1),children:[s.jsx(vn,{size:12}),"刷新"]})]}),!a.trim()&&s.jsx("p",{className:"text-[10px] text-muted-foreground",children:"记得之前讨论过什么?输入一句话中的关键词,就能找到对应会话。历史对话与索引保存在当前服务机器上。"}),s.jsx("div",{className:"divide-y divide-border/10 border-y border-border/10",children:l.map(oe=>{const te=oe.live||!!(oe.nativeKey||oe.resumeHistoryId),Ce=Q===oe.sessionId?"正在恢复…":oe.live?"打开会话":te?"恢复会话":"仅供查阅",qe=oe.source==="codex"||oe.source==="claude"?oe.snippet:jF(oe),ve=oe.source==="codex"?"Codex 历史":oe.source==="claude"?"Claude 历史":"终端记录",Y=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"break-words text-[12px] font-medium text-foreground",children:s.jsx(Km,{value:oe.title,query:a})}),s.jsx("p",{className:"mt-0.5 break-all text-[9px] text-muted-foreground",children:s.jsx(Km,{value:oe.cwd||"项目目录待索引",query:a})})]}),s.jsx("span",{className:`shrink-0 text-[10px] ${oe.live?"text-[var(--success)]":te?"text-primary":"text-muted-foreground"}`,children:Ce})]}),qe&&s.jsx("p",{className:"mt-2 line-clamp-3 break-words text-[10px] leading-relaxed text-foreground/75",children:s.jsx(Km,{value:qe,query:a})}),s.jsxs("p",{className:"mt-2 text-[9px] text-muted-foreground",children:[ve," · ",ip(oe.updatedAt),a.trim()?` · ${oe.matchCount>=999?"999+":oe.matchCount} 处匹配`:"",te?"":" · 没有可恢复记录"]}),oe.agentNativeSessionId&&s.jsx("p",{className:"mt-1 select-text break-all text-[9px] text-muted-foreground",children:oe.agentNativeSessionId})]});return te?s.jsx("button",{disabled:!!Q,onClick:()=>{ye(oe)},className:"block w-full px-2 py-3 text-left transition hover:bg-surface-2 focus-visible:bg-surface-2 focus-visible:outline-none",children:Y},oe.nativeKey||oe.sessionId):s.jsx("article",{className:"px-2 py-3",children:Y},oe.sessionId)})}),f>l.length&&w<5e3&&s.jsx("button",{type:"button",disabled:I,className:`${Sr} w-full bg-surface-2 text-foreground`,onClick:()=>v(oe=>oe+50),children:I?"正在加载…":"加载更多会话"}),P&&s.jsxs("div",{role:"alert",className:"rounded-lg bg-destructive/10 p-3 text-[11px] text-destructive",children:["搜索失败:",P,s.jsx("button",{type:"button",className:`${Sr} ml-2`,onClick:()=>S(oe=>oe+1),children:"重试"})]}),!I&&!P&&l.length===0&&s.jsxs("div",{className:"border-y border-border/15 py-8 text-center",children:[s.jsx("p",{className:"text-[12px] text-foreground",children:x?.building?"历史对话仍在索引,请稍候":x?.warning||x?.failed?"暂未找到结果,部分历史记录尚不可搜索":a.trim()?`没有找到“${a.trim()}”`:"当前服务还没有可搜索的历史会话"}),s.jsx("p",{className:"mt-1 text-[10px] text-muted-foreground",children:x?.building?"新结果会自动显示,也可以先搜会话名称或目录。":"可尝试更短的关键词、项目目录或 session ID;其他机器的历史需切换到对应服务搜索。"}),a.trim()&&s.jsx("button",{className:`${Sr} mt-3 bg-surface-2 text-foreground`,onClick:()=>H(""),children:"查看最近会话"})]})]})}function sp(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g," ").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g," ").replace(/\(B/g," ").replace(/<[^>]{1,120}>/g," ").replace(/[─━│┃┄┅┆┇┈┉┊┋┌┐└┘├┤┬┴┼╭╮╯╰═║╔╗╚╝╠╣╦╩╬]+/g," ").replace(/([^\p{L}\p{N}\s])\1{3,}/gu," ").replace(/([A-Za-z])\1{12,}/g," ").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g," ").replace(/\s+/g," ").trim().slice(0,280)}function jF(e){let t=sp(e.snippet);for(const r of[e.title,e.cwd,e.agentSlug])r&&(t=t.split(r).join(" "));return sp(t)}function DF(e){if(e.schedule.kind==="interval")return e.schedule.everyMinutes===60?"每小时":e.schedule.everyMinutes===1440?"每天":`每 ${e.schedule.everyMinutes} 分钟`;const t=["日","一","二","三","四","五","六"];return`${e.schedule.weekdays.length===7?"每天":e.schedule.weekdays.map(n=>`周${t[n]}`).join("、")} ${e.schedule.time}`}function BF(e,t=Date.now(),r=t){if(e.kind==="interval"){const c=e.everyMinutes*6e4,l=Math.max(0,t-r);return r+(Math.floor(l/c)+1)*c}const[n,a]=e.time.split(":").map(Number);for(let c=0;c<=7;c+=1){const l=new Date(t);if(l.setDate(l.getDate()+c),l.setHours(n,a,0,0),l.getTime()>t&&e.weekdays.includes(l.getDay()))return l.getTime()}return t}function ip(e){return new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)}function QF(e){return e==="running"?"投递中":e==="success"?"已投递":e==="failed"?"投递失败":""}function PF(e){return e==="running"?"text-[var(--warning)]":e==="success"?"text-[var(--success)]":e==="failed"?"text-destructive":"text-muted-foreground"}function OF({text:e}){return s.jsx("div",{className:"rounded-xl border border-dashed border-border/20 px-4 py-8 text-center text-[11px] text-muted-foreground",children:e})}const e0=64,dy=10,FF=120;function $F({children:e,open:t,onOpenChange:r,onClose:n,closeLabel:a,closeTitle:c,compact:l}){const d=b.useRef(null),f=b.useRef(null),m=b.useRef(0),[x,y]=b.useState(null),w=x??(t?e0:0);return b.useEffect(()=>{if(!t)return;const v=T=>{T.target instanceof Node&&!d.current?.contains(T.target)&&r(!1)};return document.addEventListener("pointerdown",v,!0),()=>document.removeEventListener("pointerdown",v,!0)},[t,r]),s.jsxs("div",{ref:d,"data-sidebar-gesture-ignore":!0,"data-session-swipe":!0,className:`relative flex min-w-0 flex-1 items-center ${l?"":"gap-1"}`,style:{touchAction:"pan-y"},onPointerDown:v=>{if(m.current=0,!(v.pointerType!=="touch"&&v.pointerType!=="pen")){if(v.isPrimary===!1){f.current=null,y(null);return}!(v.target instanceof Element)||!v.target.closest(".sidebar-session-primary")||(f.current={pointerId:v.pointerId,x:v.clientX,y:v.clientY,startedAt:Date.now(),initialOffset:t?e0:0,offset:t?e0:0,horizontal:!1})}},onPointerMove:v=>{const T=f.current;if(!T||T.pointerId!==v.pointerId)return;const S=v.clientX-T.x,I=v.clientY-T.y;if(!T.horizontal){if(v.defaultPrevented||Date.now()-T.startedAt>=FF||Math.abs(I)>dy){f.current=null;return}if(Math.abs(S)<=dy)return;if(Math.abs(S)<Math.abs(I)*1.5||!t&&S<0){f.current=null;return}T.horizontal=!0,v.currentTarget.setPointerCapture?.(v.pointerId)}v.preventDefault(),T.offset=Math.max(0,Math.min(e0,T.initialOffset+S)),y(T.offset)},onPointerUp:v=>{const T=f.current;!T||T.pointerId!==v.pointerId||(f.current=null,T.horizontal&&(m.current=Date.now()+600,r(T.offset>=e0/2),y(null)))},onPointerCancel:()=>{f.current?.horizontal&&(m.current=Date.now()+600),f.current=null,y(null)},onClickCapture:v=>{if(Date.now()<m.current){m.current=0,v.preventDefault(),v.stopPropagation();return}t&&v.target instanceof Element&&v.target.closest(".sidebar-session-primary")&&(r(!1),v.preventDefault(),v.stopPropagation())},onKeyDown:v=>{t&&v.key==="Escape"&&(v.stopPropagation(),r(!1))},children:[s.jsx("div",{className:"shrink-0 overflow-hidden rounded-md transition-[width] duration-150 ease-out motion-reduce:transition-none",style:{width:w,transition:x===null?void 0:"none"},children:w>0&&s.jsxs("button",{type:"button",tabIndex:t?0:-1,"aria-hidden":!t,"aria-label":c,className:"flex min-h-8 w-16 flex-col items-center justify-center gap-0.5 bg-destructive py-1 text-[10px] text-destructive-foreground",onClick:v=>{v.stopPropagation(),r(!1),n(v)},children:[s.jsx(Ms,{size:14}),a]})}),e]})}const hy="recoverable-tmux";function UF({sessions:e,loading:t,attachingName:r,onRefresh:n,onRestore:a,onClose:c}){const{t:l}=Ur(),d=Yt(N=>N.collapsedGroups.has(hy)),f=Yt(N=>N.toggleGroupCollapsed),[m,x]=b.useState(null),[y,w]=b.useState(null),[v,T]=b.useState(null),S=b.useRef(!1),I=async N=>{if(!(!c||S.current)){S.current=!0,w(N),T(null);try{await c(N),x(null)}catch(P){T(P instanceof Error?P.message:l("sidebar.closeRecoverableSessionFailed"))}finally{S.current=!1,w(null)}}};return e.length===0?null:s.jsxs("section",{className:"mb-2 shrink-0 rounded-lg bg-[rgb(var(--tmux-rgb)_/_0.07)] p-1","aria-label":l("sidebar.recoverableSessions"),children:[s.jsxs("div",{className:"flex items-center gap-1 text-[10.5px] font-semibold text-[color:var(--tmux)]",children:[s.jsxs("button",{type:"button","aria-expanded":!d,onClick:()=>f(hy),className:"flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left hover:bg-surface-elevated md:min-h-8",children:[s.jsx(qs,{size:12,className:`shrink-0 ${d?"":"rotate-90"}`}),s.jsx(qc,{size:12,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:l("sidebar.recoverableSessions")}),s.jsx("span",{className:"text-muted-foreground",children:e.length})]}),n&&s.jsx("button",{type:"button",onClick:n,disabled:t||y!==null,className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.refreshRecoverableSessions"),title:l("sidebar.refreshRecoverableSessions"),children:s.jsx(vn,{size:11,className:t?"animate-spin":""})})]}),!d&&s.jsx("div",{className:"space-y-0.5",children:e.map(N=>{const P=N.friendlyName?.trim()||N.label?.trim()||N.name,$=ld(N.cwd??null),Q=r===N.name,U=m===N.name;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex min-w-0 items-center",children:[s.jsxs("button",{type:"button",disabled:r!==null||y!==null||U,onClick:()=>a(N),className:"group flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-60 md:min-h-10","aria-label":l("sidebar.restoreRecoverableSession",{name:P}),title:N.cwd||N.name,children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--tmux-rgb)_/_0.11)] text-[color:var(--tmux)]",children:Q?s.jsx(Dn,{size:12,className:"animate-spin"}):s.jsx(su,{size:12})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-[11.5px] font-semibold text-foreground",children:P}),s.jsx("span",{className:"block truncate text-[9.5px] text-muted-foreground",children:[N.program,$].filter(Boolean).join(" · ")||`tmux:${N.name}`})]}),s.jsx("span",{className:"shrink-0 text-[10px] font-medium text-[color:var(--tmux)] group-hover:text-foreground",children:l(Q?"sidebar.restoringRecoverableSession":"sidebar.restore")})]}),c&&s.jsx("button",{type:"button",disabled:r!==null||y!==null,onClick:()=>{x(N.name),T(null)},className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition hover:bg-destructive/15 hover:text-destructive disabled:opacity-50 md:h-7 md:w-7","aria-label":l("sidebar.closeSession",{name:P}),title:l("sidebar.closeSession",{name:P}),children:s.jsx(jn,{size:12})})]}),U&&s.jsxs("div",{role:"group","aria-label":l("sidebar.closeSession",{name:P}),className:"space-y-2 rounded-md bg-surface px-2 py-2",children:[s.jsx("p",{className:"text-[11px] text-foreground",children:l("sidebar.confirmCloseRecoverableSession",{name:P})}),v&&s.jsx("p",{role:"alert",className:"text-[11px] text-destructive",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{x(null),T(null)},className:"min-h-11 rounded-md px-2 text-[11px] text-muted-foreground hover:bg-surface-elevated disabled:opacity-50 md:min-h-8",children:l("common.cancel")}),s.jsx("button",{type:"button",disabled:y!==null,onClick:()=>{I(N.name)},className:"min-h-11 rounded-md bg-destructive/15 px-2 text-[11px] text-destructive hover:bg-destructive/25 disabled:opacity-50 md:min-h-8",children:y===N.name?l("common.loading"):l("sidebar.endRecoverableSession")})]})]})]},N.name)})})]})}const ju="flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-xs transition hover:bg-surface-2 focus:bg-surface-2 focus:outline-none",fy="min-h-11 rounded-lg px-4 text-xs transition disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary";function zF({group:e,collapsed:t,onOpen:r,onMessages:n,onToggleCollapsed:a,onChanged:c,children:l}){const[d,f]=b.useState(null),[m,x]=b.useState(null),[y,w]=b.useState(""),[v,T]=b.useState(!1),S=b.useRef(!1),[I,N]=b.useState(""),P=b.useRef(null),$=b.useRef(null),Q=b.useRef(null),U=b.useRef(null),Z=b.useRef(null),J=b.useId(),H=ex(),ye=()=>Z.current?.isConnected?Z.current:$.current,oe=()=>{S.current||(x(null),N(""))};vc(Q,!!d,()=>f(null),ye),vc(U,!!m,oe,ye);const te=Y=>{Z.current=document.activeElement instanceof HTMLElement&&P.current?.contains(document.activeElement)?document.activeElement:$.current;const st=$.current?.getBoundingClientRect();f(Y??{x:st?.left??8,y:st?.bottom??8})};b.useEffect(()=>{d&&Q.current?.querySelector('[role="menuitem"]')?.focus({preventScroll:!0})},[d]),b.useEffect(()=>{if(!d)return;const Y=he=>{he.target instanceof Node&&!Q.current?.contains(he.target)&&!P.current?.contains(he.target)&&f(null)},st=he=>{he.target instanceof Node&&Q.current?.contains(he.target)||f(null)};return document.addEventListener("pointerdown",Y),window.addEventListener("resize",st),window.addEventListener("scroll",st,!0),()=>{document.removeEventListener("pointerdown",Y),window.removeEventListener("resize",st),window.removeEventListener("scroll",st,!0)}},[d]),b.useLayoutEffect(()=>{if(!d||!Q.current)return;const Y=window.visualViewport,st=(Y?.offsetLeft??0)+8,he=(Y?.offsetTop??0)+8,Qe=Math.min(240,(Y?.width??innerWidth)-16),ie=he+(Y?.height??innerHeight)-16;Object.assign(Q.current.style,{width:`${Qe}px`,maxHeight:`${ie-he}px`,left:`${Math.max(st,Math.min(d.x,st+(Y?.width??innerWidth)-16-Qe))}px`,top:`${Math.max(he,Math.min(d.y,ie-Q.current.offsetHeight))}px`})},[d]);const Ce=Y=>{f(null),Y()},qe=Y=>{N(""),w(e.name),x({kind:Y,group:e})},ve=async()=>{if(!(!m||S.current||m.kind==="rename"&&!y.trim())){S.current=!0,T(!0),N("");try{const Y=m.group,st=m.kind==="delete"?(await o3(Y.id,Y.updatedAt),null):m.kind==="archive"||m.kind==="unarchive"?await T9(Y,m.kind==="archive"):(await Wl({id:Y.id,name:y.trim(),sessionIds:Y.sessionIds,expectedUpdatedAt:Y.updatedAt})).group;x(null),c(st)}catch(Y){const st=Y instanceof Error?Y.message:"操作失败,请重试";N(st.includes("协作组已变化")?"协作组刚刚发生变化,请取消后重新打开操作。":st)}finally{S.current=!1,T(!1)}}};return s.jsxs("div",{ref:P,className:"flex min-w-0 items-center","data-sidebar-gesture-ignore":!0,...H(()=>te()),onContextMenu:Y=>{Y.preventDefault(),Y.stopPropagation(),te({x:Y.clientX,y:Y.clientY})},onKeyDown:Y=>{(Y.key==="ContextMenu"||Y.shiftKey&&Y.key==="F10")&&(Y.preventDefault(),Y.stopPropagation(),te())},children:[l,s.jsx("button",{ref:$,type:"button","aria-label":`协作组操作:${e.name}`,title:"协作组操作","aria-haspopup":"menu","aria-expanded":!!d,"aria-controls":d?`${J}-menu`:void 0,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:Y=>{Y.stopPropagation(),d?f(null):te()},children:s.jsx(Do,{size:14})}),d&&Zs.createPortal(s.jsxs("div",{ref:Q,id:`${J}-menu`,role:"menu",tabIndex:-1,"aria-label":`协作组操作:${e.name}`,"data-sidebar-gesture-ignore":!0,className:"fixed z-popover overflow-y-auto overscroll-contain rounded-xl border border-border/15 bg-surface p-1 shadow-[0_12px_32px_var(--app-shadow-soft)]",onKeyDown:Y=>{const st=Array.from(Y.currentTarget.querySelectorAll('[role="menuitem"]:not(:disabled)')),he=st.indexOf(document.activeElement),Qe=Y.key==="ArrowDown"?(he+1)%st.length:Y.key==="ArrowUp"?(he-1+st.length)%st.length:Y.key==="Home"?0:Y.key==="End"?st.length-1:null;Qe!==null&&(Y.preventDefault(),Y.stopPropagation(),st[Qe]?.focus({preventScroll:!0})),Y.key==="Tab"&&(Y.preventDefault(),f(null))},children:[s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(r),children:[s.jsx(su,{size:15}),"打开看板"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,disabled:!n,className:`${ju} disabled:opacity-40`,onClick:()=>Ce(()=>n?.()),children:[s.jsx(cd,{size:15}),"成员与消息"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(a),children:[s.jsx(qs,{size:15,className:t?"":"rotate-90"}),t?"展开成员会话":"收起成员会话"]}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(()=>qe("rename")),children:[s.jsx(Vu,{size:15}),"重命名协作组"]}),!e.federated&&s.jsxs("button",{role:"menuitem",tabIndex:-1,className:ju,onClick:()=>Ce(()=>qe(e.archivedAt===void 0?"archive":"unarchive")),children:[s.jsx(Cf,{size:15}),e.archivedAt===void 0?"归档协作组":"恢复显示"]}),s.jsx("div",{role:"separator",className:"mx-2 my-1 h-px bg-border/30"}),s.jsxs("button",{role:"menuitem",tabIndex:-1,className:`${ju} text-destructive`,onClick:()=>Ce(()=>qe("delete")),children:[s.jsx(Ms,{size:15}),"删除协作组"]})]}),document.body),m&&Zs.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-modal-backdrop bg-black/50 backdrop-blur-sm",onClick:oe}),s.jsxs("section",{ref:U,role:"dialog","aria-modal":"true","aria-labelledby":`${J}-title`,"aria-describedby":`${J}-description`,tabIndex:-1,className:"fixed left-1/2 top-1/2 z-modal-panel max-h-[calc(100dvh-2rem)] w-[min(24rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-border/15 bg-surface p-4 text-foreground shadow-[0_28px_70px_var(--app-shadow-strong)]",children:[s.jsxs("header",{className:"flex items-center gap-2",children:[s.jsx("h2",{id:`${J}-title`,className:"min-w-0 flex-1 text-sm font-semibold",children:m.kind==="delete"?"删除协作组":m.kind==="archive"?"归档协作组":m.kind==="unarchive"?"恢复协作组显示":"重命名协作组"}),s.jsx("button",{type:"button","aria-label":"关闭协作组操作",disabled:v,className:"flex h-11 w-11 items-center justify-center rounded-lg hover:bg-surface-2",onClick:oe,children:s.jsx(jn,{size:16})})]}),s.jsx("p",{id:`${J}-description`,className:"my-3 break-words text-xs leading-6 text-muted-foreground",children:m.kind==="delete"?s.jsxs(s.Fragment,{children:["确定删除“",m.group.name,"”?协作组及组内消息会被移除,成员终端会保留。此操作无法撤销。",m.group.federated&&"删除会同步到其他服务。"]}):m.kind==="archive"?s.jsxs(s.Fragment,{children:["归档“",m.group.name,"”后,它会从默认侧栏隐藏。组、成员、消息和历史都会保留,之后可以恢复显示。"]}):m.kind==="unarchive"?s.jsxs(s.Fragment,{children:["恢复“",m.group.name,"”的显示后,它会重新出现在侧栏;不会自动恢复已关闭的会话。"]}):"修改协作组的名称。"}),s.jsxs("form",{onSubmit:Y=>{Y.preventDefault(),ve()},children:[m.kind==="rename"&&s.jsxs("label",{className:"block text-xs text-muted-foreground",children:["协作组名称",s.jsx("input",{autoFocus:!0,required:!0,maxLength:256,disabled:v,className:"mt-2 min-h-11 w-full rounded-lg border border-border/30 bg-surface-2 px-3 text-sm text-foreground outline-none focus:border-primary",value:y,onChange:Y=>w(Y.target.value)})]}),I&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs leading-5 text-destructive",children:I}),s.jsxs("footer",{className:"mt-4 flex justify-end gap-2",children:[s.jsx("button",{type:"button",disabled:v,className:`${fy} bg-surface-2`,onClick:oe,children:"取消"}),s.jsxs("button",{type:"submit",disabled:v||m.kind==="rename"&&!y.trim(),className:`${fy} inline-flex items-center gap-2 ${m.kind==="delete"?"bg-destructive text-destructive-foreground":"bg-primary text-primary-foreground"}`,children:[v&&s.jsx(vn,{size:14,className:"animate-spin"}),v?m.kind==="delete"?"正在删除…":"正在保存…":m.kind==="delete"?"确认删除":m.kind==="archive"?"归档并隐藏":m.kind==="unarchive"?"恢复显示":"保存名称"]})]})]})]})]}),document.body)]})}function HF(e,t){return fg(e.filter(r=>r.archivedAt===void 0),t)}function t0(e,t){const r=new Set(e),n=t.filter(c=>c.sessionIds.length>=2&&c.sessionIds.every(l=>r.has(l))),a=new Set;return e.flatMap(c=>{const l=n.find(d=>d.sessionIds.includes(c));return l?a.has(l.id)?[]:(a.add(l.id),[{sessionIds:l.sessionIds,workspace:l}]):[{sessionIds:[c]}]})}function r0(e,t,r,n=[]){const a=new Map,c=new Map,l=new Set(e.map(x=>x.id));for(const x of n){const y=x.sessionIds.filter(v=>l.has(v));if(!y.length)continue;const w=y.length===x.sessionIds.length?x:{...x,sessionIds:y};y.forEach(v=>a.set(v,w))}for(const x of t)if(!(x.sessionIds.length<2||!x.sessionIds.every(y=>l.has(y)))&&!x.sessionIds.some(y=>a.has(y)))for(const y of x.sessionIds)c.set(y,x);const d=new Set,f=new Set,m=[];for(const x of e){const y=a.get(x.id);if(y){if(d.has(y.id))continue;d.add(y.id);const T=y.sessionIds.flatMap(S=>{const I=r.get(S);return I?[I]:[]});m.push({kind:"collaboration",id:`collaboration:${y.id}`,group:y,members:T,sessionIds:y.sessionIds});continue}const w=c.get(x.id);if(!w){m.push({kind:"session",id:`session:${x.id}`,session:x,sessionIds:[x.id]});continue}if(f.has(w.id))continue;f.add(w.id);const v=w.sessionIds.flatMap(T=>{const S=r.get(T);return S?[S]:[]});m.push({kind:"workspace",id:`workspace:${w.id}`,workspace:w,members:v,sessionIds:w.sessionIds})}return m}function py(e,t,r){const n=Math.min(e.length,Math.max(0,r)),a=e.slice(0,n).flatMap(l=>l.sessionIds.filter(d=>d!==t)),c=e.slice(n).flatMap(l=>l.sessionIds.filter(d=>d!==t));return[...a,t,...c]}function WF({status:e,detail:t,needsReview:r,inCopyMode:n}){return s.jsx(CO,{status:e,detail:t,needsReview:r,inCopyMode:n})}function my({isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,sessions:a,activeSessionId:c,sessionStates:l,onJumpToNextAttention:d,onNewSession:f,onCloseSession:m,onSplitSession:x,onCloseSplit:y,onRemoveFromSplit:w,splitWorkspaces:v,onSetSplitLayout:T,onReorderSplitWorkspace:S,onCombineSplitSessions:I,onReorderSessions:N,onSessionMenu:P,onOpenSettings:$,onOpenQuota:Q,updateState:U,updateActionPending:Z=!1,onConfirmUpdateRestart:J,onRetryUpdate:H,serverHealthState:ye,tmuxAvailable:oe=!0,defaultSessionMode:te="shell",push:Ce,pinned:qe,onTogglePinned:ve,recoverableTmuxSessions:Y=[],recoverableTmuxSessionsLoading:st=!1,onRefreshRecoverableTmuxSessions:he,onCloseRecoverableTmuxSession:Qe}){const{t:ie}=Ur(),[,Pe]=b.useState(0),[Fe,ce]=b.useState(null),[Ie,je]=b.useState(!1),[Ze,we]=b.useState(!1),[le,Ge]=b.useState(null),He=b.useRef(!1),tt=b.useRef(0),xe=b.useCallback(W=>{W||(tt.current+=1),je(W)},[]),[dt,it]=b.useState(!1),_e=Bi(W=>W.groupId),[Ue,ke]=b.useState({}),V=dt||Object.keys(Ue).length>0,ae=b.useRef(!1),pe=b.useRef(!1),[$e,Xe]=b.useState(null);b.useEffect(()=>{let W=!1;return Cc().then(Re=>{W||ae.current||ke(Object.fromEntries(M3(Re.collaborationPanels?.[lp()]).map(Ke=>[Ke,!0])))}).catch(()=>{}),()=>{W=!0}},[]);const wt=async(W,Re)=>{ae.current=!0,await eo({floatingGroupId:Re},W),ke(Ke=>({...Ke,[W]:Re!==null}))},[Ut,qt]=b.useState([]),[Nt,sr]=b.useState(!1),[jt,Xt]=b.useState(null),[Rt,ir]=b.useState(null),[ge,Je]=b.useState(null),[at,Et]=b.useState(null),X=Pu(W=>W.tasks),vt=Pu(W=>W.allTasks),[Bt,Me]=b.useState(0),[Dr,Le]=b.useState(null),At=b.useRef(!1),[Ot,er]=b.useState({}),ot=Pu(W=>W.error),[Lt,nr]=b.useState(!1),[ur,Rr]=b.useState(!1);b.useEffect(()=>ou(()=>{Pu.getState().refresh()},5e3,[k0]),[]);const Gr=async W=>(xe(!1),ae.current=!0,W?(Bi.getState().open(W),tr(),!0):(it(!0),tr(),!0)),Tt=Ef(W=>W.collaborationGroups),Ft=Ef(W=>W.setCollaborationGroups),[be,Ct]=b.useState({mode:te}),{preference:gt,agents:rt,detecting:cn,refresh:Kr,selectAgent:wn}=tF(),Oe=b.useRef(null);let ft=!1;if(U?.latestVersion)try{ft=OQ(U.latestVersion,U.currentVersion)>0}catch{}const ht=!!(ft&&U&&["checking","installing","ready","restarting","error"].includes(U.status)),Cr=!!ye?.attention,Ht=[ie("sidebar.moreActions"),ht&&U?.latestVersion?ie("sidebar.updateAvailable",{version:U.latestVersion}):null].filter(Boolean).join(": "),yr=Yt(W=>W.groupByFolder),Xr=Yt(W=>W.collapsedGroups),Bn=Yt(W=>W.toggleGroupCollapsed),mn=b.useRef(null),hn=b.useRef(null),gn=b.useRef(null),an=b.useRef(0),ne=b.useRef(!1),Ye=b.useRef(null),St=b.useRef(null),[Jt,Or]=b.useState(!1),un=b.useRef([]),Jr=b.useRef(null),en=b.useRef(null),mr=b.useRef(new Set),tn=b.useRef(null),Sn=b.useMemo(()=>new Set(v.flatMap(W=>W.sessionIds)),[v]),Zr=b.useMemo(()=>new Map(a.map(W=>[W.id,W])),[a]),Qr=b.useMemo(()=>HF(Tt,new Set(Zr.keys())),[Tt,Zr]),lr=b.useMemo(()=>fg(Tt.filter(W=>W.archivedAt!==void 0),new Set(Zr.keys())),[Tt,Zr]),fn=b.useCallback(async()=>{const W=++an.current;try{const Re=await lg();if(W!==an.current)return;Ft(Array.isArray(Re.groups)?Re.groups:[])}catch{if(W!==an.current)return;Ft(Re=>Re.map(Ke=>({...Ke,remoteSessions:Ke.remoteSessions?.map(lt=>({...lt,status:"offline",serviceConnected:!1}))})))}},[]);b.useEffect(()=>l3(W=>Ft(W.groups)),[]),b.useEffect(()=>{const W=ou(()=>{fn()},1e4,["focus",k0]);return()=>{an.current+=1,W()}},[fn]),b.useEffect(()=>{(e||!V)&&fn()},[V,e,fn]);const Ss=b.useCallback(()=>{un.current=Array.from(document.querySelectorAll("[data-collaboration-member], [data-collaboration-background]")).flatMap(W=>{const Re=W.dataset.collaborationMember??"",Ke=W.hasAttribute("data-collaboration-background"),lt=W.closest("[data-collaboration-group]")?.dataset.collaborationGroup;if(!Re&&!Ke||!lt)return[];const ut=[];for(let It=W.parentElement;It;It=It.parentElement)ut.push({element:It,top:It.scrollTop,left:It.scrollLeft});return[{element:W,sessionId:Re,groupId:lt,background:Ke,rect:W.getBoundingClientRect(),scrollParents:ut}]})},[]),Ar=b.useCallback((W,Re)=>{if(!ne.current)return;document.querySelectorAll("[data-split-exit-drop-index]").forEach(q=>q.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(q=>q.removeAttribute("data-drop-active"));const lt=document.elementsFromPoint(W,Re).map(q=>q.closest("[data-collaboration-background]")).find(Boolean)?.closest("[data-collaboration-group]");if(lt?.dataset.collaborationGroup){lt.dataset.dropActive="true",en.current={kind:"collaboration",groupId:lt.dataset.collaborationGroup,background:!0};return}const ut=un.current.find(q=>{if(q.sessionId===St.current||!q.element.isConnected)return!1;const se=q.scrollParents.reduce((We,mt)=>We+mt.element.scrollLeft-mt.left,0),Ee=q.scrollParents.reduce((We,mt)=>We+mt.element.scrollTop-mt.top,0);return W>=q.rect.left-se&&W<=q.rect.right-se&&Re>=q.rect.top-Ee+q.rect.height*.25&&Re<=q.rect.bottom-Ee-q.rect.height*.25});if(ut?.background){ut.element.closest("[data-collaboration-group]")?.setAttribute("data-drop-active","true"),en.current={kind:"collaboration",groupId:ut.groupId,background:!0};return}if(ut&&!v.find(se=>se.sessionIds.includes(ut.sessionId))?.sessionIds.includes(St.current??"")){ut.element.dataset.dropActive="true",en.current={kind:"split",sessionId:ut.sessionId,groupId:ut.groupId};return}const It=document.elementsFromPoint(W,Re).filter(q=>{const se=q.closest("[data-rfd-draggable-id]");return!se||!["session:","split-member:","collaboration-member:"].some(Ee=>se.dataset.rfdDraggableId===`${Ee}${St.current}`)}),_t=It.map(q=>q.closest("[data-collaboration-group]")).find(q=>q?.dataset.collaborationGroup);if(_t?.dataset.collaborationGroup){const q=_t.dataset.collaborationGroup,se=It.map(et=>et.closest("[data-collaboration-split]")).find(Boolean),Ee=It.map(et=>et.closest("[data-collaboration-member]")).find(Boolean),We=Ee?.dataset.collaborationMember??se?.dataset.splitAnchor,mt=q===Ye.current&&v.some(et=>et.sessionIds.includes(We??"")&&et.sessionIds.includes(St.current??""));if(We&&!mt&&(q!==Ye.current||!Ee&&se)){_t.dataset.dropActive="true";const et=Ee??se;et&&(et.dataset.dropActive="true"),en.current={kind:"split",sessionId:We,groupId:q}}else{const et=It.some(dr=>dr.closest("[data-collaboration-background]"));(q!==Ye.current||et)&&(_t.dataset.dropActive="true"),en.current={kind:"collaboration",groupId:q,background:et}}return}const xt=Array.from(document.querySelectorAll("[data-sidebar-entity-list-id]")).filter(q=>q.dataset.sidebarEntityListId===Jr.current).find(q=>{const se=q.getBoundingClientRect();return W>=se.left&&W<=se.right&&Re>=se.top-8&&Re<=se.bottom+8});if(!xt){en.current=null;return}const Pt=Array.from(xt.children).filter(q=>q instanceof HTMLElement&&q.hasAttribute("data-sidebar-entity-index")),z=Pt.findIndex(q=>{const se=q.getBoundingClientRect();return Re<se.top+se.height/2}),R=z<0?Pt.length:z;en.current={kind:"list",listId:xt.dataset.sidebarEntityListId??"",index:R};const F=Array.from(xt.querySelectorAll(":scope > [data-sidebar-entity-index] > [data-split-exit-drop-index]")).find(q=>q.dataset.splitExitDropIndex===String(R));F instanceof HTMLElement&&(F.dataset.active="true")},[v]);b.useEffect(()=>{const W=Ke=>Ar(Ke.clientX,Ke.clientY),Re=Ke=>{const lt=Ke.touches[0];lt&&Ar(lt.clientX,lt.clientY)};return window.addEventListener("pointermove",W),window.addEventListener("touchmove",Re,{passive:!0}),()=>{window.removeEventListener("pointermove",W),window.removeEventListener("touchmove",Re)}},[Ar]);const En=b.useCallback((W,Re)=>{try{W(Re)}finally{document.querySelectorAll("[data-sidebar-dragging]").forEach(Ke=>{delete Ke.dataset.sidebarDragging}),ne.current=!1,un.current=[],Or(!1),Ye.current=null,St.current=null,Jr.current=null,en.current=null,document.querySelectorAll("[data-split-exit-drop-index]").forEach(Ke=>Ke.removeAttribute("data-active")),document.querySelectorAll("[data-drop-active]").forEach(Ke=>Ke.removeAttribute("data-drop-active"))}},[]),qr=b.useMemo(()=>a.filter(W=>!Sn.has(W.id)),[a,Sn]),Lr=b.useMemo(()=>{let W=0;for(const Re of a)l.get(Re.id)?.agentStatus==="working"&&(W+=1);return W},[a,l]);b.useLayoutEffect(()=>{const W=mn.current,Re=hn.current;if(!e||!W||!Re){gn.current=null;return}const Ke=Re.getBoundingClientRect(),lt=W.getBoundingClientRect(),ut={item:W,top:Math.round(lt.top-Ke.top+Re.scrollTop),height:Math.round(lt.height),viewportHeight:Re.clientHeight},It=gn.current;if(gn.current=ut,It?.item===ut.item&&It.top===ut.top&&It.height===ut.height&&It.viewportHeight===ut.viewportHeight||ne.current||Re.clientHeight===0)return;const _t=8,Qt=lt.top-Ke.top,xt=lt.bottom-Ke.top;Qt<_t?Re.scrollTop+=Qt-_t:xt>Re.clientHeight-_t&&(Re.scrollTop+=xt-Re.clientHeight+_t)});const On=b.useMemo(()=>{if(!yr||!c)return null;const W=l.get(c)?.cwd??null;return gC(W)},[yr,c,l]);b.useEffect(()=>{if(!yr){tn.current=null,mr.current.clear();return}if(!c){tn.current=null;return}const W=Yt.getState(),Re=mr.current,Ke=tn.current,lt=On;Ke!==null&&Ke!==lt&&Re.has(Ke)&&(W.collapsedGroups.has(Ke)||W.toggleGroupCollapsed(Ke),Re.delete(Ke)),lt!==null&&lt!==""&&W.collapsedGroups.has(lt)&&(W.toggleGroupCollapsed(lt),Re.add(lt)),tn.current=lt},[yr,c,On]),b.useEffect(()=>{e||xe(!1)},[e]),b.useEffect(()=>{Ct(W=>({...W,command:gt?.command}))},[gt]),b.useEffect(()=>{if(!Ie)return;let W=!1;return sr(!0),ir(null),Qx().then(Re=>{W||qt(Re)}).catch(()=>{W||ir(ie("sidebar.resumeHistoryLoadFailed"))}).finally(()=>{W||sr(!1)}),()=>{W=!0}},[Ie,ie]),b.useEffect(()=>{if(!Fe)return;const W=Re=>{Re instanceof KeyboardEvent&&Re.key!=="Escape"||Re instanceof PointerEvent&&Re.target instanceof Node&&Oe.current?.contains(Re.target)||ce(null)};return window.addEventListener("pointerdown",W),window.addEventListener("keydown",W),()=>{window.removeEventListener("pointerdown",W),window.removeEventListener("keydown",W)}},[Fe]);const tr=()=>{!Ce&&!qe&&r()};b.useEffect(()=>{const W=Re=>{xe(!1);const{groupId:Ke,dock:lt}=Re.detail;ae.current=!0,os.getState().setDock(Ke,{...lt,preferredWidth:360}),ke(ut=>({...ut,[Ke]:!0})),Bi.getState().terminal(),tr()};return window.addEventListener("termdock:open-collaboration-messages",W),()=>window.removeEventListener("termdock:open-collaboration-messages",W)},[tr]);const K=te==="tmux"&&!oe?"shell":te,De=(W,Re=!1)=>{if(He.current)return;He.current=!0,we(!0),Ge(null);const Ke=tt.current;f({...W,shouldActivate:()=>Ke===tt.current&&(W.shouldActivate?.()??!0),onResult:lt=>{if(He.current=!1,we(!1),!lt.ok){Ge(lt.error);return}Ke===tt.current&&(Re&&xe(!1),tr())}})},Mt=()=>{De({mode:K})},vr=()=>{gt&&De({mode:K,command:gt.command})},Dt=W=>{xe(!1),Je(W.name),f({mode:"tmux",tmuxSessionName:W.name,cwd:W.cwd??void 0}),tr()};b.useEffect(()=>{ge&&(Y.some(W=>W.name===ge)||Je(null))},[ge,Y]);const Br=(W,Re)=>{De({...be,cwd:be.cwd?.trim()||void 0,command:Re??W?.command},!0)},Pr=async W=>{Xt(W.id),ir(null);try{const Re=await c3(W.id);De({mode:"shell",cwd:Re.cwd,command:Re.command},!0)}catch(Re){const Ke=Re&&typeof Re=="object"&&"code"in Re?String(Re.code??""):"";ir(ie(Ke==="AGENT_SESSION_ACTIVE_ELSEWHERE"?"tab.resumeAgentConflict":"sidebar.resumeHistoryFailed"))}finally{Xt(null)}},xn=async W=>{qt(Re=>Re.filter(Ke=>Ke.id!==W));try{await M9(W)}catch{ir(ie("sidebar.resumeHistoryRemoveFailed")),Qx().then(qt).catch(()=>{})}},Kn=()=>{if(Ie){xe(!1);return}He.current||(tt.current+=1,He.current||Ge(null),Ct({mode:te==="tmux"&&!oe?"shell":te,cwd:c?l.get(c)?.cwd??void 0:void 0,command:gt?.command}),xe(!0))},Cs=b.useCallback(W=>!_e&&W===c?"sidebar-session-selected text-foreground":"text-muted-foreground hover:bg-surface-2",[c,_e]),ws=ex(),[Wr,Qn]=b.useState(null);b.useEffect(()=>{e||Qn(null)},[e]);const Pn=b.useCallback((W,Re,Ke,lt,ut)=>{const It=!_e&&W.id===c,_t=Sn.has(W.id),Qt=!!(Ke&&_t),xt=l.get(W.id),Pt=ld(xt?.cwd??null),z=xt?.shellTitle??S9(W.id),R=z===xt?.cwd||z===Pt?null:z,F=C9(W,xt?.activeProgram??null,null,_9,R,xt?.promptState??null),q=!!(xt?.tuiProgress&&xt.tuiProgress.state!=="remove");return s.jsxs($F,{open:Wr===W.id,onOpenChange:se=>Qn(Ee=>se?W.id:Ee===W.id?null:Ee),onClose:se=>m(W.id,se,{skipConfirmation:!0}),closeLabel:ie("common.close"),closeTitle:ie("sidebar.closeSession",{name:F}),compact:Ke,children:[s.jsxs("button",{ref:It?mn:null,"aria-current":It?"page":void 0,type:"button",...Re??{},onContextMenu:se=>{P&&(se.preventDefault(),P(W.id,{x:se.clientX,y:se.clientY}))},onClick:()=>{xe(!1),Bi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:W.id})),tr()},className:`sidebar-session-primary relative min-w-0 flex flex-1 items-center overflow-hidden text-left ${Re?"cursor-grab active:cursor-grabbing ":""}${Ke?"min-h-7 gap-1.5 py-0.5 pl-2 pr-0.5":"min-h-[30px] gap-1.5 py-1 pl-2 pr-1"}`,title:xt?.cwd??W.name,children:[It&&s.jsx("span",{"aria-hidden":"true",className:"absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-primary"}),s.jsxs("span",{className:`relative inline-flex shrink-0 items-center justify-center rounded-md ${Ke?"h-5 w-[22px]":"h-[22px] w-[22px]"} ${It?W.mode==="tmux"?"bg-[rgb(var(--tmux-rgb)_/_0.15)] text-[color:var(--tmux)]":"bg-primary/15 text-primary":W.mode==="tmux"?"bg-surface text-[rgb(var(--tmux-rgb)_/_0.80)]":"bg-surface text-muted-foreground"}`,children:[xt?.isConnecting||q&&!xt?.agentStatus?s.jsx(Dn,{size:Ke?10:11,className:"animate-spin"}):xt?.agent??Px(W.id)?s.jsx(ru,{agent:xt?.agent??Px(W.id),size:Ke?13:15}):W.mode==="tmux"?s.jsx(su,{size:Ke?10:11}):s.jsx(tl,{size:Ke?10:11}),s.jsx(WF,{status:xt?.agentStatus??null,detail:xt?.agentStatusDetail,needsReview:xt?.agentNeedsReview,inCopyMode:xt?.inCopyMode})]}),s.jsx("span",{className:`min-w-0 flex-1 truncate leading-tight ${Ke?"text-[11px]":"text-[12px]"} ${It?"font-medium text-foreground":""} ${xt?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:F}),s.jsx(yb,{sessionIds:[W.id]})]}),lt,s.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),Qt?w(W.id):_t?y(W.id):x(W.id)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md transition hover:bg-primary/15 hover:text-primary active:scale-95 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"} text-muted-foreground`,"aria-label":`${ie(Qt?"tab.splitRemovePane":_t?"tab.splitClose":"tab.split")} ${F}`,title:ie(Qt?"tab.splitRemovePane":_t?"tab.splitClose":"tab.split"),children:Qt?s.jsx(nC,{size:11}):s.jsx($l,{size:12})}),ut??s.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),m(W.id,se)},className:`sidebar-session-action inline-flex shrink-0 items-center justify-center rounded-md text-muted-foreground/70 transition hover:bg-destructive/15 hover:text-destructive active:scale-95 ${Ke?"h-6 w-6":"h-[26px] w-[26px]"}`,"aria-label":ie("sidebar.closeSession",{name:F}),title:ie("common.close"),children:s.jsx(jn,{size:Ke?11:12})})]})},[c,_e,Sn,l,m,x,y,w,P,ie,Wr]),jr=b.useMemo(()=>Lf(a,W=>l.get(W.id)?.cwd??null,yr,ie("sidebar.ungrouped"),v,Qr).groups,[Qr,yr,a,l,v,ie]),ds=b.useMemo(()=>r0(a,v,Zr,Qr),[Qr,a,Zr,v]),Tr=b.useCallback(W=>{Or(W.draggableId.startsWith("collaboration:")||W.draggableId.startsWith("workspace:"));const Re=W.draggableId.replace(/^split-member:/,"");St.current=W.draggableId.replace(/^(?:session|split-member|collaboration-member):/,"");const Ke=W.type==="split-member"?v.find(Qt=>Qt.sessionIds.includes(Re)):null,lt=W.type==="collaboration-member"?W.source.droppableId.replace(/^collaboration-members:/,""):null,ut=lt?Qr.find(Qt=>Qt.id===lt):null;ne.current=!!(Ke||ut||W.type==="session"&&W.draggableId.startsWith("session:")),ne.current&&document.querySelectorAll("[data-collaboration-group]").forEach(Qt=>{Qt.dataset.sidebarDragging="true"}),Ye.current=ut?.id??null;const It=Ke?.sessionIds??ut?.sessionIds??[],_t=It.length>0?jr.find(Qt=>It.every(xt=>Qt.sessions.some(Pt=>Pt.id===xt))):null;Jr.current=yr?_t?`group-sessions:${_t.key}`:null:It.length>0?"sidebar-entities":null,en.current=null},[Qr,jr,yr,v]),bn=b.useCallback((W,Re,Ke)=>{if(Re===Ke)return;const lt=Re?Tt.find(xt=>xt.id===Re):null,ut=Ke?Tt.find(xt=>xt.id===Ke):null;if(Ke&&!ut)return;if(ut){const xt=a.map(z=>z.id).filter(z=>z!==W);let Pt=-1;xt.forEach((z,R)=>{ut.sessionIds.includes(z)&&(Pt=R)}),Pt>=0&&(xt.splice(Pt+1,0,W),N(xt))}const It=lt?.sessionIds.filter(xt=>xt!==W)??[],_t=ut?[...ut.sessionIds.filter(xt=>xt!==W),W]:[];Ft(xt=>xt.flatMap(Pt=>Pt.id===Re?[{...Pt,sessionIds:It}]:Pt.id===Ke?[{...Pt,sessionIds:_t}]:[Pt])),Et(null),(lt&&ut?k9({sourceGroupId:lt.id,targetGroupId:ut.id,sessionId:W,expectedSourceUpdatedAt:lt.updatedAt,expectedTargetUpdatedAt:ut.updatedAt}):lt?Wl({id:lt.id,name:lt.name,sessionIds:It,expectedUpdatedAt:lt.updatedAt}):ut?Wl({id:ut.id,name:ut.name,sessionIds:_t,expectedUpdatedAt:ut.updatedAt}):Promise.resolve()).then(()=>fn(),xt=>(Et(xt instanceof Error?xt.message:"协作成员移动失败"),fn()))},[Tt,fn,a,N]),An=b.useCallback((W,Re,Ke,lt=!1)=>{const ut=Tt.find(se=>se.id===W);if(!ut||Re===Ke)return;const It=ut.sessionIds.filter(se=>!se.startsWith("remote:")),_t=t0(It,v).flatMap(se=>se.sessionIds),Qt=mb(vt,ut.id),xt=lt&&!Ot[ut.id]?_t.filter(se=>!Qt.has(se)||se===c||Sn.has(se)):_t.slice(),Pt=new Set(xt),[z]=xt.splice(Re,1);if(!z)return;xt.splice(Ke,0,z);let R=0;const F=_t.map(se=>Pt.has(se)?xt[R++]:se),q=v.find(se=>se.sessionIds.includes(z));if(q&&q.sessionIds.every(se=>ut.sessionIds.includes(se))){const se=F.filter(Ee=>q.sessionIds.includes(Ee));S(q.id,se)}F.push(...ut.sessionIds.filter(se=>se.startsWith("remote:"))),Ft(se=>se.map(Ee=>Ee.id===W?{...Ee,sessionIds:F}:Ee)),Et(null),Wl({id:ut.id,name:ut.name,sessionIds:F,expectedUpdatedAt:ut.updatedAt}).then(()=>fn(),se=>(Et(se instanceof Error?se.message:"成员排序失败"),fn()))},[Tt,fn,v,S,vt,Ot,c,Sn]);b.useEffect(()=>{const W=Re=>{const{sourceId:Ke,targetId:lt}=Re.detail;if(!Ke||!lt||Ke===lt)return;const ut=Lf(a,We=>l.get(We.id)?.cwd??null,yr,"",v,Qr).arranged.map(We=>We.id),It=ut.indexOf(Ke),_t=ut.indexOf(lt);if(It<0||_t<0)return;const Qt=Qr.find(We=>We.sessionIds.includes(Ke));if(Qt?.sessionIds.includes(lt)){const We=t0(Qt.sessionIds,v).flatMap(mt=>mt.sessionIds);An(Qt.id,We.indexOf(Ke),We.indexOf(lt));return}const xt=v.filter(We=>We.sessionIds.length>=2&&We.sessionIds.every(mt=>Zr.has(mt))&&!Qr.some(mt=>We.sessionIds.some(et=>mt.sessionIds.includes(et)))),Pt=xt.find(We=>We.sessionIds.includes(Ke));if(Pt?.sessionIds.includes(lt)){const We=[...Pt.sessionIds];We.splice(We.indexOf(Ke),1),We.splice(Pt.sessionIds.indexOf(lt),0,Ke),S(Pt.id,We);return}const z=We=>Qr.find(mt=>mt.sessionIds.includes(We))?.sessionIds??xt.find(mt=>mt.sessionIds.includes(We))?.sessionIds??[We],R=new Set(z(Ke)),F=new Set(z(lt)),q=ut.filter(We=>!R.has(We)),se=q.flatMap((We,mt)=>F.has(We)?[mt]:[]),Ee=It<_t?Math.max(...se)+1:Math.min(...se);q.splice(Ee,0,...ut.filter(We=>R.has(We))),N(q)};return window.addEventListener("reorder-navigation-session",W),()=>window.removeEventListener("reorder-navigation-session",W)},[a,l,yr,v,Qr,Zr,An,S,N]);const rr=b.useCallback(W=>{if(W.type!=="collaboration-member")return!1;if(W.reason==="CANCEL")return!0;const Re=W.source.droppableId.replace(/^collaboration-members:/,""),Ke=W.draggableId.replace(/^collaboration-member:/,""),lt=en.current;if(lt?.kind==="split")return bn(Ke,Re,lt.groupId),I(lt.sessionId,Ke),!0;if(lt?.kind==="collaboration"&&lt.groupId!==Re)return bn(Ke,Re,lt.groupId),!0;if(lt?.kind==="collaboration"&&lt.background)return Sn.has(Ke)&&w(Ke),!0;if(W.destination&&W.destination.droppableId!==W.source.droppableId){const ut=W.destination.droppableId.replace(/^collaboration-members:/,"");if(Qr.some(It=>It.id===ut))return bn(Ke,Re,ut),!0}if(W.combine){const ut=W.combine.droppableId.replace(/^collaboration-members:/,"");ut!==Re&&bn(Ke,Re,ut);const It=W.combine.draggableId.replace(/^collaboration-member:/,"");if(v.find(Qt=>Qt.sessionIds.includes(Ke))?.sessionIds.includes(It)){const Qt=Qr.find(Pt=>Pt.id===Re),xt=Qt?t0(Qt.sessionIds,v).flatMap(Pt=>Pt.sessionIds).indexOf(It):-1;xt>=0&&Qt&&An(Re,t0(Qt.sessionIds,v).flatMap(Pt=>Pt.sessionIds).indexOf(Ke),xt)}else Zr.has(It)&&I(It,Ke);return!0}if(W.destination?.droppableId===W.source.droppableId)return An(Re,W.source.index,W.destination.index,!0),!0;if(lt?.kind!=="list")return!0;if(lt?.kind==="list"){const ut=jr.find(_t=>`group-sessions:${_t.key}`===lt.listId),It=lt.listId==="sidebar-entities"?ds:ut?r0(ut.sessions,v,Zr,Qr):null;if(It){const _t=py(It,Ke,lt.index);lt.listId==="sidebar-entities"?N(_t):ut&&N(jr.flatMap(Qt=>Qt.key===ut.key?_t:Qt.sessions.map(xt=>xt.id)))}}return bn(Ke,Re,null),!0},[Qr,ds,jr,bn,N,An,Zr,v,Sn,w,I]),kn=b.useCallback(W=>{if(W.type!=="split-member")return!1;if(W.reason==="CANCEL")return!0;const Re=W.draggableId.replace(/^split-member:/,""),Ke=v.find(xt=>xt.sessionIds.includes(Re));if(!Ke?.sessionIds.includes(Re))return!0;const lt=Ke.id,ut=en.current;if(ut?.kind==="split")return bn(Re,null,ut.groupId),I(ut.sessionId,Re),!0;if(ut?.kind==="collaboration")return bn(Re,null,ut.groupId),!0;if(!W.destination&&ut?.kind==="list"){const xt=jr.find(R=>`group-sessions:${R.key}`===ut.listId),Pt=ut.listId==="sidebar-entities"?ds:xt?r0(xt.sessions,v,Zr,Qr):null;if(!Pt)return!0;const z=py(Pt,Re,ut.index);return w(Re),ut.listId==="sidebar-entities"?N(z):xt&&N(jr.flatMap(R=>R.key===xt.key?z:R.sessions.map(F=>F.id))),!0}if(!W.destination)return!0;const It=W.destination.droppableId.replace(/^split-members:/,"");if(It!==lt){const Pt=v.find(z=>z.id===It)?.sessionIds[0];return Pt&&I(Pt,Re),!0}if(W.source.index===W.destination.index)return!0;const _t=[...Ke.sessionIds],[Qt]=_t.splice(W.source.index,1);return Qt&&(_t.splice(W.destination.index,0,Qt),S(lt,_t)),!0},[Qr,ds,jr,bn,I,w,N,S,Zr,v]),Cn=(W,Re="top")=>s.jsx("div",{"data-split-exit-drop-index":W,className:`group/split-exit pointer-events-none absolute inset-x-0 z-10 h-2 ${Re==="top"?"-top-1":"-bottom-1"}`,children:s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-1 top-1/2 h-px -translate-y-1/2 rounded-full bg-transparent transition-colors group-data-[active=true]/split-exit:bg-primary"})}),wr=b.useCallback((W,Re,Ke)=>{if(rr(W)||kn(W)||W.reason==="CANCEL")return;const lt=Re.find(xt=>xt.id===W.draggableId);if(!lt)return;const ut=en.current;if(ut?.kind==="split"&&lt.kind==="session"){bn(lt.session.id,null,ut.groupId),I(ut.sessionId,lt.session.id);return}if(ut?.kind==="collaboration"&&lt.kind==="session"){bn(lt.session.id,null,ut.groupId);return}if(W.combine&&lt.kind!=="session"){const xt=Re.findIndex(Pt=>Pt.id===W.combine?.draggableId);if(xt<0)return;W={...W,combine:null,destination:{...W.source,index:xt}}}if(W.combine){const xt=Re.find(q=>q.id===W.combine?.draggableId);if(!xt)return;const Pt=xt.kind==="workspace"?xt:lt.kind==="workspace"?lt:xt,z=Pt===lt?xt:lt,R=Pt.sessionIds[0],F=z.sessionIds[0];R&&F&&R!==F&&I(R,F);return}if(!W.destination||W.source.index===W.destination.index)return;const It=[...Re],[_t]=It.splice(W.source.index,1);if(!_t)return;It.splice(W.destination.index,0,_t);const Qt=It.flatMap(xt=>xt.sessionIds);if(Ke===void 0){N(Qt);return}N(jr.flatMap(xt=>xt.key===Ke?Qt:xt.sessions.map(Pt=>Pt.id)))},[jr,rr,kn,bn,I,N]),ps=b.useCallback(W=>{if(W.reason==="CANCEL"||rr(W)||kn(W))return;if(W.type==="group"){if(!W.destination||W.source.index===W.destination.index)return;N(S3(jr,W.source.index,W.destination.index));return}const Re=W.source.droppableId.replace(/^group-sessions:/,""),Ke=jr.find(ut=>ut.key===Re);if(!Ke)return;const lt=r0(Ke.sessions,v,Zr,Qr);if(W.combine||en.current?.kind==="collaboration"||en.current?.kind==="split"){wr(W,lt,Re);return}!W.destination||W.destination.droppableId!==W.source.droppableId||wr(W,lt,Re)},[Qr,jr,Zr,v,rr,wr,kn,N]),Ks=(W,Re)=>{const Ke=Fe===W.id,lt=[{layout:"horizontal",label:ie("tab.splitHorizontal"),icon:$l},{layout:"vertical",label:ie("tab.splitVertical"),icon:zx},...W.sessionIds.length>=3||W.layout==="grid"?[{layout:"grid",label:ie("tab.splitGrid"),icon:Ux}]:[]],ut=W.layout==="vertical"?zx:W.layout==="grid"?Ux:$l,It=lt.find(_t=>_t.layout===W.layout)?.label??ie("tab.splitHorizontal");return s.jsxs("div",{ref:Ke?Oe:void 0,className:"relative shrink-0",onPointerDown:_t=>_t.stopPropagation(),children:[s.jsx("button",{...Re??{},type:"button",className:`sidebar-session-action inline-flex h-6 w-6 items-center justify-center rounded-md transition active:scale-95 ${Ke?"bg-primary/15 text-primary":"text-muted-foreground/70 hover:bg-surface-2 hover:text-foreground"}`,"aria-label":`${ie("tab.splitLayout")}: ${It}`,"aria-haspopup":"menu","aria-expanded":Ke,title:Re?`${ie("tab.splitLayout")} · 按住拖动分屏组`:ie("tab.splitLayout"),onClick:_t=>{_t.stopPropagation(),ce(Qt=>Qt===W.id?null:W.id)},children:s.jsx(ut,{size:12})}),Ke&&s.jsx("div",{role:"menu","aria-label":ie("tab.splitLayout"),className:"absolute right-0 top-full z-30 mt-1 flex gap-0.5 rounded-md border border-border bg-surface-elevated p-1 shadow-lg",children:lt.map(_t=>{const Qt=_t.icon,xt=_t.layout===W.layout;return s.jsx("button",{type:"button",role:"menuitemradio","aria-checked":xt,"aria-label":_t.label,title:_t.label,className:`sidebar-session-action inline-flex h-7 w-7 items-center justify-center rounded-sm transition active:scale-95 ${xt?"bg-primary/15 text-primary":"text-muted-foreground hover:bg-surface-2 hover:text-foreground"}`,onClick:Pt=>{Pt.stopPropagation(),T(W.sessionIds[0],_t.layout),ce(null)},children:s.jsx(Qt,{size:13})},_t.layout)})})]})},rs=(W,Re,Ke=!1,lt=!1,ut)=>{if(Re.length<2)return null;const It=W.name?.trim()||`${ie("tab.splitWorkspace")} ${v.findIndex(Qt=>Qt.id===W.id)+1}`,_t=Fe===W.id;return s.jsx("section",{"data-split-workspace":W.id,"aria-label":It,className:`group/split relative rounded-md my-1 p-0.5 before:opacity-40 before:pointer-events-none before:absolute before:inset-0 before:rounded-md before:border before:border-border transition-colors ${lt?"bg-primary/15 ring-1 ring-primary/40":Ke?"bg-surface-elevated opacity-90 shadow-lg":"bg-[var(--chrome-bg)]"}`,children:s.jsx(Fl,{droppableId:`split-members:${W.id}`,type:"split-member",direction:"vertical",children:(Qt,xt)=>s.jsxs("div",{ref:Qt.innerRef,...Qt.droppableProps,"data-split-members":!0,className:xt.isDraggingOver?"rounded-sm bg-primary/10 ring-1 ring-primary/40":"",children:[Re.map((Pt,z)=>s.jsx(Ol,{draggableId:`split-member:${Pt.id}`,index:z,disableInteractiveElementBlocking:!0,children:(R,F)=>s.jsx("div",{ref:R.innerRef,...R.draggableProps,...P?ws(()=>P(Pt.id)):{},className:`sidebar-session-row ${z===0&&_t?"relative z-20 ":"relative "}flex items-center rounded-sm pr-0.5 transition-colors ${F.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Cs(Pt.id)}`,children:Pn(Pt,R.dragHandleProps,!0,z===0?Ks(W,ut):void 0)})},Pt.id)),Qt.placeholder]})})})},on=(W,Re)=>{const Ke=c??Re;pe.current||!Ke||(xe(!1),pe.current=!0,Xe(W),Et(null),PC(W,Ke).catch(lt=>Et(lt instanceof Error?lt.message:"消息面板打开失败,请重试")).finally(()=>{pe.current=!1,Xe(null)}))},Hn=(W,Re)=>{an.current+=1,Ft(Ke=>Re?Ke.map(lt=>lt.id===W?Re:lt):Ke.filter(lt=>lt.id!==W)),Re||(Bi.getState().groupId===W&&Bi.getState().terminal(),os.getState().setDock(W,null),ke(Ke=>{const lt={...Ke};return delete lt[W],lt}),requestAnimationFrame(()=>mn.current?.focus({preventScroll:!0})),eo({floatingGroupId:null},W).catch(()=>Et("协作组已删除,面板布局保存失败,请刷新后检查。"))),fn()},Fr=(W,Re,Ke,lt=!1,ut=!1)=>{const It=`collaboration:${W.id}`,_t=Xr.has(It),Qt=`collaboration-members-${W.id}`,xt=mb(vt,W.id),Pt=W.sessionIds.filter(Ee=>xt.has(Ee)&&Ee!==c&&!Sn.has(Ee)),z=Ot[W.id]===!0,R=z?W.sessionIds:W.sessionIds.filter(Ee=>!Pt.includes(Ee)),F=t0(R,v),q=F.flatMap(Ee=>Ee.sessionIds),se=F.length===1?F[0]?.workspace:void 0;return s.jsxs("section",{"data-collaboration-group":W.id,"data-collaboration-group-name":W.name,"aria-label":`Agent 工作组:${W.name}`,className:`group/collaboration relative my-1 rounded-lg p-1 before:pointer-events-none before:absolute before:inset-0 before:rounded-lg before:border before:border-border/60 transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${ut?"bg-primary/15 ring-1 ring-primary/40":lt?"bg-surface-elevated opacity-90 shadow-lg":"bg-[var(--chrome-bg)]"}`,children:[s.jsx("div",{className:"rounded-md bg-surface",children:s.jsxs(zF,{group:Tt.find(Ee=>Ee.id===W.id)??W,collapsed:_t,onOpen:()=>{Gr(W.id)},onMessages:$e===null&&(c||Re.length)?()=>on(W.id,Re[0]?.id):void 0,onToggleCollapsed:()=>Bn(It),onChanged:Ee=>Hn(W.id,Ee),children:[s.jsx("button",{type:"button","aria-label":`${_t?"展开":"收起"} ${W.name} 的成员会话`,"aria-expanded":!_t,"aria-controls":Qt,title:`${_t?"展开":"收起"}成员会话`,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-5",onClick:Ee=>{Ee.stopPropagation(),Bn(It)},children:s.jsx(qs,{size:14,className:_t?"":"rotate-90"})}),s.jsxs("button",{...Ke??{},type:"button",className:"flex min-h-11 min-w-0 flex-1 cursor-grab items-center gap-1.5 rounded-sm px-1 text-left text-xs font-medium text-foreground transition hover:text-primary active:cursor-grabbing md:min-h-[30px]",title:`打开 ${W.name} 的协作工作区 · 按住标题拖动排序`,"aria-label":`打开协作工作区:${W.name}`,"aria-current":_e===W.id?"page":void 0,onClick:Ee=>{Ee.stopPropagation(),Gr(W.id)},children:[s.jsx(Wp,{size:14,className:"shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:W.name}),X.some(Ee=>Ee.groupId===W.id)&&s.jsxs("span",{className:"shrink-0 text-[10px] font-normal text-primary",children:[X.filter(Ee=>Ee.groupId===W.id).length," 待处理"]})]}),s.jsx("button",{type:"button","aria-label":`成员与消息:${W.name}`,title:"在终端旁打开成员与消息",disabled:$e!==null||!c&&!Re.length,"aria-busy":$e===W.id,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-surface-elevated hover:text-primary disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary md:h-[30px] md:w-7",onClick:Ee=>{Ee.stopPropagation(),on(W.id,Re[0]?.id)},children:$e===W.id?s.jsx(vn,{size:14,className:"animate-spin"}):s.jsx(cd,{size:14})})]})}),s.jsx("div",{id:Qt,className:_t?void 0:"px-0.5 pt-1",children:!_t&&s.jsxs(s.Fragment,{children:[Pt.length>0&&s.jsxs("button",{type:"button","aria-expanded":z,className:"flex min-h-11 w-full items-center gap-2 rounded-sm px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-elevated md:min-h-8",title:"展开后可查看或归档执行会话,任务结果保留。",onClick:()=>er(Ee=>({...Ee,[W.id]:!z})),children:[s.jsx(qs,{size:12,className:z?"rotate-90":""}),"已完成的执行会话 · ",Pt.length]}),s.jsx(Fl,{droppableId:`collaboration-members:${W.id}`,type:"collaboration-member",direction:"vertical",isCombineEnabled:!0,children:(Ee,We)=>s.jsxs("div",{ref:Ee.innerRef,...Ee.droppableProps,"data-collaboration-members":!0,className:`${We.isDraggingOver?"rounded-sm bg-primary/10":""}`,children:[F.map(mt=>s.jsx("div",{"data-collaboration-split":mt.workspace?.id,"data-split-anchor":mt.workspace?.sessionIds[0],role:mt.workspace?"region":void 0,"aria-label":mt.workspace?`${ie("tab.splitWorkspace")} · ${mt.sessionIds.length}`:void 0,className:mt.workspace&&!se?`relative my-0.5 rounded-sm before:pointer-events-none before:absolute before:inset-0 before:rounded-sm before:border before:border-border data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${mt.sessionIds.includes(c??"")?"bg-primary/[0.07]":"bg-surface/35"}`:void 0,children:mt.sessionIds.map(et=>{const dr=Zr.get(et);return dr?s.jsx(Ol,{draggableId:`collaboration-member:${dr.id}`,index:q.indexOf(dr.id),disableInteractiveElementBlocking:!0,children:(Wn,Gt)=>s.jsxs("div",{ref:Wn.innerRef,...Wn.draggableProps,"data-collaboration-member":dr.id,"data-split-member":Sn.has(dr.id)?"true":void 0,...P?ws(()=>P(dr.id)):{},className:`${mt.workspace&&et===mt.sessionIds[0]&&Fe===mt.workspace.id?"z-20 ":""}sidebar-session-row relative flex items-center rounded-sm pr-0.5 transition-colors data-[drop-active=true]:bg-primary/15 data-[drop-active=true]:ring-1 data-[drop-active=true]:ring-primary/40 ${Gt.combineTargetFor?"bg-primary/15 ring-1 ring-primary/40 ":Gt.isDragging?"bg-surface-elevated opacity-90 shadow-lg ":""}${Cs(dr.id)}`,children:[Pn(dr,Wn.dragHandleProps,!0,mt.workspace&&et===mt.sessionIds[0]?Ks(mt.workspace):void 0,xt.has(et)?s.jsxs("button",{type:"button","aria-label":`归档 ${dr.name}`,title:"保存 Agent 会话 ID 并停止终端;只回收干净的执行目录,结果和分支保留",disabled:Dr!==null,className:"sidebar-session-action inline-flex h-11 min-w-11 shrink-0 items-center justify-center gap-1 rounded-md px-2 text-muted-foreground hover:bg-primary/15 hover:text-primary disabled:opacity-40 md:h-6 md:min-w-6 md:px-1",onClick:zr=>{zr.stopPropagation(),!At.current&&(At.current=!0,Le(et),Et(null),N9(et).then(async()=>{Me(_r=>_r+1),await fn()}).catch(_r=>Et(_r instanceof Error?_r.message:"归档失败,终端已保留")).finally(()=>{At.current=!1,Le(null)}))},children:[Dr===et?s.jsx(vn,{size:13,className:"animate-spin"}):s.jsx(Cf,{size:13}),s.jsx("span",{className:"text-[10px] md:sr-only",children:"归档"})]}):void 0),!mt.workspace&&Sn.has(dr.id)&&s.jsx("button",{type:"button",className:"shrink-0 px-1 text-[10px] text-primary",title:`与 ${v.find(zr=>zr.sessionIds.includes(dr.id))?.sessionIds.filter(zr=>zr!==dr.id).map(zr=>Zr.get(zr)?.name??zr).join("、")} 分屏`,"aria-label":`查看 ${dr.name} 的跨组分屏`,onClick:()=>{xe(!1),Bi.getState().terminal(),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:dr.id})),tr()},children:s.jsx($l,{size:10})})]})},dr.id):null})},mt.workspace?.id??mt.sessionIds[0])),Ee.placeholder]})}),s.jsx(BQ,{groupId:W.id,version:Bt,onRestore:async Ee=>{xe(!1),window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:"tmux",cwd:Ee.cwd,preferredFrontendSessionId:Ee.sessionId,requireExisting:!0}})),await fn(),Bi.getState().terminal(),tr()}}),W.remoteSessions?.map(Ee=>{const We=R9(Ee),mt=We==="connected",et=We==="unknown"?"连接状态未知":"连接已断开";return s.jsxs("button",{type:"button",title:`${Ac(Ee)} · ${mt?"服务已连接":et}`,className:"flex w-full min-w-0 items-center gap-1.5 rounded-sm px-2 py-1 text-left text-[11px] text-muted-foreground hover:bg-surface-2",onClick:()=>{xe(!1),K6(Ee.sessionId).catch(()=>{Gr(W.id)})},children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${mt?"bg-primary":"bg-muted-foreground"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Ee.name}),s.jsx("span",{className:"max-w-20 truncate rounded border border-border/20 px-1 text-[9px]",children:Ac(Ee)}),!mt&&s.jsx("span",{className:"shrink-0 text-[9px]",children:et})]},Ee.sessionId)})]})}),s.jsx("div",{"data-collaboration-background":!0,className:_t?"absolute inset-0 pointer-events-none":"h-1.5"})]})},$r=(W,Re,Ke)=>s.jsx(Gu,{onBeforeCapture:Ss,onDragStart:Tr,onDragEnd:lt=>En(ut=>wr(ut,W,Ke),lt),children:s.jsx(Fl,{droppableId:Re,direction:"vertical",isCombineEnabled:!Jt,children:lt=>s.jsxs("div",{ref:lt.innerRef,...lt.droppableProps,"data-sidebar-entity-list-id":Re,className:"flex-1 space-y-0.5",children:[W.map((ut,It)=>s.jsx(Ol,{draggableId:ut.id,index:It,disableInteractiveElementBlocking:!0,children:(_t,Qt)=>s.jsxs("div",{ref:_t.innerRef,..._t.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":It,className:"relative",children:[Cn(It),It===W.length-1&&Cn(W.length,"bottom"),ut.kind==="workspace"?rs(ut.workspace,ut.members,Qt.isDragging,!!Qt.combineTargetFor,_t.dragHandleProps):ut.kind==="collaboration"?Fr(ut.group,ut.members,_t.dragHandleProps,Qt.isDragging,!!Qt.combineTargetFor):s.jsx("div",{...P?ws(()=>P(ut.session.id)):{},className:`sidebar-session-row group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Qt.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Qt.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Cs(ut.session.id)} cursor-grab active:cursor-grabbing`,children:Pn(ut.session,_t.dragHandleProps)})]})},ut.id)),lt.placeholder]})})}),pn=s.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[s.jsx(XO,{label:ie("sidebar.sessions"),count:a.length,badge:Lr>0?s.jsx(f4,{count:Lr,tone:"running",title:ie("agent.aiRunning")}):null,pinned:!!qe,onClose:r,onTogglePinned:ve?()=>{xe(!1),ve()}:void 0,serverAttention:Cr,onOpenSettings:()=>{xe(!1),$()},actions:[...Q?[{label:ie("sidebar.subscriptionQuota"),icon:hT,onSelect:()=>{xe(!1),Q()}}]:[],{label:"Agent 工作台",icon:Wp,onSelect:()=>{xe(!1),Gr(null)}},{label:"服务与设备",icon:L9,onSelect:()=>{xe(!1),I9()}},{label:ie("sidebar.settings"),icon:y3,onSelect:()=>{xe(!1),$()}}]}),at&&s.jsxs("div",{role:"alert",className:"mx-2 mt-2 flex items-start gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:[s.jsx("span",{className:"min-w-0 flex-1",children:at}),s.jsx("button",{type:"button","aria-label":"关闭协作错误提示",className:"shrink-0",onClick:()=>Et(null),children:s.jsx(jn,{size:14})})]}),s.jsxs("div",{ref:hn,className:"relative z-10 flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain px-1.5 pt-0.5 pb-1.5",children:[X.length>0&&s.jsxs("section",{className:"mb-2 rounded-lg border border-primary/20 bg-primary/5","aria-label":"协作待处理事项",children:[X.length>0&&s.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center gap-2 px-3 text-left text-xs text-primary","aria-expanded":Lt,onClick:()=>nr(W=>!W),children:[s.jsx(Wp,{size:14}),s.jsx("span",{className:"min-w-0 flex-1",children:"需要你处理"}),s.jsx("span",{children:X.length}),s.jsx(qs,{size:12,className:Lt?"rotate-90":""})]}),(Lt||X.length===0)&&s.jsxs("div",{className:"space-y-1 p-1 pt-0",children:[ot&&s.jsxs("p",{role:"alert",className:"px-2 py-2 text-[11px] text-destructive",children:[ot,s.jsx("button",{type:"button",className:"ml-2 text-primary",onClick:()=>{Pu.getState().refresh()},children:"重试"})]}),X.map(W=>s.jsxs("button",{type:"button",className:"min-h-11 w-full rounded-md px-2 py-2 text-left hover:bg-surface-2",onClick:()=>{xb(W.groupId,W.id),Gr(W.groupId).then(Re=>{Re&&xb(W.groupId,W.id)})},children:[s.jsx("span",{className:"block truncate text-xs text-foreground",children:W.title}),s.jsxs("span",{className:"mt-1 block truncate text-[10px] text-muted-foreground",children:[Tt.find(Re=>Re.id===W.groupId)?.name??"协作组"," · ",cu(W)]})]},W.id))]})]}),s.jsx(UF,{sessions:Y,loading:st,attachingName:ge,onRefresh:he,onRestore:Dt,onClose:Qe}),lr.length>0&&s.jsxs("section",{className:"mb-1","aria-label":"已归档协作组",children:[s.jsxs("button",{type:"button",className:"flex min-h-10 w-full items-center gap-2 rounded-md px-2 text-left text-[11px] text-muted-foreground hover:bg-surface-2","aria-expanded":ur,onClick:()=>Rr(W=>!W),children:[s.jsx(Cf,{size:13}),s.jsx("span",{className:"flex-1",children:"已归档协作组"}),s.jsx("span",{children:lr.length}),s.jsx(qs,{size:12,className:ur?"rotate-90":""})]}),ur&&s.jsx("div",{className:"space-y-1",children:lr.map(W=>s.jsx(Gu,{onDragEnd:()=>{},children:Fr(W,W.sessionIds.flatMap(Re=>Zr.get(Re)??[]))},W.id))})]}),Qr.filter(W=>!W.sessionIds.length).map(W=>s.jsx(Gu,{onDragEnd:()=>{},children:Fr(W,[])},W.id)),a.length===0?s.jsxs("div",{className:"rounded-xl bg-surface-2/60 px-4 py-8 text-center",children:[s.jsx(tl,{size:26,className:"mx-auto mb-2 text-muted-foreground"}),s.jsx("p",{className:"text-[12px] text-muted-foreground",children:ie("sidebar.noSessions")})]}):qr.length===0&&v.length===0?s.jsx("div",{className:"rounded-xl bg-surface-2/60 px-4 py-6 text-center",children:s.jsx("p",{className:"text-[12px] text-muted-foreground",children:ie("sidebar.noMatchingSessions")})}):yr?s.jsx("div",{className:"flex flex-1 flex-col",children:s.jsx(Gu,{onBeforeCapture:Ss,onDragStart:Tr,onDragEnd:W=>En(ps,W),children:s.jsx(Fl,{droppableId:"sidebar-groups",type:"group",direction:"vertical",children:W=>s.jsxs("div",{ref:W.innerRef,...W.droppableProps,className:"flex flex-1 flex-col space-y-1.5",children:[jr.map((Re,Ke)=>{const lt=Xr.has(Re.key),ut=!lt&&Ke===jr.length-1,It=r0(Re.sessions,v,Zr,Qr);let _t=0,Qt=0;for(const Pt of Re.sessions){const z=l.get(Pt.id);z?.agentStatus==="working"&&(_t+=1),(z?.agentStatus==="waiting"||z?.agentNeedsReview)&&(Qt+=1)}const xt=Re.key==="";return s.jsx(Ol,{draggableId:`sidebar-group:${Re.key||"__ungrouped__"}`,index:Ke,isDragDisabled:xt,disableInteractiveElementBlocking:!0,children:(Pt,z)=>s.jsxs("div",{ref:Pt.innerRef,...Pt.draggableProps,className:`shrink-0 rounded-md transition-colors ${ut?"flex flex-1 flex-col ":""}${z.isDragging?"bg-surface-elevated shadow-lg opacity-90":""}`,children:[s.jsxs("button",{type:"button",...xt?{}:Pt.dragHandleProps,onClick:()=>{Bn(Re.key),mr.current.delete(Re.key)},className:`flex w-full shrink-0 items-center gap-1.5 rounded-md px-1.5 pb-1 pt-2.5 text-left text-muted-foreground transition hover:bg-surface-2 ${xt?"":"cursor-grab active:cursor-grabbing"}`,title:Re.key||Re.label,children:[s.jsx(qs,{size:13,className:`shrink-0 transition-transform ${lt?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[10.5px] font-semibold uppercase tracking-[0.08em]",children:Re.label}),_t>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)] animate-pulse"}),Qt>0&&s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] animate-pulse"}),s.jsx(yb,{sessionIds:Re.sessions.map(R=>R.id)}),s.jsx("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:Re.sessions.length})]}),!lt&&s.jsx("div",{className:`mt-0.5 pl-2 ${ut?"flex flex-1 flex-col":""}`,children:s.jsx(Fl,{droppableId:`group-sessions:${Re.key}`,type:"session",direction:"vertical",isCombineEnabled:!Jt,children:R=>s.jsxs("div",{ref:R.innerRef,...R.droppableProps,"data-sidebar-entity-list-id":`group-sessions:${Re.key}`,className:`${ut?"flex-1 ":""}space-y-0.5`,children:[It.map((F,q)=>s.jsx(Ol,{draggableId:F.id,index:q,disableInteractiveElementBlocking:!0,children:(se,Ee)=>s.jsxs("div",{ref:se.innerRef,...se.draggableProps,"data-sidebar-gesture-ignore":!0,"data-sidebar-entity-index":q,className:"relative",children:[Cn(q),q===It.length-1&&Cn(It.length,"bottom"),F.kind==="workspace"?rs(F.workspace,F.members,Ee.isDragging,!!Ee.combineTargetFor,se.dragHandleProps):F.kind==="collaboration"?Fr(F.group,F.members,se.dragHandleProps,Ee.isDragging,!!Ee.combineTargetFor):s.jsx("div",{...P?ws(()=>P(F.session.id)):{},className:`sidebar-session-row group relative flex items-center gap-1 rounded-md pr-1 transition-colors ${Ee.combineTargetFor?"bg-primary/15 text-foreground ring-1 ring-primary/40":Ee.isDragging?"bg-surface-elevated text-foreground opacity-90 shadow-lg":Cs(F.session.id)} cursor-grab active:cursor-grabbing`,children:Pn(F.session,se.dragHandleProps)})]})},F.id)),R.placeholder]})})})]})},Re.key||"__ungrouped__")}),W.placeholder]})})})}):$r(ds,"sidebar-entities")]}),s.jsx(E9,{onReselect:()=>{d&&(gn.current=null,Pe(W=>W+1),d())}}),Ie&&s.jsx(ZO,{directories:a.flatMap(W=>{const Re=l.get(W.id)?.cwd;return Re?[Re]:[]}),tmuxAvailable:oe,options:be,launchPending:Ze,launchError:le?ie(h1(le)):null,agents:rt,selectedAgent:gt,detecting:cn,resumeHistory:Ut,resumeHistoryLoading:Nt,resumeHistoryPendingId:jt,resumeHistoryError:Rt,onRefreshAgents:()=>{Kr().catch(()=>{})},onSelectAgent:W=>{wn(W).catch(()=>{})},onLaunchAgent:Br,onResumeHistory:W=>{Pr(W)},onRemoveResumeHistory:W=>{xn(W)},onClose:()=>xe(!1),onOptionsChange:Ct,additionalContent:ht&&U?.latestVersion&&s.jsxs("div",{className:"mb-1 rounded-lg bg-[rgb(var(--warning-rgb)_/_0.10)] px-2.5 py-2.5 text-foreground",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]",children:s.jsx(vn,{size:13,className:U.status==="checking"||U.status==="installing"||U.status==="restarting"?"animate-spin":""})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-semibold",children:ie("sidebar.updateAvailable",{version:U.latestVersion})}),s.jsx("span",{className:"mt-0.5 block text-[10.5px] leading-relaxed text-muted-foreground",children:U.status==="checking"?ie("settings.updateChecking"):U.status==="installing"?ie("sidebar.updateInstalling"):U.status==="ready"?ie("sidebar.updateReady"):U.status==="restarting"?ie("sidebar.updateRestarting"):U.error||ie("sidebar.updateFailed")})]})]}),U.status==="ready"&&J&&s.jsx("button",{type:"button",disabled:Z,onClick:J,className:"mt-2 flex w-full items-center justify-center rounded-md bg-[var(--warning)] px-2 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:ie("sidebar.updateRestart")}),U.status==="error"&&H&&s.jsx("button",{type:"button",disabled:Z,onClick:H,className:"mt-2 flex w-full items-center justify-center rounded-md bg-surface-elevated px-2 py-1.5 text-[11px] font-semibold text-foreground transition hover:bg-surface-2 disabled:cursor-wait disabled:opacity-60",children:ie("sidebar.updateRetry")})]})}),dt&&s.jsx(ay,{onEnterGroup:async W=>{if(!await Gr(W))throw new Error("协作组已保存,打开工作区失败,请重试");it(!1)},onFloatingChange:async W=>{if(W){if(!await Gr(W))throw new Error("打开协作工作区失败");it(!1)}},activeSessionId:c,defaultSessionMode:te,onClose:()=>it(!1),onNewSession:W=>f(W)}),Object.entries(Ue).map(([W,Re])=>s.jsx(ay,{activeSessionId:c,initialCollaborationGroupId:W,initialFloating:Re,visible:!_e,onEnterGroup:async Ke=>{if(Ke===W){await Gr(Ke);return}if(!await Gr(Ke))throw new Error("协作组已保存,打开工作区失败,请重试");await eo({floatingGroupId:null},W),ke(lt=>{const ut={...lt};return delete ut[W],ut})},onFloatingChange:Ke=>wt(W,Ke),defaultSessionMode:te,onClose:()=>{ae.current=!0,ke(Ke=>{const lt={...Ke};return delete lt[W],lt})},onNewSession:Ke=>f(Ke)},W)),!Ie&&s.jsxs("div",{className:"relative z-10 shrink-0 bg-[var(--chrome-bg)] px-3 pb-3 pt-1 md:border-t md:border-border md:p-2",children:[le&&s.jsx("p",{role:"alert",className:"mb-2 text-[11px] leading-relaxed text-destructive",children:ie(h1(le))}),s.jsxs("div",{className:`grid gap-1.5 [&>button]:min-h-11 [&>button]:shadow-none [&>button]:ring-0 md:[&>button]:min-h-0 ${gt?"grid-cols-[minmax(0,1fr)_minmax(0,1fr)_2.5rem]":"grid-cols-[minmax(0,1fr)_2.5rem]"}`,children:[s.jsxs("button",{type:"button",onClick:Mt,disabled:Ze,"aria-busy":Ze,className:`flex min-w-0 items-center justify-center gap-2 rounded-lg px-2 py-2.5 text-[12px] font-semibold transition active:scale-[0.99] ${gt?"bg-surface-elevated text-foreground ring-1 ring-border/30 hover:bg-surface-2":"bg-primary text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90"}`,title:ie("sidebar.newSession"),"aria-label":ie("sidebar.newSession"),children:[s.jsx(tl,{size:15,className:"shrink-0"}),s.jsx("span",{className:"truncate",children:Ze?ie("sidebar.sessionCreating"):"Terminal"})]}),gt&&s.jsxs("button",{type:"button",onClick:vr,disabled:Ze,"aria-busy":Ze,className:"flex min-w-0 items-center justify-center gap-2 rounded-lg bg-primary px-2 py-2.5 text-[12px] font-semibold text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 transition hover:bg-primary/90 active:scale-[0.99]",title:ie("sidebar.newSessionWithAgent",{agent:gt.displayName}),"aria-label":ie("sidebar.newSessionWithAgent",{agent:gt.displayName}),children:[s.jsx(ru,{agent:gt,size:15}),s.jsx("span",{className:"truncate",children:gt.displayName})]}),s.jsxs("button",{type:"button",onClick:Kn,disabled:Ze,className:"relative inline-flex w-10 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-[0.97]",title:Ht,"aria-label":Ht,"aria-expanded":Ie,"aria-controls":"sidebar-launch-options",children:[s.jsx(Do,{size:15}),ht&&s.jsx("span",{className:"absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-[var(--warning)] ring-2 ring-[var(--chrome-bg)]","aria-hidden":"true"})]})]})]})]});return qe?s.jsx("div",{"data-session-sidebar-pinned":!0,className:"h-full flex flex-col app-chrome-bg border-r border-border",children:pn}):s.jsx(u4,{side:"left",isOpen:e,drawerWidthPx:t,onClose:r,onOpen:n,push:Ce,children:pn})}function GF(e,t,r,n,a){let c=t,l=null,d=!1;const f=e.style.width,m=document.body.style.cursor,x=document.body.style.userSelect,y=()=>n(r+c-t),w=()=>{l=null,e.style.width=`${y()}px`},v=N=>{c=N.clientX,l===null&&(l=requestAnimationFrame(w))},T=N=>{d||(d=!0,window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",S),window.removeEventListener("blur",I),l!==null&&cancelAnimationFrame(l),l=null,document.body.style.cursor=m,document.body.style.userSelect=x,N?(w(),y()!==r&&a(y())):e.style.width=f)},S=N=>{c=N.clientX,T(!0)},I=()=>T(!0);return document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",v),window.addEventListener("mouseup",S),window.addEventListener("blur",I),()=>T(!1)}function VF(){const{t:e}=Ur();return s.jsxs("div",{role:"status","aria-label":e("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[s.jsx("span",{className:"sr-only",children:e("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",className:"shrink-0 border-b border-border/15 px-3 py-2",children:[s.jsxs("div",{className:"mb-2 flex h-5 items-center gap-1",children:[s.jsx("div",{className:"h-4 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-7 rounded bg-surface-2"}),s.jsx("div",{className:"h-4 w-12 rounded bg-surface-2"})]}),s.jsxs("div",{className:"flex h-[15px] items-center justify-between",children:[s.jsx("div",{className:"h-2 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-6 rounded bg-surface-2"})]}),s.jsxs("div",{className:"mt-2 flex h-7 items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-12 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-7 w-16 rounded-full bg-surface-2"}),s.jsx("div",{className:"h-3 w-24 max-w-[30%] rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-4 rounded-full bg-surface-2"})]})]}),s.jsxs("div",{"aria-hidden":"true",className:"overflow-hidden px-3 py-2",children:[s.jsxs("div",{className:"flex h-8 items-center gap-2",children:[s.jsx("div",{className:"h-3 w-3 rounded-sm bg-surface-2"}),s.jsx("div",{className:"h-2 w-32 max-w-[55%] rounded bg-surface-2"})]}),["w-3/5","w-2/5","w-1/2","w-1/3"].map((t,r)=>s.jsxs("div",{className:"flex h-9 items-center gap-2 pl-5",style:{opacity:1-r*.15},children:[s.jsx("div",{className:"h-3 w-3 shrink-0 rounded-sm bg-surface-2"}),s.jsx("div",{className:`h-2 rounded bg-surface-2 ${t}`})]},t))]})]})}function qF({slow:e=!1}){const{t}=Ur();return s.jsxs("div",{role:"status","aria-label":t("rightSidebar.loadingGitChanges"),className:"td-loading-skeleton relative h-full min-h-0 overflow-hidden bg-surface px-3",children:[s.jsx("span",{className:"sr-only",children:t("rightSidebar.loadingGitChanges")}),s.jsxs("div",{"aria-hidden":"true",children:[s.jsxs("div",{className:"flex h-[76px] items-center gap-2 border-b border-border/40 px-2",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"h-2 w-12 rounded bg-surface-2"})]})]}),s.jsxs("div",{className:"flex h-11 items-center gap-2 px-1 pt-3",children:[s.jsx("div",{className:"h-6 w-6 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"}),s.jsx("div",{className:"ml-auto h-4 w-12 rounded-full bg-surface-2"})]}),[!1,!0].map(r=>s.jsxs("div",{className:"border-b border-border/40 px-1 py-4",children:[s.jsxs("div",{className:"mb-2 flex h-8 items-center justify-between",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),r&&s.jsx("div",{className:"h-2 w-28 rounded bg-surface-2"})]}),s.jsx("div",{className:"h-8 w-12 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]},String(r))),s.jsx("div",{className:"flex h-[69px] items-center border-b border-border/40 px-2",children:s.jsx("div",{className:"h-3 w-16 rounded bg-surface-2"})}),s.jsxs("div",{className:"space-y-2 px-1 py-4",children:[s.jsxs("div",{className:"flex h-8 items-center justify-between",children:[s.jsx("div",{className:"h-3 w-14 rounded bg-surface-2"}),s.jsx("div",{className:"h-8 w-28 rounded-md bg-surface-2"})]}),s.jsx("div",{className:"h-7 rounded-md bg-surface-2"}),s.jsx("div",{className:"h-10 rounded-md bg-surface-2"})]})]}),e&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 rounded-md bg-surface-elevated px-3 py-2 text-xs text-muted-foreground",children:t("rightSidebar.loadingGitChangesSlow")})]})}const k4=()=>Zc(()=>import("./RightSidebar-akYx_nRq.js").then(e=>e.R),__vite__mapDeps([7,1,2,3,4,5,8,9,10,11,12,13,14,15,16,17])).then(e=>({default:e.RightSidebar})),YF=b.lazy(k4);function gy(e){const t=b.useRef(!1);b.useEffect(()=>{const f=navigator.connection;if(!(f?.saveData||/2g|3g/.test(f?.effectiveType??"")))return gg(()=>{k4().catch(()=>{})},3e3)},[]);const{t:r}=Ur(),n=Yt(f=>f.rootPath),a=Yt(f=>f.rightTab),c=Yt(f=>f.setRightTab),l=n?.replace(/\/+$/,"").split("/").pop()||r("rightSidebar.workspace");(e.isOpen||e.pinned)&&(t.current=!0);const d=s.jsx(u4,{side:"right",isOpen:e.isOpen,drawerWidthPx:e.drawerWidthPx,onClose:e.onClose,onOpen:e.onOpen,pinned:e.pinned,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[s.jsxs("div",{className:"shrink-0 border-b border-border/15 bg-surface px-2 pt-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"min-w-0 flex-1 px-1",children:s.jsx("div",{className:"flex min-h-[1.25rem] items-baseline gap-1.5",children:s.jsx("span",{className:"truncate text-[13px] font-semibold text-foreground",children:l})})}),s.jsx("div",{"aria-hidden":"true",className:"flex items-center gap-1.5",children:[Gl,kS,Do].map((f,m)=>s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-surface-2 text-muted-foreground",children:s.jsx(f,{size:14})},m))}),s.jsx("button",{type:"button",onClick:e.onClose,"aria-label":r("common.close"),className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:s.jsx(jn,{size:14})})]}),s.jsx("div",{className:"mt-2 grid grid-cols-5 gap-0.5 rounded-md bg-surface-2 p-0.5",children:[["git",GA,"rightSidebar.tabGit"],["diff",qA,"rightSidebar.tabChanges"],["files",nu,"rightSidebar.tabFiles"],["architecture",hS,"architecture.tab"],["computer",j9,"rightSidebar.tabComputer"]].map(([f,m,x])=>s.jsxs("button",{type:"button",onClick:()=>c(f),className:`flex items-center justify-center gap-1 rounded px-2 py-1.5 text-[11px] font-medium ${a===f?"bg-surface-elevated text-foreground":"text-muted-foreground"}`,children:[s.jsx(m,{size:12}),r(x)]},f))}),s.jsx("div",{className:"h-2"})]}),s.jsx("div",{className:"min-h-0 flex-1 bg-surface",children:a==="architecture"?s.jsx("div",{role:"status",className:"p-3 text-xs text-muted-foreground",children:r("architecture.loading")}):a==="computer"?s.jsx("div",{className:"p-3 text-xs text-muted-foreground",children:r("computer.loading")}):a==="git"?s.jsx(qF,{}):s.jsx(VF,{})})]})});return t.current?s.jsx(b.Suspense,{fallback:d,children:s.jsx(YF,{...e})}):d}const xy=Sc(e=>({overlay:"off",setOverlay:t=>e({overlay:t})}));function ZF(e){let t=1,r="terminal";for(;;){let n=!1;for(const a of e.values())if(a.name===r){n=!0;break}if(!n)break;r=`terminal-${t}`,t++}return r}const KF=Sc((e,t)=>({sessions:new Map,activeSessionId:null,nextSessionNumber:1,createSession:r=>{const n=j3(),a=Date.now(),c=t().sessions,l=ZF(c),d={id:n,cwd:r,sessionId:null,name:l,customName:!1,createdAt:a,lastActivity:a};return e(f=>{const m=new Map(f.sessions);return m.set(n,d),{sessions:m,activeSessionId:f.activeSessionId??n,nextSessionNumber:f.nextSessionNumber+1}}),n},closeSession:r=>{e(n=>{const a=new Map(n.sessions),c=n.activeSessionId===r;a.delete(r);let l=n.activeSessionId;if(c){const d=Array.from(a.keys());l=d.length>0?d[0]:null}return{sessions:a,activeSessionId:l}})},switchSession:r=>{e(n=>n.sessions.has(r)?{activeSessionId:r}:n)},updateSession:(r,n)=>{e(a=>{const c=a.sessions.get(r);if(!c)return a;const l=new Map(a.sessions);return l.set(r,{...c,...n,lastActivity:Date.now()}),{sessions:l}})},setTerminalSession:(r,n)=>{t().updateSession(r,{sessionId:n.sessionId})},getActiveSession:()=>{const r=t();if(r.activeSessionId)return r.sessions.get(r.activeSessionId)},getSessionCount:()=>t().sessions.size,clearAllSessions:()=>{e({sessions:new Map,activeSessionId:null,nextSessionNumber:1})}})),XF=[7e5,1e6,14e5,18e5,24e5,32e5,4e6,5e6,6e6,8e6,1e7,12e6].map(e=>({id:"auto",maxSize:1600,bitRate:e,maxFps:30}));class JF{level=6;badSince=null;goodSince=null;connectedAt=0;lastSample=-1/0;lastChange=-1/0;lastUpgrade=-1/0;upgradeAfter=0;failedProbes=0;baselineRtt=1/0;get quality(){return XF[this.level]}connected(t){this.connectedAt=t,this.badSince=this.goodSince=null,this.lastSample=-1/0}sample(t,r,n=1600){if(r-this.lastSample>2500&&(this.badSince=this.goodSince=null),this.lastSample=r,t.rttMs!==null&&(this.baselineRtt=Math.min(this.baselineRtt,t.rttMs)),r-this.connectedAt<3e3)return null;const a=t.rttMs!==null&&t.rttMs>this.baselineRtt+150,c=t.deliveryDelayMs>250||t.decodeQueue>=4||a&&t.frames>0&&t.deliveryDelayMs>100,l=t.deliveryDelayMs>800||t.decodeQueue>=8,d=t.rttMs!==null&&t.rttMs<this.baselineRtt+100&&t.deliveryDelayMs<80&&t.decodeQueue<=1;this.badSince=c?this.badSince??r:null,this.goodSince=d?this.goodSince??r:null;const f=n<=1080?7:n<=1600?9:11;if(this.badSince!==null&&r-this.badSince>=(l?1e3:2e3)&&r-this.lastChange>=(l?2e3:3e3)&&this.level>0){this.level=Math.max(0,this.level-(l?2:1));const m=r-this.lastUpgrade<2e4;this.failedProbes=m?this.failedProbes+1:0,this.upgradeAfter=r+(m?Math.min(3e4,8e3*2**(this.failedProbes-1)):5e3),this.lastUpgrade=-1/0}else if(this.goodSince!==null&&r-this.goodSince>=3e3&&r-this.lastChange>=4e3&&r>=this.upgradeAfter&&this.level<f)this.level++,this.lastUpgrade=r;else return null;return this.lastChange=r,this.badSince=this.goodSince=null,this.quality}}function e$(e,t){const r=new Map,n=a=>a.serial===t?0:a.state!=="device"?5:a.isNetwork?a.serial.startsWith("[")?3:2:1;for(const a of e){const c=a.physicalId?`physical:${a.physicalId}`:`serial:${a.serial}`,l=r.get(c);(!l||n(a)<n(l))&&r.set(c,a)}return[...r.values()]}async function du(e,t){const r=await fetch(e,{...t,headers:{"Content-Type":"application/json",Accept:"application/json",...t?.headers??{}}}),n=await r.json().catch(()=>null);if(!r.ok||!n){const a=n?.error||n?.code||`ANDROID_REQUEST_FAILED_${r.status}`;throw new Error(a)}return n}async function t$(){return du("/api/android/devices")}async function r$(e){return du("/api/android/connect",{method:"POST",body:JSON.stringify({address:e})})}const ap=[{id:"low",maxSize:720,bitRate:12e5,maxFps:30},{id:"medium",maxSize:1080,bitRate:4e6,maxFps:30},{id:"high",maxSize:1600,bitRate:8e6,maxFps:60}],H0=ap[1];function ng(e){if(!e||typeof e!="object")return H0;const t=e;if(t.id==="auto")return{id:"auto",maxSize:1600,bitRate:4e6,maxFps:30};const r=ap.find(l=>l.id===t.id);if(r)return r;if(t.id!=="custom")return H0;const n=typeof t.maxSize=="number"?Math.max(360,Math.min(2160,Math.round(t.maxSize))):1080,a=typeof t.bitRate=="number"?Math.max(3e5,Math.min(3e7,Math.round(t.bitRate))):4e6,c=typeof t.maxFps=="number"?Math.max(0,Math.min(60,Math.round(t.maxFps))):30;return{id:"custom",maxSize:n,bitRate:a,maxFps:c}}function n$(e,t){if(e.length>128||!/^(?:[0-9a-zA-Z_.:\-]+|\[[0-9a-fA-F:.]+\]:\d{1,5})$/.test(e))throw new Error("INVALID_SERIAL");const r=new URLSearchParams;t&&(r.set("max_size",String(t.maxSize)),r.set("bit_rate",String(t.bitRate)),t.maxFps>0&&r.set("max_fps",String(t.maxFps)));const n=r.toString();return`/api/android/${e}/ws${n?`?${n}`:""}`}function Vh(e){const t={ADB_UNAVAILABLE:"本机没有可用的 adb,请先安装 Android platform-tools。",ADB_NOT_FOUND:"找不到 adb 可执行文件,可用 TERMDOCK_ADB_BIN 指定路径。",SCRCPY_NOT_FOUND:"本机没有 scrcpy,请先安装(含 scrcpy-server)。",SCRCPY_SERVER_NOT_FOUND:"找不到 scrcpy-server,可用 TERMDOCK_SCRCPY_SERVER 指定路径。",SCRCPY_VERSION_UNKNOWN:"无法读取 scrcpy 版本,请确认 scrcpy --version 可执行。",SCRCPY_CONNECT_TIMEOUT:"设备连接超时,请确认已授权 USB 调试并保持解锁。",SCRCPY_UNSUPPORTED_CODEC:"设备返回了不支持的视频编码。",INVALID_ADDRESS:"地址格式不正确,应为 ip:port。",API_NOT_ALLOWED:"当前设备权限不足:投屏需要全权服务授权。"};for(const[r,n]of Object.entries(t))if(e.includes(r))return n;return e}function s$(e){return du(`/api/android/recordings?serial=${encodeURIComponent(e)}`)}function i$(e){return du("/api/android/recordings",{method:"POST",body:JSON.stringify({serial:e})})}function a$(e){return du(`/api/android/recordings/${encodeURIComponent(e)}/stop`,{method:"POST"})}function o$(e,t){return du(`/api/android/recordings/${encodeURIComponent(e)}/save`,{method:"POST",body:JSON.stringify({directory:t})})}function l$(e){return du(`/api/android/recordings/${encodeURIComponent(e)}`,{method:"DELETE"})}const c$=0,u$=1,d$=2,h$=3,f$=4,p$=5,m$=7,g$=10,x$=11,b$=16,by=17,yy=0,Xm=1,y$=2,vy=3,Jm=0,wy=1,Ay=1,Du=0xffffffffffffffffn,qh=0xfffffffffffffffen,n0={HOME:3,APP_SWITCH:187,POWER:26,VOLUME_UP:24,VOLUME_DOWN:25};function L4(e,t,r){e.setUint32(t,Math.max(0,Math.round(r.x))&4294967295),e.setUint32(t+4,Math.max(0,Math.round(r.y))&4294967295),e.setUint16(t+8,Math.min(65535,Math.round(r.screenWidth))),e.setUint16(t+10,Math.min(65535,Math.round(r.screenHeight)))}function v$(e,t,r,n,a,c){const l=new Uint8Array(32),d=new DataView(l.buffer);return d.setUint8(0,d$),d.setUint8(1,e),d.setBigUint64(2,t),L4(d,10,r),d.setUint16(22,Math.max(0,Math.min(65535,Math.round(n*65536)))),d.setUint32(24,a>>>0),d.setUint32(28,c>>>0),l}function e1(e,t,r=0,n=0){const a=new Uint8Array(14),c=new DataView(a.buffer);return c.setUint8(0,c$),c.setUint8(1,e),c.setUint32(2,t>>>0),c.setUint32(6,r>>>0),c.setUint32(10,n>>>0),a}function w$(e,t,r,n=0){const a=new Uint8Array(21),c=new DataView(a.buffer);c.setUint8(0,h$),L4(c,1,e);const l=d=>Math.max(-32768,Math.min(32767,Math.round(Math.max(-1,Math.min(1,d/16))*32768)));return c.setInt16(13,l(t)),c.setInt16(15,l(r)),c.setUint32(17,n>>>0),a}function A$(e){const t=new TextEncoder().encode(e);if(!t.length)return null;const r=t.subarray(0,300),n=new Uint8Array(5+r.length),a=new DataView(n.buffer);return a.setUint8(0,u$),a.setUint32(1,r.length),n.set(r,5),n}function T$(e){const t=new TextEncoder().encode(e);if(!t.length||t.length>255)return null;const r=new Uint8Array(2+t.length);return r[0]=b$,r[1]=t.length,r.set(t,2),r}function s0(e){return new Uint8Array([e])}function Ty(e){return new Uint8Array([f$,e])}function S$(e){return new Uint8Array([g$,e?1:0])}function C$(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}function _$(e){const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function t1(e){return e.toString(16).padStart(2,"0")}function I4(e,t,r){for(let n=0;n+4<e.length;n++){const a=e[n]===0&&e[n+1]===0&&e[n+2]===1,l=e[n]===0&&e[n+1]===0&&e[n+2]===0&&e[n+3]===1?n+4:a?n+3:-1;if(l<0||l>=e.length)continue;if((r?e[l]>>1&63:e[l]&31)!==t){n=l-1;continue}let f=l+1;for(;f+2<e.length&&!(e[f]===0&&e[f+1]===0&&(e[f+2]===1||e[f+2]===0&&e[f+3]===1));)f++;return e.subarray(l,Math.min(e.length,f))}return null}function k$(e){const t=e?I4(e,7,!1):null;return t&&t.length>=4?`avc1.${t1(t[1])}${t1(t[2])}${t1(t[3])}`:"avc1.42e01e"}function L$(e){const t=e?I4(e,32,!0):null;if(t&&t.length>=13){const r=t[1]>>6&3,n=t[1]&31,a=t[12];return`hev1.${r}.${n}.L${a}.B0`}return"hev1.1.6.L120.B0"}class I${constructor(t,r){this.canvas=t,this.callbacks=r}canvas;callbacks;liveBitrate=!1;bitrateFailureDetail;get lastBitrateFailure(){return this.bitrateFailureDetail}bitrateRequestId=0;bitratePending=null;get supportsLiveBitrate(){return this.liveBitrate}get canSetBitrate(){return this.liveBitrate&&!this.bitratePending&&this.socket?.readyState===1}setBitrate(t){return!this.canSetBitrate||!Number.isInteger(t)||t<3e5||t>3e7?Promise.resolve(!1):new Promise(r=>{const n=++this.bitrateRequestId,a=setTimeout(()=>this.finishBitrate(!1,`BITRATE_CLIENT_TIMEOUT: requested=${t} bps; no server confirmation within 4000ms`),4e3);this.bitratePending={id:n,value:t,resolve:r,timer:a},this.send({type:"bitrate",requestId:n,bitRate:t})})}finishBitrate(t,r){const n=this.bitratePending;n&&(this.bitratePending=null,clearTimeout(n.timer),t||(this.liveBitrate=!1,this.bitrateFailureDetail=r??this.bitrateFailureDetail??"BITRATE_REASON_UNAVAILABLE: server rejected adjustment without a diagnostic",this.closedByUser||this.callbacks.onBitrateSupport?.(!1,this.bitrateFailureDetail)),n.resolve(t))}socket=null;decoder=null;configured=!1;configData=null;header=null;closedByUser=!1;failureReason=null;lastMessageAt=0;lastFrameAt=0;lastResetAt=0;heartbeat=null;statsTimer=null;stallTimer=null;pendingConfig=null;needsKeyframe=!1;frameCount=0;receivedFrames=0;decodedFrames=0;controlsSent=0;lastSeq=0;lastType="";bytesSinceSample=0;warnedUnsupported=!1;lastSampleAt=0;serial="";autoQuality=!1;pingAt=null;rttMs=null;rttAt=0;minimumFrameOffset=1/0;deliveryDelayMs=0;peakDecodeQueue=0;sampleFrames=0;get currentHeader(){return this.header}connect(t,r){this.liveBitrate=!1,this.bitrateFailureDetail=void 0,this.serial=t,this.autoQuality=r?.id==="auto",this.closedByUser=!1,this.failureReason=null,this.callbacks.onState("connecting");let n;try{n=D9(n$(t,r))}catch(a){this.reportError(a instanceof Error?a.message:"ANDROID_STREAM_FAILED");return}this.socket=n,n.onopen=()=>{this.lastMessageAt=Date.now()},n.onmessage=a=>{this.closedByUser||this.handleMessage(a.data)},n.onerror=()=>{!this.closedByUser&&!this.failureReason&&this.reportError("SCRCPY_CONNECTION_LOST")},n.onclose=a=>{if(this.finishBitrate(!1,"BITRATE_CONNECTION_CLOSED: preview connection closed"),this.liveBitrate=!1,this.teardownTimers(),this.closedByUser)this.callbacks.onState("idle");else{const c=`WebSocket close code=${a.code}${a.reason?`: ${a.reason}`:""}`;this.reportError(`${this.failureReason||"SCRCPY_CONNECTION_CLOSED"}
163
163
  ${c}`)}},this.startTimers()}reportError(t){this.failureReason=t,this.callbacks.onState("error",t)}disconnect(){this.closedByUser=!0,this.finishBitrate(!1),this.liveBitrate=!1,this.teardownTimers();try{this.decoder?.close()}catch{}this.decoder=null,this.configured=!1;try{this.socket?.close()}catch{}this.socket=null,this.callbacks.onState("idle")}teardownTimers(){this.heartbeat&&clearInterval(this.heartbeat),this.statsTimer&&clearInterval(this.statsTimer),this.stallTimer&&clearInterval(this.stallTimer),this.heartbeat=null,this.statsTimer=null,this.stallTimer=null}startTimers(){this.lastSampleAt=Date.now(),this.heartbeat=setInterval(()=>{if(!(!this.socket||this.socket.readyState!==1)){if(Date.now()-this.lastMessageAt>45e3){try{this.socket.close()}catch{}return}this.pingAt===null&&(this.pingAt=performance.now(),this.send({type:"ping"}))}},this.autoQuality?2e3:15e3),this.stallTimer=setInterval(()=>{if(!this.header||this.closedByUser)return;const t=Date.now();t-this.lastFrameAt>8e3&&t-this.lastResetAt>8e3&&(this.lastResetAt=t,console.warn("[android] no frames for 8s; requesting keyframe reset"),this.sendControl(s0(by)))},2e3),this.statsTimer=setInterval(()=>{const t=Date.now(),r=(t-this.lastSampleAt)/1e3;r<=0||(this.callbacks.onStats({fps:Math.round(this.frameCount/r*10)/10,kbps:Math.round(this.bytesSinceSample*8/r/1e3),width:this.header?.width??0,height:this.header?.height??0,received:this.receivedFrames,decoded:this.decodedFrames,controls:this.controlsSent,last:this.lastType,adaptation:this.autoQuality?{rttMs:this.pingAt!==null&&performance.now()-this.pingAt>2e3?performance.now()-this.pingAt:performance.now()-this.rttAt<6e3?this.rttMs:null,deliveryDelayMs:this.sampleFrames?this.deliveryDelayMs:0,decodeQueue:Math.max(this.peakDecodeQueue,this.decoder?.decodeQueueSize??0),frames:this.sampleFrames}:void 0}),this.sampleFrames=0,this.peakDecodeQueue=0,this.frameCount=0,this.bytesSinceSample=0,this.lastSampleAt=t)},1e3)}send(t){if(!(!this.socket||this.socket.readyState!==1))try{this.socket.send(JSON.stringify(t))}catch{}}sendControl(t){t&&(this.controlsSent++,this.send({type:"control",data:C$(t)}))}ack(){this.send({type:"ack",seq:this.lastSeq})}handleMessage(t){if(typeof t!="string")return;this.lastMessageAt=Date.now();let r;try{r=JSON.parse(t)}catch{return}this.lastType=`${r.type??"?"}${r.config?":cfg":""}${r.key?":key":""}`;try{this.dispatchMessage(r)}catch(n){console.warn("[android] message handling failed",n),this.callbacks.onWarning(`处理消息失败:${n instanceof Error?n.message:String(n)}`)}}dispatchMessage(t){switch(t.type){case"bitrate-support":this.liveBitrate=t.supported===!0,this.bitrateFailureDetail=this.liveBitrate?void 0:typeof t.detail=="string"?t.detail.slice(0,4096):"BITRATE_REASON_UNAVAILABLE: server did not provide diagnostics",this.liveBitrate||this.finishBitrate(!1,this.bitrateFailureDetail),this.callbacks.onBitrateSupport?.(this.liveBitrate,this.bitrateFailureDetail);break;case"bitrate-result":t.requestId===this.bitratePending?.id&&this.finishBitrate(t.applied===!0&&t.bitRate===this.bitratePending?.value,typeof t.detail=="string"?t.detail.slice(0,4096):void 0);break;case"header":this.header={deviceName:t.deviceName??this.serial,codec:t.codec??"h264",width:t.width??0,height:t.height??0},this.lastFrameAt=Date.now(),this.callbacks.onHeader(this.header),this.failureReason=null,this.callbacks.onState("streaming");break;case"frame":this.handleFrame(t);break;case"error":this.reportError(t.message||"SCRCPY_ERROR");break;case"closed":this.reportError(this.failureReason||"SCRCPY_SESSION_CLOSED");break;case"pong":this.pingAt!==null&&(this.rttMs=performance.now()-this.pingAt,this.rttAt=performance.now(),this.pingAt=null);break}}handleFrame(t){if(typeof t.data!="string")return;typeof t.seq=="number"&&(this.lastSeq=t.seq);const r=_$(t.data);if(this.bytesSinceSample+=t.data.length,this.receivedFrames++,this.lastFrameAt=Date.now(),this.decoder?.state==="closed"&&(this.decoder=null,this.configured=!1),t.config){this.configData=r,this.pendingConfig=r,this.configureDecoder(),this.ack();return}this.sampleFrames++;const n=Number(t.pts);if(t.pts!==void 0&&Number.isFinite(n)){const l=performance.now()-n/1e3;this.minimumFrameOffset=Math.min(this.minimumFrameOffset,l),this.deliveryDelayMs=Math.max(0,l-this.minimumFrameOffset)}this.configured||this.configureDecoder();const a=t.key===!0;if(this.needsKeyframe&&!a){this.ack();return}let c=r;this.pendingConfig&&(c=new Uint8Array(this.pendingConfig.length+r.length),c.set(this.pendingConfig,0),c.set(r,this.pendingConfig.length),this.pendingConfig=null),a&&(this.needsKeyframe=!1),this.decode(c,a,t.pts),this.ack()}configureDecoder(){const t=this.header?.codec??"h264";if(!this.decoder||this.decoder.state==="closed"){if(typeof VideoDecoder>"u"){this.warnedUnsupported||(this.warnedUnsupported=!0,this.callbacks.onWarning("当前浏览器不支持 WebCodecs(VideoDecoder),无法解码投屏画面。")),this.reportError("VIDEO_DECODER_UNSUPPORTED");return}try{this.decoder=new VideoDecoder({output:c=>this.onDecodedFrame(c),error:c=>{this.closedByUser||(this.configured=!1,this.decoderRecovering=!0,console.warn("[android] video decoder error",c),this.reportError(`VIDEO_DECODER_ERROR: ${c.message}`),this.sendControl(s0(by)))}})}catch(c){console.warn("[android] VideoDecoder unavailable",c),this.callbacks.onWarning(`创建 VideoDecoder 失败:${c instanceof Error?c.message:String(c)}`),this.reportError("VIDEO_DECODER_UNSUPPORTED");return}}const r={codec:"avc1.42e01e",optimizeForLatency:!0};let n;t==="h264"?(n=[k$(this.configData),"avc1.42e01e","avc1.4d401e","avc1.64001f"].filter((l,d,f)=>f.indexOf(l)===d),r.avc={format:"annexb"}):t==="h265"?(n=[L$(this.configData),"hev1.1.6.L120.B0","hvc1.1.6.L120.B0"],r.hevc={format:"annexb"}):n=["av01.0.04M.08"];const a=[];for(const c of n)try{this.decoder.configure({...r,codec:c}),this.configured=!0,this.needsKeyframe=!0,c!==n[0]&&console.warn("[android] decoder configured with fallback codec",c);return}catch(l){a.push(`${c}: ${l instanceof Error?l.message:String(l)}`),console.warn("[android] decoder configure failed",c,l)}this.callbacks.onWarning(`解码器配置失败(${a.join(";")})`),this.reportError("VIDEO_DECODER_UNSUPPORTED")}decode(t,r,n){if(!(!this.decoder||this.decoder.state!=="configured"))try{this.decoder.decode(new EncodedVideoChunk({type:r?"key":"delta",timestamp:n?Number(n):this.lastTimestamp+1,data:t})),this.peakDecodeQueue=Math.max(this.peakDecodeQueue,this.decoder.decodeQueueSize),this.lastTimestamp=n?Number(n):this.lastTimestamp+1}catch(a){this.decodeFailureCount++<3&&(console.warn("[android] decode threw",a),this.callbacks.onWarning(`送入解码器失败:${a instanceof Error?a.message:String(a)}`))}}decoderRecovering=!1;decodeFailureCount=0;lastTimestamp=0;onDecodedFrame(t){if(this.closedByUser){t.close();return}this.frameCount++,this.decodedFrames++;const r=t.displayWidth||t.codedWidth,n=t.displayHeight||t.codedHeight,a=this.canvas;(a.width!==r||a.height!==n)&&(a.width=r,a.height=n,this.header&&(this.header={...this.header,width:r,height:n},this.callbacks.onHeader(this.header)));const c=a.getContext("2d");c&&c.drawImage(t,0,0,a.width,a.height),t.close(),this.decoderRecovering&&(this.decoderRecovering=!1,this.failureReason=null,this.callbacks.onState("streaming"))}pointerPoint(t,r){return{x:t,y:r,screenWidth:this.header?.width??0,screenHeight:this.header?.height??0}}touch(t,r,n,a){const c=t===Xm||t===vy,l=c?0:1,d=a===Du&&!c?Ay:0,f=(t===yy||t===Xm)&&a===Du?Ay:0;this.sendControl(v$(t,a,this.pointerPoint(r,n),l,f,d))}pointerDown(t,r,n){this.touch(yy,t,r,n==="mouse"?Du:qh)}pointerMove(t,r,n){this.touch(y$,t,r,n==="mouse"?Du:qh)}pointerUp(t,r,n){this.touch(Xm,t,r,n==="mouse"?Du:qh)}pointerCancel(t,r,n){this.touch(vy,t,r,n==="mouse"?Du:qh)}scroll(t,r,n,a){this.sendControl(w$(this.pointerPoint(t,r),n,a))}key(t,r=Jm){this.sendControl(e1(r,t))}tapKey(t){this.sendControl(e1(Jm,t)),this.sendControl(e1(wy,t))}back(){this.sendControl(Ty(Jm)),this.sendControl(Ty(wy))}home(){this.tapKey(n0.HOME)}recents(){this.tapKey(n0.APP_SWITCH)}power(){this.tapKey(n0.POWER)}volumeUp(){this.tapKey(n0.VOLUME_UP)}volumeDown(){this.tapKey(n0.VOLUME_DOWN)}rotate(){this.sendControl(s0(x$))}expandNotifications(){this.sendControl(s0(p$))}collapsePanels(){this.sendControl(s0(m$))}setDisplayPower(t){this.sendControl(S$(t))}sendText(t){this.sendControl(A$(t))}startApp(t){this.sendControl(T$(t))}}function E$(){try{return crypto.randomUUID().slice(0,8)}catch{return Math.random().toString(36).slice(2,10)}}function N$(){return`termdock-mirror-shot-${new Date().toISOString().replace(/[-:T]/g,"").slice(0,14)}-${E$()}.png`}function Sy(e){const t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return`${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`}async function R$(e,t=N$()){const r=e.width,n=e.height;if(!r||!n)throw new Error("投屏画面尚未就绪");const a=document.createElement("canvas");a.width=r,a.height=n;const c=a.getContext("2d");if(!c)throw new Error("无法读取投屏画面");c.drawImage(e,0,0);const l=await new Promise(d=>a.toBlob(d,"image/png"));if(!l||l.size===0)throw new Error("截图失败,请重试");return new File([l],t,{type:"image/png"})}function E4(e,t,r){const n=r.contentWidth*(t-1)/2,a=r.contentHeight*(t-1)/2;return{x:Math.max(-n,Math.min(n,e.x)),y:Math.max(-a,Math.min(a,e.y))}}function Cy(e,t,r,n,a){const c=Math.max(1,Math.min(8,e.zoom*a)),l=c/e.zoom;return{zoom:c,pan:E4({x:n.x-t.cx-(r.x-t.cx-e.pan.x)*l,y:n.y-t.cy-(r.y-t.cy-e.pan.y)*l},c,t)}}async function N4(e,t,r){if(!t)throw new Error("没有可接收内容的终端");if(!await M1(e,t,()=>!0,r))throw new Error("目标终端不可用,内容尚未插入,请连接终端后重试")}function _y(e,t,r){return N4(R1(e,null),t,r)}const sg=new Map;function M$(e,t){sg.set(e,t)}function j$(e,t){const r=sg.get(e.id)??t;r?.(e),r&&sg.delete(e.id)}const r1=Sc(e=>({pending:[],enqueue:(t,r,n="/",a)=>e(c=>c.pending.some(l=>l.file.id===t.id)?c:{pending:[...c.pending,{file:t,sessionId:r,initialPath:n,insert:a}]}),remove:t=>e(r=>({pending:r.pending.filter(n=>n.file.id!==t)}))}));function D$({file:e,initialPath:t,onInsert:r,onDone:n}){const{t:a}=Ur(),[c,l]=b.useState(!1),[d,f]=b.useState(!1),[m,x]=b.useState(!1),[y,w]=b.useState(!1),[v,T]=b.useState(null),S=b.useRef(!1),I=b.useRef(null);vc(I,!c,()=>{});const N=async()=>{if(!S.current){S.current=!0,f(!0),w(!0);try{await l$(e.id),n()}catch($){T($ instanceof Error?$.message:String($))}finally{S.current=!1,f(!1),w(!1)}}};b.useEffect(()=>{if(c)return;I.current?.focus();const $=Q=>{if(Q.stopPropagation(),Q.key==="Escape"&&Q.preventDefault(),Q.key!=="Tab")return;const U=Array.from(I.current?.querySelectorAll("button:not(:disabled)")??[]),Z=U[0],J=U.at(-1);Q.shiftKey&&(document.activeElement===Z||document.activeElement===I.current)?(Q.preventDefault(),J?.focus()):!Q.shiftKey&&document.activeElement===J&&(Q.preventDefault(),Z?.focus())};return document.addEventListener("keydown",$,!0),()=>document.removeEventListener("keydown",$,!0)},[c]);const P=async($,Q)=>{if(S.current)return;const U=Ig(Q);S.current=!0,f(!0),x($!==void 0),l(!1),T(null);try{const Z=await o$(e.id,$);if($===void 0&&(!U()||await r(Z.path,Q)===!1))throw new Error(a("android.captureUnavailable"));n()}catch(Z){T(Z instanceof Error?Z.message:String(Z))}finally{S.current=!1,f(!1)}};return c?s.jsx(Ap,{open:!0,initialPath:t||"/",title:a("android.recordingSave"),onCancel:()=>l(!1),onConfirm:$=>{P($)}}):Zs.createPortal(s.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-center justify-center bg-[var(--app-backdrop)] p-4",children:s.jsxs("div",{ref:I,role:"dialog","aria-modal":"true","aria-labelledby":"recording-save-title",tabIndex:-1,"aria-busy":d,className:"w-full max-w-sm rounded-xl border border-border bg-surface p-4 text-foreground shadow-xl outline-none",children:[s.jsx("h2",{id:"recording-save-title",className:"text-sm font-semibold",children:a("android.recordingConfirm")}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:a("android.recordingSaveHint")}),s.jsxs("p",{className:"mt-2 break-all text-xs text-muted-foreground",children:[e.name," · ",(e.size/1024/1024).toFixed(1)," MB"]}),(v||e.error)&&s.jsx("p",{role:"alert",className:"mt-3 break-words text-xs text-destructive",children:v||e.error}),d&&s.jsxs("p",{role:"status",className:"mt-3 flex items-center gap-2 text-sm text-primary",children:[s.jsx(Dn,{size:16,className:"animate-spin"}),y?`${a("android.recordingDiscard")}…`:a(m?"android.recordingSaving":"android.captureInserting")]}),s.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[s.jsx("button",{type:"button",disabled:d||e.status!=="ready",onClick:$=>{P(void 0,$.currentTarget)},className:"min-h-10 rounded-lg bg-primary px-3 text-sm text-primary-foreground disabled:opacity-40",children:a("android.recordingInsert")}),s.jsx("button",{type:"button",disabled:d||e.status!=="ready",onClick:()=>l(!0),className:"min-h-10 rounded-lg bg-surface-2 px-3 text-sm disabled:opacity-40",children:a("android.recordingSave")}),s.jsx("button",{type:"button",disabled:d,onClick:()=>{N()},className:"min-h-10 rounded-lg px-3 text-sm text-muted-foreground disabled:opacity-40",children:a("android.recordingDiscard")})]})]})}),document.body)}const m0="android-mirror",i0=m0,R4="termdock:android:quality:v1",n1=176,B$=204,Pl=1,Af=8,ky=[1,1.25,1.5,2,2.5,3,4,6,8],Q$=e=>Math.max(Pl,Math.min(Af,e));function P$(e){return`${Number.isInteger(e)?e:e.toFixed(1)}×`}function Yh(e){const t=e.parentElement;if(!t)return null;const r=t.getBoundingClientRect(),n=getComputedStyle(t),a=parseFloat(n.paddingLeft)||0,c=parseFloat(n.paddingTop)||0,l=t.clientWidth-a-(parseFloat(n.paddingRight)||0),d=t.clientHeight-c-(parseFloat(n.paddingBottom)||0);return{cx:r.left+t.clientLeft+a+l/2,cy:r.top+t.clientTop+c+d/2,width:l,height:d,contentWidth:e.offsetWidth,contentHeight:e.offsetHeight}}function O$(e,t){try{e.setPointerCapture?.(t)}catch{}}function Ly(e,t){try{e.releasePointerCapture?.(t)}catch{}}const Iy=e=>typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(e,16),Zh=e=>{typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):window.clearTimeout(e)},s1={auto:"android.qualityAuto",low:"android.qualityLow",medium:"android.qualityMedium",high:"android.qualityHigh",custom:"android.qualityCustom"},F$=()=>{try{const e=localStorage.getItem(R4);return e?ng(JSON.parse(e)):H0}catch{return H0}},a0=e=>{try{localStorage.setItem(R4,JSON.stringify(e))}catch{}};function $$({sessionId:e,dockOnly:t=!1,onInsertPrompt:r,onInsertFile:n,onRecordingComplete:a,onCloseTab:c}){const{t:l}=Ur(),d=xy(z=>z.overlay),f=xy(z=>z.setOverlay),m=b.useRef(null),x=b.useRef(null),y=b.useRef(null),w=b.useMemo(F$,[]),v=b.useRef(w),T=b.useRef(null),S=b.useRef(null),[I,N]=b.useState(4e6),P=b.useRef(null),$=b.useRef(new Map),Q=b.useRef(null),U=b.useRef(!1),[Z,J]=b.useState(Pl),H=b.useRef(Z),ye=b.useRef({x:0,y:0}),oe=b.useRef(null),te=b.useRef(0),Ce=b.useRef(0),qe=b.useRef(null),ve=b.useRef(0),[Y,st]=b.useState(null),[he,Qe]=b.useState(null),[ie,Pe]=b.useState(!0),[Fe,ce]=b.useState(""),[Ie,je]=b.useState(w.id),[Ze,we]=b.useState([]),[le,Ge]=b.useState(null),[He,tt]=b.useState(""),[xe,dt]=b.useState(!0),[it,_e]=b.useState({maxSize:w.maxSize,bitRate:w.bitRate,maxFps:w.maxFps}),[Ue,ke]=b.useState("idle"),[V,ae]=b.useState(null),[pe,$e]=b.useState(null),[Xe,wt]=b.useState(null),[Ut,qt]=b.useState({fps:0,kbps:0,width:0,height:0,received:0,decoded:0,controls:0,last:""}),[Nt,sr]=b.useState(null),[jt,Xt]=b.useState(null),[Rt,ir]=b.useState(null),[ge,Je]=b.useState([]),[at,Et]=b.useState(null),[X,vt]=b.useState([]),[Bt,Me]=b.useState(!1),Dr=b.useRef(null),Le=b.useRef(0),At=b.useRef([]),[Ot,er]=b.useState(!1),[ot,Lt]=b.useState(""),[nr,ur]=b.useState(!1),[Rr,Gr]=b.useState(!1),[Tt,Ft]=b.useState(""),[be,Ct]=b.useState(null),[gt,rt]=b.useState(null),[cn,Kr]=b.useState(!1),[wn,Oe]=b.useState(0),ft=b.useRef(null),[ht,Cr]=b.useState(!1),Ht=b.useRef(!1),yr=b.useRef(new Set),Xr=b.useRef(null),Bn=b.useRef(null),mn=b.useRef(!1),[hn,gn]=b.useState(!1),an=b.useRef(a);an.current=a;const[ne,Ye]=b.useState(!1),[St,Jt]=b.useState(null),Or=b.useRef(null),un=b.useRef(null),Jr=KF(z=>z.activeSessionId??z.sessions.keys().next().value??null),en=e??Jr,mr=os(z=>!!z.docks[i0]),tn=os(z=>z.hosts[i0]),Sn=os(z=>z.setDock),Zr=b.useCallback(async()=>{Pe(!0);try{const z=await t$();st(z),Qe(null)}catch(z){Qe(z instanceof Error?z.message:"ADB_UNAVAILABLE")}finally{Pe(!1)}},[]);b.useEffect(()=>{Zr()},[Zr]);const Qr=b.useMemo(()=>e$(Y?.devices??[],Fe),[Y?.devices,Fe]),lr=Qr.find(z=>z.serial===Fe)??null,fn=!!(he&&/ADB_NOT_FOUND|ADB_UNAVAILABLE/i.test(he)),Ss=!!(Y?.adbAvailable&&!Y.scrcpyVersion),Ar=b.useCallback(()=>{const z=P.current,R=[...$.current.keys()];P.current=null,$.current.clear(),Q.current=null,U.current=!1,Dr.current=null,Zh(te.current),te.current=0,z&&x.current?.pointerCancel(z.x,z.y,z.type);const F=m.current;if(F)for(const q of R)Ly(F,q);Et(null),Me(!1),vt([]),J(H.current)},[]);b.useEffect(()=>{const z=q=>{$.current.has(q.pointerId)&&(q.type==="pointercancel"||q.target!==m.current)&&Ar()},R=()=>Ar(),F=()=>{document.hidden&&Ar()};return window.addEventListener("pointerup",z,!0),window.addEventListener("pointercancel",z,!0),window.addEventListener("blur",R),document.addEventListener("visibilitychange",F),()=>{window.removeEventListener("pointerup",z,!0),window.removeEventListener("pointercancel",z,!0),window.removeEventListener("blur",R),document.removeEventListener("visibilitychange",F),Ar()}},[Ar]);const En=b.useCallback(()=>{Ar(),x.current?.disconnect(),x.current=null,ke("idle"),ae(null),$e(null),wt(null)},[Ar]),qr=b.useCallback((z,R=!1)=>{const F=m.current;if(!F||!z)return;Ar(),x.current?.disconnect(),ae(null),y.current!==z&&($e(null),ve.current=0),!R&&y.current!==z&&wt(null),y.current=z,Xt(null),sr(null);const q=new I$(F,{onBitrateSupport:(Ee,We)=>{x.current!==q||v.current.id!=="auto"||sr(Ee?null:We??"BITRATE_REASON_UNAVAILABLE")},onState:(Ee,We)=>{x.current===q&&(ke(Ee),ae(We??null),Ee==="error"?$e(We||"SCRCPY_ERROR"):Ee==="streaming"&&$e(null))},onHeader:Ee=>{x.current===q&&wt(Ee)},onStats:Ee=>{x.current===q&&qt(Ee)},onWarning:Ee=>{x.current===q&&Xt(Ee)}});x.current=q;let se=v.current;se.id==="auto"?(T.current?.serial!==z&&(T.current={serial:z,policy:new JF}),T.current.policy.connected(performance.now()),se=T.current.policy.quality,N(se.bitRate)):T.current=null,S.current=se,q.connect(z,se)},[Ar]);b.useEffect(()=>{if(Ie!=="auto"||v.current.id!=="auto"||Ue!=="streaming"||!Ut.adaptation||document.hidden)return;const z=T.current,R=x.current;if(!z||z.serial!==Fe||!R?.canSetBitrate)return;const F=m.current,q=F?Math.max(F.clientWidth,F.clientHeight)*(window.devicePixelRatio||1)*H.current:1600,se=z.policy.sample(Ut.adaptation,performance.now(),q||1600);se&&R.setBitrate(se.bitRate).then(Ee=>{Ee&&x.current===R&&(S.current=se,N(se.bitRate))})},[Ut,Ie,Ue,Fe,qr]);const Lr=b.useCallback(z=>{const R={...z.quality?{quality:{id:z.quality.id,maxSize:z.quality.maxSize,bitRate:z.quality.bitRate,maxFps:z.quality.maxFps}}:{},...z.activePresetId!==void 0?{activePresetId:z.activePresetId}:{},...z.presets!==void 0?{presets:z.presets}:{},...z.docked!==void 0?{docked:z.docked}:{},...z.deviceSerial!==void 0?{deviceSerial:z.deviceSerial}:{}};Qa({androidPanel:R}).catch(()=>{})},[]);b.useEffect(()=>{let z=!1;return Cc().then(R=>{if(z)return;const F=R.androidPanel;if(F?.quality){const q=ng(F.quality);v.current=q,je(q.id),_e({maxSize:q.maxSize,bitRate:q.bitRate,maxFps:q.maxFps}),a0(q)}we(F?.presets??[]),Ge(F?.activePresetId??null),F?.deviceSerial&&(qe.current=F.deviceSerial,ce(F.deviceSerial))}).catch(()=>{}),()=>{z=!0}},[]);const On=b.useCallback(z=>{const R=++Le.current;Je(q=>[...q,{id:R,left:z.left,top:z.top}]);const F=window.setTimeout(()=>{Je(q=>q.filter(se=>se.id!==R)),At.current=At.current.filter(q=>q!==F)},300);At.current.push(F)},[]),tr=b.useCallback((z,R)=>{const F=x.current,q=S.current;F?.supportsLiveBitrate&&y.current===z&&q&&q.maxSize===R.maxSize&&q.maxFps===R.maxFps?F.setBitrate(R.bitRate).then(se=>{x.current===F&&(se?(S.current=R,sr(null)):sr(F.lastBitrateFailure??"BITRATE_REASON_UNAVAILABLE"))}):qr(z)},[qr,l]),K=b.useCallback(z=>{if(T.current=null,z.startsWith("user:")){const F=Ze.find(se=>se.id===z.slice(5));if(!F)return;const q={id:"custom",maxSize:F.maxSize,bitRate:F.bitRate,maxFps:F.maxFps};v.current=q,je("custom"),Ge(F.id),_e({maxSize:F.maxSize,bitRate:F.bitRate,maxFps:F.maxFps}),dt(!0),a0(q),Lr({quality:q,activePresetId:F.id}),Fe&&qr(Fe);return}if(z==="custom"){const F=v.current;je("custom"),Ge(null),_e({maxSize:F.maxSize,bitRate:F.bitRate,maxFps:F.maxFps}),dt(!0);return}const R=z==="auto"?ng({id:"auto"}):ap.find(F=>F.id===z)??H0;v.current=R,je(R.id),Ge(null),a0(R),Lr({quality:R,activePresetId:null}),Fe&&qr(Fe)},[qr,Fe,Ze,Lr]),De=b.useCallback(()=>{const z={id:"custom",maxSize:it.maxSize,bitRate:it.bitRate,maxFps:it.maxFps};v.current=z,a0(z),Lr({quality:z,activePresetId:null}),je("custom"),Ge(null),Fe&&tr(Fe,z)},[tr,Fe,it,Lr]),Mt=b.useCallback(()=>{const z=He.trim();if(!z)return;const R=`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,F={id:R,name:z,maxSize:it.maxSize,bitRate:it.bitRate,maxFps:it.maxFps},q=[...Ze.filter(Ee=>Ee.name!==z),F].slice(-12),se={id:"custom",maxSize:it.maxSize,bitRate:it.bitRate,maxFps:it.maxFps};we(q),tt(""),Ge(R),je("custom"),v.current=se,a0(se),Lr({quality:se,activePresetId:R,presets:q}),Fe&&tr(Fe,se)},[He,it,Ze,Fe,tr,Lr]),vr=b.useCallback(()=>{if(!le)return;const z=Ze.filter(R=>R.id!==le);we(z),Ge(null),Lr({activePresetId:null,presets:z})},[le,Ze,Lr]);b.useEffect(()=>()=>{x.current?.disconnect(),x.current=null;for(const z of At.current)window.clearTimeout(z);At.current=[]},[]),b.useEffect(()=>{if(d==="off")return;const z=R=>{R.key==="Escape"&&f("off")};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[d,f]),b.useEffect(()=>{const z=Qr.filter(F=>F.state==="device");if(Fe||z.length!==1)return;const R=z[0].serial;qe.current!==R&&(qe.current=R,ce(R))},[Qr,Fe]),b.useEffect(()=>{Fe&&qr(Fe)},[Fe,qr]),b.useEffect(()=>{if(Ue==="streaming"&&(ve.current=0),Ue!=="error"||!Fe||!z$(V??"")){ir(null);return}const z=Math.min(8e3,700*2**ve.current),R=ve.current+1;ir({attempt:R,delayMs:z});const F=window.setTimeout(()=>{ve.current=R,ir(null),qr(Fe)},z);return()=>window.clearTimeout(F)},[Ue,V,Fe,qr]);const Dt=b.useCallback((z,R,F)=>{const q=m.current,se=F??(q?Yh(q):null);return!q||!se?{x:0,y:0}:E4(z,R,se)},[]),Br=b.useCallback(()=>{const z=m.current;if(!z)return;const{x:R,y:F}=ye.current,q=H.current,se=q===Pl&&R===0&&F===0?"":`translate3d(${R}px, ${F}px, 0) scale(${q})`;z.style.transform!==se&&(z.style.transform=se);const Ee=oe.current;Ee&&(Ee.textContent=q>Pl?P$(q):"")},[]),Pr=b.useCallback((z,R,F=!0)=>{const q=m.current,se=H.current,Ee=Q$(z);if(!q||Ee===se)return;const We=Yh(q);if(!We)return;const mt=R??{x:We.cx,y:We.cy},et=Cy({zoom:se,pan:ye.current},We,mt,mt,Ee/se);H.current=et.zoom,ye.current=et.pan,F&&Br()},[Br]),xn=b.useCallback(()=>{const z=H.current;J(R=>R<=Pl+.01==z<=Pl+.01&&R>=Af-.01==z>=Af-.01?R:z)},[]);b.useEffect(()=>()=>{Zh(te.current),Zh(Ce.current)},[]);const Kn=()=>{let z=0,R=0;for(const q of $.current.values())z+=q.x,R+=q.y;const F=$.current.size;return F?{x:z/F,y:R/F}:null},Cs=()=>{const[z,R]=Array.from($.current.values());return z&&R?Math.hypot(z.x-R.x,z.y-R.y):0},ws=()=>{const z=Kn(),R=m.current?Yh(m.current):null;!z||!R||(Q.current={startCentroid:z,startDistance:Cs(),box:R})},Wr=b.useCallback(()=>{const z=Q.current,R=Kn();if(!z||!R)return;const F=Cs(),q=z.startDistance>0&&F>0?F/z.startDistance:1,se=Cy({zoom:H.current,pan:ye.current},z.box,z.startCentroid,R,q);H.current=se.zoom,ye.current=se.pan,z.startCentroid=R,z.startDistance=F},[]),Qn=b.useCallback(()=>{te.current||(te.current=Iy(()=>{te.current=0,Wr(),Br()}))},[Wr,Br]),Pn=b.useCallback(()=>{te.current&&(Zh(te.current),te.current=0,Wr(),Br())},[Wr,Br]);b.useEffect(()=>{const z=m.current;if(!z)return;const R=z.parentElement;if(!R)return;const F=se=>{if(se.ctrlKey||se.metaKey){if(se.preventDefault(),!se.deltaY||Q.current)return;const mt=se.deltaMode===1?16:se.deltaMode===2?z.parentElement?.clientHeight||600:1,et=Math.max(-600,Math.min(600,se.deltaY*mt));Pr(H.current*Math.exp(-et*.002),{x:se.clientX,y:se.clientY},!1),Ce.current||(Ce.current=Iy(()=>{Ce.current=0,Br(),xn()}));return}const Ee=x.current;if(!Ee||se.target!==z)return;se.preventDefault();const We=Xh(z,se.clientX,se.clientY);Ee.scroll(We.x,We.y,se.deltaX,se.deltaY)},q=se=>se.preventDefault();return R.addEventListener("wheel",F,{passive:!1}),R.addEventListener("gesturestart",q,{passive:!1}),R.addEventListener("gesturechange",q,{passive:!1}),()=>{R.removeEventListener("wheel",F),R.removeEventListener("gesturestart",q),R.removeEventListener("gesturechange",q)}},[Pr,Br,xn]),b.useEffect(()=>{const z=m.current,R=z?.parentElement;if(!z||!R||typeof ResizeObserver>"u")return;const F=new ResizeObserver(()=>{Q.current&&(Q.current.box=Yh(z));const q=Dt(ye.current,H.current);q.x===ye.current.x&&q.y===ye.current.y||(ye.current=q,Br())});return F.observe(z),F.observe(R),()=>F.disconnect()},[Dt,Br]),b.useLayoutEffect(()=>{Br()});const jr=z=>{const R=x.current,F=m.current;if(!R||!F)return;if(z.pointerType==="mouse"&&z.button!==0){z.preventDefault(),z.button===2?R.back():z.button===1&&R.home();return}z.preventDefault(),F.closest(".android-mirror-panel")?.focus({preventScroll:!0}),Br(),xn(),Pn(),O$(F,z.pointerId),$.current.set(z.pointerId,{x:z.clientX,y:z.clientY});const q=z.pointerType==="mouse"&&z.altKey;if($.current.size>=2||q){const We=P.current;We&&(R.pointerCancel(We.x,We.y,We.type),P.current=null,Dr.current=null,Et(null),Me(!1),vt([])),U.current=!0,ws();return}if(U.current)return;const se=Xh(F,z.clientX,z.clientY);P.current={id:z.pointerId,type:z.pointerType,x:se.x,y:se.y},R.pointerDown(se.x,se.y,z.pointerType);const Ee=jy(F,z.clientX,z.clientY);Ee&&(Dr.current={left:Ee.left,top:Ee.top},vt([]),Me(!1),Et(Ee))},ds=z=>{const R=x.current,F=m.current;if(!F||!$.current.has(z.pointerId))return;if(z.pointerType==="mouse"){const mt=F.getBoundingClientRect(),et=F.parentElement?.getBoundingClientRect()??mt;if(!(z.buttons&1)||z.clientX<Math.max(mt.left,et.left)||z.clientX>=Math.min(mt.right,et.right)||z.clientY<Math.max(mt.top,et.top)||z.clientY>=Math.min(mt.bottom,et.bottom)){Ar();return}}if(z.preventDefault(),$.current.set(z.pointerId,{x:z.clientX,y:z.clientY}),Q.current){Qn();return}const q=P.current;if(!R||!q||q.id!==z.pointerId)return;const se=Xh(F,z.clientX,z.clientY);q.x=se.x,q.y=se.y,R.pointerMove(se.x,se.y,q.type);const Ee=jy(F,z.clientX,z.clientY),We=Dr.current;!Ee||!We||(Et(Ee),Math.hypot(Ee.left-We.left,Ee.top-We.top)>=6&&(Me(!0),vt(mt=>{const et=mt[mt.length-1];if(et&&Math.hypot(Ee.left-et.x,Ee.top-et.y)<4)return mt;const dr=[...mt,{x:Ee.left,y:Ee.top}];return dr.length>12?dr.slice(dr.length-12):dr})))},Tr=z=>{const R=x.current,F=m.current;if(!F||!$.current.has(z.pointerId))return;if(Pn(),$.current.delete(z.pointerId),Ly(F,z.pointerId),$.current.size===0&&(U.current=!1),Q.current){$.current.size===0?(Q.current=null,J(H.current)):ws();return}const q=P.current;if(!q||q.id!==z.pointerId)return;const se=Xh(F,z.clientX,z.clientY);R?.pointerUp(se.x,se.y,q.type),at&&On(at),Et(null),Me(!1),window.setTimeout(()=>vt([]),200),P.current=null,Dr.current=null},bn=z=>{if(ne||Ot||Rr)return;const R=x.current;R&&(z.key==="Backspace"?(z.preventDefault(),R.key(67)):z.key==="Escape"?(z.preventDefault(),R.back()):z.key==="Enter"&&(z.preventDefault(),R.key(66)))},An=async()=>{const z=ot.trim();if(z){ur(!0);try{const R=await r$(z);Lt(""),er(!1),await Zr(),ce(R.serial)}catch(R){Qe(R instanceof Error?R.message:"ADB_CONNECT_FAILED")}finally{ur(!1)}}},rr=()=>{const z=x.current,R=Tt;!z||!R||(z.sendText(R),Ft(""))},kn=b.useCallback(z=>{Ct(z),Bn.current!==null&&window.clearTimeout(Bn.current),Bn.current=window.setTimeout(()=>{Bn.current=null,Ct(null)},2500)},[]),Cn=b.useCallback(z=>{const R=H.current,F=z==="in"?ky.find(q=>q>R+.01):[...ky].reverse().find(q=>q<R-.01);F!==void 0&&(R<=Pl&&F>Pl&&kn(l("android.zoomPanHint")),Pn(),Pr(F),J(F))},[Pr,Pn,kn,l]),wr=(z,R)=>{Promise.resolve().then(()=>r?.(z,R)).catch(F=>{rt(F instanceof Error?F.message:String(F))})},ps=b.useCallback(async(z,R,F)=>{try{if(!n)throw new Error(l("android.captureUnavailable"));if(await n(z,F)===!1)throw new Error(l("android.captureUnavailable"));kn(R)}catch(q){rt(l("android.captureFailed")+(q instanceof Error?`:${q.message}`:""))}},[n,kn,l]),Ks=async z=>{const R=Ig(z),F=m.current;if(!(!F||mn.current)){mn.current=!0,gn(!0),rt(null);try{const q=await R$(F);if(!R())throw new Error(l("android.captureUnavailable"));await ps(q,l("android.captureInserted"),z)}catch(q){rt(q instanceof Error?q.message:String(q))}finally{mn.current=!1,gn(!1)}}},rs=b.useCallback(z=>{(z.status==="ready"||z.status==="error")&&an.current&&!yr.current.has(z.id)&&(yr.current.add(z.id),j$(z,an.current))},[]),on=b.useCallback(async z=>{const R=ft.current;if(!(!R||Ht.current)){Ht.current=!0,Cr(!0),rt(null);try{const F=await a$(R.id);ft.current=null,Kr(!1),rs(F)}catch(F){rt(F instanceof Error?F.message:String(F))}finally{Ht.current=!1,Cr(!1)}}},[rs]),Hn=async()=>{if(!Fe||Ht.current||ft.current)return;const z=an.current;Ht.current=!0,Cr(!0),rt(null);try{const R=await i$(Fe);z&&M$(R.id,z),R.status==="recording"||R.status==="starting"||R.status==="stopping"?(ft.current=R,Kr(!0),Oe(Math.max(0,Date.now()-R.startedAt))):rs(R)}catch(R){rt(R instanceof Error?R.message:String(R))}finally{Ht.current=!1,Cr(!1)}};b.useEffect(()=>{let z=!1,R=!1;ft.current=null,Kr(!1);const F=async()=>{if(!(!Fe||R||Ht.current)){R=!0;try{const{recordings:se}=await s$(Fe);if(z||Ht.current)return;const Ee=se.find(We=>["starting","recording","stopping"].includes(We.status));ft.current=Ee??null,Kr(!!Ee);for(const We of se)rs(We)}catch{}finally{R=!1}}};F();const q=window.setInterval(()=>{F()},2e3);return Xr.current=window.setInterval(()=>{ft.current&&Oe(Math.max(0,Date.now()-ft.current.startedAt))},500),()=>{z=!0,window.clearInterval(q),Xr.current!==null&&window.clearInterval(Xr.current)}},[Fe,rs]),b.useEffect(()=>{if(!ne)return;const z=()=>Ye(!1),R=q=>{const se=q.target;se instanceof Node&&(Or.current?.contains(se)||un.current?.contains(se)||z())},F=q=>{q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),z())};return document.addEventListener("pointerdown",R,!0),document.addEventListener("keydown",F,!0),window.addEventListener("resize",z),()=>{document.removeEventListener("pointerdown",R,!0),document.removeEventListener("keydown",F,!0),window.removeEventListener("resize",z)}},[ne]),b.useEffect(()=>()=>{Bn.current!==null&&window.clearTimeout(Bn.current)},[]);const Fr=Ue==="streaming",$r=mr,pn=$r?"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-surface-2 disabled:opacity-40":"rounded p-1.5 hover:bg-surface-2 disabled:opacity-40",W=lr?(lr.model||lr.serial)+Dy(lr,l):Qr.length?l("android.selectDevice"):l("android.noDevices"),Ke=(le?Ze.find(z=>z.id===le):null)?.name??(Ie==="auto"?`${l("android.qualityAuto")} · ${I/1e6} Mbps`:l(s1[Ie])),lt=$r?"relative flex h-5 min-w-0 items-center rounded bg-surface-2 focus-within:ring-1 focus-within:ring-primary/50":"relative flex h-7 min-w-0 items-center rounded bg-surface-2 focus-within:ring-1 focus-within:ring-primary/50",ut=$r?"pointer-events-none block min-w-0 truncate px-1 text-[10px] leading-none text-foreground":"pointer-events-none block min-w-0 truncate px-2 text-[11px] leading-none text-foreground",It="absolute inset-0 h-full w-full cursor-pointer opacity-0",_t=()=>{const z=Or.current?.getBoundingClientRect();z&&Jt({left:Math.max(8,Math.min(z.right-n1,window.innerWidth-n1-8)),top:Math.min(z.bottom+4,Math.max(8,window.innerHeight-B$-8))}),Ye(!0)},Qt=()=>{if(mr){Sn(i0,null),Lr({docked:null});return}if(!en)return;const z={sessionId:en,side:"right"};Sn(i0,z),Lr({docked:z})},xt=Ot||mr||d!=="off",Pt=s.jsxs("div",{className:"android-mirror-panel flex h-full min-h-0 min-w-0 flex-col bg-surface text-foreground","data-sidebar-gesture-ignore":"true",onKeyDown:bn,tabIndex:-1,children:[s.jsxs("div",{"data-panel-drag-title":mr?"true":void 0,className:$r?"flex h-6 min-h-6 shrink-0 flex-nowrap items-center gap-1 overflow-hidden border-b border-border/15 bg-[var(--chrome-bg)] px-1.5 cursor-grab select-none active:cursor-grabbing":"flex flex-wrap items-center gap-1.5 border-b border-border px-2 py-2",children:[mr&&s.jsx("span",{"data-panel-drag-title":"true",role:"button","aria-label":l("android.splitDrag"),title:l("android.splitDrag"),className:"flex h-4 w-4 shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground hover:text-foreground active:cursor-grabbing",children:s.jsx(hg,{size:12})}),s.jsx(B9,{size:$r?12:14,className:"shrink-0 text-muted-foreground"}),s.jsxs("div",{className:`${lt} flex-1`,children:[s.jsx("span",{"aria-hidden":"true",className:`${ut} w-full`,children:W}),s.jsxs("select",{value:Fe,onChange:z=>{const R=z.target.value;ce(R),qe.current=R,R&&Lr({deviceSerial:R})},className:It,"aria-label":l("android.device"),children:[s.jsx("option",{value:"",children:Qr.length?l("android.selectDevice"):l("android.noDevices")}),Qr.map(z=>s.jsx("option",{value:z.serial,children:(z.model||z.serial)+Dy(z,l)},z.serial))]})]}),s.jsxs("div",{className:`${lt} max-w-[45%] shrink-0`,children:[s.jsx("span",{"aria-hidden":"true",className:ut,children:Ke}),s.jsxs("select",{value:le?`user:${le}`:Ie,onChange:z=>K(z.target.value),className:It,title:l(Ie==="auto"?"android.qualityAutoHint":"android.quality"),"aria-label":l("android.quality"),children:[s.jsxs("option",{value:"auto",children:[l("android.qualityAuto"),Ie==="auto"?` · ${I/1e6} Mbps`:""]}),ap.map(z=>s.jsx("option",{value:z.id,children:l(s1[z.id])},z.id)),Ze.map(z=>s.jsx("option",{value:`user:${z.id}`,children:z.name},z.id)),s.jsx("option",{value:"custom",children:l(s1.custom)})]})]}),s.jsx("button",{type:"button",onClick:()=>{Zr()},className:`${pn} text-muted-foreground`,title:l("android.refresh"),children:ie?s.jsx(Dn,{size:13,className:"animate-spin"}):s.jsx(vn,{size:13})}),Fr?s.jsx("button",{type:"button",onClick:En,className:`${pn} text-destructive`,title:l("android.disconnect"),children:s.jsx(w3,{size:13})}):s.jsx("button",{type:"button",onClick:()=>Fe&&qr(Fe),disabled:!Fe,className:`${pn} text-primary`,title:l("android.connect"),children:s.jsx(RS,{size:13})}),(Fr||cn)&&s.jsx("button",{type:"button",onClick:z=>{Ks(z.currentTarget)},disabled:!n||hn,className:`${pn} text-muted-foreground`,title:l(n?"android.screenshot":"android.captureUnavailable"),"aria-label":l("android.screenshot"),children:hn?s.jsx(Dn,{size:$r?12:13,className:"animate-spin"}):s.jsx(uT,{size:$r?12:13})}),(Fr||cn)&&s.jsx("button",{type:"button",onClick:()=>{cn?on("manual"):Hn()},disabled:ht||!cn&&!a,className:`${pn} ${cn?"text-destructive":"text-muted-foreground"}`,title:l(cn?"android.recordingStop":a?"android.recordingStart":"android.captureUnavailable"),"aria-label":l(cn?"android.recordingStop":"android.recordingStart"),children:ht?s.jsx(Dn,{className:"animate-spin",size:13}):cn?s.jsx(v3,{size:$r?10:11,fill:"currentColor"}):s.jsx(A3,{size:$r?12:13})}),s.jsx("button",{ref:Or,type:"button",onClick:()=>ne?Ye(!1):_t(),"aria-haspopup":"menu","aria-expanded":ne,className:`${pn} ${xt?"text-primary":"text-muted-foreground"}`,title:l("android.more"),"aria-label":l("android.more"),children:s.jsx(Do,{size:$r?13:14})}),c&&!t&&s.jsx("button",{type:"button",onClick:()=>{Ye(!1),f("off"),c()},className:`${pn} text-muted-foreground hover:bg-destructive/20 hover:text-destructive`,title:l("android.closeTab"),"aria-label":l("android.closeTab"),children:s.jsx(jn,{size:14})})]}),ne&&St&&Zs.createPortal(s.jsxs("div",{ref:un,role:"menu","aria-label":l("android.more"),style:{left:St.left,top:St.top,width:n1},className:"fixed z-popover overflow-hidden rounded-md border border-border bg-surface-elevated py-1 text-[11px] shadow-lg",children:[s.jsx(Kh,{icon:s.jsx(Al,{size:13}),label:l("android.addDevice"),active:Ot,onSelect:()=>{er(z=>!z),Ye(!1)}}),s.jsx(Kh,{icon:mr?s.jsx(jn,{size:13}):s.jsx($l,{size:13}),label:l(mr?"android.splitClose":"android.splitOpen"),active:mr,disabled:!mr&&!en,onSelect:()=>{Qt(),Ye(!1)}}),s.jsx(Kh,{icon:d==="window"?s.jsx(sS,{size:13}):s.jsx(eS,{size:13}),label:l(d==="window"?"android.exitFullscreen":"android.fullscreen"),active:d==="window",onSelect:()=>{f(d==="window"?"off":"window"),Ye(!1)}}),!t&&s.jsx(Kh,{icon:d==="sidebar"?s.jsx(pS,{size:13}):s.jsx(bS,{size:13}),label:l(d==="sidebar"?"android.exitFullscreen":"android.fillSidebar"),active:d==="sidebar",onSelect:()=>{f(d==="sidebar"?"off":"sidebar"),Ye(!1)}}),Xe&&s.jsxs("div",{className:"mt-1 border-t border-border px-3 py-2 text-[10px] leading-4 tabular-nums text-muted-foreground",children:[s.jsx("div",{className:"truncate",children:`${Ut.fps} fps · ${Ut.kbps} kbps`}),s.jsx("div",{className:"truncate",children:`${Ut.width}×${Ut.height}`})]})]}),document.body),(Ie==="custom"||le)&&s.jsxs("div",{className:"border-b border-border bg-surface-2/40 px-2 py-2 text-[11px]",children:[s.jsxs("button",{type:"button",onClick:()=>dt(z=>!z),"aria-expanded":xe,className:"flex w-full items-center gap-1 rounded text-muted-foreground hover:text-foreground",children:[s.jsx(Al,{size:12,className:`transition-transform ${xe?"":"-rotate-90"}`}),s.jsxs("span",{children:[l("android.quality"),le?` · ${Ze.find(z=>z.id===le)?.name??""}`:""]})]}),xe&&s.jsxs("div",{className:"mt-2 grid gap-2",children:[s.jsx(My,{label:l("android.qualityResolution"),display:`${it.maxSize}px`,min:360,max:2160,step:8,value:it.maxSize,onChange:z=>_e(R=>({...R,maxSize:z}))}),s.jsx(My,{label:l("android.qualityBitRate"),display:`${(it.bitRate/1e6).toFixed(1)} Mbps`,min:.5,max:20,step:.5,value:it.bitRate/1e6,onChange:z=>_e(R=>({...R,bitRate:Math.round(z*1e6)}))}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-14 shrink-0 text-muted-foreground",children:l("android.qualityFrameRate")}),s.jsxs("div",{className:"flex gap-1",children:[[15,30,60].map(z=>s.jsx("button",{type:"button",onClick:()=>_e(R=>({...R,maxFps:z})),className:`rounded px-2 py-0.5 ${it.maxFps===z?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:z},z)),s.jsx("button",{type:"button",onClick:()=>_e(z=>({...z,maxFps:0})),className:`rounded px-2 py-0.5 ${it.maxFps===0?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:l("android.qualityAuto")})]}),s.jsx("button",{type:"button",onClick:De,disabled:!Fe,className:"ml-auto rounded bg-primary/15 px-2 py-1 text-primary disabled:opacity-40",children:l("android.qualityApply")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:He,onChange:z=>tt(z.target.value),onKeyDown:z=>{z.key==="Enter"&&!z.nativeEvent.isComposing&&Mt()},placeholder:l("android.presetNamePlaceholder"),maxLength:40,className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:Mt,disabled:!He.trim(),className:"shrink-0 rounded bg-surface-2 px-2 py-1 text-primary disabled:opacity-40",children:l("android.presetSave")}),le&&s.jsx("button",{type:"button",onClick:vr,className:"shrink-0 rounded px-2 py-1 text-destructive hover:bg-surface-2",children:l("android.presetDelete")})]})]})]}),Ot&&s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-2",children:[s.jsx("input",{value:ot,onChange:z=>Lt(z.target.value),onKeyDown:z=>{z.key==="Enter"&&An()},placeholder:l("android.addressPlaceholder"),className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:()=>{An()},disabled:nr,className:"rounded bg-surface-2 px-2 py-1 text-[11px] text-primary disabled:opacity-40",children:nr?s.jsx(Dn,{size:12,className:"animate-spin"}):l("android.connect")})]}),fn&&s.jsxs("div",{className:"flex items-start gap-2 border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:[s.jsx("span",{className:"min-w-0 flex-1",children:l("android.adbUnavailable")}),s.jsx(Ny,{label:l("android.insertFixPrompt"),onClick:z=>wr(Ry("adb",he??""),z),enabled:!!r})]}),!fn&&Ss&&s.jsxs("div",{className:"flex items-start gap-2 border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:[s.jsx("span",{className:"min-w-0 flex-1",children:l("android.scrcpyUnavailable")}),s.jsx(Ny,{label:l("android.insertFixPrompt"),onClick:z=>wr(Ry("scrcpy",""),z),enabled:!!r})]}),lr&&lr.state!=="device"&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:H$(lr,l)}),he&&!fn&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:Vh(he)}),Nt&&s.jsxs("details",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:[s.jsxs("summary",{className:"cursor-pointer",children:[l("android.qualityAutoUnavailable")," ",l(Nt.startsWith("SCRCPY_VERSION")?"android.qualityAutoVersionError":Nt.startsWith("SCRCPY_BUILD")?"android.qualityAutoBuildError":/EXTENSION|SERVER_READ|PUSH/.test(Nt.split(":")[0])?"android.qualityAutoExtensionError":/TIMEOUT/.test(Nt.split(":")[0])?"android.qualityAutoTimeoutError":/ENCODER_REJECTED/.test(Nt.split(":")[0])?"android.qualityAutoEncoderError":/CHANNEL|TUNNEL|LISTEN|PROTOCOL|CONNECTION/.test(Nt.split(":")[0])?"android.qualityAutoChannelError":"android.qualityAutoUnknownError")]}),s.jsx("pre",{className:"mt-1 select-text whitespace-pre-wrap break-all text-[10px]",children:Nt})]}),jt&&s.jsx("div",{className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-warning",children:jt}),gt&&s.jsx("div",{role:"alert",className:"border-b border-border bg-surface-2 px-2 py-1.5 text-[11px] text-destructive",children:gt}),s.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1 touch-none items-center justify-center overflow-hidden bg-[var(--chrome-bg)] p-1",children:[s.jsx("canvas",{ref:m,className:"max-h-full max-w-full touch-none select-none rounded",style:{display:Fr||Xe?"block":"none",transformOrigin:"center",transition:"none"},onPointerDown:jr,onPointerMove:ds,onPointerUp:Tr,onPointerCancel:()=>Ar(),onLostPointerCapture:z=>{$.current.has(z.pointerId)&&Ar()},onPointerLeave:z=>{$.current.has(z.pointerId)&&!z.currentTarget.hasPointerCapture?.(z.pointerId)&&Ar()},onContextMenu:z=>z.preventDefault()}),at&&s.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-primary/80 bg-primary/35",style:{left:at.left,top:at.top}}),X.length>1&&s.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 h-full w-full",style:{opacity:Bt?1:0,transition:"opacity 160ms linear"},children:X.slice(1).map((z,R)=>{const F=X[R],q=(R+1)/(X.length-1);return s.jsx("line",{x1:F.x,y1:F.y,x2:z.x,y2:z.y,stroke:"var(--primary)",strokeWidth:1+1.6*q,strokeLinecap:"round",opacity:.06+.45*q},R)})}),ge.map(z=>s.jsx("span",{"aria-hidden":"true",className:"termdock-tap-fade pointer-events-none absolute h-4 w-4 rounded-full bg-primary",style:{left:z.left,top:z.top}},z.id)),!Fr&&s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 text-center text-[11px] text-muted-foreground",children:[Ue==="connecting"&&s.jsxs(s.Fragment,{children:[s.jsx(Dn,{size:18,className:"animate-spin"}),s.jsx("span",{children:l("android.connecting")})]}),Ue==="error"&&s.jsxs(s.Fragment,{children:[s.jsx(V0,{size:14,className:"text-destructive"}),s.jsx("span",{className:"max-w-[80%] text-destructive",children:Rt?l("android.retrySchedule",{attempt:Rt.attempt,seconds:Rt.delayMs/1e3}):Vh(V||"")}),Fe&&s.jsx("button",{type:"button",onClick:()=>{ve.current=0,qr(Fe)},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.retry")})]}),pe&&(Ue==="error"||Ue==="connecting")&&s.jsxs("div",{className:"max-h-[40%] w-[90%] shrink-0 select-text overflow-auto rounded bg-surface-2 px-3 py-2 text-left",role:"status",children:[s.jsx("span",{className:"text-muted-foreground",children:l("android.lastError")}),Vh(pe)!==pe&&s.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words",children:Vh(pe)}),s.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-[10px] text-foreground",children:pe})]}),Ue==="idle"&&!fn&&!Ss&&s.jsxs(s.Fragment,{children:[s.jsx(aS,{size:22,className:"opacity-60"}),s.jsx("span",{children:Qr.length?l("android.idleHint"):l("android.noDevicesHint")})]})]})]}),s.jsxs("div",{className:`flex flex-wrap items-center gap-1 border-t border-border ${$r?"px-1.5 py-0.5":"px-2 py-1.5"}`,children:[s.jsx(Zo,{compact:$r,label:l("android.back"),onClick:()=>x.current?.back(),disabled:!Fr,children:s.jsx(a3,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.home"),onClick:()=>x.current?.home(),disabled:!Fr,children:s.jsx(WT,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.recents"),onClick:()=>x.current?.recents(),disabled:!Fr,children:s.jsx(m3,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.notifications"),onClick:()=>x.current?.expandNotifications(),disabled:!Fr,children:s.jsx(d3,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.rotate"),onClick:()=>x.current?.rotate(),disabled:!Fr,children:s.jsx(PS,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.volumeDown"),onClick:()=>x.current?.volumeDown(),disabled:!Fr,children:s.jsx(cC,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.volumeUp"),onClick:()=>x.current?.volumeUp(),disabled:!Fr,children:s.jsx(dC,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.power"),onClick:()=>x.current?.power(),disabled:!Fr,children:s.jsx(jS,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.inputText"),active:Rr,onClick:()=>Gr(z=>!z),disabled:!Fr,children:s.jsx(p3,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.zoomIn"),onClick:()=>Cn("in"),disabled:!Fr||Z>=Af-.01,children:s.jsx(Ys,{size:14})}),s.jsx(Zo,{compact:$r,label:l("android.zoomOut"),onClick:()=>Cn("out"),disabled:!Fr||Z<=Pl+.01,children:s.jsx(g3,{size:14})}),s.jsxs("div",{className:"relative ml-auto h-5 w-24 min-w-0 max-w-full shrink-0","data-mirror-capture-status":!0,children:[s.jsx("span",{"aria-hidden":cn||!!be||hn,className:`block truncate text-right text-[10px] leading-5 tabular-nums text-muted-foreground ${cn||be||hn?"invisible":""}`,children:Xe?s.jsx(s.Fragment,{children:s.jsx("span",{ref:oe})}):""}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-end overflow-hidden",children:s.jsx(U$,{recording:cn,elapsed:wn,status:hn?l("android.captureInserting"):be,stopLabel:l("android.recordingStop"),onStop:()=>{on("manual")}})})]})]}),Rr&&s.jsxs("div",{className:"flex items-center gap-1.5 border-t border-border px-2 py-1.5",children:[s.jsx("input",{value:Tt,onChange:z=>Ft(z.target.value),onKeyDown:z=>{z.key==="Enter"&&!z.nativeEvent.isComposing&&(z.preventDefault(),rr())},placeholder:l("android.inputPlaceholder"),className:"min-w-0 flex-1 rounded bg-surface-2 px-2 py-1 text-[11px] outline-none placeholder:text-muted-foreground",autoFocus:!0}),s.jsx("button",{type:"button",onClick:rr,disabled:!Tt,className:"rounded bg-surface-2 p-1.5 text-primary disabled:opacity-40",title:l("android.send"),children:s.jsx(b0,{size:13})})]})]});return d==="window"?Zs.createPortal(s.jsx("div",{className:"fixed inset-0 z-modal-panel flex flex-col bg-[var(--chrome-bg)]",style:{paddingTop:"var(--safe-top-inset, env(safe-area-inset-top, 0px))",paddingBottom:"var(--safe-bottom-inset, env(safe-area-inset-bottom, 0px))"},children:Pt}),document.body):t?mr&&tn?Zs.createPortal(Pt,tn):null:mr&&tn?s.jsxs(s.Fragment,{children:[Zs.createPortal(Pt,tn),s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-[11px] text-muted-foreground",children:[s.jsx($l,{size:18,className:"opacity-60"}),s.jsx("span",{children:l("android.splitDockedHint")}),s.jsx("button",{type:"button",onClick:()=>{Sn(i0,null),Lr({docked:null})},className:"rounded bg-surface-2 px-2 py-1 text-foreground",children:l("android.splitClose")})]})]}):Pt}function Kh({icon:e,label:t,active:r=!1,disabled:n=!1,onSelect:a}){return s.jsxs("button",{type:"button",role:"menuitem",disabled:n,onClick:a,className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition hover:bg-surface-2 disabled:opacity-40 disabled:hover:bg-transparent ${r?"text-primary":"text-foreground"}`,children:[s.jsx("span",{"aria-hidden":"true",className:"shrink-0",children:e}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:t}),r&&s.jsx(oi,{size:12,className:"shrink-0"})]})}function U$({recording:e,elapsed:t,status:r,stopLabel:n,onStop:a}){return e?s.jsxs("span",{role:"status","aria-live":"polite",className:"ml-auto inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded bg-destructive/15 px-1.5 py-0.5 text-[10px] tabular-nums text-destructive",children:[s.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-destructive"}),Sy(t),s.jsx("button",{type:"button",onClick:a,title:n,"aria-label":`${n} · ${Sy(t)}`,className:"ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-destructive/25",children:s.jsx(v3,{size:8,fill:"currentColor"})})]}):r?s.jsx("span",{role:"status","aria-live":"polite",title:r,className:"ml-auto truncate text-[10px] text-primary",children:r}):null}function Ey({sessionId:e}){const t=os(x=>x.docks[m0]),r=!!t,n=t?.sessionId??e??null,c=r1(x=>x.pending)[0],l=b.useCallback(async(x,y)=>{const w=Ig(y);if(!n)throw new Error("没有可接收截图的终端");const T=(await W0("/tmp",[x])).files[0]?.path;if(!T)throw new Error("截图上传未返回文件路径");if(!w())throw new Error("截图尚未插入,请返回原投屏面板重试");await _y(T,n,y)},[n]),d=b.useCallback(x=>{r1.getState().enqueue(x,n)},[n]),f=os(x=>!!x.hosts[m0]),m=b.useRef(!1);return b.useEffect(()=>{m.current||(m.current=!0,Cc().then(x=>{const y=x.androidPanel?.docked;y&&(os.getState().docks[m0]||os.getState().setDock(m0,y))}).catch(()=>{}))},[]),s.jsxs(s.Fragment,{children:[r&&f&&s.jsx($$,{sessionId:n,dockOnly:!0,onInsertFile:n?l:void 0,onInsertPrompt:n?(x,y)=>N4(x,n,y):void 0,onRecordingComplete:d}),c&&s.jsx(D$,{file:c.file,initialPath:c.initialPath,onInsert:(x,y)=>c.insert?c.insert(x,y):_y(x,c.sessionId,y),onDone:()=>r1.getState().remove(c.file.id)},c.file.id)]})}function Ny({label:e,onClick:t,enabled:r}){return r?s.jsx("button",{type:"button",onClick:n=>t(n.currentTarget),className:"shrink-0 rounded bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-elevated",children:e}):null}function Ry(e,t){return[`Termdock 的“设备投屏”在当前服务端不可用:未找到 ${e==="adb"?"adb(Android platform-tools)":"scrcpy / scrcpy-server"}${t?`(错误:${t})`:""}。`,"请在本机安装并让 Termdock 恢复可用:","1) 安装依赖:"," - macOS: brew install android-platform-tools scrcpy"," - Ubuntu/Debian: sudo apt install adb scrcpy"," - Windows: winget install Google.PlatformTools && winget install Genymobile.scrcpy","2) 若不在 PATH,请在 ~/.termdock/.env 指定 TERMDOCK_ADB_BIN / TERMDOCK_SCRCPY_BIN / TERMDOCK_SCRCPY_SERVER。","3) 完成后重启 Termdock 服务,并用 adb version、scrcpy --version 验证。","边界:只做本机环境安装与配置,不要改动 Termdock 仓库代码。"].join(`
164
164
  `)}function My({label:e,display:t,min:r,max:n,step:a,value:c,onChange:l}){return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"w-14 shrink-0 text-muted-foreground",children:e}),s.jsx("input",{type:"range",min:r,max:n,step:a,value:c,onChange:d=>l(Number(d.target.value)),className:"h-1 min-w-0 flex-1 accent-primary","aria-label":e}),s.jsx("span",{className:"w-16 shrink-0 text-right tabular-nums text-muted-foreground",children:t})]})}function Zo({label:e,onClick:t,disabled:r,active:n,compact:a,children:c}){return s.jsx("button",{type:"button",onClick:t,disabled:r,title:e,"aria-label":e,className:`${a?"inline-flex h-5 w-5 items-center justify-center":"p-1.5"} rounded transition active:scale-95 disabled:opacity-30 ${n?"bg-surface-elevated text-primary":"text-muted-foreground hover:bg-surface-2"}`,children:c})}function jy(e,t,r){const n=e.parentElement;if(!n)return null;const a=e.getBoundingClientRect(),c=n.getBoundingClientRect();return{left:a.left-c.left+(t-a.left),top:a.top-c.top+(r-a.top)}}function Xh(e,t,r){const n=e.getBoundingClientRect(),a=e.width||n.width,c=e.height||n.height,l=n.width?(t-n.left)/n.width*a:0,d=n.height?(r-n.top)/n.height*c:0;return{x:Math.max(0,Math.min(a,l)),y:Math.max(0,Math.min(c,d))}}function z$(e){return!(/ADB_NOT_FOUND|SCRCPY_NOT_FOUND|SCRCPY_SERVER_NOT_FOUND|SCRCPY_VERSION_UNKNOWN|SCRCPY_UNSUPPORTED_CODEC|VIDEO_DECODER_UNSUPPORTED/i.test(e)||/INVALID_SERIAL|INVALID_ADDRESS|API_NOT_ALLOWED|AUTHORIZATION_DENIED/i.test(e))}function Dy(e,t){return e.state==="device"?e.androidVersion?` · Android ${e.androidVersion}`:"":e.state==="unauthorized"?` · ${t("android.stateUnauthorized")}`:e.state==="offline"?` · ${t("android.stateOffline")}`:` · ${t("android.stateUnknown")}`}function H$(e,t){return e.state==="unauthorized"?t("android.unauthorizedHint"):e.state==="offline"?t("android.offlineHint"):t("android.stateUnknown")}function W$(e){return e>=90?"var(--destructive)":e>=70?"var(--warning)":"var(--success)"}function G$(e){return e>=90?"var(--destructive)/0.15":e>=70?"var(--warning)/0.15":"var(--success)/0.12"}function V$(e){if(!e)return"";const t=new Date(e),r=Date.now(),n=t.getTime()-r;if(n<=0)return"";const a=Math.floor(n/6e4),c=Math.floor(a/60),l=Math.floor(c/24),d=c%24,f=a%60,m=t.toLocaleDateString(void 0,{month:"short",day:"numeric"}),x=t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"});let y;return l>0?y=`${l}d ${d}h`:d>0?y=`${d}h ${f}m`:f>0?y=`${f}m`:y="soon",`resets in ${y} (${m} ${x})`}function q$(e){return{claude:"🧠",codex:"✨",kimi:"🌙",copilot:"🐙",grok:"🚀",gemini:"💎"}[e]||"📊"}function Y$({result:e}){const{t}=Ur(),r=e.windows.filter(d=>d.percent===0&&!d.resetAt),n=e.windows.filter(d=>d.percent>0||d.resetAt),a=r.length>0?r.map(d=>d.label).join(" · "):"",c=!!e.error;let l=null;return!c&&e.entitlement&&(e.usagePercent>=90?l=t("quota.exhausted"):e.remaining!==void 0&&e.remaining<e.entitlement?l=t("quota.left",{n:e.remaining}):l=`${Math.round(e.usagePercent)}%`),s.jsxs("div",{className:"rounded-xl border border-border/15 bg-surface-2 p-3 sm:p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 text-[13px] font-semibold text-foreground",children:[s.jsx("span",{className:"shrink-0",children:q$(e.slug)}),s.jsx("span",{className:"truncate",children:e.displayName}),a&&s.jsx("span",{className:"shrink-0 rounded-full bg-surface-elevated px-2 py-0.5 text-[10px] font-normal text-muted-foreground",children:a})]}),l&&s.jsx("span",{className:"shrink-0 text-[11px] tabular-nums text-muted-foreground",children:l})]}),n.length>0?s.jsx("div",{className:"mt-2.5 space-y-2",children:n.map(d=>{const f=Math.max(0,Math.min(100,d.percent));return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 text-[12px]",children:[s.jsx("span",{className:"w-14 shrink-0 truncate text-muted-foreground sm:w-16",children:d.label}),s.jsx("div",{className:"flex-1",children:s.jsx("div",{className:"h-2 rounded-full",style:{background:G$(d.percent)},children:s.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${f}%`,background:W$(d.percent)}})})}),s.jsxs("span",{className:"w-9 shrink-0 text-right tabular-nums font-medium text-foreground",children:[Math.round(d.percent),"%"]})]}),d.resetAt&&s.jsx("p",{className:"mt-1 pl-14 text-[10px] text-muted-foreground sm:pl-16",children:V$(d.resetAt)})]},d.label)})}):c?s.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:e.error}):null]})}function Z$({isOpen:e,onClose:t}){const{t:r}=Ur(),[n,a]=b.useState([]),[c,l]=b.useState(!1),d=async(x=!1)=>{l(!0);try{const y=x?await Q9():await P9();a(y.providers||[])}catch{}finally{l(!1)}};if(b.useEffect(()=>{e&&d()},[e]),b.useEffect(()=>{if(!e)return;const x=y=>{const w=y.detail;Array.isArray(w)&&a(w)};return window.addEventListener("termdock:quota-update",x),()=>{window.removeEventListener("termdock:quota-update",x)}},[e]),!e)return null;const f=n.filter(x=>!x.error),m=f.length>0?new Date(Math.max(...f.map(x=>x.fetchedAt||0))):null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:t}),s.jsxs("div",{className:"fixed inset-x-3 z-modal-panel mx-auto flex max-w-lg flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)]",style:{top:"max(1.5rem, env(safe-area-inset-top, 0px))",bottom:"max(1.5rem, env(safe-area-inset-bottom, 0px))"},children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-3 py-2.5 sm:px-6 sm:py-3",children:[s.jsx("h2",{className:"text-[14px] font-semibold text-foreground sm:text-base",children:r("quota.title")}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("button",{type:"button",onClick:()=>d(!0),disabled:c,className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50","aria-label":r("quota.refresh"),children:s.jsx(vn,{size:15,className:c?"animate-spin":""})}),s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":r("quota.close"),children:s.jsx(jn,{size:17})})]})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-3 sm:p-5",children:[c&&f.length===0?s.jsx(_0,{label:r("common.loading"),className:"py-12"}):f.length===0?s.jsxs("div",{className:"py-8 text-center text-[13px] text-muted-foreground",children:[s.jsx("p",{children:r("quota.noProviders")}),s.jsx("p",{className:"mt-1.5 text-[11px]",children:r("quota.noProvidersHint")})]}):s.jsx("div",{className:"space-y-2.5",children:f.map(x=>s.jsx(Y$,{result:x},x.slug))}),m&&s.jsx("p",{className:"mt-3 text-center text-[10px] text-muted-foreground",children:r("quota.updated",{time:m.toLocaleTimeString()})})]})]})]})}const By=[{label:"Esc",sequence:"\\u001b"},{label:"Tab",sequence:"\\t"},{label:"Enter",sequence:"\\r"},{label:"S-Tab",sequence:"\\u001b[Z"},{label:"C-c",sequence:"\\u0003"},{label:"C-d",sequence:"\\u0004"},{label:"C-l",sequence:"\\u000c"},{label:"C-r",sequence:"\\u0012"},{label:"C-z",sequence:"\\u001a"},{label:"C-w",sequence:"\\u0017"},{label:"Up",sequence:"\\u001b[A"},{label:"Down",sequence:"\\u001b[B"},{label:"Left",sequence:"\\u001b[D"},{label:"Right",sequence:"\\u001b[C"},{label:"PgUp",sequence:"\\u001b[5~"},{label:"PgDn",sequence:"\\u001b[6~"}],K$=2,X$=20;function J$({label:e}){return s.jsx("div",{className:"h-7 rounded-full bg-surface-2 px-3 text-[11px] leading-7 text-center text-muted-foreground truncate",children:e})}function eU({value:e,onChange:t,placeholder:r}){const{t:n}=Ur(),[a,c]=k.useState(""),l=y=>{const w=[];let v="",T=!1;const S=()=>{const N=v.trim();N&&w.push(N),v=""};for(let N=0;N<y.length;N+=1){const P=y[N];if(!T&&P==="/"&&v.trim().length===0){T=!0,v+=P;continue}if(T){if(v+=P,P==="/"&&y[N-1]!=="\\"&&v.length>1){for(;N+1<y.length&&/[gimsuy]/.test(y[N+1]??"");)N+=1,v+=y[N];S(),T=!1}continue}if(P===","||/\s/.test(P)){S();continue}v+=P}if(S(),w.length===0)return;const I=[...e];for(const N of w){const P=Lv(N);P&&(I.includes(P)||I.push(P))}t(I),c("")},d=y=>{t(e.filter(w=>w!==y))},f=a.trim(),m=f.length>0&&d5(f),x=m&&!Pf(f);return s.jsx("div",{className:"rounded-2xl bg-surface px-3 py-2 ring-1 ring-border/15 focus-within:ring-accent/40",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.map(y=>{const w=d5(y),v=w&&!Pf(y);return s.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] ${v?"bg-destructive/15 text-destructive":w?"bg-accent/15 font-mono text-accent":"bg-surface-elevated text-foreground"}`,title:w?v?n("settings.invalidRegex"):"Regex match":"Substring match (case-insensitive)",children:[w&&s.jsx("span",{className:"text-[10px] opacity-70",children:"re"}),y,s.jsx("button",{type:"button",onClick:()=>d(y),className:"rounded-full p-0.5 text-muted-foreground hover:bg-destructive/20 hover:text-destructive","aria-label":n("toolbarPresets.removeAction",{name:y}),children:s.jsx(jn,{size:12})})]},y)}),s.jsx("input",{type:"text",value:a,onChange:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"||y.key===","&&!m?(y.preventDefault(),l(a)):y.key==="Backspace"&&a.length===0&&e.length>0&&d(e[e.length-1])},onBlur:()=>l(a),placeholder:e.length===0?r:"",className:`min-w-[8ch] flex-1 bg-transparent py-1 text-sm outline-none placeholder:text-muted/60 ${m?"font-mono":""} ${x?"text-destructive":""}`,autoCapitalize:"off",autoCorrect:"off",autoComplete:"off"})]})})}function tU({value:e,min:t,max:r,onChange:n}){const{t:a}=Ur();return s.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full bg-surface px-1 py-1 ring-1 ring-border/15",children:[s.jsx("button",{type:"button",onClick:()=>n(Math.max(t,e-1)),disabled:e<=t,className:"h-7 w-7 rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated disabled:opacity-40 inline-flex items-center justify-center","aria-label":a("common.decrease"),children:s.jsx(g3,{size:14})}),s.jsx("span",{className:"w-6 text-center text-sm font-medium tabular-nums text-foreground",children:e}),s.jsx("button",{type:"button",onClick:()=>n(Math.min(r,e+1)),disabled:e>=r,className:"h-7 w-7 rounded-full bg-surface-2 text-muted-foreground transition hover:bg-surface-elevated disabled:opacity-40 inline-flex items-center justify-center","aria-label":a("common.increase"),children:s.jsx(Ys,{size:14})})]})}const rU=({presets:e,selectedPresetId:t,onSelectPreset:r,onUpdatePreset:n,onAddPreset:a,onRemovePreset:c,onResetDefaults:l})=>{const{t:d}=Ur(),f=e.find(N=>N.id===t)??e[0]??null,[m,x]=k.useState(null);if(!f)return null;const y=f.actions.length>0,w=[{id:"preview-auto",label:f.label,kind:"preset"},...f.includeAlt?[{id:"preview-alt",label:"Alt"}]:[],...y?f.actions.map((N,P)=>({id:N.id,label:E1(N,P)})):["Enter","Home","End","Ctrl-C","Ctrl-D"].map(N=>({id:N,label:N}))],v=Iv(w,f.rowLayout),T=(N,P)=>{n(f.id,$=>{const Q=$.actions.findIndex(J=>J.id===N);if(Q===-1)return $;const U=Q+P;if(U<0||U>=$.actions.length)return $;const Z=[...$.actions];return[Z[Q],Z[U]]=[Z[U],Z[Q]],{...$,actions:Z}})},S=f.rowLayout.reduce((N,P)=>N+P,0),I=1+(f.includeAlt?1:0);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"sticky top-[-1rem] sm:top-[-1.5rem] z-10 -mx-4 -mt-4 sm:-mx-6 sm:-mt-6 border-b border-border/15 bg-surface/95 backdrop-blur px-4 py-3 sm:px-6",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.preview")}),s.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[f.actions.length," button",f.actions.length===1?"":"s"," · ",S," slot",S===1?"":"s"]})]}),s.jsx("div",{className:"space-y-1 rounded-2xl bg-surface-2/60 p-2",children:v.map((N,P)=>{const $=N.items[0]?.kind==="preset",Q=Math.max(2,N.columns),U=$?`${Ev}px repeat(${Math.max(1,Q-1)}, minmax(0, 1fr))`:`repeat(${Q}, minmax(0, 1fr))`;return s.jsx("div",{className:"grid gap-1",style:{gridTemplateColumns:U},children:N.items.map(Z=>Z.kind==="preset"?s.jsx(Nv,{mode:"auto",presetLabel:Z.label,title:`Auto preset · ${Z.label}`,disabled:!0},Z.id):s.jsx(J$,{label:Z.label},Z.id))},`preview-row-${P}`)})}),f.actions.length>S-I&&s.jsx("p",{className:"mt-1.5 text-[10px] text-muted-foreground",children:d("toolbarPresets.overCapacityHint")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.presets")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-2 text-xs font-medium hover:bg-surface-elevated transition",children:[s.jsx(Ys,{size:14}),d("toolbarPresets.new")]}),s.jsxs("button",{type:"button",onClick:l,className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-2 text-xs font-medium hover:bg-surface-elevated transition",children:[s.jsx(vn,{size:14}),d("toolbarPresets.reset")]})]})]}),s.jsx("div",{className:"-mx-1 flex flex-wrap gap-1.5 px-1",children:e.map(N=>s.jsxs("button",{type:"button",onClick:()=>r(N.id),className:`rounded-full px-3 py-2 text-xs font-medium transition ${N.id===f.id?"bg-primary/20 text-primary ring-1 ring-primary/30":"bg-surface-2 text-muted-foreground hover:bg-surface-elevated"}`,children:[N.label,N.actions.length>0&&s.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:N.actions.length})]},N.id))})]}),s.jsxs("div",{className:"space-y-4 rounded-2xl bg-surface p-4 ring-1 ring-border/10",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.label")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:f.label,onChange:N=>n(f.id,P=>({...P,label:N.target.value})),className:"flex-1 rounded-full bg-surface-2 px-4 py-2.5 text-sm placeholder:text-muted/60 outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.presetLabelPlaceholder"),autoCapitalize:"off",autoCorrect:"off"}),f.id!=="default"&&s.jsx("button",{type:"button",onClick:()=>c(f.id),className:"shrink-0 rounded-full bg-surface-2 px-3 py-2.5 text-destructive hover:bg-destructive/15","aria-label":d("toolbarPresets.deletePreset",{name:f.label}),children:s.jsx(Ms,{size:14})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.matchPrograms")}),s.jsx("span",{className:"text-[10px] text-muted-foreground",children:d("toolbarPresets.typeEnterHint")})]}),s.jsx(eU,{value:f.programs,onChange:N=>n(f.id,P=>({...P,programs:N})),placeholder:d("toolbarPresets.programsPlaceholder")}),s.jsx("p",{className:"text-[10px] text-muted-foreground",children:d("toolbarPresets.programsHelp")})]}),s.jsxs("button",{type:"button",onClick:()=>n(f.id,N=>({...N,includeAlt:!N.includeAlt})),className:"flex w-full items-center justify-between rounded-2xl bg-surface-2 px-4 py-3 text-sm transition hover:bg-surface-elevated",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-foreground",children:d("toolbarPresets.altSlot")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:d("toolbarPresets.altSlotHint")})]}),s.jsx(vl,{checked:f.includeAlt})]}),s.jsxs("button",{type:"button",onClick:()=>n(f.id,N=>({...N,showOnDesktop:!N.showOnDesktop})),className:"flex w-full items-center justify-between rounded-2xl bg-surface-2 px-4 py-3 text-sm transition hover:bg-surface-elevated",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-foreground",children:d("toolbarPresets.desktopVisibility")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:d("toolbarPresets.desktopVisibilityHint")})]}),s.jsx(vl,{checked:f.showOnDesktop===!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.rowLayout")}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:d("toolbarPresets.rowLayoutHint")})]}),s.jsxs("button",{type:"button",onClick:()=>n(f.id,N=>({...N,rowLayout:[...kg(N.rowLayout),3]})),className:"inline-flex items-center gap-1 rounded-full bg-surface-2 px-3 py-1.5 text-xs font-medium hover:bg-surface-elevated",children:[s.jsx(Ys,{size:12}),d("toolbarPresets.addRow")]})]}),s.jsx("div",{className:"space-y-2",children:f.rowLayout.map((N,P)=>s.jsxs("div",{className:"flex items-center gap-3 rounded-2xl bg-surface-2 px-3 py-2",children:[s.jsx("span",{className:"w-12 shrink-0 text-xs text-muted-foreground",children:d("toolbarPresets.rowN",{n:P+1})}),s.jsx("div",{className:"flex-1"}),s.jsx(tU,{value:N,min:K$,max:X$,onChange:$=>n(f.id,Q=>({...Q,rowLayout:Q.rowLayout.map((U,Z)=>Z===P?$:U)}))}),f.rowLayout.length>1&&s.jsx("button",{type:"button",onClick:()=>n(f.id,$=>({...$,rowLayout:$.rowLayout.filter((Q,U)=>U!==P)})),className:"rounded-full bg-surface px-2.5 py-1 text-[11px] text-muted-foreground hover:bg-destructive/15 hover:text-destructive","aria-label":d("toolbarPresets.removeRow",{n:P+1}),children:d("toolbarPresets.del")})]},`row-${P}`))})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("span",{className:"ui-kicker",children:d("toolbarPresets.buttons")}),s.jsx("p",{className:"text-[11px] text-muted-foreground",children:d("toolbarPresets.buttonsHint")})]}),s.jsxs("button",{type:"button",onClick:()=>{const N=`${f.id}-action-${Date.now()}`;n(f.id,P=>({...P,actions:[...P.actions,{id:N,label:`Key ${P.actions.length+1}`,sequence:""}]})),x(N)},className:"inline-flex items-center gap-1 rounded-full bg-primary/15 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/25",children:[s.jsx(Ys,{size:12}),d("toolbarPresets.addButton")]})]}),f.actions.length===0&&s.jsx("div",{className:"rounded-2xl bg-surface-2/60 px-4 py-6 text-center text-[11px] text-muted-foreground",children:d("toolbarPresets.noCustomButtons")}),f.actions.map((N,P)=>{const $=m===N.id;return s.jsxs("div",{className:`rounded-2xl bg-surface-2 transition ${$?"ring-1 ring-accent/40":""}`,children:[s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>T(N.id,-1),disabled:P===0,className:"h-6 w-6 rounded-full bg-surface text-muted-foreground hover:bg-surface-elevated disabled:opacity-30 inline-flex items-center justify-center","aria-label":d("toolbarPresets.moveUp"),children:s.jsx(u3,{size:12})}),s.jsx("button",{type:"button",onClick:()=>T(N.id,1),disabled:P===f.actions.length-1,className:"h-6 w-6 rounded-full bg-surface text-muted-foreground hover:bg-surface-elevated disabled:opacity-30 inline-flex items-center justify-center","aria-label":d("toolbarPresets.moveDown"),children:s.jsx(JA,{size:12})})]}),s.jsxs("button",{type:"button",onClick:()=>x($?null:N.id),className:"min-w-0 flex-1 text-left",children:[s.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:E1(N,P)}),s.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[N.sequence?N.sequence:d("toolbarPresets.noSequence"),N.doubleTapSequence&&s.jsxs("span",{className:"ml-1 text-accent/70",children:["· 2× ",N.doubleTapSequence]})]})]}),s.jsx("button",{type:"button",onClick:()=>n(f.id,Q=>({...Q,actions:Q.actions.filter(U=>U.id!==N.id)})),className:"shrink-0 rounded-full bg-surface p-2 text-muted-foreground hover:bg-destructive/15 hover:text-destructive","aria-label":d("toolbarPresets.removeAction",{name:N.label}),children:s.jsx(Ms,{size:14})})]}),$&&s.jsxs("div",{className:"space-y-3 border-t border-border/10 px-3 py-3",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:d("toolbarPresets.labelField")}),s.jsx("input",{type:"text",value:N.label,onChange:Q=>n(f.id,U=>({...U,actions:U.actions.map(Z=>Z.id===N.id?{...Z,label:Q.target.value}:Z)})),className:"w-full rounded-full bg-surface px-4 py-2.5 text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.labelPlaceholder"),autoCapitalize:"off",autoCorrect:"off"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:d("toolbarPresets.sequence")}),s.jsx("input",{type:"text",value:N.sequence,onChange:Q=>n(f.id,U=>({...U,actions:U.actions.map(Z=>Z.id===N.id?{...Z,sequence:Q.target.value}:Z)})),className:"w-full rounded-full bg-surface px-4 py-2.5 font-mono text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.sequencePlaceholder"),autoCapitalize:"off",autoCorrect:"off",spellCheck:!1}),s.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:By.map(Q=>s.jsx("button",{type:"button",onClick:()=>n(f.id,U=>({...U,actions:U.actions.map(Z=>Z.id===N.id?{...Z,sequence:Q.sequence}:Z)})),className:"rounded-full bg-surface px-2.5 py-1 text-[11px] font-medium text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:Q.label},Q.label))})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:d("toolbarPresets.doubleTap")}),!N.doubleTapSequence&&s.jsx("button",{type:"button",onClick:()=>n(f.id,Q=>({...Q,actions:Q.actions.map(U=>U.id===N.id?{...U,doubleTapSequence:""}:U)})),className:"text-[10px] text-accent hover:text-accent/80",children:d("toolbarPresets.doubleTapAdd")})]}),N.doubleTapSequence!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:N.doubleTapSequence,onChange:Q=>n(f.id,U=>({...U,actions:U.actions.map(Z=>Z.id===N.id?{...Z,doubleTapSequence:Q.target.value}:Z)})),className:"w-full rounded-full bg-surface px-4 py-2.5 font-mono text-sm outline-none ring-1 ring-transparent focus:ring-accent/40",placeholder:d("toolbarPresets.doubleTapPlaceholder"),autoCapitalize:"off",autoCorrect:"off",spellCheck:!1}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[By.map(Q=>s.jsx("button",{type:"button",onClick:()=>n(f.id,U=>({...U,actions:U.actions.map(Z=>Z.id===N.id?{...Z,doubleTapSequence:(Z.doubleTapSequence??"")+Q.sequence}:Z)})),className:"rounded-full bg-surface px-2.5 py-1 text-[11px] font-medium text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:Q.label},Q.label)),s.jsx("button",{type:"button",onClick:()=>n(f.id,Q=>({...Q,actions:Q.actions.map(U=>{if(U.id!==N.id)return U;const{doubleTapSequence:Z,...J}=U;return J})})),className:"rounded-full bg-destructive/10 px-2.5 py-1 text-[11px] font-medium text-destructive/70 hover:bg-destructive/20 hover:text-destructive",children:d("toolbarPresets.remove")})]})]})]})]})]},N.id)})]})]})]})},nU={installed:"text-[color:var(--success)]",outdated:"text-[color:var(--warning)]","needs-approval":"text-[color:var(--warning)]","not-installed":"text-muted-foreground"};function sU(){const{t:e}=Ur(),[t,r]=k.useState(null),[n,a]=k.useState(null),[c,l]=k.useState(null),[d,f]=k.useState(null),[m,x]=k.useState(!1),[y,w]=k.useState(!1),[v,T]=k.useState(""),[S,I]=k.useState(""),[N,P]=k.useState(null),[$,Q]=k.useState([]),[U,Z]=k.useState([]),[J,H]=k.useState(null),[ye,oe]=k.useState(new Set),[te,Ce]=k.useState(null),[qe,ve]=k.useState("auto"),[Y,st]=k.useState({}),[he,Qe]=k.useState(null),[ie,Pe]=k.useState(null),[Fe,ce]=k.useState(10),[Ie,je]=k.useState(""),[Ze,we]=k.useState(""),[le,Ge]=k.useState(12e3),[He,tt]=k.useState(null),[xe,dt]=k.useState(null),it=k.useCallback(async()=>{const[ge,Je,at,Et]=await Promise.allSettled([O9(),F9(),Cc(),kd()]);if(r(ge.status==="fulfilled"?ge.value:[]),Je.status==="fulfilled"){const X=Je.value;Q(X.plugins??[]),Z(X.errors??[])}else Q([]),Z([]);if(at.status==="fulfilled"){const X=at.value;oe(new Set(X.autoRenameAgents??[])),ve(X.autoRenameNamer??"auto"),st(X.autoRenameModels??{}),ce(X.autoRenameIntervalMinutes??10),je(X.autoRenamePromptPreference??""),we(X.autoRenamePromptPreference??""),Ge(X.autoRenamePromptPayloadChars??12e3)}else oe(new Set);Qe(Et.status==="fulfilled"?Et.value:[])},[]);k.useEffect(()=>{it()},[it]);const _e=async(ge,Je)=>{a(ge),l(null);try{Je==="install"?(await $9(ge)).devMode&&f(ge):(await U9(ge),d===ge&&f(null)),await it()}catch(at){l(at instanceof Error?at.message:String(at))}finally{a(null)}},Ue=ge=>e(ge==="installed"?"settings.agentHooksInstalled":ge==="outdated"?"settings.agentHooksOutdated":ge==="needs-approval"?"settings.agentHooksNeedsApproval":"settings.agentHooksNotInstalled"),ke=async()=>{P(null);let ge;try{ge=JSON.parse(S)}catch{P("Invalid JSON");return}try{await q9(ge),I(""),x(!1),await it()}catch(Je){if(Je instanceof Y9&&Je.migration){Z(at=>[{slug:typeof ge.slug=="string"?ge.slug:"manifest.json",errors:Je.message.split(`
165
165
  `),code:Je.code,migration:Je.migration},...at.filter(Et=>Et.slug!==ge.slug)]);return}P(Je instanceof Error?Je.message:String(Je))}},V=async()=>{const ge=v.trim();if(ge){tt("install"),P(null);try{await z9(ge),T(""),w(!1),await it()}catch(Je){P(Je instanceof Error?Je.message:String(Je))}finally{tt(null)}}},ae=async ge=>{tt(`remove:${ge}`);try{await V9(ge),dt(Je=>Je?.slug===ge?null:Je),await it()}catch(Je){l(Je instanceof Error?Je.message:String(Je))}finally{tt(null)}},pe=async ge=>{tt(`check:${ge}`),l(null);try{await G9(ge),await it()}catch(Je){l(Je instanceof Error?Je.message:String(Je))}finally{tt(null)}},$e=async ge=>{tt(`update:${ge}`),l(null);try{const Je=await W9(ge),at=[Je.hookWarning,Je.titleWarning].filter(Boolean).join(" ");at&&l(at),dt(Et=>Et?.slug===ge?null:Et),await it()}catch(Je){l(Je instanceof Error?Je.message:String(Je))}finally{tt(null)}},Xe=async ge=>{tt(`doctor:${ge}`),l(null),dt(null);try{const Je=await H9(ge);dt(Je),Qe(await kd())}catch(Je){l(Je instanceof Error?Je.message:String(Je))}finally{tt(null)}},wt=async ge=>{const Je=ge.migration?.aiPrompt??ge.errors.join(`
@@ -183,5 +183,5 @@ ${c}`)}},this.startTimers()}reportError(t){this.failureReason=t,this.callbacks.o
183
183
  { "hook": "Stop", "event": "stop", "status": "complete" }
184
184
  ]
185
185
  }
186
- }`}),N&&s.jsx("div",{className:"whitespace-pre-wrap break-words text-[10px] text-[color:var(--warning)]",children:N}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{ke()},className:"flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.14)] px-3 py-1 text-[11px] font-medium text-[color:var(--success)] hover:bg-[rgb(var(--success-rgb)_/_0.22)] transition",children:[s.jsx(ST,{size:11}),e("settings.agentPluginCreate")]}),s.jsx("button",{type:"button",onClick:()=>{x(!1),I(""),P(null)},className:"rounded-full px-3 py-1 text-[11px] text-muted-foreground hover:text-foreground transition",children:e("common.cancel")})]})]})]})]})}function iU({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:f,onInstallDesktop:m}){const{t:x}=Ur(),y=e?.status??"idle",w=t||y==="checking"||y==="installing"||y==="restarting",v=y==="ready"&&!!e?.latestVersion,T=y==="checking"?x("settings.updateChecking"):y==="installing"?x("sidebar.updateInstalling"):y==="ready"?x("sidebar.updateReady"):y==="restarting"?x("sidebar.updateRestarting"):y==="current"?x("settings.updateCurrent"):y==="error"?e?.error||x("sidebar.updateFailed"):x("settings.updateHint"),S=a?.currentVersion||l?.appVersion,I=a?.status??"idle",N=c||I==="checking"||I==="downloading"||I==="installing",P=I==="ready",$=a?.error||(I==="unsupported"?x("settings.desktopUpdateUnsupported"):I==="checking"?x("settings.desktopUpdateChecking"):I==="current"?x("settings.desktopUpdateCurrent"):I==="downloading"?x("settings.desktopUpdateDownloading"):I==="ready"?x("settings.desktopUpdateReady"):I==="installing"?x("settings.desktopUpdateInstalling"):I==="error"&&a?.error||x("settings.desktopUpdateHint"));return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"termdock-update-title",children:[s.jsx("div",{id:"termdock-update-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:x("settings.updateTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(vn,{size:15,className:w?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.updateRuntimeTitle")}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:T}),e&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:v&&e.latestVersion?`${e.currentVersion} → ${e.latestVersion}`:`v${e.currentVersion}`})]})]}),v?s.jsx("button",{type:"button",disabled:w,onClick:n,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("sidebar.updateRestart")}):s.jsx("button",{type:"button",disabled:w,onClick:r,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(y==="checking"?"settings.updateCheckingShort":y==="installing"?"settings.updateInstallingShort":y==="error"?"sidebar.updateRetry":y==="current"?"settings.updateCheckAgain":"settings.updateCheck")})]}),(a||d)&&s.jsxs("div",{className:"flex items-start justify-between gap-3 border-t border-border/10 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${P?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(vn,{size:15,className:N?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.desktopUpdateTitle")}),s.jsx("div",{className:`mt-0.5 text-[10px] leading-relaxed ${a?.error?"text-destructive":"text-muted-foreground"}`,role:a?.error?"alert":void 0,children:a?$:x(f?"settings.desktopStatusLoading":"settings.desktopUpdateUnsupported")}),s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:P&&a?.latestVersion?`${a.currentVersion} → ${a.latestVersion}`:S?`v${S}`:null})]})]}),P?s.jsx("button",{type:"button",disabled:N||!m,onClick:m,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("settings.desktopUpdateRestart")}):s.jsx("button",{type:"button",disabled:!a||N||I==="unsupported"||!f,onClick:f,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(I==="installing"?"settings.updateInstallingShort":I==="downloading"?"settings.desktopUpdateDownloadingShort":I==="checking"?"settings.updateCheckingShort":I==="current"||I==="error"?"settings.desktopUpdateCheckAgain":"settings.desktopUpdateCheck")})]}),d]})}function aU({quality:e}){const{locale:t}=Ur(),r=(d,f)=>t==="zh"?d:f,n=d=>d==null||!Number.isFinite(d)?"—":`${d.toFixed(1)} ms`,a=e?.diagnostics,c=d=>s.jsx("dl",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1.5 tabular-nums",children:d.map(([f,m])=>s.jsxs(k.Fragment,{children:[s.jsx("dt",{children:f}),s.jsx("dd",{className:"text-right text-foreground break-all",children:m})]},f))}),l=(d,f)=>s.jsxs("section",{className:"mt-3 border-t border-border/30 pt-3",children:[s.jsx("h3",{className:"mb-2 font-medium text-foreground",children:d}),f]});return s.jsxs("div",{className:"text-[11px] leading-relaxed",children:[l(r("往返统计","Round-trip statistics"),s.jsxs(s.Fragment,{children:[c([[r("平均延迟","Average latency"),n(e?.average)],["P95",n(e?.p95)],[r("服务端回包处理","Server reply handler"),n(e?.handlerMs)]]),s.jsx("p",{className:"mt-2",children:r("8 秒未响应计为超时,不等于网络丢包。回包处理仅含消息解析至构造回复,不含解密、排队和发包。","A probe times out after 8s; this is not packet loss. Handler timing covers parsing through reply creation, excluding decryption, queues and transmission.")})]})),l(r("当前发送与排队","Current buffers and queues"),a?s.jsxs(s.Fragment,{children:[c([[r("当前传输","Current transport"),a.transport==="webtransport"?"QUIC / HTTP/3":"WebSocket / TCP"],[r("传输层发送缓冲","Transport send buffer"),`${a.bufferedBytes} B`],[r("加密通道待发送","Channel writes pending"),a.pendingWrites?r("有","Yes"):r("无","No")],[r("进行中的非终端请求","Active non-terminal requests"),a.activeRequests],[r("等待通道的请求","Requests waiting for capacity"),a.waitingRequests]]),s.jsx("p",{className:"mt-2",children:a.transport==="webtransport"?r("此终端使用独立加密流,文件请求使用其他流。","This terminal has an independent encrypted stream; file requests use other streams."):r("属于此服务共用的连接,包含文件等其他请求。","Shared by this service, including file transfers and other requests.")})]}):s.jsx("p",{children:r("尚无连接记录。","No connection record yet.")})),l(r("本次连接建立 · 历史耗时","Connection setup · recorded timings"),s.jsxs(s.Fragment,{children:[c([[r("传输通道就绪","Transport ready"),n(a?.transportOpenMs)],...a?.relay?[[r("其中:连上入口 WebSocket","Within transport: entry WebSocket"),n(a.relay.entryOpenMs)],[r("其中:请求中转至通道打开","Within transport: relay open request"),n(a.relay.routeOpenMs)]]:[],[r("Noise 加密握手","Noise handshake"),n(a?.handshakeMs)],[r("终端逻辑通道就绪","Terminal logical channel ready"),n(a?.socketOpenMs)],[r("其中:等待本地通道名额","Within logical open: local capacity wait"),n(a?.socketQueueMs)]]),s.jsx("p",{className:"mt-2",children:r("这是建链时的历史耗时,不代表当前延迟。“其中”为子项,不能重复相加;中转耗时含处理和建链,不含之前的授权。","Recorded setup timings, not live latency. “Within” rows are subsets, not additive. Relay timing includes processing and setup, excluding earlier authorization.")})]}))]})}function oU({backendSessionId:e}){const{locale:t}=Ur(),r=t==="zh",[n,a]=k.useState(null),[c,l]=k.useState(!1);k.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(Z9(e));y();const w=setInterval(y,1e3);return document.addEventListener("visibilitychange",y),()=>{clearInterval(w),document.removeEventListener("visibilitychange",y)}},[e,c]);const d=n?.diagnostics,f=n?.rtt,m=n?.connected?n.waiting?r?"等待响应…":"Waiting for reply…":f==null?r?"测量中…":"Measuring…":`${f} ms · ${f<150?r?"流畅":"Low latency":f<300?r?"有延迟":"Moderate latency":r?"高延迟":"High latency"}`:r?"未连接":"Disconnected",x=y=>y==null?"—":`${Math.round(y)} ms`;return s.jsxs("div",{className:"mt-3 rounded-xl bg-surface-2 px-3 text-muted-foreground",children:[s.jsxs("button",{type:"button","aria-expanded":c,onClick:()=>l(y=>!y),className:"flex min-h-11 w-full items-center gap-2 py-2 text-[12px] tabular-nums hover:text-foreground","aria-label":`${r?"连接质量":"Connection quality"}${c?`: ${m}`:""}`,children:[s.jsx("span",{"aria-hidden":"true",className:`h-1.5 w-1.5 rounded-full ${c&&n&&(!n.connected||n.waiting||f!=null&&f>=300)?"bg-destructive":"bg-current"}`}),s.jsxs("span",{className:"flex-1 text-left",children:[r?"连接质量":"Connection quality",c?` · ${m}`:""]}),s.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})]}),c&&s.jsxs("div",{className:"pb-3 text-[11px] leading-relaxed",children:[!e&&s.jsx("p",{children:r?"请先打开一个终端会话,再查看连接质量。":"Open a terminal session to measure connection quality."}),s.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 tabular-nums",children:[s.jsx("dt",{children:r?"近期延迟":"Recent latency"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.minimum==null?"—":`${Math.round(n.minimum)}–${Math.round(n.maximum??n.minimum)} ms`}),s.jsx("dt",{children:r?"波动":"Jitter"}),s.jsx("dd",{className:"text-right text-foreground",children:x(n?.jitter)}),s.jsx("dt",{children:r?"探测超时":"Probe timeouts"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.samples?`${n.timeouts} / ${n.samples}`:"—"}),s.jsx("dt",{children:r?"连接路径":"Connection route"}),s.jsx("dd",{className:"text-right text-foreground break-words",children:d?`${d.path==="relay"?r?"经入口中转":"Via relay":r?"直连":"Direct"} · ${d.endpoint}`:"—"})]}),s.jsx("p",{className:"mt-2",children:r?"每 5 秒更新,统计最近 20 次;波动越小越稳定。":"Updates every 5s, using the last 20 probes. Lower jitter means more consistent latency."}),s.jsxs("details",{className:"mt-3 border-t border-border/30 pt-2",children:[s.jsx("summary",{className:"cursor-pointer py-1 hover:text-foreground",children:r?"诊断详情":"Diagnostics"}),s.jsx(aU,{quality:n})]})]})]})}const Qy={"startup-failure":"settings.serverHealthEventStartupFailure",crash:"settings.serverHealthEventCrash","crash-native":"settings.serverHealthEventCrashNative",killed:"settings.serverHealthEventKilled",wedge:"settings.serverHealthEventWedge","port-conflict":"settings.serverHealthEventPortConflict","gave-up":"settings.serverHealthEventGaveUp","exit-zero-unexpected":"settings.serverHealthEventExitZero","terminated-externally":"settings.serverHealthEventTerminated","supervisor-lost":"settings.serverHealthEventSupervisorLost","uncaught-exception":"settings.serverHealthEventUncaughtException","unhandled-rejection":"settings.serverHealthEventUnhandledRejection","exit-nonzero":"settings.serverHealthEventExitNonzero"};function lU(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function cU({state:e,onDismiss:t}){const{t:r}=Ur(),[n,a]=b.useState(!1),[c,l]=b.useState(!1),d=b.useRef(!1),f=b.useRef(!0);b.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]),b.useEffect(()=>{e?.supervised&&(d.current=!1,a(!1),l(!1))},[e?.supervised]),b.useEffect(()=>{if(!n)return;const $=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout($)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await K9()}catch{if(!f.current)return;d.current=!1,a(!1),l(!0)}}};if(!e)return null;const x=e.incident,y=!e.supervised&&e.supervisor?.phase==="gave-up",w=!e.supervised&&e.supervisor!==null&&!e.supervisor.alive,v=y||w||e.attention,T=e.supervised&&e.supervisor?.alive&&e.supervisor.phase==="running",S=y?r("settings.serverHealthGaveUp",{count:e.supervisor?.consecutiveCrashes??0}):w?r("settings.serverHealthSupervisorLost"):e.supervised?r("settings.serverHealthSupervised"):r("settings.serverHealthUnsupervised"),I=x?r(Qy[x.event]??"settings.serverHealthUnknownEvent"):"",N=x?.causeEvent?r(Qy[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",P=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:lU(x.uptimeMs)}):null,x.signal?`signal ${x.signal}`:null,x.exitCode!==null?`exit ${x.exitCode}`:null].filter(Boolean).join(" · "):"";return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"server-health-title",children:[s.jsx("div",{id:"server-health-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:r("settings.serverHealthTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-destructive/15 text-destructive":"bg-primary/15 text-primary"}`,children:v?s.jsx(HS,{size:15}):s.jsx(GS,{size:15})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:S}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:x?`${r(T?"settings.serverHealthHistory":"settings.serverHealthLastIncident")}: ${I}${N?` · ${N}`:""}`:r("settings.serverHealthClean")}),x&&T&&s.jsx("div",{className:"mt-1 text-[11px] text-primary",children:r("settings.serverHealthRunningNow")}),x&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:P}),x?.detail&&s.jsx("div",{className:"mt-1 break-words text-[10px] text-muted-foreground/75",children:x.detail}),x?.oomSuspect&&s.jsx("div",{className:"mt-1 text-[10px] text-[color:var(--warning)]",children:r("settings.serverHealthOomNote")}),e.supervisor&&e.supervisor.restarts>0&&!y&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:r("settings.serverHealthRestarted",{count:e.supervisor.restarts})})]})]}),e.attention&&s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated",children:r("settings.serverHealthDismiss")})]}),!e.supervised&&s.jsxs("div",{className:"border-t border-border px-3 py-3",children:[s.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:e.canEnableSupervision?r("settings.serverHealthEnableHint"):r("settings.serverHealthEnableUnavailable")}),e.canEnableSupervision&&s.jsx("button",{type:"button",onClick:m,disabled:n,className:"mt-2 min-h-11 rounded-lg bg-primary px-3 text-[12px] font-medium text-primary-foreground disabled:opacity-60",children:r(n?"settings.serverHealthEnabling":"settings.serverHealthEnable")}),n&&s.jsx("p",{role:"status",className:"mt-2 text-[11px] text-muted-foreground",children:r("settings.serverHealthEnablePending")}),c&&s.jsx("p",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:r("settings.serverHealthEnableError")})]})]})}const uU=()=>()=>{},dU=()=>1/0;function hU(){const{t:e}=Ur(),t=b.useId(),r=Xo(),n=b.useSyncExternalStore(r?.subscribe??uU,r?.retentionLimit??dU);if(!r)return null;const a=X9+1,c=n===1/0?e("settings.workspaceUnlimited"):String(n);return s.jsxs("div",{className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("label",{htmlFor:t,className:"shrink-0 text-[12px] font-medium text-foreground/90",children:e("settings.workspaceLimit")}),s.jsx("input",{id:t,type:"range",min:3,max:a,step:1,value:n===1/0?a:n,"aria-valuetext":c,"aria-describedby":`${t}-hint`,onChange:l=>{const d=Number(l.target.value);r.setRetentionLimit(d===a?1/0:d)},className:"h-8 min-w-0 flex-1"}),s.jsx("output",{htmlFor:t,className:"min-w-12 shrink-0 text-right text-[11px] tabular-nums text-muted-foreground",children:c})]}),s.jsx("p",{id:`${t}-hint`,className:"text-[11px] leading-relaxed text-muted-foreground",children:e("settings.workspaceLimitHint")})]})}const ig="mobile-session-destroy";function fU(e,t){return t&&e.type==="session"&&e.destination?.droppableId===ig}const ja="termdock-program-rules-cache",Jh="termdock-toolbar-presets-cache",o0="termdock-settings-cache",Py="termdock-color-theme",Oy="termdock:right-sidebar:file-preview-open-by-session:v2",l0="termdock:running-session-button-enabled:v1",c0="termdock:attention-button-enabled:v1",pU=60,Fy=320,$y=420,Ko=8;function Uy(e,t,r){return Math.min(Math.max(e,t),r)}function zy(e){if(typeof window>"u")return{left:Ko,top:Ko};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(Ko,window.innerWidth-Fy-Ko),l=Math.max(Ko,window.innerHeight-$y-Ko);return{left:Uy(n+Ko,Ko,c),top:Uy(a+Ko,Ko,l),width:Fy,maxHeight:`min(${$y}px, calc(100vh - ${Ko*2}px))`}}function mU(e){return e==="dark"||e==="light"}function gU(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.entries(e).every(([t,r])=>{if(!t||!r||typeof r!="object"||Array.isArray(r))return!1;const n=r;return typeof n.updatedAt=="number"&&Number.isFinite(n.updatedAt)})}function i1(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,pU);return Object.fromEntries(t)}function xU(e){return Array.isArray(e)&&e.every(t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.id=="string"&&typeof r.pattern=="string"&&typeof r.output=="string"&&(r.matchType==="exact"||r.matchType==="includes"||r.matchType==="prefix"||r.matchType==="regex")})}function bU(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function yU(e,t){const r=D0(),n=new Set(ZE()),a=Array.isArray(e)?e:[],c=Hu(a),l=t<f0;if(c.length===0)return r;if(l){const f=new Map(c.map(w=>[w.id,w])),m=new Map(a.map(w=>[typeof w.id=="string"?w.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):"",w])),x=c.filter(w=>!n.has(w.id));return[...r.map(w=>{const v=f.get(w.id),T=m.get(w.id);return v?{...w,rowLayout:v.rowLayout,showOnDesktop:typeof T?.showOnDesktop=="boolean"?T.showOnDesktop:w.showOnDesktop}:w}),...x]}const d=new Set(c.map(f=>f.id));return[...c,...r.filter(f=>!d.has(f.id))]}function vU(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const wU={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},Tp="__termdockOverlay",Sp="__termdockBaseAnchor",Cp="__termdockBaseGuard",AU=3,Hy=250,TU="termdock-notification-target-v1",Wy="/__termdock-notification-target",Gy=3e4;function SU(e){return e==="left-sidebar"||e==="right-sidebar"||e==="right-sidebar-repo-picker"||e==="right-sidebar-file-preview"||e==="settings"||e==="markdown-outline"||e==="markdown-image-lightbox"}function Bu(e){if(!e||typeof e!="object")return null;const t=e[Tp];return SU(t)?t:null}function ax(e){return e&&typeof e=="object"?{...e}:{}}function M4(e){const t=ax(e);return delete t[Tp],t}function CU(e){const t=M4(e);return delete t[Cp],{...t,[Sp]:!0}}function _U(){typeof window>"u"||window.history.pushState({...M4(window.history.state),[Sp]:!0,[Cp]:!0},"",window.location.href)}function j4(){for(let e=0;e<AU;e+=1)_U()}function ef(){typeof window>"u"||(window.history.replaceState(CU(window.history.state),"",window.location.href),j4())}function u0(e){typeof window>"u"||window.history.pushState({...ax(window.history.state),[Sp]:!0,[Tp]:e,[Cp]:!1},"",window.location.href)}function kU(e){typeof window>"u"||window.history.replaceState({...ax(window.history.state),[Sp]:!0,[Tp]:e,[Cp]:!1},"",window.location.href)}const D4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let Da=new Set(D4);function Vy(e){const t=new Map;for(const[r,n]of e)t.set(r,{cwd:n.cwd,activeProgram:n.activeProgram,activeProgramRaw:n.activeProgramRaw,inCopyMode:n.inCopyMode,isConnecting:n.isConnecting,agentStatus:n.agentStatus,agentIndicator:n.agentIndicator,agentStatusDetail:n.agentStatusDetail,agent:n.agent,agentMessage:n.agentMessage,agentNativeSessionId:n.agentNativeSessionId,agentResumeRecovered:n.agentResumeRecovered,terminalSessionId:n.terminalSessionId,agentNeedsReview:n.agentNeedsReview,gitStatus:n.gitStatus,shellTitle:n.shellTitle,promptState:n.promptState,tuiProgress:n.tuiProgress});return t}function LU(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t){const a=e.get(r);if(!a||a.cwd!==n.cwd||a.activeProgram!==n.activeProgram||a.activeProgramRaw!==n.activeProgramRaw||a.inCopyMode!==n.inCopyMode||a.isConnecting!==n.isConnecting||a.agentStatus!==n.agentStatus||a.agentIndicator!==n.agentIndicator||a.agentStatusDetail!==n.agentStatusDetail||a.agent!==n.agent||a.agentMessage!==n.agentMessage||a.agentNativeSessionId!==n.agentNativeSessionId||a.agentResumeRecovered!==n.agentResumeRecovered||a.terminalSessionId!==n.terminalSessionId||a.agentNeedsReview!==n.agentNeedsReview||a.gitStatus!==n.gitStatus||a.shellTitle!==n.shellTitle||a.promptState!==n.promptState||a.tuiProgress?.state!==n.tuiProgress?.state||a.tuiProgress?.progress!==n.tuiProgress?.progress)return!1}return!0}function qy(e,t){return s.jsx(SO,{sessionMode:e,state:t})}function IU(e,t){const r=new Map(e.map(l=>[l.id,l])),n=t.map(l=>r.get(l)).filter(l=>l!==void 0),a=new Set(t),c=e.filter(l=>!a.has(l.id));return[...n,...c]}const EU=k.lazy(()=>Zc(()=>import("./CollaborationMainWorkspace-B1PZuCC6.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));async function B4(e,t){return pg(e,t)}function NU(){const{t:e,locale:t,setLocale:r}=Ur(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";J9();const c=k.useMemo(()=>typeof window>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,[]),[l,d]=k.useState(!1),[f,m]=k.useState(()=>Dc(Py,mU)??"dark"),x=k.useRef(Dc(o0,vU)).current,[y,w]=k.useState(x?.preventSleep??!1),[v,T]=k.useState(x?.networkAvailable??!0),[S,I]=k.useState(eA),[N,P]=k.useState(tA),[$,Q]=k.useState(rA),[U,Z]=k.useState(nA),[J,H]=k.useState(zp),[ye,oe]=k.useState(x?.localAccess??wU),[te,Ce]=k.useState(x?.localAccess?.name??""),[qe,ve]=k.useState(!1),[Y,st]=k.useState(null),[he,Qe]=k.useState(null),[ie,Pe]=k.useState(null),[Fe,ce]=k.useState(!1),Ie=b.useRef({busy:!1}),je=b.useRef(0),Ze=b.useRef(ie?.latestVersion);Ze.current=ie?.latestVersion;const[we,le]=b.useState(null);b.useEffect(()=>{const C=()=>{je.current++};for(const O of["pagehide","auth:unauthorized",Fu])window.addEventListener(O,C);return()=>{C();for(const O of["pagehide","auth:unauthorized",Fu])window.removeEventListener(O,C)}},[]);const[Ge,He]=k.useState(null),tt=k.useMemo(()=>Gi(),[]),xe=!!(tt?.desktopUpdateState&&tt.checkDesktopUpdate&&tt.installDesktopUpdate),[dt,it]=k.useState(null),[_e,Ue]=k.useState(null),[ke,V]=k.useState(!1),ae=b.useRef({busy:!1}),pe=b.useRef(_e);pe.current=_e;const[$e,Xe]=k.useState(null),[wt,Ut]=k.useState(!1),[qt,Nt]=k.useState(()=>i1(Dc(Oy,gU)??{})),[sr,jt]=k.useState(0),[Xt,Rt]=k.useState(!1),[ir,ge]=k.useState(0),[Je,at]=k.useState(!1),[Et,X]=k.useState(0),[vt,Bt]=k.useState(!1),[Me,Dr]=k.useState(0),Le=k.useRef(null),[At,Ot]=k.useState({}),{terminalSettings:er,updateTerminalSettings:ot}=kQ(),Lt=er.fontSize,nr=er.rendererMode,[ur,Rr]=k.useState(!1),Gr=k.useRef(sA()).current,[Tt,Ft]=b.useState(()=>Gr.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),be=Bi(C=>C.groupId);k.useEffect(()=>{const C=()=>Bi.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[Ct,gt]=k.useState(Gr.activeSessionId),[rt,cn]=k.useState(!1);k.useEffect(()=>{rt&&iA({rendered:!0})},[rt]);const[Kr,wn]=k.useState(null),[Oe,ft]=k.useState(null),[ht,Cr]=k.useState([]),[Ht,yr]=b.useState(()=>{const C=Hr.getState();return Gr.sessions.forEach(O=>{O.backendSessionId&&C.setTerminalSession(O.sessionId,{sessionId:O.backendSessionId,cols:80,rows:24,mode:O.mode,tmuxSessionName:O.tmuxSessionName}),O.activeProgram!=null&&C.setSessionActiveProgram(O.sessionId,O.activeProgram),O.cwd!=null&&C.setSessionCwd(O.sessionId,O.cwd),O.shellTitle!=null&&C.setSessionShellTitle(O.sessionId,O.shellTitle)}),Wu("session-chrome-hydrated"),Vy(Hr.getState().sessions)});b.useEffect(()=>{!tt||!ur||Promise.all([tt.snapshot(),tt.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,O])=>{it(C),Ue(O)}).catch(C=>Xe(C instanceof Error?C.message:String(C)))},[tt,ur]),b.useEffect(()=>{tt?.onDesktopUpdateState&&tt.onDesktopUpdateState(Ue)},[tt]),b.useEffect(()=>Hr.subscribe(C=>{const O=Vy(C.sessions);yr(fe=>LU(fe,O)?fe:O)}),[]);const Xr=b.useCallback(async(C,O)=>{ft(null),wn({sessionId:C,status:"submitting",error:null});try{await aA(O),wn(fe=>fe?.sessionId===C?{...fe,status:"waiting",error:null}:fe)}catch(fe){const kt=(fe&&typeof fe=="object"&&"code"in fe?String(fe.code??""):"")==="AGENT_SESSION_ACTIVE_ELSEWHERE"?e("tab.resumeAgentConflict"):fe instanceof Error&&/busy/i.test(fe.message)?e("tab.resumeAgentBusy"):e("tab.resumeAgentFailed");wn(Kt=>Kt?.sessionId===C?{...Kt,error:kt}:Kt),ft({tone:"error",message:kt})}},[e]);b.useEffect(()=>{if(!Kr||Kr.status!=="waiting")return;const C=Ht.get(Kr.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const O=C.agent?.displayName??"Agent";wn(null),ft({tone:"success",message:e("tab.resumeAgentSuccess",{agent:O})})},[Kr,Ht,e]),b.useEffect(()=>{if(!Kr||Kr.status!=="waiting"||Kr.error)return;const C=Kr.sessionId,O=window.setTimeout(()=>{const fe=e("tab.resumeAgentTimeout");wn(nt=>nt?.sessionId===C&&nt.status==="waiting"?{...nt,error:fe}:nt),ft({tone:"error",message:fe})},15e3);return()=>window.clearTimeout(O)},[Kr,e]),b.useEffect(()=>{if(Oe?.tone!=="success")return;const C=window.setTimeout(()=>ft(null),3200);return()=>window.clearTimeout(C)},[Oe]),b.useEffect(()=>{let C=!1;oA().then(fe=>{C||Pe(fe)}).catch(()=>{}),lA().then(fe=>{C||He(fe)}).catch(()=>{});const O=Ox(fe=>{C||(fe.type==="update-state"?Pe(fe.state):fe.type==="server-health"&&He(fe.state))});return()=>{C=!0,O()}},[]);const Bn=b.useCallback(async()=>{try{He(await cA())}catch(C){d1(C instanceof Error?C.message:String(C))}},[]),mn=b.useCallback(async()=>{const C=ie?.latestVersion;if(!C||Fe)return;const O=je.current,fe=mi(),nt=Eo(),kt=()=>O===je.current&&fe===mi()&&nt===Eo()&&!nt?.closed&&Ze.current===C,Kt=tt?.confirmationUI==="page-v1"&&typeof tt.confirm=="function";le(null),await B4(Ie.current,{current:kt,submit:RA,apply:Pe,pending:ce,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again.",confirm:()=>Kt?tt.confirm({title:e("sidebar.updateRestart"),message:e("sidebar.updateRestartConfirm",{version:C}),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}):window.confirm(e("sidebar.updateRestartConfirm",{version:C})),failure:Er=>{Kt?le(Er):window.alert(Er)}})},[ie?.latestVersion,e,Fe,tt,t]),hn=b.useCallback(async()=>{if(!Fe){ce(!0);try{Pe(await uA())}catch(C){d1(C instanceof Error?C.message:String(C))}finally{ce(!1)}}},[Fe]),gn=b.useCallback(async()=>{if(!(!tt?.checkDesktopUpdate||ke)){V(!0);try{Ue(await tt.checkDesktopUpdate())}catch(C){Xe(C instanceof Error?C.message:String(C))}finally{V(!1)}}},[tt,ke]),an=b.useCallback(async()=>{const C=_e;if(!tt?.installDesktopUpdate||ke||C?.status!=="ready")return;const O=je.current,fe=mi(),nt=Eo(),kt=()=>O===je.current&&C===pe.current&&C.status==="ready"&&fe===mi()&&nt===Eo()&&!nt?.closed;await pg(ae.current,{current:kt,confirm:()=>C3({title:e("settings.desktopUpdateRestartConfirm"),message:e("settings.desktopUpdateRestartConfirm"),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}),submit:async()=>{if(!kt())throw new Error("Desktop update context changed");return tt.installDesktopUpdate()},apply:Ue,pending:V,failure:Xe,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again."})},[tt,ke,_e,e,t]);b.useEffect(()=>{document.documentElement.dataset.theme=f,dA(f),Yn(Py,f)},[f]),b.useEffect(()=>{Yn(Oy,i1(qt))},[qt]);const ne=Yt(C=>C.leftOpen),Ye=Yt(C=>C.rightOpen),St=Yt(C=>C.leftPinned),Jt=Yt(C=>C.leftSidebarWidth),Or=Yt(C=>C.rightPinned),un=Yt(C=>C.rightSidebarWidth),Jr=Yt(C=>C.rootPath),en=Yt(C=>C.contextKey),mr=Yt(C=>C.selectedFilePath),tn=Yt(C=>C.groupByFolder),Sn=Ef(C=>C.collaborationGroups),Zr=Yt(C=>C.collapsedGroups),Qr=Yt(C=>C.toggleGroupCollapsed),[lr,fn]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Ss,Ar]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[En,qr]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[Lr,On]=b.useState([]),[tr,K]=b.useState({available:!0,version:null,reason:null}),[De,Mt]=b.useState(!1),[vr,Dt]=b.useState(null),[Br,Pr]=b.useState(null),[xn,Kn]=b.useState(null),[Cs,ws]=b.useState(null),[Wr,Qn]=b.useState(null),[Pn,jr]=b.useState(null),[ds,Tr]=b.useState(null),[,bn]=b.useState(0),[An,rr]=b.useState(null),[kn,Cn]=b.useState(null),[wr,ps]=b.useState(null),[Ks,rs]=b.useState(!1),[on,Hn]=b.useState(()=>Dc(l0,C=>typeof C=="boolean")??!1),Fr=b.useCallback(async C=>{const O=on;Hn(C),Yn(l0,C);try{const fe=await Qa({runningSessionButtonEnabled:C});Hn(fe.runningSessionButtonEnabled),Yn(l0,fe.runningSessionButtonEnabled)}catch{Hn(O),Yn(l0,O)}},[on]),[$r,pn]=b.useState(()=>Dc(c0,C=>typeof C=="boolean")??!0),W=b.useCallback(async C=>{const O=$r;pn(C),Yn(c0,C);try{const fe=await Qa({attentionButtonEnabled:C});pn(fe.attentionButtonEnabled),Yn(c0,fe.attentionButtonEnabled)}catch{pn(O),Yn(c0,O)}},[$r]),[Re,Ke]=b.useState(null),lt=b.useCallback(C=>{Ke(C)},[]),ut=b.useRef(!1),[It,_t]=b.useState(null),Qt=k.useRef(null),xt=b.useCallback(C=>{const O=Tt.find(fe=>fe.id===C);O&&(Qt.current={id:C,target:mi(),client:Eo(),backend:Hr.getState().sessions.get(C)?.terminalSessionId??null,mode:O.mode,tmux:O.tmuxSessionName},_t(C))},[Tt]),Pt=b.useCallback(()=>{const C=Qt.current,O=C&&Tt.find(fe=>fe.id===C.id);return!!C&&!C.client?.closed&&MQ(C,O?{id:O.id,target:mi(),client:Eo(),backend:Hr.getState().sessions.get(O.id)?.terminalSessionId??null,mode:O.mode,tmux:O.tmuxSessionName}:null)},[Tt]),[z,R]=b.useState(null),F=k.useRef(null),q=k.useRef(!1),se=k.useRef(null),Ee=k.useRef(!1),We=b.useCallback(()=>{jr(null),Tr(null)},[]),mt=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[et,dr]=k.useState(mt.current),[Wn,Gt]=k.useState(!0),zr=k.useRef(mt.current),_r=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("_notifTrace"));b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(min-width: 1024px)"),O=()=>{fn(C.matches),Ar(window.innerWidth)};return O(),C.addEventListener("change",O),window.addEventListener("resize",O),()=>{C.removeEventListener("change",O),window.removeEventListener("resize",O)}},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(orientation: landscape)"),O=()=>qr(C.matches);return O(),C.addEventListener("change",O),()=>C.removeEventListener("change",O)},[]);const Xn=k.useMemo(()=>Ct?ht.find(C=>C.sessionIds.includes(Ct))??null:null,[Ct,ht]),ms=Xn?.id??null,dn=Xn?.sessionIds[0]??Ct,pr=k.useRef([]);k.useLayoutEffect(()=>{const C=pr.current;if(pr.current=ht,C.length===0)return;const O=new Set(ht.flatMap(fe=>fe.sessionIds));for(const fe of C){const nt=fe.sessionIds.filter(kt=>!O.has(kt)).map(kt=>({sessionId:kt,rootPath:Hr.getState().sessions.get(kt)?.cwd??null}));nt.length>0&&Yt.getState().inheritRightSidebarStateFromSplitWorkspace(fe.id,nt)}},[ht]),k.useLayoutEffect(()=>((()=>{const O=dn?Hr.getState().sessions.get(dn)?.cwd??null:null;Yt.getState().setRootPath(O,dn,ms)})(),Hr.subscribe((O,fe)=>{const nt=dn?O.sessions.get(dn)?.cwd??null:null,kt=dn?fe.sessions.get(dn)?.cwd??null:null;nt!==kt&&Yt.getState().setRootPath(nt,dn,ms)})),[ms,dn]);const ar=k.useRef(I3(window.location.search)??LC(mi()?.targetPeerId)),[Fn,ls]=k.useState("");k.useEffect(()=>{const C=ar.current;if(!C)return;if(C.peerId&&C.peerId!==mi()?.targetPeerId){const nt=hA().find(kt=>kt.targetPeerId===C.peerId);if(nt&&Xo()){try{kC(C)}catch{ls(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(fA(nt)){ar.current=null;const kt=new URL(window.location.href);kt.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",kt);return}}ls(t==="zh"?`此架构属于 ${C.serviceName??C.peerId}。请先连接该 Termdock 服务,再打开链接。`:`This architecture belongs to ${C.serviceName??C.peerId}. Connect to that Termdock service, then open this link.`);return}ls("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const O=Yt.getState();O.setRootPath(C.root,dn,ms),O.setRightTab("architecture"),O.openRight();const fe=new URL(window.location.href);fe.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",fe),dn&&(ar.current=null)},[dn,ms,t]);const ya=lr||En,Jn=Ss*.95,Bo=ya?Math.min(Math.max(Ss*.22,280),340):Math.min(Ss*.86,380),Fs=Ct&&Jr?`${Ct}\0${Jr}`:"",Pa=!!(Fs&&mr&&qt[Fs]),li=b.useCallback(C=>{Fs&&(C&&!Yt.getState().selectedFilePath||Nt(O=>{if(!!O[Fs]===C)return O;if(C)return i1({...O,[Fs]:{updatedAt:Date.now()}});const nt={...O};return delete nt[Fs],nt}))},[Fs]);b.useEffect(()=>{DQ(Fs,en,mr)&&Nt(C=>{if(!C[Fs])return C;const O={...C};return delete O[Fs],O})},[Fs,en,mr]);const gs=vt?"markdown-image-lightbox":Je?"markdown-outline":Xt?"right-sidebar-repo-picker":Ye&&Pa?"right-sidebar-file-preview":ur?"settings":Ye&&!(Or&&lr)?"right-sidebar":ne&&!(St&&lr)?"left-sidebar":null,hs=k.useRef(gs),qi=k.useRef(gs),Ls=k.useRef(!1),Xs=k.useRef(!1),Js=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!lr||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[lr]),Oa=b.useCallback(C=>{if(C==="markdown-image-lightbox"){Bt(!1),Dr(O=>O+1);return}if(C==="markdown-outline"){at(!1),X(O=>O+1);return}if(C==="right-sidebar-file-preview"){at(!1),X(O=>O+1),li(!1),jt(O=>O+1);return}if(C==="right-sidebar-repo-picker"){Rt(!1),ge(O=>O+1);return}if(C==="settings"){Rr(!1),Ga(!1),ta(!1),ue(!1);return}if(C==="left-sidebar"){Yt.getState().closeLeft();return}at(!1),X(O=>O+1),Rt(!1),ge(O=>O+1),Bt(!1),Dr(O=>O+1),Yt.getState().closeRight()},[li]),Nn=b.useCallback(C=>{if(!c&&typeof window<"u"&&hs.current===C&&Bu(window.history.state)===C){window.history.back();return}Oa(C)},[Oa,c]),Fa=b.useCallback(()=>{Rr(!1);const C=Yt.getState();C.closeRight(),C.openLeft()},[]),$a=b.useCallback(()=>{Rr(!1);const C=Yt.getState();C.closeLeft(),C.openRight()},[]),va=b.useCallback(()=>{Rr(!1);const C=Yt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),_s=b.useCallback(()=>{const C=Yt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(ne){Nn("left-sidebar");return}Fa()},[Fa,Nn,ne]),ci=b.useCallback(()=>{const C=Yt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),ei=b.useCallback(()=>{const C=Yt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),io=b.useCallback(()=>{const C=Yt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),$n=b.useCallback(()=>{const C=Yt.getState();C.setRightPinned(!1),C.closeRight()},[]),wa=b.useRef(null),ui=b.useRef(null);b.useEffect(()=>()=>ui.current?.(),[]);const Ua=b.useCallback(C=>{if(C.button!==0||!wa.current)return;C.preventDefault(),ui.current?.();const O=Yt.getState();ui.current=GF(wa.current,C.clientX,O.leftSidebarWidth,fe=>Math.min(Math.max(fe,200),500),fe=>Yt.getState().setLeftSidebarWidth(fe))},[]),js=b.useRef(0),ao=b.useRef(0),za=b.useRef(null),_c=b.useCallback(C=>{C.preventDefault(),js.current=C.clientX;const O=Yt.getState(),fe=O.leftPinned?O.leftSidebarWidth:0;ao.current=rf(O.rightSidebarWidth,window.innerWidth,fe);const nt=Kt=>{za.current===null&&(za.current=requestAnimationFrame(()=>{za.current=null;const Er=js.current-Kt.clientX,Mn=Yt.getState(),Vn=Mn.leftPinned?Mn.leftSidebarWidth:0;Mn.setRightSidebarWidth(rf(ao.current+Er,window.innerWidth,Vn))}))},kt=()=>{window.removeEventListener("mousemove",nt),window.removeEventListener("mouseup",kt),za.current!==null&&(cancelAnimationFrame(za.current),za.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",nt),window.addEventListener("mouseup",kt)},[]),di=b.useCallback(()=>{const C=Yt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(Ye){Nn("right-sidebar");return}$a()},[$a,Nn,Ye]),Vl=b.useCallback(()=>{!Pa&&!c&&typeof window<"u"&&hs.current==="right-sidebar"&&Bu(window.history.state)==="right-sidebar"&&(u0("right-sidebar-file-preview"),qi.current="right-sidebar-file-preview"),li(!0)},[Pa,c,li]),Ci=b.useCallback(()=>{Nn("right-sidebar-file-preview")},[Nn]),oo=b.useCallback(()=>{!Xt&&!c&&typeof window<"u"&&hs.current==="right-sidebar"&&Bu(window.history.state)==="right-sidebar"&&(u0("right-sidebar-repo-picker"),qi.current="right-sidebar-repo-picker"),Rt(!0)},[Xt,c]),$s=b.useCallback(()=>{Nn("right-sidebar-repo-picker")},[Nn]),Aa=b.useCallback(()=>{!Je&&!c&&typeof window<"u"&&hs.current&&Bu(window.history.state)===hs.current&&(u0("markdown-outline"),qi.current="markdown-outline"),at(!0)},[Je,c]),Sl=b.useCallback(()=>{Nn("markdown-outline")},[Nn]),es=b.useCallback(()=>{!c&&typeof window<"u"&&hs.current&&Bu(window.history.state)===hs.current&&(u0("markdown-image-lightbox"),qi.current="markdown-image-lightbox"),Bt(!0)},[c]),ti=b.useCallback(()=>{Nn("markdown-image-lightbox")},[Nn]),Pi=b.useCallback(()=>{!c&&typeof window<"u"&&hs.current&&Bu(window.history.state)===hs.current&&(kU("settings"),qi.current="settings"),Yt.getState().closeAll(),Rr(!0)},[c]),Ta=b.useCallback(()=>{Nn("settings")},[Nn]);b.useEffect(()=>{if(!tt)return;const C=()=>Pi();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[tt,Pi]);const ql=b.useCallback(()=>{Ut(!0),Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)},[]),Yl=b.useCallback(()=>{Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null),Ut(!1),Xs.current=!0,ef(),Xs.current},[]);b.useEffect(()=>()=>{Le.current!==null&&window.clearTimeout(Le.current)},[]),b.useEffect(()=>{c||ef()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const O=()=>{C!==null&&(window.clearTimeout(C),C=null)},fe=Mn=>{if(hs.current,Xs.current,hs.current){hs.current;return}!Mn?.force&&Xs.current||(Mn?.userActivated&&(Xs.current=!0),ef(),Xs.current,void 0)},nt=()=>{O(),C=window.setTimeout(()=>{C=null,fe({force:!0})},Hy)},kt=()=>{fe({userActivated:!0})},Kt=()=>{nt()},Er=()=>{document.visibilityState==="visible"&&nt()};return window.addEventListener("pointerdown",kt,{capture:!0,passive:!0}),window.addEventListener("touchstart",kt,{capture:!0,passive:!0}),window.addEventListener("keydown",kt,{capture:!0}),window.addEventListener("pageshow",Kt),document.addEventListener("visibilitychange",Er),()=>{O(),window.removeEventListener("pointerdown",kt,{capture:!0}),window.removeEventListener("touchstart",kt,{capture:!0}),window.removeEventListener("keydown",kt,{capture:!0}),window.removeEventListener("pageshow",Kt),document.removeEventListener("visibilitychange",Er)}},[c]),b.useEffect(()=>{hs.current=gs},[gs]),b.useEffect(()=>{if(typeof window>"u"||gs||c)return;const C=window.setTimeout(()=>{hs.current?(hs.current,void 0):ef()},Hy);return()=>window.clearTimeout(C)},[gs,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=qi.current;Ls.current,gs&&gs!==C&&!Ls.current&&u0(gs),!gs&&C&&Js(),qi.current=gs,!gs&&Ls.current&&window.setTimeout(()=>{Ls.current=!1},0)},[gs,c,Js]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const O=hs.current;if(Xs.current,!O){Xs.current=!1,Xs.current,ql(),j4();return}Ls.current=!0,Oa(O)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[Oa,ql,c]),b.useEffect(()=>{const C=O=>{const fe=O.metaKey||O.ctrlKey;if(fe&&O.key==="b"&&!O.shiftKey&&(O.preventDefault(),_s()),fe&&O.shiftKey&&O.key==="E"&&(O.preventDefault(),di()),fe&&O.shiftKey&&O.key==="P"&&(O.preventDefault(),va()),fe&&!O.shiftKey&&O.altKey&&(O.key==="ArrowLeft"||O.key==="ArrowRight")){O.preventDefault();const nt=O.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:nt}}));return}if(fe&&O.shiftKey&&!O.altKey&&(O.code==="BracketLeft"||O.code==="BracketRight")){O.preventDefault();const nt=O.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:nt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[_s,di,va]);const kc=b.useCallback(async()=>{ve(!0),st(null);try{const C=await Qa({localAccess:{name:te}});oe(C.localAccess),Ce(C.localAccess.name),Yn(o0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){st(C instanceof Error?C.message:"Failed to save local access name")}finally{ve(!1)}},[te]),Lc=b.useCallback(async()=>{ve(!0),st(null);try{const C=await Qa({localAccess:{reset:!0}});oe(C.localAccess),Ce(C.localAccess.name),Yn(o0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){st(C instanceof Error?C.message:"Failed to reset local access name")}finally{ve(!1)}},[]),Gn=b.useCallback(async(C,O="url")=>{if(C)try{if(typeof navigator<"u"&&navigator.clipboard)await navigator.clipboard.writeText(C);else{const fe=document.createElement("textarea");fe.value=C,fe.style.position="fixed",fe.style.left="-9999px",document.body.appendChild(fe),fe.focus(),fe.select(),document.execCommand("copy"),document.body.removeChild(fe)}Qe(O),window.setTimeout(()=>Qe(fe=>fe===O?null:fe),1600)}catch{Qe(null)}},[]),_i=b.useCallback(C=>{const O=IU(Tt,C);O.map(fe=>fe.id).join("\0")!==Tt.map(fe=>fe.id).join("\0")&&(Ft(O),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:O.map(fe=>fe.id)}})))},[Tt]),Yi=b.useCallback(C=>{lr||C.type!=="session"||(ut.current=!1,rs(!1),ps(C.draggableId))},[lr]),Ha=b.useCallback(C=>{if(lr||C.type!=="session")return;const O=C.destination?.droppableId===ig;O!==ut.current&&(ut.current=O,rs(O),O&&navigator.vibrate?.(20))},[lr]),Zi=b.useCallback(C=>{const O=fU(C,!lr);if(ut.current=!1,rs(!1),ps(null),!O)return!1;const fe=Tt.find(kt=>kt.id===C.draggableId),nt=fe?Ht.get(fe.id):null;return fe&&pb({mode:fe.mode,activeProgram:nt?.activeProgram??null,promptState:nt?.promptState??null,shellNames:Da})?(R(null),xt(fe.id),Kn(null)):fe&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:fe.id,source:"other",closeMode:fe.mode==="tmux"?"destroy":"auto"}})),!0},[lr,Tt,Ht,xt]),{groups:lo,arranged:Us}=k.useMemo(()=>Lf(Tt,C=>Ht.get(C.id)?.cwd??null,tn,e("sidebar.ungrouped"),ht,Sn),[Tt,Ht,tn,e,ht,Sn]),Ki=b.useCallback(C=>{Zi(C)||!C.destination||C.source.index===C.destination.index||window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:Us[C.source.index]?.id,targetId:Us[C.destination.index]?.id}}))},[Zi,Us]),Sa=b.useCallback((C,O)=>{const fe=O.trim();fe&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:fe}}))},[]),_n=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:ns,newSessionTmuxName:Ca,userSelectedNewSessionMode:cs,setNewSessionMode:Wa}=EQ(),[ki,co]=b.useState(null),[Li,Ga]=k.useState(!1),[Xi,Ji]=k.useState(!1),[ea,ta]=k.useState(!1),[xs,ra]=k.useState("idle"),Va=k.useRef(Dc(Jh,bU)).current,[Ds,_a]=k.useState(()=>{const C=Va?.presets;if(C&&C.length>0){const O=Hu(C);if(O.length>0)return O}return D0()}),[Cl,Zl]=k.useState(!1),[rl,ka]=k.useState("default"),na=k.useRef(typeof Va?.updatedAt=="number"?Va.updatedAt:null),As=k.useRef(!1),[Qo,ue]=k.useState(!1),[Ve,bt]=k.useState(!1),_=k.useRef(Dc(ja,xU)).current,[M,B]=k.useState(_??[]),[G,Te]=k.useState(_!==null),[Se,Be]=k.useState(!1),ct=!be&&(!gs||gs==="right-sidebar"||gs==="right-sidebar-file-preview"||gs==="left-sidebar")&&!Xi&&!ea&&!Li&&!Qo&&!Ve&&!Pn&&!It&&!ki,yt=ct&&!gs,$t=k.useCallback(C=>{const O=typeof C.version=="number"?C.version:0,fe=yU(Array.isArray(C.presets)?C.presets:[],O);na.current=typeof C.updatedAt=="number"?C.updatedAt:null,_a(nt=>pA(nt,fe)?nt:(As.current=!0,fe)),Yn(Jh,{version:f0,presets:fe,updatedAt:na.current??void 0})},[]);b.useEffect(()=>{const C=O=>{if(O.key!=="Escape"||O.defaultPrevented||O.isComposing||og())return;if(Xi){O.preventDefault(),Ji(!1);return}if(ea){O.preventDefault(),ta(!1);return}if(Li){O.preventDefault(),Ga(!1);return}if(Qo){O.preventDefault(),ue(!1);return}if(Ve){O.preventDefault(),bt(!1);return}if(Pn){O.preventDefault(),We();return}if(An){O.preventDefault(),Qn(null),rr(null);return}if(ur){O.preventDefault(),Ta();return}if(Ye&&!(Or&&lr)){O.preventDefault(),Nn("right-sidebar");return}ne&&!(St&&lr)&&(O.preventDefault(),Nn("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[Xi,ea,Li,Qo,Pn,We,ur,Ye,Or,ne,St,lr,Ta,Nn]),b.useEffect(()=>{Te(!0)},[]);const[Ir,ln]=k.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:D4}),[,rn]=k.useState(!1),ss=k.useCallback(()=>mA().then(C=>{ln(C),Da=new Set(C.shellNames),rn(!0)}).catch(()=>{}),[]);b.useEffect(()=>{ss()},[ss]),b.useEffect(()=>Ox(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){Fx().then(O=>$t(O)).catch(O=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",O)});return}C.key==="program-detection"&&ss()}}),[$t,ss]),b.useEffect(()=>{let C=!1;return(async()=>{try{const O=await Fx();if(C)return;$t(O)}catch(O){console.warn("[toolbar-presets] Failed to load from server:",O)}finally{C||Zl(!0)}})(),()=>{C=!0}},[$t]),b.useEffect(()=>{if(Cl){if(As.current){As.current=!1;return}Yn(Jh,{version:f0,presets:Ds,updatedAt:na.current??void 0}),gA({version:f0,presets:Ds,baseUpdatedAt:na.current??void 0}).then(C=>{na.current=typeof C.updatedAt=="number"?C.updatedAt:null,Yn(Jh,{version:f0,presets:Ds,updatedAt:na.current??void 0})}).catch(C=>{const O=C instanceof Error&&"current"in C?C.current:null;O&&typeof O=="object"&&$t(O),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[$t,Ds,Cl]),b.useEffect(()=>{Cc().then(C=>{w(O=>O===C.preventSleep?O:C.preventSleep),T(O=>O===C.networkAvailable?O:C.networkAvailable),oe(C.localAccess),Ce(C.localAccess.name),Hn(C.runningSessionButtonEnabled),Yn(l0,C.runningSessionButtonEnabled),pn(C.attentionButtonEnabled),Yn(c0,C.attentionButtonEnabled),Yn(o0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!S)return;const C=zp();H(C),C!=="granted"&&(I(!1),bh(!1))},[S]),b.useEffect(()=>{if(!S)return;Ld();const C=()=>{document.visibilityState==="visible"&&(Ld(),IA())},O=window.setInterval(()=>{Ld()},360*60*1e3);return document.addEventListener("visibilitychange",C),window.addEventListener("focus",C),()=>{window.clearInterval(O),document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",C)}},[S]);const Oi=b.useCallback(async()=>{if(S){I(!1),bh(!1),xA(),H(zp());return}const C=await bA();if(H(C),C!=="granted"){I(!1),bh(!1);return}I(!0),bh(!0),await Ld(!0,!0),ra("idle")},[S]),Vr=b.useCallback(async()=>{ra("checking"),await Gi()?.prepareNotificationTest?.();const C=await yA({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});ra(C?"delivered":"failed")},[e]),yn=b.useCallback(C=>{P(C),vA(C),Hp()},[]),Bs=b.useCallback(C=>{Q(C),wA(C),Hp()},[]),Kl=b.useCallback(C=>{Z(C),AA(C),Hp()},[]);b.useEffect(()=>{Ds.some(C=>C.id===rl)||ka(Ds[0]?.id??"default")},[rl,Ds]),b.useEffect(()=>{if(!tr.available&&ns==="tmux"){Wa("shell",{userInitiated:!1});return}tr.available&&cs!=="shell"&&ns!=="tmux"&&Wa("tmux",{userInitiated:!1})},[ns,tr.available,cs,Wa]),b.useEffect(()=>{co(null)},[ur,ns,tr.available]),b.useEffect(()=>{const C={};typeof navigator<"u"&&(C.userAgent=navigator.userAgent,C.platform=navigator.platform,C.maxTouchPoints=navigator.maxTouchPoints,C.hasTouch=navigator.maxTouchPoints>0||"ontouchstart"in window,C.vendor=navigator.vendor),typeof window<"u"&&(C.screenWidth=window.innerWidth,C.screenHeight=window.innerHeight,C.pixelRatio=window.devicePixelRatio,C.orientation=window.screen?.orientation?.type||"unknown",C.hasVisualViewport=!!window.visualViewport,C.visualViewportHeight=window.visualViewport?.height,C.visualViewportWidth=window.visualViewport?.width,C.location=window.location.href),C.timestamp=new Date().toISOString(),C.isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,C.isAndroid=/Android/.test(navigator.userAgent),Ot(C)},[]);const md=b.useCallback(C=>{if(Zi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;_i(S3(lo,C.source.index,C.destination.index));return}if(C.source.droppableId!==C.destination.droppableId||C.source.index===C.destination.index)return;const O=C.source.droppableId.replace(/^group-sessions:/,""),fe=lo.find(nt=>nt.key===O);fe&&window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:fe.sessions[C.source.index]?.id,targetId:fe.sessions[C.destination.index]?.id}}))},[lo,_i,Zi]),Rn=k.useMemo(()=>Us.flatMap(C=>{const O=Ht.get(C.id);if(O?.agentStatus!=="working")return[];const{primary:fe,secondary:nt}=xl(C,O?.activeProgram??null,O?.cwd??null,Da,O?.shellTitle??null,O?.promptState??null);return[{id:C.id,label:fe,detail:nt}]}),[Us,Ht]),Po=Ct?Us.findIndex(C=>C.id===Ct):-1,Oo=Us.length>0&&Po>=0?`${Po+1}/${Us.length}`:`${Us.length}`,hi=k.useMemo(()=>{let C=0;for(const O of Tt){const fe=Ht.get(O.id);(fe?.agentStatus==="waiting"||fe?.agentNeedsReview)&&(C+=1)}return{running:Rn.length,review:C}},[Rn.length,Tt,Ht]),gd=k.useMemo(()=>Us.flatMap(C=>{const O=Ht.get(C.id);if(O?.agentStatus!=="waiting"&&!O?.agentNeedsReview)return[];const{primary:fe}=xl(C,O.activeProgram,O.cwd,Da,O.shellTitle,O.promptState);return[{id:O.terminalSessionId??C.id,label:fe,waiting:O.agentStatus==="waiting"}]}),[Us,Ht]);TA(hi.running,hi.review,gd);const La=Ct?Tt.find(C=>C.id===Ct)??null:null,Fo=La?Ht.get(La.id):void 0,_p=!!(La&&Fo?.agentResumeRecovered&&Fo.agentNativeSessionId&&Fo.terminalSessionId),qa=La&&Kr?.sessionId===La.id?Kr:null;k.useLayoutEffect(()=>{if(!Wn)return;const C=se.current;if(!C)return;const O=!Ee.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:O?"auto":"smooth"}),Ee.current=!0,O&&Wu("active-tab-positioned")},[Ct,Wn]),b.useEffect(()=>{Wr&&F.current&&(F.current.scrollIntoView({block:"nearest",inline:"nearest"}),F.current.focus(),F.current.select()),Wr||(q.current=!1)},[Wr]);const th=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),xd=b.useCallback((C,O)=>{Tr(O??null),jr(C)},[]),kp=ex(),uo=b.useCallback(C=>{if(!C)return;dr(C),_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:_r.current,requestedSessionId:C,activeSessionId:Ct,sessions:Tt.map(fe=>({id:fe.id,terminalSessionId:Ht.get(fe.id)?.terminalSessionId??null}))}),SA(C);const O=Tt.find(fe=>fe.id===C||Ht.get(fe.id)?.terminalSessionId===C);O?(zr.current=null,_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:_r.current,requestedSessionId:C,targetSessionId:O.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O.id}))):(zr.current=C,_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:_r.current,requestedSessionId:C}))},[Ct,Tt,Ht]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const O=async()=>{if(window.parent!==window&&Xo()){Gt(!0);return}try{const nt=await caches.open(TU),kt=await nt.match(Wy);if(!kt)return;await nt.delete(Wy);const Kt=await kt.json();if(C)return;const Er=typeof Kt.sessionId=="string"?Kt.sessionId:null,Mn=typeof Kt.traceId=="string"?Kt.traceId:null,Vn=typeof Kt.clickedAt=="number"?Kt.clickedAt:0,Un=Date.now()-Vn;Ba("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:Mn,sessionId:Er,ageMs:Un,valid:!!(Er&&Un>=0&&Un<=Gy),visibilityState:document.visibilityState}),Er&&Un>=0&&Un<=Gy&&(_r.current=Mn,typeof Kt.targetPeerId=="string"&&Kt.targetPeerId!==mi()?.targetPeerId?Xo()?.focusSession(Kt.targetPeerId,Er):uo(Er))}catch(nt){Ba("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:nt instanceof Error?nt.message:String(nt)})}finally{C||Gt(!0)}},fe=()=>{document.visibilityState==="visible"&&O()};return O(),document.addEventListener("visibilitychange",fe),window.addEventListener("pageshow",O),()=>{C=!0,document.removeEventListener("visibilitychange",fe),window.removeEventListener("pageshow",O)}},[uo]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),O=C.get("session");if(!O)return;Ba("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:_r.current,targetSessionId:O,href:window.location.href,visibilityState:document.visibilityState});const fe=C.get("service");fe&&fe!==mi()?.targetPeerId?Xo()?.focusSession(fe,O):zr.current=O,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const nt=C.toString(),kt=`${window.location.pathname}${nt?`?${nt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",kt)},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search);if(C.get("_notif")!=="1")return;const O=C.get("session");C.delete("_notif");const fe=C.toString(),nt=`${window.location.pathname}${fe?`?${fe}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",nt),window.parent!==window&&Xo())return;const kt=new BroadcastChannel("termdock:notif");let Kt=!1;const Er=Vn=>{Vn.data?.type==="termdock:notif-pong"&&!Kt&&(Kt=!0,kt.close(),window.close())};kt.addEventListener("message",Er),kt.postMessage({type:"termdock:notif-ping",sessionId:O,targetPeerId:C.get("service")});const Mn=setTimeout(()=>{Kt||kt.close()},500);return()=>{clearTimeout(Mn),Kt||kt.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Xo())return;const C=new BroadcastChannel("termdock:notif"),O=fe=>{fe.data?.type==="termdock:notif-ping"&&(C.postMessage({type:"termdock:notif-pong"}),typeof fe.data.sessionId=="string"&&(typeof fe.data.targetPeerId=="string"&&fe.data.targetPeerId!==mi()?.targetPeerId?Xo()?.focusSession(fe.data.targetPeerId,fe.data.sessionId):uo(fe.data.sessionId)))};return C.addEventListener("message",O),()=>C.close()},[uo]),b.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const C=O=>{const fe=O.data;if(fe&&fe.type==="termdock:focus-session"&&typeof fe.sessionId=="string"){if(typeof fe.targetPeerId=="string"&&fe.targetPeerId!==mi()?.targetPeerId){Xo()?.focusSession(fe.targetPeerId,fe.sessionId)&&O.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}O.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),uo(fe.sessionId)}else fe?.type==="termdock:push-subscription-changed"?Ld(!0):fe?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[uo]),b.useEffect(()=>{const C=O=>{const fe=O.detail;typeof fe=="string"&&uo(fe)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[uo]),b.useEffect(()=>{const C=()=>{const O=EA(mi()?.targetPeerId);O&&uo(O)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[uo]),b.useEffect(()=>{const C=zr.current;if(!C)return;const O=Tt.find(fe=>fe.id===C||Ht.get(fe.id)?.terminalSessionId===C);O?(zr.current=null,_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:_r.current,requestedSessionId:C,targetSessionId:O.id,activeSessionId:Ct}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O.id}))):_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:_r.current,requestedSessionId:C,activeSessionId:Ct,sessions:Tt.map(fe=>({id:fe.id,terminalSessionId:Ht.get(fe.id)?.terminalSessionId??null}))})},[Ct,Tt,Ht]);const sa=k.useMemo(()=>{const C=[];for(const O of Tt){const fe=Ht.get(O.id);(fe?.agentStatus==="waiting"||fe?.agentNeedsReview)&&C.push(O.id)}return C},[Tt,Ht]),_l=b.useCallback(()=>{if(sa.length===0)return;Ct&&Hr.getState().clearAgentNeedsReview(Ct);const C=Ct?Tt.findIndex(fe=>fe.id===Ct):-1,O=sa.find(fe=>Tt.findIndex(nt=>nt.id===fe)>C)??sa[0];O&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O}))},[sa,Tt,Ct]),Ic=b.useCallback(()=>{if(sa.length===0)return;Ct&&Hr.getState().clearAgentNeedsReview(Ct);const C=Ct?Tt.findIndex(fe=>fe.id===Ct):Tt.length,O=[...sa].reverse().find(fe=>Tt.findIndex(nt=>nt.id===fe)<C)??sa[sa.length-1];O&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O}))},[sa,Tt,Ct]);b.useEffect(()=>{const C=O=>{!O.altKey||!O.shiftKey||O.metaKey||O.ctrlKey||O.key!=="ArrowUp"&&O.key!=="ArrowDown"||(O.preventDefault(),O.key==="ArrowUp"?Ic():_l())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[_l,Ic]);const hu=b.useCallback(async C=>{const fe=Hr.getState().sessions.get(C)?.cwd;if(fe)try{await navigator.clipboard?.writeText(fe),Cn(fe),window.setTimeout(()=>{Cn(nt=>nt===fe?null:nt)},1400)}catch{}},[]),Lp=b.useCallback(C=>{Ft(C.sessions),gt(C.activeSessionId),Cr(C.splitWorkspaces),Hr.getState().setActiveSessionId(C.activeSessionId)},[]),bd=b.useCallback(()=>{cn(!0)},[]),rh=b.useCallback(()=>{cn(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!et||!Ct)return;Tt.find(O=>O.id===et||Ht.get(O.id)?.terminalSessionId===et)?.id===Ct&&dr(null)},[Ct,et,Tt,Ht]);const yd=b.useRef(!1),[fu,nh]=b.useState(!1),ho=b.useCallback(C=>{const O=!C?.onResult;if(O&&yd.current)return;O&&(yd.current=!0,nh(!0));const fe=C?.mode??ns,nt=fe==="tmux"&&(C?.tmuxSessionName?.trim()||Ca.trim())||void 0,kt=C?.cwd||(Ct?Hr.getState().sessions.get(Ct)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:fe,tmuxSessionName:nt,cwd:kt,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Kt=>{yd.current=!1,nh(!1),Kt.ok||ft({tone:"error",message:e(h1(Kt.error))})})}}))},[ns,Ca,Ct,e]),kl=b.useCallback(async()=>{Mt(!0);try{const C=await a1();if(K(C),!C.available){On([]);return}const O=await o1();On(O)}catch{K({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),On([])}finally{Mt(!1)}},[]),pu=b.useCallback(async C=>{const{cleanedSessions:O}=await e3(C);for(const fe of O)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:fe}));await kl()},[kl]),sh=b.useCallback(async C=>{Pr(C),Kn(null);try{await pu(C),Dt(null)}catch(O){Kn(O instanceof Error?O.message:"Failed to kill tmux session")}finally{Pr(null)}},[pu]);b.useEffect(()=>{if(!Cs)return;if(Lr.find(fe=>fe.name===Cs&&(fe.connected||fe.boundFrontendSessionId))){ws(null);return}const O=setTimeout(()=>ws(null),1e4);return()=>clearTimeout(O)},[Cs,Lr]);const nl=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),Ec=b.useCallback(C=>{const O=C??Ct;O&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:O}))},[Ct]),vd=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:O}}))},[]),sl=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:O}}))},[]),wd=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:O}}))},[]),mu=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:O}}))},[]),Xl=b.useCallback((C,O,fe)=>{const nt=Tt.find(Kt=>Kt.id===C);if(!nt)return;const kt=Ht.get(C);if(fe?.skipConfirmation||!pb({mode:nt.mode,activeProgram:kt?.activeProgram??null,promptState:kt?.promptState??null,shellNames:Da})){nl({sessionId:C,source:"sidebar",closeMode:nt.mode==="tmux"?"destroy":"auto"});return}R(O?{x:O.clientX,y:O.clientY}:null),xt(C),Kn(null)},[Tt,Ht,nl,xt]);b.useEffect(()=>{if(!tt)return;const C=O=>{const fe=O.detail;fe==="new-session"?ho():fe==="close-session"?Ct&&!It&&Xl(Ct):fe==="previous-session"||fe==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:fe==="next-session"?"next":"prev"}})):fe==="toggle-left-sidebar"?_s():fe==="toggle-right-sidebar"?di():fe==="previous-attention"?Ic():fe==="next-attention"&&_l()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[Ct,It,tt,ho,Xl,_s,di,_l,Ic]);const $o=k.useMemo(()=>Tt.find(C=>C.id===It)??null,[Tt,It]),Ad=b.useCallback(()=>{if(!$o||!Pt()){_t(null),R(null);return}nl({sessionId:$o.id,source:"sidebar",closeMode:"destroy"}),_t(null),R(null)},[$o,nl,Pt]),ih=k.useRef(null),gu=b.useCallback(()=>{_t(null),R(null),Kn(null)},[]);k.useLayoutEffect(()=>{if(!It)return;const C=()=>{Pt()||gu()},O=()=>gu();C();const fe=Hr.subscribe(C);return window.addEventListener(Fu,C),window.addEventListener("auth:unauthorized",O),()=>{fe(),window.removeEventListener(Fu,C),window.removeEventListener("auth:unauthorized",O)}},[It,Ht,Pt,gu]);const Ip=k.useMemo(()=>{if(!$o)return"";const C=Ht.get($o.id);return xl($o,C?.activeProgram??null,C?.cwd??null,Da,C?.shellTitle??null,C?.promptState??null).primary},[$o,Ht]);b.useEffect(()=>{if(!ur)return;let C=!1,O=!1;const fe=async()=>{if(!O)try{const kt=await a1();if(C||K(kt),!kt.available){C||On([]);return}const Kt=await o1();C||On(Kt)}catch{O=!0,C||(K({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),On([]))}};fe();const nt=setInterval(()=>{fe()},4e3);return()=>{C=!0,clearInterval(nt)}},[ur]);const ah=ki??ns,xu=ah==="shell",Ia=ah==="tmux"&&tr.available,Uo=k.useMemo(()=>T3(Lr.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[Lr,e]),Jl=k.useMemo(()=>Lr.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,O)=>(O.lastActiveAt??O.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[Lr]);b.useEffect(()=>{!ne&&!(St&&lr)||kl()},[ne,St,lr,Tt.length,kl]);const Ll=(C,O,fe,nt=!1)=>{const kt=C.id===Ct,Kt=C.id===Wr,Er=Ht.get(C.id),{primary:Mn,secondary:Vn}=xl(C,Er?.activeProgram??null,Er?.cwd??null,Da,Er?.shellTitle??null,Er?.promptState??null),Un=ld(Er?.cwd??null),Fi=O?Vn??(Un&&Un!==Mn?Un:null):null,Ln=Er?.gitStatus,ia=`${Er?.cwd||C.name}${Ln?`
186
+ }`}),N&&s.jsx("div",{className:"whitespace-pre-wrap break-words text-[10px] text-[color:var(--warning)]",children:N}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{ke()},className:"flex items-center gap-1 rounded-full bg-[rgb(var(--success-rgb)_/_0.14)] px-3 py-1 text-[11px] font-medium text-[color:var(--success)] hover:bg-[rgb(var(--success-rgb)_/_0.22)] transition",children:[s.jsx(ST,{size:11}),e("settings.agentPluginCreate")]}),s.jsx("button",{type:"button",onClick:()=>{x(!1),I(""),P(null)},className:"rounded-full px-3 py-1 text-[11px] text-muted-foreground hover:text-foreground transition",children:e("common.cancel")})]})]})]})]})}function iU({state:e,pending:t,onCheck:r,onConfirmRestart:n,desktopState:a,desktopPending:c=!1,desktopSnapshot:l,desktopActions:d,onCheckDesktop:f,onInstallDesktop:m}){const{t:x}=Ur(),y=e?.status??"idle",w=t||y==="checking"||y==="installing"||y==="restarting",v=y==="ready"&&!!e?.latestVersion,T=y==="checking"?x("settings.updateChecking"):y==="installing"?x("sidebar.updateInstalling"):y==="ready"?x("sidebar.updateReady"):y==="restarting"?x("sidebar.updateRestarting"):y==="current"?x("settings.updateCurrent"):y==="error"?e?.error||x("sidebar.updateFailed"):x("settings.updateHint"),S=a?.currentVersion||l?.appVersion,I=a?.status??"idle",N=c||I==="checking"||I==="downloading"||I==="installing",P=I==="ready",$=a?.error||(I==="unsupported"?x("settings.desktopUpdateUnsupported"):I==="checking"?x("settings.desktopUpdateChecking"):I==="current"?x("settings.desktopUpdateCurrent"):I==="downloading"?x("settings.desktopUpdateDownloading"):I==="ready"?x("settings.desktopUpdateReady"):I==="installing"?x("settings.desktopUpdateInstalling"):I==="error"&&a?.error||x("settings.desktopUpdateHint"));return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"termdock-update-title",children:[s.jsx("div",{id:"termdock-update-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:x("settings.updateTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(vn,{size:15,className:w?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.updateRuntimeTitle")}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:T}),e&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:v&&e.latestVersion?`${e.currentVersion} → ${e.latestVersion}`:`v${e.currentVersion}`})]})]}),v?s.jsx("button",{type:"button",disabled:w,onClick:n,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("sidebar.updateRestart")}):s.jsx("button",{type:"button",disabled:w,onClick:r,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(y==="checking"?"settings.updateCheckingShort":y==="installing"?"settings.updateInstallingShort":y==="error"?"sidebar.updateRetry":y==="current"?"settings.updateCheckAgain":"settings.updateCheck")})]}),(a||d)&&s.jsxs("div",{className:"flex items-start justify-between gap-3 border-t border-border/10 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${P?"bg-[rgb(var(--warning-rgb)_/_0.16)] text-[color:var(--warning)]":"bg-primary/15 text-primary"}`,children:s.jsx(vn,{size:15,className:N?"animate-spin":""})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:x("settings.desktopUpdateTitle")}),s.jsx("div",{className:`mt-0.5 text-[10px] leading-relaxed ${a?.error?"text-destructive":"text-muted-foreground"}`,role:a?.error?"alert":void 0,children:a?$:x(f?"settings.desktopStatusLoading":"settings.desktopUpdateUnsupported")}),s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:P&&a?.latestVersion?`${a.currentVersion} → ${a.latestVersion}`:S?`v${S}`:null})]})]}),P?s.jsx("button",{type:"button",disabled:N||!m,onClick:m,className:"shrink-0 rounded-full bg-[var(--warning)] px-3 py-1.5 text-[11px] font-semibold text-[color:var(--bg)] transition hover:opacity-90 disabled:cursor-wait disabled:opacity-60",children:x("settings.desktopUpdateRestart")}):s.jsx("button",{type:"button",disabled:!a||N||I==="unsupported"||!f,onClick:f,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated disabled:cursor-wait disabled:opacity-60",children:x(I==="installing"?"settings.updateInstallingShort":I==="downloading"?"settings.desktopUpdateDownloadingShort":I==="checking"?"settings.updateCheckingShort":I==="current"||I==="error"?"settings.desktopUpdateCheckAgain":"settings.desktopUpdateCheck")})]}),d]})}function aU({quality:e}){const{locale:t}=Ur(),r=(d,f)=>t==="zh"?d:f,n=d=>d==null||!Number.isFinite(d)?"—":`${d.toFixed(1)} ms`,a=e?.diagnostics,c=d=>s.jsx("dl",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-1.5 tabular-nums",children:d.map(([f,m])=>s.jsxs(k.Fragment,{children:[s.jsx("dt",{children:f}),s.jsx("dd",{className:"text-right text-foreground break-all",children:m})]},f))}),l=(d,f)=>s.jsxs("section",{className:"mt-3 border-t border-border/30 pt-3",children:[s.jsx("h3",{className:"mb-2 font-medium text-foreground",children:d}),f]});return s.jsxs("div",{className:"text-[11px] leading-relaxed",children:[l(r("往返统计","Round-trip statistics"),s.jsxs(s.Fragment,{children:[c([[r("平均延迟","Average latency"),n(e?.average)],["P95",n(e?.p95)],[r("服务端回包处理","Server reply handler"),n(e?.handlerMs)]]),s.jsx("p",{className:"mt-2",children:r("8 秒未响应计为超时,不等于网络丢包。回包处理仅含消息解析至构造回复,不含解密、排队和发包。","A probe times out after 8s; this is not packet loss. Handler timing covers parsing through reply creation, excluding decryption, queues and transmission.")})]})),l(r("当前发送与排队","Current buffers and queues"),a?s.jsxs(s.Fragment,{children:[c([[r("当前传输","Current transport"),a.transport==="webtransport"?"QUIC / HTTP/3":"WebSocket / TCP"],[r("传输层发送缓冲","Transport send buffer"),`${a.bufferedBytes} B`],[r("加密通道待发送","Channel writes pending"),a.pendingWrites?r("有","Yes"):r("无","No")],[r("进行中的非终端请求","Active non-terminal requests"),a.activeRequests],[r("等待通道的请求","Requests waiting for capacity"),a.waitingRequests]]),s.jsx("p",{className:"mt-2",children:a.transport==="webtransport"?r("此终端使用独立加密流,文件请求使用其他流。","This terminal has an independent encrypted stream; file requests use other streams."):r("属于此服务共用的连接,包含文件等其他请求。","Shared by this service, including file transfers and other requests.")})]}):s.jsx("p",{children:r("尚无连接记录。","No connection record yet.")})),l(r("本次连接建立 · 历史耗时","Connection setup · recorded timings"),s.jsxs(s.Fragment,{children:[c([[r("传输通道就绪","Transport ready"),n(a?.transportOpenMs)],...a?.relay?[[r("其中:连上入口 WebSocket","Within transport: entry WebSocket"),n(a.relay.entryOpenMs)],[r("其中:请求中转至通道打开","Within transport: relay open request"),n(a.relay.routeOpenMs)]]:[],[r("Noise 加密握手","Noise handshake"),n(a?.handshakeMs)],[r("终端逻辑通道就绪","Terminal logical channel ready"),n(a?.socketOpenMs)],[r("其中:等待本地通道名额","Within logical open: local capacity wait"),n(a?.socketQueueMs)]]),s.jsx("p",{className:"mt-2",children:r("这是建链时的历史耗时,不代表当前延迟。“其中”为子项,不能重复相加;中转耗时含处理和建链,不含之前的授权。","Recorded setup timings, not live latency. “Within” rows are subsets, not additive. Relay timing includes processing and setup, excluding earlier authorization.")})]}))]})}function oU({backendSessionId:e}){const{locale:t}=Ur(),r=t==="zh",[n,a]=k.useState(null),[c,l]=k.useState(!1);k.useEffect(()=>{if(a(null),!c||!e)return;const y=()=>a(Z9(e));y();const w=setInterval(y,1e3);return document.addEventListener("visibilitychange",y),()=>{clearInterval(w),document.removeEventListener("visibilitychange",y)}},[e,c]);const d=n?.diagnostics,f=n?.rtt,m=n?.connected?n.waiting?r?"等待响应…":"Waiting for reply…":f==null?r?"测量中…":"Measuring…":`${f} ms · ${f<150?r?"流畅":"Low latency":f<300?r?"有延迟":"Moderate latency":r?"高延迟":"High latency"}`:r?"未连接":"Disconnected",x=y=>y==null?"—":`${Math.round(y)} ms`;return s.jsxs("div",{className:"mt-3 rounded-xl bg-surface-2 px-3 text-muted-foreground",children:[s.jsxs("button",{type:"button","aria-expanded":c,onClick:()=>l(y=>!y),className:"flex min-h-11 w-full items-center gap-2 py-2 text-[12px] tabular-nums hover:text-foreground","aria-label":`${r?"连接质量":"Connection quality"}${c?`: ${m}`:""}`,children:[s.jsx("span",{"aria-hidden":"true",className:`h-1.5 w-1.5 rounded-full ${c&&n&&(!n.connected||n.waiting||f!=null&&f>=300)?"bg-destructive":"bg-current"}`}),s.jsxs("span",{className:"flex-1 text-left",children:[r?"连接质量":"Connection quality",c?` · ${m}`:""]}),s.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})]}),c&&s.jsxs("div",{className:"pb-3 text-[11px] leading-relaxed",children:[!e&&s.jsx("p",{children:r?"请先打开一个终端会话,再查看连接质量。":"Open a terminal session to measure connection quality."}),s.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 tabular-nums",children:[s.jsx("dt",{children:r?"近期延迟":"Recent latency"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.minimum==null?"—":`${Math.round(n.minimum)}–${Math.round(n.maximum??n.minimum)} ms`}),s.jsx("dt",{children:r?"波动":"Jitter"}),s.jsx("dd",{className:"text-right text-foreground",children:x(n?.jitter)}),s.jsx("dt",{children:r?"探测超时":"Probe timeouts"}),s.jsx("dd",{className:"text-right text-foreground",children:n?.samples?`${n.timeouts} / ${n.samples}`:"—"}),s.jsx("dt",{children:r?"连接路径":"Connection route"}),s.jsx("dd",{className:"text-right text-foreground break-words",children:d?`${d.path==="relay"?r?"经入口中转":"Via relay":r?"直连":"Direct"} · ${d.endpoint}`:"—"})]}),s.jsx("p",{className:"mt-2",children:r?"每 5 秒更新,统计最近 20 次;波动越小越稳定。":"Updates every 5s, using the last 20 probes. Lower jitter means more consistent latency."}),s.jsxs("details",{className:"mt-3 border-t border-border/30 pt-2",children:[s.jsx("summary",{className:"cursor-pointer py-1 hover:text-foreground",children:r?"诊断详情":"Diagnostics"}),s.jsx(aU,{quality:n})]})]})]})}const Qy={"startup-failure":"settings.serverHealthEventStartupFailure",crash:"settings.serverHealthEventCrash","crash-native":"settings.serverHealthEventCrashNative",killed:"settings.serverHealthEventKilled",wedge:"settings.serverHealthEventWedge","port-conflict":"settings.serverHealthEventPortConflict","gave-up":"settings.serverHealthEventGaveUp","exit-zero-unexpected":"settings.serverHealthEventExitZero","terminated-externally":"settings.serverHealthEventTerminated","supervisor-lost":"settings.serverHealthEventSupervisorLost","uncaught-exception":"settings.serverHealthEventUncaughtException","unhandled-rejection":"settings.serverHealthEventUnhandledRejection","exit-nonzero":"settings.serverHealthEventExitNonzero"};function lU(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}function cU({state:e,onDismiss:t}){const{t:r}=Ur(),[n,a]=b.useState(!1),[c,l]=b.useState(!1),d=b.useRef(!1),f=b.useRef(!0);b.useEffect(()=>(f.current=!0,()=>{f.current=!1}),[]),b.useEffect(()=>{e?.supervised&&(d.current=!1,a(!1),l(!1))},[e?.supervised]),b.useEffect(()=>{if(!n)return;const $=window.setTimeout(()=>{d.current=!1,a(!1),l(!0)},45e3);return()=>window.clearTimeout($)},[n]);const m=async()=>{if(!d.current){d.current=!0,l(!1),a(!0);try{await K9()}catch{if(!f.current)return;d.current=!1,a(!1),l(!0)}}};if(!e)return null;const x=e.incident,y=!e.supervised&&e.supervisor?.phase==="gave-up",w=!e.supervised&&e.supervisor!==null&&!e.supervisor.alive,v=y||w||e.attention,T=e.supervised&&e.supervisor?.alive&&e.supervisor.phase==="running",S=y?r("settings.serverHealthGaveUp",{count:e.supervisor?.consecutiveCrashes??0}):w?r("settings.serverHealthSupervisorLost"):e.supervised?r("settings.serverHealthSupervised"):r("settings.serverHealthUnsupervised"),I=x?r(Qy[x.event]??"settings.serverHealthUnknownEvent"):"",N=x?.causeEvent?r(Qy[x.causeEvent]??"settings.serverHealthUnknownEvent"):"",P=x?[new Date(x.at).toLocaleString(),x.uptimeMs!==null?r("settings.serverHealthUptime",{duration:lU(x.uptimeMs)}):null,x.signal?`signal ${x.signal}`:null,x.exitCode!==null?`exit ${x.exitCode}`:null].filter(Boolean).join(" · "):"";return s.jsxs("section",{className:"mt-3 overflow-hidden rounded-xl bg-surface-2","aria-labelledby":"server-health-title",children:[s.jsx("div",{id:"server-health-title",className:"px-3 pt-3 text-[12px] font-semibold text-foreground",children:r("settings.serverHealthTitle")}),s.jsxs("div",{className:"flex items-start justify-between gap-3 px-3 py-3",children:[s.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[s.jsx("span",{className:`mt-0.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${v?"bg-destructive/15 text-destructive":"bg-primary/15 text-primary"}`,children:v?s.jsx(HS,{size:15}):s.jsx(GS,{size:15})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-medium text-foreground",children:S}),s.jsx("div",{className:"mt-0.5 text-[10px] leading-relaxed text-muted-foreground",children:x?`${r(T?"settings.serverHealthHistory":"settings.serverHealthLastIncident")}: ${I}${N?` · ${N}`:""}`:r("settings.serverHealthClean")}),x&&T&&s.jsx("div",{className:"mt-1 text-[11px] text-primary",children:r("settings.serverHealthRunningNow")}),x&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:P}),x?.detail&&s.jsx("div",{className:"mt-1 break-words text-[10px] text-muted-foreground/75",children:x.detail}),x?.oomSuspect&&s.jsx("div",{className:"mt-1 text-[10px] text-[color:var(--warning)]",children:r("settings.serverHealthOomNote")}),e.supervisor&&e.supervisor.restarts>0&&!y&&s.jsx("div",{className:"mt-1 text-[10px] tabular-nums text-muted-foreground/75",children:r("settings.serverHealthRestarted",{count:e.supervisor.restarts})})]})]}),e.attention&&s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated",children:r("settings.serverHealthDismiss")})]}),!e.supervised&&s.jsxs("div",{className:"border-t border-border px-3 py-3",children:[s.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:e.canEnableSupervision?r("settings.serverHealthEnableHint"):r("settings.serverHealthEnableUnavailable")}),e.canEnableSupervision&&s.jsx("button",{type:"button",onClick:m,disabled:n,className:"mt-2 min-h-11 rounded-lg bg-primary px-3 text-[12px] font-medium text-primary-foreground disabled:opacity-60",children:r(n?"settings.serverHealthEnabling":"settings.serverHealthEnable")}),n&&s.jsx("p",{role:"status",className:"mt-2 text-[11px] text-muted-foreground",children:r("settings.serverHealthEnablePending")}),c&&s.jsx("p",{role:"alert",className:"mt-2 text-[11px] text-destructive",children:r("settings.serverHealthEnableError")})]})]})}const uU=()=>()=>{},dU=()=>1/0;function hU(){const{t:e}=Ur(),t=b.useId(),r=Xo(),n=b.useSyncExternalStore(r?.subscribe??uU,r?.retentionLimit??dU);if(!r)return null;const a=X9+1,c=n===1/0?e("settings.workspaceUnlimited"):String(n);return s.jsxs("div",{className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("label",{htmlFor:t,className:"shrink-0 text-[12px] font-medium text-foreground/90",children:e("settings.workspaceLimit")}),s.jsx("input",{id:t,type:"range",min:3,max:a,step:1,value:n===1/0?a:n,"aria-valuetext":c,"aria-describedby":`${t}-hint`,onChange:l=>{const d=Number(l.target.value);r.setRetentionLimit(d===a?1/0:d)},className:"h-8 min-w-0 flex-1"}),s.jsx("output",{htmlFor:t,className:"min-w-12 shrink-0 text-right text-[11px] tabular-nums text-muted-foreground",children:c})]}),s.jsx("p",{id:`${t}-hint`,className:"text-[11px] leading-relaxed text-muted-foreground",children:e("settings.workspaceLimitHint")})]})}const ig="mobile-session-destroy";function fU(e,t){return t&&e.type==="session"&&e.destination?.droppableId===ig}const ja="termdock-program-rules-cache",Jh="termdock-toolbar-presets-cache",o0="termdock-settings-cache",Py="termdock-color-theme",Oy="termdock:right-sidebar:file-preview-open-by-session:v2",l0="termdock:running-session-button-enabled:v1",c0="termdock:attention-button-enabled:v1",pU=60,Fy=320,$y=420,Ko=8;function Uy(e,t,r){return Math.min(Math.max(e,t),r)}function zy(e){if(typeof window>"u")return{left:Ko,top:Ko};const t=window.innerWidth/2,r=Math.min(64,window.innerHeight/4),n=e?.x??t,a=e?.y??r,c=Math.max(Ko,window.innerWidth-Fy-Ko),l=Math.max(Ko,window.innerHeight-$y-Ko);return{left:Uy(n+Ko,Ko,c),top:Uy(a+Ko,Ko,l),width:Fy,maxHeight:`min(${$y}px, calc(100vh - ${Ko*2}px))`}}function mU(e){return e==="dark"||e==="light"}function gU(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.entries(e).every(([t,r])=>{if(!t||!r||typeof r!="object"||Array.isArray(r))return!1;const n=r;return typeof n.updatedAt=="number"&&Number.isFinite(n.updatedAt)})}function i1(e){const t=Object.entries(e).filter(([r,n])=>r&&Number.isFinite(n.updatedAt)).sort(([,r],[,n])=>n.updatedAt-r.updatedAt).slice(0,pU);return Object.fromEntries(t)}function xU(e){return Array.isArray(e)&&e.every(t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.id=="string"&&typeof r.pattern=="string"&&typeof r.output=="string"&&(r.matchType==="exact"||r.matchType==="includes"||r.matchType==="prefix"||r.matchType==="regex")})}function bU(e){return typeof e=="object"&&e!==null&&typeof e.version=="number"&&Array.isArray(e.presets)}function yU(e,t){const r=D0(),n=new Set(ZE()),a=Array.isArray(e)?e:[],c=Hu(a),l=t<f0;if(c.length===0)return r;if(l){const f=new Map(c.map(w=>[w.id,w])),m=new Map(a.map(w=>[typeof w.id=="string"?w.id.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-"):"",w])),x=c.filter(w=>!n.has(w.id));return[...r.map(w=>{const v=f.get(w.id),T=m.get(w.id);return v?{...w,rowLayout:v.rowLayout,showOnDesktop:typeof T?.showOnDesktop=="boolean"?T.showOnDesktop:w.showOnDesktop}:w}),...x]}const d=new Set(c.map(f=>f.id));return[...c,...r.filter(f=>!d.has(f.id))]}function vU(e){return typeof e=="object"&&e!==null&&typeof e.preventSleep=="boolean"&&typeof e.networkAvailable=="boolean"}const wU={name:"",source:"auto",hostname:"",fallbackHostname:"",url:"",fallbackUrl:"",onboardingUrl:null,status:"disabled",reason:null,httpsEnabled:!1,caAvailable:!1,lanAddresses:[],interfaces:[]},Tp="__termdockOverlay",Sp="__termdockBaseAnchor",Cp="__termdockBaseGuard",AU=3,Hy=250,TU="termdock-notification-target-v1",Wy="/__termdock-notification-target",Gy=3e4;function SU(e){return e==="left-sidebar"||e==="right-sidebar"||e==="right-sidebar-repo-picker"||e==="right-sidebar-file-preview"||e==="settings"||e==="markdown-outline"||e==="markdown-image-lightbox"}function Bu(e){if(!e||typeof e!="object")return null;const t=e[Tp];return SU(t)?t:null}function ax(e){return e&&typeof e=="object"?{...e}:{}}function M4(e){const t=ax(e);return delete t[Tp],t}function CU(e){const t=M4(e);return delete t[Cp],{...t,[Sp]:!0}}function _U(){typeof window>"u"||window.history.pushState({...M4(window.history.state),[Sp]:!0,[Cp]:!0},"",window.location.href)}function j4(){for(let e=0;e<AU;e+=1)_U()}function ef(){typeof window>"u"||(window.history.replaceState(CU(window.history.state),"",window.location.href),j4())}function u0(e){typeof window>"u"||window.history.pushState({...ax(window.history.state),[Sp]:!0,[Tp]:e,[Cp]:!1},"",window.location.href)}function kU(e){typeof window>"u"||window.history.replaceState({...ax(window.history.state),[Sp]:!0,[Tp]:e,[Cp]:!1},"",window.location.href)}const D4=["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"];let Da=new Set(D4);function Vy(e){const t=new Map;for(const[r,n]of e)t.set(r,{cwd:n.cwd,activeProgram:n.activeProgram,activeProgramRaw:n.activeProgramRaw,inCopyMode:n.inCopyMode,isConnecting:n.isConnecting,agentStatus:n.agentStatus,agentIndicator:n.agentIndicator,agentStatusDetail:n.agentStatusDetail,agent:n.agent,agentMessage:n.agentMessage,agentNativeSessionId:n.agentNativeSessionId,agentResumeRecovered:n.agentResumeRecovered,terminalSessionId:n.terminalSessionId,agentNeedsReview:n.agentNeedsReview,gitStatus:n.gitStatus,shellTitle:n.shellTitle,promptState:n.promptState,tuiProgress:n.tuiProgress});return t}function LU(e,t){if(e.size!==t.size)return!1;for(const[r,n]of t){const a=e.get(r);if(!a||a.cwd!==n.cwd||a.activeProgram!==n.activeProgram||a.activeProgramRaw!==n.activeProgramRaw||a.inCopyMode!==n.inCopyMode||a.isConnecting!==n.isConnecting||a.agentStatus!==n.agentStatus||a.agentIndicator!==n.agentIndicator||a.agentStatusDetail!==n.agentStatusDetail||a.agent!==n.agent||a.agentMessage!==n.agentMessage||a.agentNativeSessionId!==n.agentNativeSessionId||a.agentResumeRecovered!==n.agentResumeRecovered||a.terminalSessionId!==n.terminalSessionId||a.agentNeedsReview!==n.agentNeedsReview||a.gitStatus!==n.gitStatus||a.shellTitle!==n.shellTitle||a.promptState!==n.promptState||a.tuiProgress?.state!==n.tuiProgress?.state||a.tuiProgress?.progress!==n.tuiProgress?.progress)return!1}return!0}function qy(e,t){return s.jsx(SO,{sessionMode:e,state:t})}function IU(e,t){const r=new Map(e.map(l=>[l.id,l])),n=t.map(l=>r.get(l)).filter(l=>l!==void 0),a=new Set(t),c=e.filter(l=>!a.has(l.id));return[...n,...c]}const EU=k.lazy(()=>Zc(()=>import("./CollaborationMainWorkspace-D-TgDrxX.js"),__vite__mapDeps([18,1,2,3,4,5,8,9,15,13])));async function B4(e,t){return pg(e,t)}function NU(){const{t:e,locale:t,setLocale:r}=Ur(),n="env(safe-area-inset-top, 0px)",a="env(safe-area-inset-bottom, 0px)";J9();const c=k.useMemo(()=>typeof window>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,[]),[l,d]=k.useState(!1),[f,m]=k.useState(()=>Dc(Py,mU)??"dark"),x=k.useRef(Dc(o0,vU)).current,[y,w]=k.useState(x?.preventSleep??!1),[v,T]=k.useState(x?.networkAvailable??!0),[S,I]=k.useState(eA),[N,P]=k.useState(tA),[$,Q]=k.useState(rA),[U,Z]=k.useState(nA),[J,H]=k.useState(zp),[ye,oe]=k.useState(x?.localAccess??wU),[te,Ce]=k.useState(x?.localAccess?.name??""),[qe,ve]=k.useState(!1),[Y,st]=k.useState(null),[he,Qe]=k.useState(null),[ie,Pe]=k.useState(null),[Fe,ce]=k.useState(!1),Ie=b.useRef({busy:!1}),je=b.useRef(0),Ze=b.useRef(ie?.latestVersion);Ze.current=ie?.latestVersion;const[we,le]=b.useState(null);b.useEffect(()=>{const C=()=>{je.current++};for(const O of["pagehide","auth:unauthorized",Fu])window.addEventListener(O,C);return()=>{C();for(const O of["pagehide","auth:unauthorized",Fu])window.removeEventListener(O,C)}},[]);const[Ge,He]=k.useState(null),tt=k.useMemo(()=>Gi(),[]),xe=!!(tt?.desktopUpdateState&&tt.checkDesktopUpdate&&tt.installDesktopUpdate),[dt,it]=k.useState(null),[_e,Ue]=k.useState(null),[ke,V]=k.useState(!1),ae=b.useRef({busy:!1}),pe=b.useRef(_e);pe.current=_e;const[$e,Xe]=k.useState(null),[wt,Ut]=k.useState(!1),[qt,Nt]=k.useState(()=>i1(Dc(Oy,gU)??{})),[sr,jt]=k.useState(0),[Xt,Rt]=k.useState(!1),[ir,ge]=k.useState(0),[Je,at]=k.useState(!1),[Et,X]=k.useState(0),[vt,Bt]=k.useState(!1),[Me,Dr]=k.useState(0),Le=k.useRef(null),[At,Ot]=k.useState({}),{terminalSettings:er,updateTerminalSettings:ot}=kQ(),Lt=er.fontSize,nr=er.rendererMode,[ur,Rr]=k.useState(!1),Gr=k.useRef(sA()).current,[Tt,Ft]=b.useState(()=>Gr.sessions.map(C=>({id:C.sessionId,name:C.name,customName:C.customName,mode:C.mode,tmuxSessionName:C.tmuxSessionName}))),be=Bi(C=>C.groupId);k.useEffect(()=>{const C=()=>Bi.getState().terminal();return window.addEventListener("switch-terminal-session",C),()=>window.removeEventListener("switch-terminal-session",C)},[]);const[Ct,gt]=k.useState(Gr.activeSessionId),[rt,cn]=k.useState(!1);k.useEffect(()=>{rt&&iA({rendered:!0})},[rt]);const[Kr,wn]=k.useState(null),[Oe,ft]=k.useState(null),[ht,Cr]=k.useState([]),[Ht,yr]=b.useState(()=>{const C=Hr.getState();return Gr.sessions.forEach(O=>{O.backendSessionId&&C.setTerminalSession(O.sessionId,{sessionId:O.backendSessionId,cols:80,rows:24,mode:O.mode,tmuxSessionName:O.tmuxSessionName}),O.activeProgram!=null&&C.setSessionActiveProgram(O.sessionId,O.activeProgram),O.cwd!=null&&C.setSessionCwd(O.sessionId,O.cwd),O.shellTitle!=null&&C.setSessionShellTitle(O.sessionId,O.shellTitle)}),Wu("session-chrome-hydrated"),Vy(Hr.getState().sessions)});b.useEffect(()=>{!tt||!ur||Promise.all([tt.snapshot(),tt.desktopUpdateState?.()??Promise.resolve(null)]).then(([C,O])=>{it(C),Ue(O)}).catch(C=>Xe(C instanceof Error?C.message:String(C)))},[tt,ur]),b.useEffect(()=>{tt?.onDesktopUpdateState&&tt.onDesktopUpdateState(Ue)},[tt]),b.useEffect(()=>Hr.subscribe(C=>{const O=Vy(C.sessions);yr(fe=>LU(fe,O)?fe:O)}),[]);const Xr=b.useCallback(async(C,O)=>{ft(null),wn({sessionId:C,status:"submitting",error:null});try{await aA(O),wn(fe=>fe?.sessionId===C?{...fe,status:"waiting",error:null}:fe)}catch(fe){const kt=(fe&&typeof fe=="object"&&"code"in fe?String(fe.code??""):"")==="AGENT_SESSION_ACTIVE_ELSEWHERE"?e("tab.resumeAgentConflict"):fe instanceof Error&&/busy/i.test(fe.message)?e("tab.resumeAgentBusy"):e("tab.resumeAgentFailed");wn(Kt=>Kt?.sessionId===C?{...Kt,error:kt}:Kt),ft({tone:"error",message:kt})}},[e]);b.useEffect(()=>{if(!Kr||Kr.status!=="waiting")return;const C=Ht.get(Kr.sessionId);if(!C||C.agentResumeRecovered||C.agentStatus===null&&!C.agent)return;const O=C.agent?.displayName??"Agent";wn(null),ft({tone:"success",message:e("tab.resumeAgentSuccess",{agent:O})})},[Kr,Ht,e]),b.useEffect(()=>{if(!Kr||Kr.status!=="waiting"||Kr.error)return;const C=Kr.sessionId,O=window.setTimeout(()=>{const fe=e("tab.resumeAgentTimeout");wn(nt=>nt?.sessionId===C&&nt.status==="waiting"?{...nt,error:fe}:nt),ft({tone:"error",message:fe})},15e3);return()=>window.clearTimeout(O)},[Kr,e]),b.useEffect(()=>{if(Oe?.tone!=="success")return;const C=window.setTimeout(()=>ft(null),3200);return()=>window.clearTimeout(C)},[Oe]),b.useEffect(()=>{let C=!1;oA().then(fe=>{C||Pe(fe)}).catch(()=>{}),lA().then(fe=>{C||He(fe)}).catch(()=>{});const O=Ox(fe=>{C||(fe.type==="update-state"?Pe(fe.state):fe.type==="server-health"&&He(fe.state))});return()=>{C=!0,O()}},[]);const Bn=b.useCallback(async()=>{try{He(await cA())}catch(C){d1(C instanceof Error?C.message:String(C))}},[]),mn=b.useCallback(async()=>{const C=ie?.latestVersion;if(!C||Fe)return;const O=je.current,fe=mi(),nt=Eo(),kt=()=>O===je.current&&fe===mi()&&nt===Eo()&&!nt?.closed&&Ze.current===C,Kt=tt?.confirmationUI==="page-v1"&&typeof tt.confirm=="function";le(null),await B4(Ie.current,{current:kt,submit:RA,apply:Pe,pending:ce,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again.",confirm:()=>Kt?tt.confirm({title:e("sidebar.updateRestart"),message:e("sidebar.updateRestartConfirm",{version:C}),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}):window.confirm(e("sidebar.updateRestartConfirm",{version:C})),failure:Er=>{Kt?le(Er):window.alert(Er)}})},[ie?.latestVersion,e,Fe,tt,t]),hn=b.useCallback(async()=>{if(!Fe){ce(!0);try{Pe(await uA())}catch(C){d1(C instanceof Error?C.message:String(C))}finally{ce(!1)}}},[Fe]),gn=b.useCallback(async()=>{if(!(!tt?.checkDesktopUpdate||ke)){V(!0);try{Ue(await tt.checkDesktopUpdate())}catch(C){Xe(C instanceof Error?C.message:String(C))}finally{V(!1)}}},[tt,ke]),an=b.useCallback(async()=>{const C=_e;if(!tt?.installDesktopUpdate||ke||C?.status!=="ready")return;const O=je.current,fe=mi(),nt=Eo(),kt=()=>O===je.current&&C===pe.current&&C.status==="ready"&&fe===mi()&&nt===Eo()&&!nt?.closed;await pg(ae.current,{current:kt,confirm:()=>C3({title:e("settings.desktopUpdateRestartConfirm"),message:e("settings.desktopUpdateRestartConfirm"),confirmLabel:e("sidebar.updateRestart"),cancelLabel:e("common.cancel")}),submit:async()=>{if(!kt())throw new Error("Desktop update context changed");return tt.installDesktopUpdate()},apply:Ue,pending:V,failure:Xe,expiredMessage:t==="zh"?"连接已变化,请重新确认。":"Connection changed. Please confirm again."})},[tt,ke,_e,e,t]);b.useEffect(()=>{document.documentElement.dataset.theme=f,dA(f),Yn(Py,f)},[f]),b.useEffect(()=>{Yn(Oy,i1(qt))},[qt]);const ne=Yt(C=>C.leftOpen),Ye=Yt(C=>C.rightOpen),St=Yt(C=>C.leftPinned),Jt=Yt(C=>C.leftSidebarWidth),Or=Yt(C=>C.rightPinned),un=Yt(C=>C.rightSidebarWidth),Jr=Yt(C=>C.rootPath),en=Yt(C=>C.contextKey),mr=Yt(C=>C.selectedFilePath),tn=Yt(C=>C.groupByFolder),Sn=Ef(C=>C.collaborationGroups),Zr=Yt(C=>C.collapsedGroups),Qr=Yt(C=>C.toggleGroupCollapsed),[lr,fn]=b.useState(()=>typeof window>"u"?!0:window.matchMedia("(min-width: 1024px)").matches),[Ss,Ar]=b.useState(()=>typeof window>"u"?1024:window.innerWidth),[En,qr]=b.useState(()=>typeof window>"u"?!1:window.matchMedia("(orientation: landscape)").matches),[Lr,On]=b.useState([]),[tr,K]=b.useState({available:!0,version:null,reason:null}),[De,Mt]=b.useState(!1),[vr,Dt]=b.useState(null),[Br,Pr]=b.useState(null),[xn,Kn]=b.useState(null),[Cs,ws]=b.useState(null),[Wr,Qn]=b.useState(null),[Pn,jr]=b.useState(null),[ds,Tr]=b.useState(null),[,bn]=b.useState(0),[An,rr]=b.useState(null),[kn,Cn]=b.useState(null),[wr,ps]=b.useState(null),[Ks,rs]=b.useState(!1),[on,Hn]=b.useState(()=>Dc(l0,C=>typeof C=="boolean")??!1),Fr=b.useCallback(async C=>{const O=on;Hn(C),Yn(l0,C);try{const fe=await Qa({runningSessionButtonEnabled:C});Hn(fe.runningSessionButtonEnabled),Yn(l0,fe.runningSessionButtonEnabled)}catch{Hn(O),Yn(l0,O)}},[on]),[$r,pn]=b.useState(()=>Dc(c0,C=>typeof C=="boolean")??!0),W=b.useCallback(async C=>{const O=$r;pn(C),Yn(c0,C);try{const fe=await Qa({attentionButtonEnabled:C});pn(fe.attentionButtonEnabled),Yn(c0,fe.attentionButtonEnabled)}catch{pn(O),Yn(c0,O)}},[$r]),[Re,Ke]=b.useState(null),lt=b.useCallback(C=>{Ke(C)},[]),ut=b.useRef(!1),[It,_t]=b.useState(null),Qt=k.useRef(null),xt=b.useCallback(C=>{const O=Tt.find(fe=>fe.id===C);O&&(Qt.current={id:C,target:mi(),client:Eo(),backend:Hr.getState().sessions.get(C)?.terminalSessionId??null,mode:O.mode,tmux:O.tmuxSessionName},_t(C))},[Tt]),Pt=b.useCallback(()=>{const C=Qt.current,O=C&&Tt.find(fe=>fe.id===C.id);return!!C&&!C.client?.closed&&MQ(C,O?{id:O.id,target:mi(),client:Eo(),backend:Hr.getState().sessions.get(O.id)?.terminalSessionId??null,mode:O.mode,tmux:O.tmuxSessionName}:null)},[Tt]),[z,R]=b.useState(null),F=k.useRef(null),q=k.useRef(!1),se=k.useRef(null),Ee=k.useRef(!1),We=b.useCallback(()=>{jr(null),Tr(null)},[]),mt=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("session")),[et,dr]=k.useState(mt.current),[Wn,Gt]=k.useState(!0),zr=k.useRef(mt.current),_r=k.useRef(typeof window>"u"?null:new URLSearchParams(window.location.search).get("_notifTrace"));b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(min-width: 1024px)"),O=()=>{fn(C.matches),Ar(window.innerWidth)};return O(),C.addEventListener("change",O),window.addEventListener("resize",O),()=>{C.removeEventListener("change",O),window.removeEventListener("resize",O)}},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=window.matchMedia("(orientation: landscape)"),O=()=>qr(C.matches);return O(),C.addEventListener("change",O),()=>C.removeEventListener("change",O)},[]);const Xn=k.useMemo(()=>Ct?ht.find(C=>C.sessionIds.includes(Ct))??null:null,[Ct,ht]),ms=Xn?.id??null,dn=Xn?.sessionIds[0]??Ct,pr=k.useRef([]);k.useLayoutEffect(()=>{const C=pr.current;if(pr.current=ht,C.length===0)return;const O=new Set(ht.flatMap(fe=>fe.sessionIds));for(const fe of C){const nt=fe.sessionIds.filter(kt=>!O.has(kt)).map(kt=>({sessionId:kt,rootPath:Hr.getState().sessions.get(kt)?.cwd??null}));nt.length>0&&Yt.getState().inheritRightSidebarStateFromSplitWorkspace(fe.id,nt)}},[ht]),k.useLayoutEffect(()=>((()=>{const O=dn?Hr.getState().sessions.get(dn)?.cwd??null:null;Yt.getState().setRootPath(O,dn,ms)})(),Hr.subscribe((O,fe)=>{const nt=dn?O.sessions.get(dn)?.cwd??null:null,kt=dn?fe.sessions.get(dn)?.cwd??null:null;nt!==kt&&Yt.getState().setRootPath(nt,dn,ms)})),[ms,dn]);const ar=k.useRef(I3(window.location.search)??LC(mi()?.targetPeerId)),[Fn,ls]=k.useState("");k.useEffect(()=>{const C=ar.current;if(!C)return;if(C.peerId&&C.peerId!==mi()?.targetPeerId){const nt=hA().find(kt=>kt.targetPeerId===C.peerId);if(nt&&Xo()){try{kC(C)}catch{ls(t==="zh"?"无法在此浏览器打开架构链接。":"Cannot open this architecture link in this browser.");return}if(fA(nt)){ar.current=null;const kt=new URL(window.location.href);kt.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",kt);return}}ls(t==="zh"?`此架构属于 ${C.serviceName??C.peerId}。请先连接该 Termdock 服务,再打开链接。`:`This architecture belongs to ${C.serviceName??C.peerId}. Connect to that Termdock service, then open this link.`);return}ls("");try{sessionStorage.setItem(`termdock.architecture.selection:${C.root}`,C.file)}catch{}const O=Yt.getState();O.setRootPath(C.root,dn,ms),O.setRightTab("architecture"),O.openRight();const fe=new URL(window.location.href);fe.searchParams.delete("architecture"),window.history.replaceState(window.history.state,"",fe),dn&&(ar.current=null)},[dn,ms,t]);const ya=lr||En,Jn=Ss*.95,Bo=ya?Math.min(Math.max(Ss*.22,280),340):Math.min(Ss*.86,380),Fs=Ct&&Jr?`${Ct}\0${Jr}`:"",Pa=!!(Fs&&mr&&qt[Fs]),li=b.useCallback(C=>{Fs&&(C&&!Yt.getState().selectedFilePath||Nt(O=>{if(!!O[Fs]===C)return O;if(C)return i1({...O,[Fs]:{updatedAt:Date.now()}});const nt={...O};return delete nt[Fs],nt}))},[Fs]);b.useEffect(()=>{DQ(Fs,en,mr)&&Nt(C=>{if(!C[Fs])return C;const O={...C};return delete O[Fs],O})},[Fs,en,mr]);const gs=vt?"markdown-image-lightbox":Je?"markdown-outline":Xt?"right-sidebar-repo-picker":Ye&&Pa?"right-sidebar-file-preview":ur?"settings":Ye&&!(Or&&lr)?"right-sidebar":ne&&!(St&&lr)?"left-sidebar":null,hs=k.useRef(gs),qi=k.useRef(gs),Ls=k.useRef(!1),Xs=k.useRef(!1),Js=b.useCallback(()=>{if(typeof window>"u")return;const C=window.matchMedia("(hover: hover) and (pointer: fine)").matches;!lr||!C||navigator.maxTouchPoints>0||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("focus-active-terminal-session"))},0)},[lr]),Oa=b.useCallback(C=>{if(C==="markdown-image-lightbox"){Bt(!1),Dr(O=>O+1);return}if(C==="markdown-outline"){at(!1),X(O=>O+1);return}if(C==="right-sidebar-file-preview"){at(!1),X(O=>O+1),li(!1),jt(O=>O+1);return}if(C==="right-sidebar-repo-picker"){Rt(!1),ge(O=>O+1);return}if(C==="settings"){Rr(!1),Ga(!1),ta(!1),ue(!1);return}if(C==="left-sidebar"){Yt.getState().closeLeft();return}at(!1),X(O=>O+1),Rt(!1),ge(O=>O+1),Bt(!1),Dr(O=>O+1),Yt.getState().closeRight()},[li]),Nn=b.useCallback(C=>{if(!c&&typeof window<"u"&&hs.current===C&&Bu(window.history.state)===C){window.history.back();return}Oa(C)},[Oa,c]),Fa=b.useCallback(()=>{Rr(!1);const C=Yt.getState();C.closeRight(),C.openLeft()},[]),$a=b.useCallback(()=>{Rr(!1);const C=Yt.getState();C.closeLeft(),C.openRight()},[]),va=b.useCallback(()=>{Rr(!1);const C=Yt.getState();C.closeLeft(),C.openRight(),C.setRightTab("files"),C.openRightSearch()},[]),_s=b.useCallback(()=>{const C=Yt.getState();if(C.leftPinned){C.setLeftPinned(!1),C.closeLeft();return}if(ne){Nn("left-sidebar");return}Fa()},[Fa,Nn,ne]),ci=b.useCallback(()=>{const C=Yt.getState();C.leftPinned?(C.setLeftPinned(!1),C.openLeft()):(C.setLeftPinned(!0),C.openLeft())},[]),ei=b.useCallback(()=>{const C=Yt.getState();C.setLeftPinned(!1),C.closeLeft()},[]),io=b.useCallback(()=>{const C=Yt.getState();C.rightPinned?(C.setRightPinned(!1),C.openRight()):(C.setRightPinned(!0),C.openRight())},[]),$n=b.useCallback(()=>{const C=Yt.getState();C.setRightPinned(!1),C.closeRight()},[]),wa=b.useRef(null),ui=b.useRef(null);b.useEffect(()=>()=>ui.current?.(),[]);const Ua=b.useCallback(C=>{if(C.button!==0||!wa.current)return;C.preventDefault(),ui.current?.();const O=Yt.getState();ui.current=GF(wa.current,C.clientX,O.leftSidebarWidth,fe=>Math.min(Math.max(fe,200),500),fe=>Yt.getState().setLeftSidebarWidth(fe))},[]),js=b.useRef(0),ao=b.useRef(0),za=b.useRef(null),_c=b.useCallback(C=>{C.preventDefault(),js.current=C.clientX;const O=Yt.getState(),fe=O.leftPinned?O.leftSidebarWidth:0;ao.current=rf(O.rightSidebarWidth,window.innerWidth,fe);const nt=Kt=>{za.current===null&&(za.current=requestAnimationFrame(()=>{za.current=null;const Er=js.current-Kt.clientX,Mn=Yt.getState(),Vn=Mn.leftPinned?Mn.leftSidebarWidth:0;Mn.setRightSidebarWidth(rf(ao.current+Er,window.innerWidth,Vn))}))},kt=()=>{window.removeEventListener("mousemove",nt),window.removeEventListener("mouseup",kt),za.current!==null&&(cancelAnimationFrame(za.current),za.current=null),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",nt),window.addEventListener("mouseup",kt)},[]),di=b.useCallback(()=>{const C=Yt.getState();if(C.rightPinned){C.setRightPinned(!1),C.closeRight();return}if(Ye){Nn("right-sidebar");return}$a()},[$a,Nn,Ye]),Vl=b.useCallback(()=>{!Pa&&!c&&typeof window<"u"&&hs.current==="right-sidebar"&&Bu(window.history.state)==="right-sidebar"&&(u0("right-sidebar-file-preview"),qi.current="right-sidebar-file-preview"),li(!0)},[Pa,c,li]),Ci=b.useCallback(()=>{Nn("right-sidebar-file-preview")},[Nn]),oo=b.useCallback(()=>{!Xt&&!c&&typeof window<"u"&&hs.current==="right-sidebar"&&Bu(window.history.state)==="right-sidebar"&&(u0("right-sidebar-repo-picker"),qi.current="right-sidebar-repo-picker"),Rt(!0)},[Xt,c]),$s=b.useCallback(()=>{Nn("right-sidebar-repo-picker")},[Nn]),Aa=b.useCallback(()=>{!Je&&!c&&typeof window<"u"&&hs.current&&Bu(window.history.state)===hs.current&&(u0("markdown-outline"),qi.current="markdown-outline"),at(!0)},[Je,c]),Sl=b.useCallback(()=>{Nn("markdown-outline")},[Nn]),es=b.useCallback(()=>{!c&&typeof window<"u"&&hs.current&&Bu(window.history.state)===hs.current&&(u0("markdown-image-lightbox"),qi.current="markdown-image-lightbox"),Bt(!0)},[c]),ti=b.useCallback(()=>{Nn("markdown-image-lightbox")},[Nn]),Pi=b.useCallback(()=>{!c&&typeof window<"u"&&hs.current&&Bu(window.history.state)===hs.current&&(kU("settings"),qi.current="settings"),Yt.getState().closeAll(),Rr(!0)},[c]),Ta=b.useCallback(()=>{Nn("settings")},[Nn]);b.useEffect(()=>{if(!tt)return;const C=()=>Pi();return window.addEventListener("termdock:open-settings",C),()=>window.removeEventListener("termdock:open-settings",C)},[tt,Pi]);const ql=b.useCallback(()=>{Ut(!0),Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)},[]),Yl=b.useCallback(()=>{Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null),Ut(!1),Xs.current=!0,ef(),Xs.current},[]);b.useEffect(()=>()=>{Le.current!==null&&window.clearTimeout(Le.current)},[]),b.useEffect(()=>{c||ef()},[c]),b.useEffect(()=>{if(typeof window>"u"||c)return;let C=null;const O=()=>{C!==null&&(window.clearTimeout(C),C=null)},fe=Mn=>{if(hs.current,Xs.current,hs.current){hs.current;return}!Mn?.force&&Xs.current||(Mn?.userActivated&&(Xs.current=!0),ef(),Xs.current,void 0)},nt=()=>{O(),C=window.setTimeout(()=>{C=null,fe({force:!0})},Hy)},kt=()=>{fe({userActivated:!0})},Kt=()=>{nt()},Er=()=>{document.visibilityState==="visible"&&nt()};return window.addEventListener("pointerdown",kt,{capture:!0,passive:!0}),window.addEventListener("touchstart",kt,{capture:!0,passive:!0}),window.addEventListener("keydown",kt,{capture:!0}),window.addEventListener("pageshow",Kt),document.addEventListener("visibilitychange",Er),()=>{O(),window.removeEventListener("pointerdown",kt,{capture:!0}),window.removeEventListener("touchstart",kt,{capture:!0}),window.removeEventListener("keydown",kt,{capture:!0}),window.removeEventListener("pageshow",Kt),document.removeEventListener("visibilitychange",Er)}},[c]),b.useEffect(()=>{hs.current=gs},[gs]),b.useEffect(()=>{if(typeof window>"u"||gs||c)return;const C=window.setTimeout(()=>{hs.current?(hs.current,void 0):ef()},Hy);return()=>window.clearTimeout(C)},[gs,c]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=qi.current;Ls.current,gs&&gs!==C&&!Ls.current&&u0(gs),!gs&&C&&Js(),qi.current=gs,!gs&&Ls.current&&window.setTimeout(()=>{Ls.current=!1},0)},[gs,c,Js]),b.useEffect(()=>{if(typeof window>"u"||c)return;const C=()=>{const O=hs.current;if(Xs.current,!O){Xs.current=!1,Xs.current,ql(),j4();return}Ls.current=!0,Oa(O)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[Oa,ql,c]),b.useEffect(()=>{const C=O=>{const fe=O.metaKey||O.ctrlKey;if(fe&&O.key==="b"&&!O.shiftKey&&(O.preventDefault(),_s()),fe&&O.shiftKey&&O.key==="E"&&(O.preventDefault(),di()),fe&&O.shiftKey&&O.key==="P"&&(O.preventDefault(),va()),fe&&!O.shiftKey&&O.altKey&&(O.key==="ArrowLeft"||O.key==="ArrowRight")){O.preventDefault();const nt=O.key==="ArrowRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:nt}}));return}if(fe&&O.shiftKey&&!O.altKey&&(O.code==="BracketLeft"||O.code==="BracketRight")){O.preventDefault();const nt=O.code==="BracketRight"?"next":"prev";window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:nt}}));return}};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[_s,di,va]);const kc=b.useCallback(async()=>{ve(!0),st(null);try{const C=await Qa({localAccess:{name:te}});oe(C.localAccess),Ce(C.localAccess.name),Yn(o0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){st(C instanceof Error?C.message:"Failed to save local access name")}finally{ve(!1)}},[te]),Lc=b.useCallback(async()=>{ve(!0),st(null);try{const C=await Qa({localAccess:{reset:!0}});oe(C.localAccess),Ce(C.localAccess.name),Yn(o0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}catch(C){st(C instanceof Error?C.message:"Failed to reset local access name")}finally{ve(!1)}},[]),Gn=b.useCallback(async(C,O="url")=>{if(C)try{if(typeof navigator<"u"&&navigator.clipboard)await navigator.clipboard.writeText(C);else{const fe=document.createElement("textarea");fe.value=C,fe.style.position="fixed",fe.style.left="-9999px",document.body.appendChild(fe),fe.focus(),fe.select(),document.execCommand("copy"),document.body.removeChild(fe)}Qe(O),window.setTimeout(()=>Qe(fe=>fe===O?null:fe),1600)}catch{Qe(null)}},[]),_i=b.useCallback(C=>{const O=IU(Tt,C);O.map(fe=>fe.id).join("\0")!==Tt.map(fe=>fe.id).join("\0")&&(Ft(O),window.dispatchEvent(new CustomEvent("reorder-terminal-session",{detail:{sessionIds:O.map(fe=>fe.id)}})))},[Tt]),Yi=b.useCallback(C=>{lr||C.type!=="session"||(ut.current=!1,rs(!1),ps(C.draggableId))},[lr]),Ha=b.useCallback(C=>{if(lr||C.type!=="session")return;const O=C.destination?.droppableId===ig;O!==ut.current&&(ut.current=O,rs(O),O&&navigator.vibrate?.(20))},[lr]),Zi=b.useCallback(C=>{const O=fU(C,!lr);if(ut.current=!1,rs(!1),ps(null),!O)return!1;const fe=Tt.find(kt=>kt.id===C.draggableId),nt=fe?Ht.get(fe.id):null;return fe&&pb({mode:fe.mode,activeProgram:nt?.activeProgram??null,promptState:nt?.promptState??null,shellNames:Da})?(R(null),xt(fe.id),Kn(null)):fe&&window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:{sessionId:fe.id,source:"other",closeMode:fe.mode==="tmux"?"destroy":"auto"}})),!0},[lr,Tt,Ht,xt]),{groups:lo,arranged:Us}=k.useMemo(()=>Lf(Tt,C=>Ht.get(C.id)?.cwd??null,tn,e("sidebar.ungrouped"),ht,Sn),[Tt,Ht,tn,e,ht,Sn]),Ki=b.useCallback(C=>{Zi(C)||!C.destination||C.source.index===C.destination.index||window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:Us[C.source.index]?.id,targetId:Us[C.destination.index]?.id}}))},[Zi,Us]),Sa=b.useCallback((C,O)=>{const fe=O.trim();fe&&window.dispatchEvent(new CustomEvent("rename-terminal-session",{detail:{sessionId:C,name:fe}}))},[]),_n=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("reset-terminal-session-name",{detail:{sessionId:C}}))},[]),{newSessionMode:ns,newSessionTmuxName:Ca,userSelectedNewSessionMode:cs,setNewSessionMode:Wa}=EQ(),[ki,co]=b.useState(null),[Li,Ga]=k.useState(!1),[Xi,Ji]=k.useState(!1),[ea,ta]=k.useState(!1),[xs,ra]=k.useState("idle"),Va=k.useRef(Dc(Jh,bU)).current,[Ds,_a]=k.useState(()=>{const C=Va?.presets;if(C&&C.length>0){const O=Hu(C);if(O.length>0)return O}return D0()}),[Cl,Zl]=k.useState(!1),[rl,ka]=k.useState("default"),na=k.useRef(typeof Va?.updatedAt=="number"?Va.updatedAt:null),As=k.useRef(!1),[Qo,ue]=k.useState(!1),[Ve,bt]=k.useState(!1),_=k.useRef(Dc(ja,xU)).current,[M,B]=k.useState(_??[]),[G,Te]=k.useState(_!==null),[Se,Be]=k.useState(!1),ct=!be&&(!gs||gs==="right-sidebar"||gs==="right-sidebar-file-preview"||gs==="left-sidebar")&&!Xi&&!ea&&!Li&&!Qo&&!Ve&&!Pn&&!It&&!ki,yt=ct&&!gs,$t=k.useCallback(C=>{const O=typeof C.version=="number"?C.version:0,fe=yU(Array.isArray(C.presets)?C.presets:[],O);na.current=typeof C.updatedAt=="number"?C.updatedAt:null,_a(nt=>pA(nt,fe)?nt:(As.current=!0,fe)),Yn(Jh,{version:f0,presets:fe,updatedAt:na.current??void 0})},[]);b.useEffect(()=>{const C=O=>{if(O.key!=="Escape"||O.defaultPrevented||O.isComposing||og())return;if(Xi){O.preventDefault(),Ji(!1);return}if(ea){O.preventDefault(),ta(!1);return}if(Li){O.preventDefault(),Ga(!1);return}if(Qo){O.preventDefault(),ue(!1);return}if(Ve){O.preventDefault(),bt(!1);return}if(Pn){O.preventDefault(),We();return}if(An){O.preventDefault(),Qn(null),rr(null);return}if(ur){O.preventDefault(),Ta();return}if(Ye&&!(Or&&lr)){O.preventDefault(),Nn("right-sidebar");return}ne&&!(St&&lr)&&(O.preventDefault(),Nn("left-sidebar"))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[Xi,ea,Li,Qo,Pn,We,ur,Ye,Or,ne,St,lr,Ta,Nn]),b.useEffect(()=>{Te(!0)},[]);const[Ir,ln]=k.useState({genericProgramNames:[],wrapperScriptNames:[],shellNames:D4}),[,rn]=k.useState(!1),ss=k.useCallback(()=>mA().then(C=>{ln(C),Da=new Set(C.shellNames),rn(!0)}).catch(()=>{}),[]);b.useEffect(()=>{ss()},[ss]),b.useEffect(()=>Ox(C=>{if(C.type==="config-updated"){if(C.key==="toolbar-presets"){Fx().then(O=>$t(O)).catch(O=>{console.warn("[toolbar-presets] Failed to refresh after remote update:",O)});return}C.key==="program-detection"&&ss()}}),[$t,ss]),b.useEffect(()=>{let C=!1;return(async()=>{try{const O=await Fx();if(C)return;$t(O)}catch(O){console.warn("[toolbar-presets] Failed to load from server:",O)}finally{C||Zl(!0)}})(),()=>{C=!0}},[$t]),b.useEffect(()=>{if(Cl){if(As.current){As.current=!1;return}Yn(Jh,{version:f0,presets:Ds,updatedAt:na.current??void 0}),gA({version:f0,presets:Ds,baseUpdatedAt:na.current??void 0}).then(C=>{na.current=typeof C.updatedAt=="number"?C.updatedAt:null,Yn(Jh,{version:f0,presets:Ds,updatedAt:na.current??void 0})}).catch(C=>{const O=C instanceof Error&&"current"in C?C.current:null;O&&typeof O=="object"&&$t(O),console.warn("[toolbar-presets] Failed to save to server:",C)})}},[$t,Ds,Cl]),b.useEffect(()=>{Cc().then(C=>{w(O=>O===C.preventSleep?O:C.preventSleep),T(O=>O===C.networkAvailable?O:C.networkAvailable),oe(C.localAccess),Ce(C.localAccess.name),Hn(C.runningSessionButtonEnabled),Yn(l0,C.runningSessionButtonEnabled),pn(C.attentionButtonEnabled),Yn(c0,C.attentionButtonEnabled),Yn(o0,{preventSleep:C.preventSleep,networkAvailable:C.networkAvailable,localAccess:C.localAccess})}).catch(()=>{})},[]),b.useEffect(()=>{if(!S)return;const C=zp();H(C),C!=="granted"&&(I(!1),bh(!1))},[S]),b.useEffect(()=>{if(!S)return;Ld();const C=()=>{document.visibilityState==="visible"&&(Ld(),IA())},O=window.setInterval(()=>{Ld()},360*60*1e3);return document.addEventListener("visibilitychange",C),window.addEventListener("focus",C),()=>{window.clearInterval(O),document.removeEventListener("visibilitychange",C),window.removeEventListener("focus",C)}},[S]);const Oi=b.useCallback(async()=>{if(S){I(!1),bh(!1),xA(),H(zp());return}const C=await bA();if(H(C),C!=="granted"){I(!1),bh(!1);return}I(!0),bh(!0),await Ld(!0,!0),ra("idle")},[S]),Vr=b.useCallback(async()=>{ra("checking"),await Gi()?.prepareNotificationTest?.();const C=await yA({title:"Termdock",body:e("settings.notificationsTestBody"),tag:"termdock-notification-test",requireHidden:!1,data:{url:"/"}});ra(C?"delivered":"failed")},[e]),yn=b.useCallback(C=>{P(C),vA(C),Hp()},[]),Bs=b.useCallback(C=>{Q(C),wA(C),Hp()},[]),Kl=b.useCallback(C=>{Z(C),AA(C),Hp()},[]);b.useEffect(()=>{Ds.some(C=>C.id===rl)||ka(Ds[0]?.id??"default")},[rl,Ds]),b.useEffect(()=>{if(!tr.available&&ns==="tmux"){Wa("shell",{userInitiated:!1});return}tr.available&&cs!=="shell"&&ns!=="tmux"&&Wa("tmux",{userInitiated:!1})},[ns,tr.available,cs,Wa]),b.useEffect(()=>{co(null)},[ur,ns,tr.available]),b.useEffect(()=>{const C={};typeof navigator<"u"&&(C.userAgent=navigator.userAgent,C.platform=navigator.platform,C.maxTouchPoints=navigator.maxTouchPoints,C.hasTouch=navigator.maxTouchPoints>0||"ontouchstart"in window,C.vendor=navigator.vendor),typeof window<"u"&&(C.screenWidth=window.innerWidth,C.screenHeight=window.innerHeight,C.pixelRatio=window.devicePixelRatio,C.orientation=window.screen?.orientation?.type||"unknown",C.hasVisualViewport=!!window.visualViewport,C.visualViewportHeight=window.visualViewport?.height,C.visualViewportWidth=window.visualViewport?.width,C.location=window.location.href),C.timestamp=new Date().toISOString(),C.isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,C.isAndroid=/Android/.test(navigator.userAgent),Ot(C)},[]);const md=b.useCallback(C=>{if(Zi(C)||!C.destination)return;if(C.type==="group"){if(C.source.index===C.destination.index)return;_i(S3(lo,C.source.index,C.destination.index));return}if(C.source.droppableId!==C.destination.droppableId||C.source.index===C.destination.index)return;const O=C.source.droppableId.replace(/^group-sessions:/,""),fe=lo.find(nt=>nt.key===O);fe&&window.dispatchEvent(new CustomEvent("reorder-navigation-session",{detail:{sourceId:fe.sessions[C.source.index]?.id,targetId:fe.sessions[C.destination.index]?.id}}))},[lo,_i,Zi]),Rn=k.useMemo(()=>Us.flatMap(C=>{const O=Ht.get(C.id);if(O?.agentStatus!=="working")return[];const{primary:fe,secondary:nt}=xl(C,O?.activeProgram??null,O?.cwd??null,Da,O?.shellTitle??null,O?.promptState??null);return[{id:C.id,label:fe,detail:nt}]}),[Us,Ht]),Po=Ct?Us.findIndex(C=>C.id===Ct):-1,Oo=Us.length>0&&Po>=0?`${Po+1}/${Us.length}`:`${Us.length}`,hi=k.useMemo(()=>{let C=0;for(const O of Tt){const fe=Ht.get(O.id);(fe?.agentStatus==="waiting"||fe?.agentNeedsReview)&&(C+=1)}return{running:Rn.length,review:C}},[Rn.length,Tt,Ht]),gd=k.useMemo(()=>Us.flatMap(C=>{const O=Ht.get(C.id);if(O?.agentStatus!=="waiting"&&!O?.agentNeedsReview)return[];const{primary:fe}=xl(C,O.activeProgram,O.cwd,Da,O.shellTitle,O.promptState);return[{id:O.terminalSessionId??C.id,label:fe,waiting:O.agentStatus==="waiting"}]}),[Us,Ht]);TA(hi.running,hi.review,gd);const La=Ct?Tt.find(C=>C.id===Ct)??null:null,Fo=La?Ht.get(La.id):void 0,_p=!!(La&&Fo?.agentResumeRecovered&&Fo.agentNativeSessionId&&Fo.terminalSessionId),qa=La&&Kr?.sessionId===La.id?Kr:null;k.useLayoutEffect(()=>{if(!Wn)return;const C=se.current;if(!C)return;const O=!Ee.current;C.scrollIntoView({inline:"nearest",block:"nearest",behavior:O?"auto":"smooth"}),Ee.current=!0,O&&Wu("active-tab-positioned")},[Ct,Wn]),b.useEffect(()=>{Wr&&F.current&&(F.current.scrollIntoView({block:"nearest",inline:"nearest"}),F.current.focus(),F.current.select()),Wr||(q.current=!1)},[Wr]);const th=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:C}))},[]),xd=b.useCallback((C,O)=>{Tr(O??null),jr(C)},[]),kp=ex(),uo=b.useCallback(C=>{if(!C)return;dr(C),_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-focus-request",{traceId:_r.current,requestedSessionId:C,activeSessionId:Ct,sessions:Tt.map(fe=>({id:fe.id,terminalSessionId:Ht.get(fe.id)?.terminalSessionId??null}))}),SA(C);const O=Tt.find(fe=>fe.id===C||Ht.get(fe.id)?.terminalSessionId===C);O?(zr.current=null,_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-focus-dispatch",{traceId:_r.current,requestedSessionId:C,targetSessionId:O.id}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O.id}))):(zr.current=C,_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-focus-pending",{traceId:_r.current,requestedSessionId:C}))},[Ct,Tt,Ht]);b.useEffect(()=>{if(typeof window>"u"||typeof caches>"u")return;let C=!1;const O=async()=>{if(window.parent!==window&&Xo()){Gt(!0);return}try{const nt=await caches.open(TU),kt=await nt.match(Wy);if(!kt)return;await nt.delete(Wy);const Kt=await kt.json();if(C)return;const Er=typeof Kt.sessionId=="string"?Kt.sessionId:null,Mn=typeof Kt.traceId=="string"?Kt.traceId:null,Vn=typeof Kt.clickedAt=="number"?Kt.clickedAt:0,Un=Date.now()-Vn;Ba("info","PWA_NOTIFICATION_CLICK app-cache-consumed",{traceId:Mn,sessionId:Er,ageMs:Un,valid:!!(Er&&Un>=0&&Un<=Gy),visibilityState:document.visibilityState}),Er&&Un>=0&&Un<=Gy&&(_r.current=Mn,typeof Kt.targetPeerId=="string"&&Kt.targetPeerId!==mi()?.targetPeerId?Xo()?.focusSession(Kt.targetPeerId,Er):uo(Er))}catch(nt){Ba("warn","PWA_NOTIFICATION_CLICK app-cache-failed",{error:nt instanceof Error?nt.message:String(nt)})}finally{C||Gt(!0)}},fe=()=>{document.visibilityState==="visible"&&O()};return O(),document.addEventListener("visibilitychange",fe),window.addEventListener("pageshow",O),()=>{C=!0,document.removeEventListener("visibilitychange",fe),window.removeEventListener("pageshow",O)}},[uo]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search),O=C.get("session");if(!O)return;Ba("info","PWA_NOTIFICATION_CLICK app-url-received",{traceId:_r.current,targetSessionId:O,href:window.location.href,visibilityState:document.visibilityState});const fe=C.get("service");fe&&fe!==mi()?.targetPeerId?Xo()?.focusSession(fe,O):zr.current=O,C.delete("service"),C.delete("session"),C.delete("_notifTrace");const nt=C.toString(),kt=`${window.location.pathname}${nt?`?${nt}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",kt)},[]),b.useEffect(()=>{if(typeof window>"u")return;const C=new URLSearchParams(window.location.search);if(C.get("_notif")!=="1")return;const O=C.get("session");C.delete("_notif");const fe=C.toString(),nt=`${window.location.pathname}${fe?`?${fe}`:""}${window.location.hash}`;if(window.history.replaceState(window.history.state,"",nt),window.parent!==window&&Xo())return;const kt=new BroadcastChannel("termdock:notif");let Kt=!1;const Er=Vn=>{Vn.data?.type==="termdock:notif-pong"&&!Kt&&(Kt=!0,kt.close(),window.close())};kt.addEventListener("message",Er),kt.postMessage({type:"termdock:notif-ping",sessionId:O,targetPeerId:C.get("service")});const Mn=setTimeout(()=>{Kt||kt.close()},500);return()=>{clearTimeout(Mn),Kt||kt.close()}},[]),b.useEffect(()=>{if(typeof window>"u"||window.parent!==window&&Xo())return;const C=new BroadcastChannel("termdock:notif"),O=fe=>{fe.data?.type==="termdock:notif-ping"&&(C.postMessage({type:"termdock:notif-pong"}),typeof fe.data.sessionId=="string"&&(typeof fe.data.targetPeerId=="string"&&fe.data.targetPeerId!==mi()?.targetPeerId?Xo()?.focusSession(fe.data.targetPeerId,fe.data.sessionId):uo(fe.data.sessionId)))};return C.addEventListener("message",O),()=>C.close()},[uo]),b.useEffect(()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))return;const C=O=>{const fe=O.data;if(fe&&fe.type==="termdock:focus-session"&&typeof fe.sessionId=="string"){if(typeof fe.targetPeerId=="string"&&fe.targetPeerId!==mi()?.targetPeerId){Xo()?.focusSession(fe.targetPeerId,fe.sessionId)&&O.ports[0]?.postMessage({type:"termdock:focus-session-ack"});return}O.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),uo(fe.sessionId)}else fe?.type==="termdock:push-subscription-changed"?Ld(!0):fe?.type};return navigator.serviceWorker.addEventListener("message",C),()=>navigator.serviceWorker.removeEventListener("message",C)},[uo]),b.useEffect(()=>{const C=O=>{const fe=O.detail;typeof fe=="string"&&uo(fe)};return window.addEventListener("termdock:focus-session",C),()=>window.removeEventListener("termdock:focus-session",C)},[uo]),b.useEffect(()=>{const C=()=>{const O=EA(mi()?.targetPeerId);O&&uo(O)};return C(),window.addEventListener("termdock:workspace-session",C),()=>window.removeEventListener("termdock:workspace-session",C)},[uo]),b.useEffect(()=>{const C=zr.current;if(!C)return;const O=Tt.find(fe=>fe.id===C||Ht.get(fe.id)?.terminalSessionId===C);O?(zr.current=null,_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-pending-dispatch",{traceId:_r.current,requestedSessionId:C,targetSessionId:O.id,activeSessionId:Ct}),window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O.id}))):_r.current&&Ba("info","PWA_NOTIFICATION_CLICK app-pending-unmatched",{traceId:_r.current,requestedSessionId:C,activeSessionId:Ct,sessions:Tt.map(fe=>({id:fe.id,terminalSessionId:Ht.get(fe.id)?.terminalSessionId??null}))})},[Ct,Tt,Ht]);const sa=k.useMemo(()=>{const C=[];for(const O of Tt){const fe=Ht.get(O.id);(fe?.agentStatus==="waiting"||fe?.agentNeedsReview)&&C.push(O.id)}return C},[Tt,Ht]),_l=b.useCallback(()=>{if(sa.length===0)return;Ct&&Hr.getState().clearAgentNeedsReview(Ct);const C=Ct?Tt.findIndex(fe=>fe.id===Ct):-1,O=sa.find(fe=>Tt.findIndex(nt=>nt.id===fe)>C)??sa[0];O&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O}))},[sa,Tt,Ct]),Ic=b.useCallback(()=>{if(sa.length===0)return;Ct&&Hr.getState().clearAgentNeedsReview(Ct);const C=Ct?Tt.findIndex(fe=>fe.id===Ct):Tt.length,O=[...sa].reverse().find(fe=>Tt.findIndex(nt=>nt.id===fe)<C)??sa[sa.length-1];O&&window.dispatchEvent(new CustomEvent("switch-terminal-session",{detail:O}))},[sa,Tt,Ct]);b.useEffect(()=>{const C=O=>{!O.altKey||!O.shiftKey||O.metaKey||O.ctrlKey||O.key!=="ArrowUp"&&O.key!=="ArrowDown"||(O.preventDefault(),O.key==="ArrowUp"?Ic():_l())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[_l,Ic]);const hu=b.useCallback(async C=>{const fe=Hr.getState().sessions.get(C)?.cwd;if(fe)try{await navigator.clipboard?.writeText(fe),Cn(fe),window.setTimeout(()=>{Cn(nt=>nt===fe?null:nt)},1400)}catch{}},[]),Lp=b.useCallback(C=>{Ft(C.sessions),gt(C.activeSessionId),Cr(C.splitWorkspaces),Hr.getState().setActiveSessionId(C.activeSessionId)},[]),bd=b.useCallback(()=>{cn(!0)},[]),rh=b.useCallback(()=>{cn(!0),window.requestAnimationFrame(()=>{window.dispatchEvent(new Event("termdock:initial-viewport-presented"))})},[]);b.useEffect(()=>{if(!et||!Ct)return;Tt.find(O=>O.id===et||Ht.get(O.id)?.terminalSessionId===et)?.id===Ct&&dr(null)},[Ct,et,Tt,Ht]);const yd=b.useRef(!1),[fu,nh]=b.useState(!1),ho=b.useCallback(C=>{const O=!C?.onResult;if(O&&yd.current)return;O&&(yd.current=!0,nh(!0));const fe=C?.mode??ns,nt=fe==="tmux"&&(C?.tmuxSessionName?.trim()||Ca.trim())||void 0,kt=C?.cwd||(Ct?Hr.getState().sessions.get(Ct)?.cwd:void 0);window.dispatchEvent(new CustomEvent("new-terminal-session",{detail:{mode:fe,tmuxSessionName:nt,cwd:kt,command:C?.command,shouldActivate:C?.shouldActivate,onResult:C?.onResult??(Kt=>{yd.current=!1,nh(!1),Kt.ok||ft({tone:"error",message:e(h1(Kt.error))})})}}))},[ns,Ca,Ct,e]),kl=b.useCallback(async()=>{Mt(!0);try{const C=await a1();if(K(C),!C.available){On([]);return}const O=await o1();On(O)}catch{K({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),On([])}finally{Mt(!1)}},[]),pu=b.useCallback(async C=>{const{cleanedSessions:O}=await e3(C);for(const fe of O)window.dispatchEvent(new CustomEvent("close-terminal-session-by-backend",{detail:fe}));await kl()},[kl]),sh=b.useCallback(async C=>{Pr(C),Kn(null);try{await pu(C),Dt(null)}catch(O){Kn(O instanceof Error?O.message:"Failed to kill tmux session")}finally{Pr(null)}},[pu]);b.useEffect(()=>{if(!Cs)return;if(Lr.find(fe=>fe.name===Cs&&(fe.connected||fe.boundFrontendSessionId))){ws(null);return}const O=setTimeout(()=>ws(null),1e4);return()=>clearTimeout(O)},[Cs,Lr]);const nl=b.useCallback(C=>{window.dispatchEvent(new CustomEvent("close-terminal-session",{detail:C}))},[]),Ec=b.useCallback(C=>{const O=C??Ct;O&&window.dispatchEvent(new CustomEvent("open-terminal-split-chooser",{detail:O}))},[Ct]),vd=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("set-terminal-split-direction",{detail:{sessionId:C,layout:O}}))},[]),sl=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("reorder-terminal-split-workspace",{detail:{workspaceId:C,sessionIds:O}}))},[]),wd=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("rename-terminal-split-workspace",{detail:{workspaceId:C,name:O}}))},[]),mu=b.useCallback((C,O)=>{window.dispatchEvent(new CustomEvent("combine-terminal-split-sessions",{detail:{primaryId:C,secondaryId:O}}))},[]),Xl=b.useCallback((C,O,fe)=>{const nt=Tt.find(Kt=>Kt.id===C);if(!nt)return;const kt=Ht.get(C);if(fe?.skipConfirmation||!pb({mode:nt.mode,activeProgram:kt?.activeProgram??null,promptState:kt?.promptState??null,shellNames:Da})){nl({sessionId:C,source:"sidebar",closeMode:nt.mode==="tmux"?"destroy":"auto"});return}R(O?{x:O.clientX,y:O.clientY}:null),xt(C),Kn(null)},[Tt,Ht,nl,xt]);b.useEffect(()=>{if(!tt)return;const C=O=>{const fe=O.detail;fe==="new-session"?ho():fe==="close-session"?Ct&&!It&&Xl(Ct):fe==="previous-session"||fe==="next-session"?window.dispatchEvent(new CustomEvent("cycle-terminal-session",{detail:{direction:fe==="next-session"?"next":"prev"}})):fe==="toggle-left-sidebar"?_s():fe==="toggle-right-sidebar"?di():fe==="previous-attention"?Ic():fe==="next-attention"&&_l()};return window.addEventListener("termdock:native-command",C),()=>window.removeEventListener("termdock:native-command",C)},[Ct,It,tt,ho,Xl,_s,di,_l,Ic]);const $o=k.useMemo(()=>Tt.find(C=>C.id===It)??null,[Tt,It]),Ad=b.useCallback(()=>{if(!$o||!Pt()){_t(null),R(null);return}nl({sessionId:$o.id,source:"sidebar",closeMode:"destroy"}),_t(null),R(null)},[$o,nl,Pt]),ih=k.useRef(null),gu=b.useCallback(()=>{_t(null),R(null),Kn(null)},[]);k.useLayoutEffect(()=>{if(!It)return;const C=()=>{Pt()||gu()},O=()=>gu();C();const fe=Hr.subscribe(C);return window.addEventListener(Fu,C),window.addEventListener("auth:unauthorized",O),()=>{fe(),window.removeEventListener(Fu,C),window.removeEventListener("auth:unauthorized",O)}},[It,Ht,Pt,gu]);const Ip=k.useMemo(()=>{if(!$o)return"";const C=Ht.get($o.id);return xl($o,C?.activeProgram??null,C?.cwd??null,Da,C?.shellTitle??null,C?.promptState??null).primary},[$o,Ht]);b.useEffect(()=>{if(!ur)return;let C=!1,O=!1;const fe=async()=>{if(!O)try{const kt=await a1();if(C||K(kt),!kt.available){C||On([]);return}const Kt=await o1();C||On(Kt)}catch{O=!0,C||(K({available:!1,version:null,reason:"tmux integration is unavailable with the current server build."}),On([]))}};fe();const nt=setInterval(()=>{fe()},4e3);return()=>{C=!0,clearInterval(nt)}},[ur]);const ah=ki??ns,xu=ah==="shell",Ia=ah==="tmux"&&tr.available,Uo=k.useMemo(()=>T3(Lr.map(C=>({...C,id:C.name})),C=>C.cwd??null,e("sidebar.ungrouped")),[Lr,e]),Jl=k.useMemo(()=>Lr.filter(C=>C.recoveryCandidate===!0&&!C.connected&&!C.boundFrontendSessionId).sort((C,O)=>(O.lastActiveAt??O.createdAt??0)-(C.lastActiveAt??C.createdAt??0)),[Lr]);b.useEffect(()=>{!ne&&!(St&&lr)||kl()},[ne,St,lr,Tt.length,kl]);const Ll=(C,O,fe,nt=!1)=>{const kt=C.id===Ct,Kt=C.id===Wr,Er=Ht.get(C.id),{primary:Mn,secondary:Vn}=xl(C,Er?.activeProgram??null,Er?.cwd??null,Da,Er?.shellTitle??null,Er?.promptState??null),Un=ld(Er?.cwd??null),Fi=O?Vn??(Un&&Un!==Mn?Un:null):null,Ln=Er?.gitStatus,ia=`${Er?.cwd||C.name}${Ln?`
187
187
  ⎇ ${Ln.branch} +${Ln.added} −${Ln.removed}`:""}`,zo=!!(Er?.tuiProgress&&Er.tuiProgress.state!=="remove"),Ho=Er?.agentStatus==="working"||zo?"var(--success)":Er?.agentStatus==="waiting"||Er?.agentNeedsReview?"var(--warning)":Er?.inCopyMode?"var(--tmux)":null;if(Kt&&lr&&!An){const Ya=C.customName?C.name:Mn,$i=(mo,Ep)=>{const Cd=Ep.trim();Cd?Cd!==Ya&&Sa(mo,Cd):_n(mo),Qn(null)};return s.jsx("input",{ref:mo=>{F.current=mo},type:"text",defaultValue:Ya,className:"h-8 shrink-0 rounded-md bg-surface-elevated px-2 text-[12px] leading-none text-foreground outline-none ring-1 ring-primary/50 sm:h-8 min-w-[5rem]",style:{width:`${Math.max(Ya.length,5)}ch`},onKeyDown:mo=>{mo.key==="Enter"?$i(C.id,mo.target.value):mo.key==="Escape"&&Qn(null)},onBlur:mo=>$i(C.id,mo.target.value)})}return s.jsx("div",{ref:kt?se:null,onContextMenu:Ya=>{Ya.preventDefault(),Tr({x:Ya.clientX,y:Ya.clientY}),jr(C.id)},...kp(()=>xd(C.id)),className:nt?`group relative inline-flex h-5 shrink-0 items-center rounded-sm text-[11px] leading-none transition ${kt?"bg-surface-elevated text-foreground shadow-sm":"text-muted-foreground hover:bg-surface-elevated/40 hover:text-foreground"}`:`group relative inline-flex h-8 shrink-0 items-center rounded-md text-[12px] leading-none transition sm:h-8 ${kt?"bg-surface-elevated text-foreground shadow-sm":"text-muted-foreground hover:bg-surface-elevated/50 hover:text-foreground"}`,style:!nt&&kt&&Ho?{boxShadow:`inset 2px 0 0 0 ${Ho}`}:!nt&&kt?{boxShadow:"inset 2px 0 0 0 rgb(var(--primary-rgb, 99 102 241))"}:void 0,title:ia,children:s.jsx("button",{type:"button",...fe??{},onClick:()=>th(C.id),className:`inline-flex min-w-0 flex-1 items-center gap-1 overflow-hidden text-left ${nt?"px-1":"py-1 pl-1 pr-1.5 sm:pl-1.5 sm:pr-2"} ${fe?"cursor-grab active:cursor-grabbing":""}`,title:ia,children:s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1 overflow-hidden",children:[s.jsxs("span",{className:"inline-flex shrink-0 items-center",children:[qy(C.mode,Er),Er?.agentResumeRecovered&&s.jsx(qc,{size:nt?9:10,className:"-ml-0.5 shrink-0 text-[color:var(--warning)]","aria-label":e("tab.resumeAgentAvailable")}),zo&&!Er?.agentStatus&&s.jsx(Dn,{size:nt?9:10,className:"-ml-0.5 shrink-0 animate-spin text-[color:var(--success)]"})]}),Fi?s.jsxs("span",{className:"flex min-w-0 flex-col justify-center leading-[0.82rem] sm:leading-[0.85rem]",children:[s.jsx("span",{className:`whitespace-nowrap text-[11px] sm:text-[12px] ${Er?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:Mn}),s.jsx("span",{className:"truncate text-[9px] text-muted-foreground/80 sm:text-[9.5px]",children:Fi})]}):s.jsx("span",{className:`whitespace-nowrap text-[11px] sm:text-[12px] ${Er?.inCopyMode?"text-[color:var(--tmux)]":""}`,children:Mn})]})})})},fo=()=>s.jsx(Fl,{droppableId:ig,type:"session",isDropDisabled:lr,children:(C,O)=>{const fe=Ks||O.isDraggingOver;return s.jsxs("div",{ref:C.innerRef,...C.droppableProps,className:"pointer-events-none fixed left-1/2 top-[42%] z-toast flex h-32 w-32 -translate-x-1/2 -translate-y-1/2 items-center justify-center",role:"status","aria-live":"polite","aria-hidden":!wr,"data-mobile-session-destroy-target":"","data-active":fe?"true":"false",children:[s.jsxs("div",{className:`flex h-28 w-28 flex-col items-center justify-center gap-2 rounded-full border bg-surface-elevated/95 shadow-2xl backdrop-blur transition duration-200 ${wr?fe?"scale-110 border-destructive bg-destructive text-destructive-foreground opacity-100":"scale-100 border-destructive/50 text-destructive opacity-100":"scale-75 border-transparent opacity-0"}`,children:[s.jsx(Ms,{size:28,strokeWidth:1.8}),s.jsx("span",{className:"px-2 text-center text-[11px] font-semibold leading-tight",children:e(fe?"tab.releaseToClose":"tab.dragToClose")})]}),C.placeholder]})}}),ri=St&&lr,Nc=Or&&lr,po=rf(un,Ss,ri?Jt:0),il=Nc?po+Jy:0,Il=ri?Tt.find(C=>C.id===Ct):null,Qs=Il?Ht.get(Il.id):void 0,oh=Il?xl(Il,Qs?.activeProgram??null,Qs?.cwd??null,Da,Qs?.shellTitle??null,Qs?.promptState??null).primary:"",Td=lr?Xn:null,lh=ri&&!Td&&Qs?Qs.agentStatus==="working"?"bg-gradient-to-r from-[rgb(var(--success-rgb)_/_0.08)] to-transparent":Qs.agentStatus==="waiting"?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.14)] to-transparent":Qs.agentNeedsReview?"bg-gradient-to-r from-[rgb(var(--warning-rgb)_/_0.08)] to-transparent":Qs.inCopyMode?"bg-gradient-to-r from-[rgb(var(--tmux-rgb)_/_0.07)] to-transparent":"":"",Sd=s.jsxs("div",{className:"w-full h-full flex flex-col app-chrome-bg text-foreground",children:[we&&s.jsxs("div",{role:"alert","data-update-restart-error":!0,className:"fixed right-3 top-3 z-toast flex max-w-md items-start gap-3 rounded-xl border border-border bg-surface p-3 text-sm text-foreground shadow-xl",children:[s.jsx("p",{className:"break-words",children:we}),s.jsx("button",{type:"button",className:"shrink-0 text-primary","aria-label":e("common.close"),onClick:()=>le(null),children:e("common.close")})]}),Fn&&s.jsxs("div",{role:"alert",className:"flex shrink-0 items-center gap-2 bg-surface-2 px-3 py-2 text-xs",children:[s.jsx("p",{className:"min-w-0 flex-1 break-words",children:Fn}),s.jsx("button",{type:"button",className:"min-h-11 px-2 text-primary",onClick:()=>ls(""),children:e("common.close")})]}),s.jsx("main",{className:"relative min-h-0 flex-1 overflow-visible px-0 pb-0 pt-0",children:s.jsxs(EC,{rightInset:il,workspace:be&&s.jsx(k.Suspense,{fallback:s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-[var(--chrome-bg)] text-sm text-muted-foreground",children:"正在打开协作工作区…"}),children:s.jsx(EU,{groupId:be,activeSessionId:Ct,defaultSessionMode:ns,onOpenSidebar:_s,leftSidebarVisible:ne||ri,onToggleRightSidebar:di,rightSidebarOpen:Ye||Nc},be)}),children:[s.jsxs("div",{"data-termdock-window-header":"true",className:`${lr?"absolute inset-x-0 top-0 z-20":"relative"} shrink-0 items-center gap-1 app-chrome-bg px-1 sm:px-1.5 transition-colors duration-500 ${ri?"flex justify-end":"flex justify-between"} ${tn?"h-10 sm:h-10":"h-9 sm:h-10"} ${lh}`,style:{position:lr?"absolute":void 0,marginRight:il||void 0,display:Td?"none":void 0},children:[!ri&&s.jsxs("button",{type:"button",onClick:_s,className:"relative inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-surface-elevated hover:text-foreground sm:h-8 sm:w-8","aria-label":e("tab.sessionsTitle"),title:`${e("tab.sessionsTitle")} · ${e("agent.aiRunning")}: ${hi.running} · ${e("agent.needsReview")}: ${hi.review}`,children:[s.jsx(gS,{size:14}),s.jsx(_O,{runningCount:hi.running,reviewCount:hi.review,className:"sm:hidden"})]}),ri?s.jsx("div",{className:"absolute left-1/2 flex max-w-[40%] min-w-0 -translate-x-1/2 items-center justify-center gap-1.5 overflow-hidden",children:Il?s.jsxs(s.Fragment,{children:[qy(Il.mode,Qs),s.jsx("span",{className:`truncate text-[12px] font-medium ${Qs?.inCopyMode?"text-[color:var(--tmux)]":"text-foreground"}`,children:oh}),Qs?.agentStatus==="working"&&s.jsx("span",{title:Qs?.agentMessage??void 0,children:s.jsx(Dn,{size:12,className:"shrink-0 animate-spin text-[color:var(--success)]"})}),Qs?.agentStatus==="waiting"&&s.jsx("span",{title:Qs?.agentMessage??void 0,children:s.jsx(_f,{size:12,className:"shrink-0 animate-bounce-y text-[color:var(--warning)]"})}),!Qs?.agentStatus&&Qs?.agentNeedsReview&&s.jsx("span",{title:Qs?.agentMessage??void 0,children:s.jsx(wc,{size:13,className:"shrink-0 animate-pulse text-[color:var(--warning)]"})})]}):s.jsx("span",{className:"truncate px-2 text-[12px] text-muted-foreground",children:e("sidebar.sessions")})}):tn?s.jsxs(Gu,{onDragStart:Yi,onDragUpdate:Ha,onDragEnd:md,children:[fo(),s.jsx(Fl,{droppableId:"groups",type:"group",direction:"horizontal",children:C=>s.jsxs("div",{ref:C.innerRef,...C.droppableProps,className:"scrollbar-hidden flex h-full min-w-0 flex-1 items-center gap-1 overflow-x-auto overflow-y-hidden whitespace-nowrap px-0.5 py-0.5",style:{touchAction:"pan-x"},children:[lo.map((O,fe)=>{let nt=0,kt=0;for(const Vn of O.sessions){const Un=Ht.get(Vn.id);Un?.agentStatus==="working"&&(nt+=1),(Un?.agentStatus==="waiting"||Un?.agentNeedsReview)&&(kt+=1)}const Kt=O.sessions.some(Vn=>Vn.id===Ct),Er=Zr.has(O.key),Mn=O.key==="";return s.jsx(Ol,{draggableId:`group-${O.key||"__ungrouped__"}`,index:fe,isDragDisabled:Mn,disableInteractiveElementBlocking:!0,children:(Vn,Un)=>s.jsxs("div",{ref:Vn.innerRef,...Vn.draggableProps,className:`flex w-fit shrink-0 flex-col justify-center gap-px rounded-md py-0.5 px-1 ring-1 transition-colors ${Un.isDragging?"bg-surface-elevated ring-primary/30 shadow-lg opacity-90":Kt?"bg-primary/[0.06] ring-primary/20":"bg-surface-2/40 ring-border/10"}`,children:[s.jsxs("button",{type:"button",...Mn?{}:Vn.dragHandleProps,onClick:()=>Qr(O.key),className:`flex ${Er?"":O.sessions.length>1?"w-0 min-w-full":""} items-center gap-0.5 rounded text-[9px] font-semibold uppercase tracking-[0.08em] leading-none transition hover:bg-surface-elevated/40 ${Mn?"":"cursor-grab active:cursor-grabbing"} ${Kt?"text-primary/80":"text-muted-foreground/55"}`,title:O.key||O.label,children:[s.jsx(qs,{size:9,className:`shrink-0 opacity-70 transition-transform ${Er?"":"rotate-90"}`}),s.jsx("span",{className:"min-w-0 truncate",children:O.label}),nt>0&&s.jsx("span",{className:"ml-auto h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--success)]"}),kt>0&&s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--warning)] ${nt>0?"":"ml-auto"}`})]}),Er?s.jsx("span",{className:"flex h-5 items-center text-[10px] leading-none text-muted-foreground/50",children:e("tab.sessionCount",{count:O.sessions.length})}):s.jsx(Fl,{droppableId:`group-sessions:${O.key}`,type:"session",direction:"horizontal",children:Fi=>s.jsxs("div",{ref:Fi.innerRef,...Fi.droppableProps,className:"flex items-center gap-px",children:[O.sessions.map((Ln,ia)=>s.jsx(Ol,{draggableId:Ln.id,index:ia,disableInteractiveElementBlocking:!0,children:(zo,Ho)=>s.jsx("div",{ref:zo.innerRef,...zo.draggableProps,className:`flex shrink-0 items-center ${Ho.isDragging?"opacity-70":""}`,children:Ll(Ln,!1,zo.dragHandleProps,!0)})},Ln.id)),Fi.placeholder]})})]})},O.key||"__ungrouped__")}),C.placeholder,s.jsx("button",{type:"button",onClick:()=>ho(),disabled:fu,"aria-busy":fu,className:"my-auto inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":e("tab.new"),title:e("tab.new"),children:s.jsx(Ys,{size:14})})]})})]}):s.jsxs(Gu,{onDragStart:Yi,onDragUpdate:Ha,onDragEnd:Ki,children:[fo(),s.jsx(Fl,{droppableId:"tabs",type:"session",direction:"horizontal",children:C=>s.jsxs("div",{ref:C.innerRef,...C.droppableProps,className:"scrollbar-hidden flex h-full min-w-0 flex-1 items-center gap-1 overflow-x-auto overflow-y-hidden whitespace-nowrap",style:{touchAction:"pan-x"},children:[Us.map((O,fe)=>O.id===Wr?s.jsx(k.Fragment,{children:s.jsx(Ol,{draggableId:O.id,index:fe,isDragDisabled:!0,children:kt=>s.jsx("div",{ref:kt.innerRef,...kt.draggableProps,className:"flex h-full items-center",children:Ll(O,!0)})})},O.id):s.jsx(k.Fragment,{children:s.jsx(Ol,{draggableId:O.id,index:fe,disableInteractiveElementBlocking:!0,children:(kt,Kt)=>s.jsx("div",{ref:kt.innerRef,...kt.draggableProps,className:`flex h-full shrink-0 items-center ${Kt.isDragging?"opacity-70":""}`,children:Ll(O,!0,kt.dragHandleProps)})})},O.id)),s.jsx("button",{type:"button",onClick:()=>ho(),disabled:fu,"aria-busy":fu,className:"ml-1 inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-primary/15 hover:text-primary active:scale-95","aria-label":e("tab.new"),title:e("tab.new"),children:s.jsx(Ys,{size:14})}),C.placeholder]})})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[!ri&&hi.running>0&&s.jsx("span",{className:"hidden items-center gap-1 sm:inline-flex",children:s.jsx(f4,{count:hi.running,tone:"running",title:e("agent.aiRunning")})}),!ri&&Tt.length>0&&s.jsx("span",{className:"inline-flex shrink-0 items-center px-1 text-[10px] uppercase tracking-[0.16em] text-muted-foreground sm:text-[11px]",title:`Session ${Po+1} of ${Tt.length}`,children:Oo}),!Nc&&s.jsx("button",{type:"button",onClick:di,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface-2 text-muted-foreground ring-1 ring-border/10 transition hover:bg-surface-elevated hover:text-foreground sm:h-8 sm:w-8","aria-label":e("tab.explorerTitle"),title:e("tab.explorerTitle"),children:s.jsx(x3,{size:14})})]})]}),_p&&La&&Fo?.terminalSessionId&&s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/15 bg-surface/80 px-3 py-2 animate-fade-in sm:px-4",style:{marginRight:il||void 0},role:"status","data-testid":"agent-resume-recovery-banner",children:[s.jsx("span",{className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-[rgb(var(--warning-rgb)_/_0.14)] text-[color:var(--warning)]",children:!qa?.error&&(qa?.status==="submitting"||qa?.status==="waiting")?s.jsx(Dn,{size:14,className:"animate-spin"}):s.jsx(qc,{size:14})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:e("tab.resumeAgentRecoveredTitle",{agent:Fo.agent?.displayName??"Agent"})}),s.jsx("div",{className:`truncate text-[10px] sm:text-[11px] ${qa?.error?"text-destructive":"text-muted-foreground"}`,children:qa?.error??(qa?.status==="submitting"?e("tab.resumeAgentSubmitting"):qa?.status==="waiting"?e("tab.resumeAgentWaiting"):e("tab.resumeAgentRecoveredHint"))})]}),s.jsx("button",{type:"button",disabled:!qa?.error&&(qa?.status==="submitting"||qa?.status==="waiting"),onClick:()=>{Xr(La.id,Fo.terminalSessionId)},className:"shrink-0 rounded-full bg-primary px-3 py-1.5 text-[11px] font-semibold text-primary-foreground transition hover:opacity-90 active:scale-95 disabled:cursor-wait disabled:opacity-60 sm:text-[12px]",children:qa?.error?e("common.retry"):e("tab.resumeAgentNow")}),s.jsx("button",{type:"button",onClick:()=>{Hr.getState().setAgentResumeRecovered(La.id,!1),wn(C=>C?.sessionId===La.id?null:C)},className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":e("tab.resumeAgentLater"),title:e("tab.resumeAgentLater"),children:s.jsx(jn,{size:13})})]}),s.jsx("div",{ref:lt,className:"min-h-0 flex-1 flex overflow-hidden app-chrome-bg",children:s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(oR,{terminalSettings:er,colorTheme:f,toolbarPresets:Ds,showDebug:l&&lr,terminalFocusAvailable:yt,terminalReferenceAvailable:ct,defaultSessionMode:ns,defaultTmuxSessionName:Ca,connectionPrioritySessionId:et,connectionPriorityReady:Wn,desktopRightSidebarEnabled:lr,onToggleRightSidebar:di,desktopFloatingTitle:lr,desktopLeftSidebarPinned:ri,desktopPinnedLeftSidebarWidth:ri?Jt:0,desktopViewportWidth:Ss,onSessionDataUpdate:Lp,onInitialViewportReady:rh,onInitialRecoveryRequired:bd})})})]})}),!be&&s.jsx(NO,{reviewCount:hi.review,runningSessions:Rn,activeSessionId:Ct,runningButtonEnabled:on,attentionButtonEnabled:$r,isDesktopLayout:lr,containerElement:Re,occlusionInsets:{right:il}}),ur&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-drawer-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm animate-fade-in cursor-default",onClick:Ta,"aria-label":e("settings.closeSettings")}),s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"settings-dialog-title",className:"pointer-events-none fixed inset-0 z-drawer-panel flex items-stretch justify-center p-0 animate-fade-in sm:p-4 md:p-6",children:s.jsxs("div",{className:"pointer-events-auto flex h-full w-full max-w-5xl flex-col overflow-hidden bg-surface shadow-[0_28px_90px_var(--app-shadow-strong),0_14px_34px_var(--app-shadow-soft)] sm:max-h-[calc(100dvh-3rem)] sm:rounded-3xl sm:border sm:border-border/15",style:{paddingTop:n,paddingBottom:a},children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-border/15 px-4 py-3 sm:px-6 sm:py-4",children:[s.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-primary/15 text-primary sm:h-9 sm:w-9",children:s.jsx(u1,{size:15})}),s.jsx("h2",{id:"settings-dialog-title",className:"text-[15px] font-semibold text-foreground sm:text-[16px]",children:e("settings.title")})]}),s.jsx("button",{type:"button",onClick:Ta,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface-2 text-muted-foreground transition hover:bg-destructive/20 hover:text-destructive","aria-label":e("common.close"),children:s.jsx(jn,{size:16})})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto bg-background/25 px-3 py-3 sm:px-6 sm:py-5 md:px-8",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.font")}),s.jsx("button",{type:"button",onClick:()=>ot({fontSize:Math.max(8,Lt-1)}),className:"h-8 w-8 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:"−"}),s.jsx("input",{type:"range",min:"8",max:"32",value:Lt,onChange:C=>ot({fontSize:parseInt(C.target.value,10)}),className:"min-w-0 flex-1","aria-label":e("settings.font")}),s.jsx("button",{type:"button",onClick:()=>ot({fontSize:Math.min(32,Lt+1)}),className:"h-8 w-8 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95",children:"+"}),s.jsxs("span",{className:"w-8 shrink-0 text-right text-[11px] tabular-nums text-muted-foreground",children:[Lt,"px"]})]}),s.jsx(hU,{}),s.jsx("div",{"data-terminal-renderer-controls":"browser-fallback",className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.render")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:["auto","webgl","canvas"].map(C=>{const O=nr===C;return s.jsx("button",{type:"button",onClick:()=>ot({rendererMode:C}),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${O?"bg-primary/20 text-primary":"text-muted-foreground hover:bg-surface-elevated"}`,children:e(C==="auto"?"settings.auto":C==="webgl"?"settings.webgl":"settings.canvas")},C)})})]})}),s.jsx("div",{className:"space-y-1.5 rounded-xl bg-surface-2 px-2.5 py-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.theme")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:[["dark",lS,e("settings.darkTheme")],["light",XS,e("settings.lightTheme")]].map(([C,O,fe])=>{const nt=f===C;return s.jsxs("button",{type:"button",onClick:()=>m(C),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 text-[11px] font-medium transition ${nt?"bg-primary/20 text-primary":"text-muted-foreground hover:bg-surface-elevated"}`,children:[s.jsx(O,{size:12}),s.jsx("span",{children:fe})]},C)})})]})}),s.jsxs("div",{className:"flex items-center gap-2 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.newTab")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:["shell","tmux"].map(C=>{const O=ns===C,fe=C==="tmux"&&!tr.available;return s.jsx("button",{type:"button",disabled:fe,onClick:()=>Wa(C,{userInitiated:!0}),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${O?"bg-primary/20 text-primary":fe?"cursor-not-allowed text-muted-foreground/40":"text-muted-foreground hover:bg-surface-elevated"}`,title:fe?tr.reason||e("settings.installTmuxHint"):void 0,children:e(C==="shell"?"settings.shell":"settings.tmux")},C)})})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>d(!l),className:`flex items-center justify-between rounded-xl px-3 py-2 text-[12px] transition ${l?"bg-primary/15 text-primary":"bg-surface-2 text-foreground hover:bg-surface-elevated"}`,children:[s.jsx("span",{className:"font-medium",children:e("settings.debug")}),s.jsx(vl,{checked:l,size:"sm"})]}),s.jsxs("button",{type:"button",onClick:async()=>{const C=!y;w(C);try{const O=await Qa({preventSleep:C});w(O.preventSleep),T(O.networkAvailable),oe(O.localAccess),Yn(o0,{preventSleep:O.preventSleep,networkAvailable:O.networkAvailable,localAccess:O.localAccess})}catch{w(!C)}},className:`flex items-center justify-between rounded-xl px-3 py-2 text-[12px] transition ${y?"bg-[rgb(var(--success-rgb)_/_0.15)] text-[color:var(--success)]":"bg-surface-2 text-foreground hover:bg-surface-elevated"}`,title:!v&&y?e("settings.noSleepUnavailable"):void 0,children:[s.jsx("span",{className:"font-medium truncate",children:e("settings.noSleep")}),s.jsx(vl,{checked:y,size:"sm"})]})]})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsxs("button",{type:"button",role:"switch","aria-checked":on,"aria-label":e("sidebar.runningSessionButton"),onClick:()=>{Fr(!on)},className:"flex w-full items-center gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsx(kf,{size:14,className:on?"shrink-0 text-[color:var(--success)]":"shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium text-foreground",children:e("sidebar.runningSessionButton")}),s.jsx("span",{className:"mt-0.5 block text-[10px] leading-tight text-muted-foreground",children:e("sidebar.runningSessionButtonHint")})]}),s.jsx(vl,{checked:on,size:"sm"})]}),s.jsxs("button",{type:"button",role:"switch","aria-checked":$r,"aria-label":e("sidebar.attentionButton"),onClick:()=>{W(!$r)},className:"flex w-full items-center gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsx(wc,{size:14,className:$r?"shrink-0 text-[color:var(--warning)]":"shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium text-foreground",children:e("sidebar.attentionButton")}),s.jsx("span",{className:"mt-0.5 block text-[10px] leading-tight text-muted-foreground",children:e("sidebar.attentionButtonHint")})]}),s.jsx(vl,{checked:$r,size:"sm"})]})]}),s.jsxs("button",{type:"button",onClick:()=>ta(!0),className:"mt-3 flex w-full items-center justify-between gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(d3,{size:14,className:S?"shrink-0 text-primary":"shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block font-medium text-foreground",children:e("settings.notifications")}),s.jsx("span",{className:"block truncate text-[10px] text-muted-foreground",children:e(S?N&&$?"settings.notificationsBothOnSummary":N?"settings.notificationsAiOnSummary":$?"settings.notificationsExitOnSummary":"settings.notificationsNoEventsSummary":"settings.notificationsOffSummary")})]})]}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:e(S?"common.on":"common.off")}),s.jsx("span",{children:"›"})]})]}),s.jsxs("button",{type:"button",onClick:()=>Ji(!0),className:"mt-3 flex w-full items-center justify-between gap-3 rounded-xl bg-surface-2 px-3 py-3 text-left transition hover:bg-surface-elevated",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[12px] font-medium text-foreground/90",children:e("settings.localAccess")}),s.jsx("span",{className:"mt-0.5 block text-[10px] text-muted-foreground",children:e("settings.localAccessHint")})]}),s.jsx(qs,{size:16,className:"shrink-0 text-muted-foreground"})]}),s.jsx(iU,{state:ie,pending:Fe,onCheck:()=>{hn()},onConfirmRestart:()=>{mn()},desktopState:xe?_e:void 0,desktopPending:ke,onCheckDesktop:xe?()=>{gn()}:void 0,onInstallDesktop:()=>{an()},desktopSnapshot:dt,desktopActions:tt?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-1 gap-px border-t border-border/10 bg-border/10 sm:grid-cols-2",children:[s.jsxs("button",{type:"button",onClick:()=>{tt.showConnectionCenter()},className:"flex items-center gap-2 bg-surface-2 px-3 py-2.5 text-left text-[11px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground",children:[s.jsx(aT,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopSwitchService")]}),s.jsxs("button",{type:"button",onClick:()=>{Xe(null),tt.revealDataDirectory().catch(C=>Xe(C instanceof Error?C.message:String(C)))},className:"flex items-center gap-2 bg-surface-2 px-3 py-2.5 text-left text-[11px] text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground",children:[s.jsx(qu,{size:13,className:"shrink-0 text-primary"}),e("settings.desktopOpenDataDirectory")]})]}),$e&&s.jsx("div",{className:"border-t border-border/10 px-3 py-2 text-[10px] text-muted-foreground",children:$e})]}):void 0}),s.jsx(oU,{backendSessionId:Ct?Ht.get(Ct)?.terminalSessionId??null:null}),s.jsx(cU,{state:Ge,onDismiss:()=>{Bn()}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>{co(null),ho({mode:"shell"}),Ta()},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${xu?"flex-[2.7] bg-primary px-3 py-2.5 text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90":"flex-[0.78] bg-surface-2 px-2 py-2 text-muted-foreground hover:bg-surface-elevated hover:text-foreground"}`,title:e(ki==="shell"?"sidebar.confirmNewShell":"settings.shell"),children:[s.jsx(Ys,{size:14,className:xu?"shrink-0":"hidden"}),s.jsx(tl,{size:12}),s.jsx("span",{className:xu?"whitespace-nowrap":"hidden",children:e(ki==="shell"?"sidebar.confirmNewShell":"settings.shell")})]}),s.jsxs("button",{type:"button",disabled:!tr.available,onClick:()=>{tr.available&&(co(null),ho({mode:"tmux"}),Ta())},className:`flex min-w-0 items-center justify-center gap-1.5 rounded-xl text-[13px] font-semibold transition active:scale-[0.98] ${tr.available?Ia?"flex-[2.7] bg-primary px-3 py-2.5 text-primary-foreground ring-1 ring-primary/40 shadow-md shadow-primary/25 hover:bg-primary/90":"flex-[0.78] bg-surface-2 px-2 py-2 text-muted-foreground hover:bg-surface-elevated hover:text-foreground":"flex-1 bg-surface-2/50 text-muted-foreground/50 cursor-not-allowed"}`,title:tr.available?e(ki==="tmux"?"sidebar.confirmNewTmux":"settings.tmux"):tr.reason||e("settings.installTmuxHint"),children:[s.jsx(Ys,{size:14,className:Ia?"shrink-0":"hidden"}),s.jsx(su,{size:12}),s.jsx("span",{className:Ia?"whitespace-nowrap":"hidden",children:e(ki==="tmux"?"sidebar.confirmNewTmux":"settings.tmux")})]})]}),(tr.available||Lr.length>0)&&s.jsxs("details",{className:"mt-3 group rounded-xl bg-surface-2 [&[open]]:bg-surface-2",children:[s.jsxs("summary",{className:"flex cursor-pointer items-center justify-between rounded-xl px-3 py-2.5 text-[13px] hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`inline-flex h-2 w-2 rounded-full ${tr.available?"bg-primary":"bg-destructive"}`}),s.jsx("span",{className:"font-medium",children:e("settings.tmuxServer")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:tr.available?e("settings.sessions",{n:Lr.length}):e("settings.tmuxUnavailable")})]}),s.jsx("button",{type:"button",onClick:C=>{C.preventDefault(),kl()},disabled:De,className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:opacity-50","aria-label":e("settings.refresh"),children:s.jsx(vn,{size:12,className:De?"animate-spin":""})})]}),s.jsx("div",{className:"px-2 pb-2",children:tr.available?Lr.length===0?s.jsx("p",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:e("settings.noTmuxSessions")}):s.jsxs("div",{className:"space-y-2",children:[Uo.map(C=>s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 px-1.5 py-1 text-[10px] text-muted-foreground",children:[s.jsx(nu,{size:11,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"shrink-0 font-medium text-foreground/75",children:C.label}),s.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:e("settings.sessions",{n:C.sessions.length})}),C.key&&s.jsx("span",{className:"min-w-0 truncate text-muted-foreground/60",children:C.key})]}),C.sessions.map(O=>{const fe=O.boundFrontendSessionId??null,nt=!!(O.connected||fe),kt=fe?Tt.find($i=>$i.id===fe)??null:null,Kt=O.friendlyName?.trim()||null,Er=O.label&&O.label!==O.name?O.label:null,Mn=Kt||Er||O.name,Vn=Kt||Er?`tmux:${O.name}`:null,Un=O.clientCount&&O.clientCount>0?t==="zh"?`网页连接 ${O.clientCount}`:`Web clients ${O.clientCount}`:null,Fi=O.attached>0?t==="zh"?`原生 tmux ${O.attached}`:`Native tmux ${O.attached}`:null,Ln=[Vn,nt?O.restorable?e("settings.restorable"):e("settings.attached"):null,Un,Fi].filter($i=>!!$i),ia=[e("settings.windows",{n:O.windows}),O.createdAt?new Date(O.createdAt).toLocaleDateString():null].filter($i=>!!$i),zo=vr===O.name,Ho=Br===O.name,Ya=Cs===O.name;return s.jsxs("div",{className:`flex items-start gap-2 rounded-lg px-2.5 py-2 ${zo?"bg-destructive/10 ring-1 ring-destructive/40":"bg-surface"}`,children:[s.jsx(su,{size:13,className:nt?"mt-0.5 shrink-0 text-primary":"mt-0.5 shrink-0 text-muted-foreground"}),s.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("div",{className:"truncate text-[12px] font-semibold text-foreground",children:Mn}),O.friendlyName&&s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-[9px] font-medium text-primary",children:t==="zh"?"自定义":"custom"})]}),Ln.length>0&&s.jsx("div",{className:"flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground",children:Ln.map($i=>s.jsx("span",{className:"max-w-full truncate",children:$i},$i))}),(O.program||O.cwd)&&s.jsxs("div",{className:"grid min-w-0 gap-0.5 text-[10px] text-muted-foreground",children:[O.program&&s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx(UT,{size:10,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate text-foreground/75",children:O.program})]}),O.cwd&&s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx(nu,{size:10,className:"shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:O.cwd})]})]}),s.jsx("div",{className:"flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground/80",children:ia.map($i=>s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(AT,{size:10,className:"shrink-0 text-muted-foreground/60"}),$i]},$i))})]}),zo?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:Ho,onClick:()=>{sh(O.name)},className:"shrink-0 rounded-full bg-destructive/90 px-2.5 py-1 text-[11px] font-medium text-destructive-foreground transition hover:bg-destructive disabled:opacity-50",children:Ho?"…":e("settings.destroy")}),s.jsx("button",{type:"button",disabled:Ho,onClick:()=>{Dt(null),Kn(null)},className:"shrink-0 rounded-full bg-surface-2 px-2.5 py-1 text-[11px] font-medium text-foreground transition hover:bg-surface-elevated",children:e("common.cancel")})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>{kt?th(kt.id):(ws(O.name),ho({mode:"tmux",tmuxSessionName:O.name}))},disabled:Ya,className:`shrink-0 inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-medium transition disabled:opacity-50 ${nt?"bg-surface text-foreground hover:bg-surface-elevated":Ya?"bg-primary/10 text-primary":"bg-primary/15 text-primary hover:bg-primary/25"}`,children:Ya?s.jsxs(s.Fragment,{children:[s.jsx(Dn,{size:10,className:"animate-spin"}),e("settings.attaching")]}):e(nt?"settings.attached":"settings.attach")}),s.jsx("button",{type:"button",disabled:Ho,onClick:()=>{Kn(null),Dt(O.name)},className:"shrink-0 inline-flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground transition hover:bg-destructive/15 hover:text-destructive","aria-label":`Kill tmux session ${O.name}`,children:s.jsx(Ms,{size:12})})]})]},O.name)})]},C.key||"__ungrouped_tmux__")),xn&&s.jsx("p",{className:"px-2 text-[11px] text-destructive",children:xn})]}):s.jsx("p",{className:"px-2 py-1.5 text-[11px] text-muted-foreground",children:tr.reason||e("settings.installTmuxHint")})})]}),s.jsxs("button",{type:"button",onClick:()=>Ga(!0),className:"mt-2 flex w-full items-center justify-between gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(p3,{size:14,className:"text-muted-foreground"}),s.jsx("span",{className:"font-medium text-foreground",children:e("settings.keyboardToolbar")})]}),s.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:e("settings.sessions",{n:Ds.length})}),s.jsx("span",{children:"›"})]})]}),s.jsxs("button",{type:"button",onClick:()=>ue(!0),className:"mt-2 flex w-full items-center justify-between gap-2 rounded-xl bg-surface-2 px-3 py-2.5 text-left text-[13px] transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(G0,{size:14,className:"text-muted-foreground"}),s.jsx("span",{className:"font-medium text-foreground",children:e("settings.aiAgentDetection")})]}),s.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[s.jsx("span",{children:"hooks"}),s.jsx("span",{children:"›"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2 rounded-xl bg-surface-2 px-2.5 py-2",children:[s.jsx("span",{className:"text-[12px] font-medium text-foreground/90 w-14 shrink-0",children:e("settings.language")}),s.jsx("div",{className:"flex flex-1 items-center gap-1 rounded-md bg-surface p-0.5",children:[{code:"en",label:"English"},{code:"zh",label:"中文"}].map(C=>{const O=t===C.code;return s.jsx("button",{type:"button",onClick:()=>r(C.code),className:`flex-1 rounded px-2 py-1 text-[11px] font-medium transition ${O?"bg-primary/20 text-primary":"text-muted-foreground hover:bg-surface-elevated"}`,children:C.label},C.code)})})]}),s.jsxs("button",{type:"button",onClick:async()=>{try{await CA()}catch{}window.dispatchEvent(new CustomEvent("auth:unauthorized"))},className:"mt-3 flex w-full items-center justify-center gap-2 rounded-xl bg-destructive/10 px-3 py-2.5 text-[13px] font-medium text-destructive transition hover:bg-destructive/20 active:scale-[0.98]",children:[s.jsx(w3,{size:14}),e("settings.signOut")]})]})]})})]}),$o&&s.jsxs(s.Fragment,{children:[s.jsx(jQ,{sessionId:$o.id,confirmButton:ih,onConfirm:Ad,onCancel:gu,isCurrent:Pt}),s.jsx("button",{type:"button",className:"fixed inset-0 z-menu-backdrop bg-[var(--app-backdrop-soft)] backdrop-blur-sm cursor-default animate-fade-in",onClick:()=>{_t(null),R(null),Kn(null)},"aria-label":e("common.close")}),s.jsxs("div",{className:`fixed z-menu-panel rounded-2xl bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in ${z&&lr?"":"inset-x-3 bottom-6 mx-auto max-w-sm sm:bottom-auto sm:top-[15%]"}`,style:z&&lr?{...zy(z),paddingBottom:a}:{paddingBottom:a},children:[s.jsxs("div",{className:"border-b border-border/15 px-4 py-3",children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.closeChooserTitle")}),s.jsx("div",{className:"mt-0.5 truncate text-[14px] font-medium text-foreground",children:Ip}),s.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground/80",children:e("tab.closeChooserDescription")})]}),s.jsxs("div",{className:"flex flex-col py-1",children:[s.jsxs("button",{type:"button",ref:ih,onClick:Ad,className:"flex items-center gap-3 px-4 py-3 text-left text-[13px] text-destructive transition hover:bg-destructive/10",children:[s.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-full bg-destructive/15 text-destructive",children:s.jsx(Ms,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.confirmDestroySession")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.destroySessionHint")})]})]}),xn&&s.jsx("p",{className:"px-4 py-2 text-[11px] text-destructive",children:xn})]}),s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:()=>{_t(null),R(null),Kn(null)},className:"w-full rounded-full bg-surface-2 px-3 py-2 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")})})]})]}),Pn&&(()=>{const C=Tt.find(Un=>Un.id===Pn);if(!C)return null;const O=Ht.get(C.id),{primary:fe}=xl(C,O?.activeProgram??null,O?.cwd??null,Da),nt=lr,kt=nt?zy(ds):{paddingBottom:a},Kt=nt?"fixed z-menu-panel overflow-y-auto overflow-x-hidden rounded-lg bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in":"fixed inset-x-3 bottom-6 z-menu-panel mx-auto max-w-sm rounded-2xl bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in sm:bottom-auto sm:top-[15%]",Er=nt?"border-b border-border/15 px-3 py-2":"border-b border-border/15 px-4 py-3",Mn=nt?"flex items-center gap-2 px-3 py-2 text-left text-[12px] transition":"flex items-center gap-3 px-4 py-3 text-left text-[13px] transition",Vn=nt?"inline-flex h-6 w-6 items-center justify-center rounded-md":"inline-flex h-7 w-7 items-center justify-center rounded-full";return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:`fixed inset-0 z-menu-backdrop cursor-default animate-fade-in ${nt?"bg-transparent":"bg-[var(--app-backdrop-soft)] backdrop-blur-sm"}`,onClick:We,"aria-label":"Close menu"}),s.jsxs("div",{className:Kt,style:kt,children:[s.jsxs("div",{className:Er,children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.session")}),s.jsx("div",{className:"mt-0.5 truncate text-[14px] font-medium text-foreground",children:fe}),O?.cwd&&s.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground/80",children:O.cwd})]}),s.jsxs("div",{className:"flex flex-col py-1",children:[s.jsxs("button",{type:"button",onClick:()=>{const Un=ds;We(),rr(Un),Qn(C.id)},className:`${Mn} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${Vn} bg-primary/15 text-primary`,children:s.jsx(CS,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.rename")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.renameHint")})]})]}),s.jsxs("button",{type:"button",disabled:!O?.cwd,onClick:()=>{hu(C.id),We()},className:`${Mn} ${O?.cwd?"text-foreground hover:bg-surface-2":"text-muted-foreground/50 cursor-not-allowed"}`,children:[s.jsx("span",{className:`${Vn} bg-surface-2 text-muted-foreground`,children:s.jsx(m3,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.copyCwd")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.copyCwdHint")})]}),kn&&kn===O?.cwd&&s.jsx("span",{className:"ml-auto text-[11px] text-primary",children:e("tab.copied")})]}),(()=>{const Un=l1(C.id),Fi=Un??Lt;return s.jsxs("div",{className:`${Mn} text-foreground`,children:[s.jsx("span",{className:`${Vn} bg-surface-2 text-muted-foreground`,children:s.jsx(tC,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.fontSize")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.fontSizeHint")})]}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("button",{type:"button",onClick:()=>{tf(C.id,Fi-1),bn(Ln=>Ln+1)},className:"h-7 w-7 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95","aria-label":`${e("tab.fontSize")} -1`,children:"−"}),s.jsxs("span",{className:"w-8 text-center text-[11px] tabular-nums text-muted-foreground",children:[Fi,"px"]}),s.jsx("button",{type:"button",onClick:()=>{tf(C.id,Fi+1),bn(Ln=>Ln+1)},className:"h-7 w-7 shrink-0 rounded-md bg-surface text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground active:scale-95","aria-label":`${e("tab.fontSize")} +1`,children:"+"}),Un!==null&&s.jsx("button",{type:"button",onClick:()=>{tf(C.id,null),bn(Ln=>Ln+1)},className:"ml-1 shrink-0 rounded-md px-1.5 py-1 text-[11px] text-primary transition hover:bg-primary/10",children:e("tab.fontSizeReset")})]})]})})(),O?.agentNativeSessionId&&O.agentStatus!=="working"&&O.agentStatus!=="waiting"&&O.terminalSessionId&&s.jsxs("button",{type:"button",onClick:()=>{const Un=O.terminalSessionId;Un&&(We(),Xr(C.id,Un))},className:`${Mn} text-foreground hover:bg-surface-2`,children:[s.jsx("span",{className:`${Vn} bg-[rgb(var(--success-rgb)_/_0.14)] text-[color:var(--success)]`,children:s.jsx(qc,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"block font-medium",children:[e("tab.resumeAgent"),O.agent?.displayName?` · ${O.agent.displayName}`:""]}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.resumeAgentHint")})]})]}),s.jsx("div",{className:"my-1 border-t border-border/15"}),C.mode==="tmux"?s.jsxs("button",{type:"button",onClick:()=>{We(),Xl(C.id)},className:`${Mn} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${Vn} bg-destructive/15 text-destructive`,children:s.jsx(Ms,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.destroySession")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.destroySessionHint")})]})]}):s.jsxs("button",{type:"button",onClick:()=>{We(),nl({sessionId:C.id,source:"tab-menu",closeMode:"auto"})},className:`${Mn} text-destructive hover:bg-destructive/10`,children:[s.jsx("span",{className:`${Vn} bg-destructive/15 text-destructive`,children:s.jsx(jn,{size:14})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:e("tab.close")}),s.jsx("span",{className:"block text-[11px] text-muted-foreground",children:e("tab.closeHint")})]})]}),!nt&&s.jsx("button",{type:"button",className:"flex items-center justify-center px-4 py-2 text-[11px] text-muted-foreground/80 transition hover:text-foreground",onClick:()=>{We()},children:e("tab.longPressTip")})]}),!nt&&s.jsx("div",{className:"border-t border-border/15 px-3 py-2",children:s.jsx("button",{type:"button",onClick:We,className:"w-full rounded-full bg-surface-2 px-3 py-2 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")})})]})]})})(),Wr&&An&&lr&&(()=>{const C=Tt.find(Ln=>Ln.id===Wr);if(!C)return null;const O=Ht.get(C.id),{primary:fe}=xl(C,O?.activeProgram??null,O?.cwd??null,Da,O?.shellTitle??null,O?.promptState??null),nt=C.customName?C.name:fe,kt=Ln=>{const ia=Ln.trim();ia?ia!==nt&&Sa(C.id,ia):_n(C.id),Qn(null),rr(null)},Kt=300,Er=160,Mn=An.x,Vn=An.y,Un=Math.min(Math.max(Mn-Kt/2,12),window.innerWidth-Kt-12),Fi=Vn+Er+20>window.innerHeight?Math.max(Vn-Er-12,12):Vn+12;return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-menu-backdrop cursor-default animate-fade-in bg-transparent",onClick:()=>{Qn(null),rr(null)},"aria-label":e("common.cancel")}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e("tab.rename"),className:"fixed z-menu-panel w-[300px] rounded-xl bg-surface-elevated border border-border/15 shadow-[0_12px_36px_var(--app-shadow-soft)] animate-fade-in",style:{left:`${Un}px`,top:`${Fi}px`},children:[s.jsxs("div",{className:"border-b border-border/15 px-3 py-2.5",children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.rename")}),s.jsx("div",{className:"mt-0.5 truncate text-[13px] font-medium text-foreground",children:fe}),O?.cwd&&s.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground/70",children:O.cwd})]}),s.jsxs("form",{className:"px-3 py-2.5",onSubmit:Ln=>{Ln.preventDefault();const ia=new FormData(Ln.currentTarget).get("session-name");kt(typeof ia=="string"?ia:"")},children:[s.jsx("input",{ref:Ln=>{F.current=Ln,Ln&&!q.current&&(q.current=!0,Ln.focus({preventScroll:!0}),Ln.select())},type:"text",name:"session-name",defaultValue:nt,placeholder:e("tab.renamePlaceholder"),autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,className:"w-full rounded-lg bg-surface-2 px-3 py-2 text-[13px] leading-snug text-foreground outline-none ring-1 ring-primary/40 placeholder:text-muted-foreground/60 focus:ring-primary/70",onKeyDown:Ln=>{Ln.key==="Escape"&&(Ln.stopPropagation(),Qn(null),rr(null))}}),s.jsxs("div",{className:"mt-2.5 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Qn(null),rr(null)},className:"flex-1 rounded-full bg-surface-2 px-3 py-1.5 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")}),s.jsx("button",{type:"submit",className:"flex-1 rounded-full bg-primary px-3 py-1.5 text-[12px] font-semibold text-primary-foreground transition hover:bg-primary/90 active:scale-[0.97]",children:e("common.save")})]})]})]})]})})(),Wr&&!lr&&(()=>{const C=Tt.find(Kt=>Kt.id===Wr);if(!C)return null;const O=Ht.get(C.id),{primary:fe}=xl(C,O?.activeProgram??null,O?.cwd??null,Da,O?.shellTitle??null,O?.promptState??null),nt=C.customName?C.name:fe,kt=Kt=>{const Er=Kt.trim();Er?Er!==nt&&Sa(C.id,Er):_n(C.id),Qn(null)};return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-menu-backdrop cursor-default animate-fade-in bg-[var(--app-backdrop-soft)] backdrop-blur-sm",onClick:()=>Qn(null),"aria-label":e("common.cancel")}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":e("tab.rename"),className:"fixed inset-x-3 z-menu-panel mx-auto max-w-sm rounded-2xl bg-surface-elevated border border-border/15 shadow-[0_18px_48px_var(--app-shadow-soft)] animate-fade-in",style:{top:`calc(${n} + 3.5rem)`},children:[s.jsxs("div",{className:"border-b border-border/15 px-4 py-3",children:[s.jsx("div",{className:"text-[11px] uppercase tracking-[0.14em] text-muted-foreground",children:e("tab.session")}),s.jsx("div",{className:"mt-0.5 text-[14px] font-medium text-foreground",children:e("tab.rename")})]}),s.jsxs("form",{className:"px-4 py-3",onSubmit:Kt=>{Kt.preventDefault();const Er=new FormData(Kt.currentTarget).get("session-name");kt(typeof Er=="string"?Er:"")},children:[s.jsx("input",{ref:Kt=>{F.current=Kt,Kt&&!q.current&&(q.current=!0,Kt.focus({preventScroll:!0}),Kt.select())},type:"text",name:"session-name",defaultValue:nt,placeholder:e("tab.renamePlaceholder"),autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,enterKeyHint:"done",className:"w-full rounded-lg bg-surface-2 px-3 py-2.5 text-[16px] leading-snug text-foreground outline-none ring-1 ring-primary/40 placeholder:text-muted-foreground/60 focus:ring-primary/70",onKeyDown:Kt=>{Kt.key==="Escape"&&(Kt.stopPropagation(),Qn(null))}}),s.jsxs("div",{className:"mt-3 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>Qn(null),className:"flex-1 rounded-full bg-surface-2 px-3 py-2 text-[12px] font-medium text-muted-foreground transition hover:bg-surface hover:text-foreground",children:e("common.cancel")}),s.jsx("button",{type:"submit",className:"flex-1 rounded-full bg-primary/20 px-3 py-2 text-[12px] font-medium text-primary transition hover:bg-primary/30",children:e("common.save")})]})]})]})]})})(),Xi&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button","aria-label":e("common.close"),className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm",onClick:()=>Ji(!1)}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"local-access-title",className:"fixed inset-x-3 top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-xl flex-col overflow-hidden rounded-2xl border border-border/15 bg-surface sm:top-[10%] sm:bottom-auto sm:max-h-[80vh]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 p-4",children:[s.jsx("h2",{id:"local-access-title",className:"section-title",children:e("settings.localAccess")}),s.jsx("button",{autoFocus:!0,type:"button","aria-label":e("common.close"),onClick:()=>Ji(!1),className:"rounded-full bg-surface-2 p-2 text-muted-foreground",children:s.jsx(jn,{size:18})})]}),s.jsxs("div",{className:"overflow-y-auto overscroll-contain p-4",children:[s.jsx(NC,{state:ye,onCopy:C=>{Gn(C,"setup")},copied:he==="setup"}),s.jsxs("div",{className:"mt-3 flex items-center overflow-hidden rounded-lg bg-surface ring-1 ring-border/10 focus-within:ring-primary/40",children:[s.jsx("input",{value:te,onChange:C=>Ce(C.target.value.toLowerCase()),className:"min-w-0 flex-1 bg-transparent px-2.5 py-2 text-[12px] text-foreground outline-none",placeholder:"jovn",spellCheck:!1}),s.jsx("span",{className:"shrink-0 border-l border-border/10 px-2.5 py-2 text-[11px] text-muted-foreground",children:".termdock.local"})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",disabled:qe,onClick:()=>{kc()},className:"rounded-full bg-primary/15 px-3 py-1.5 text-[11px] font-medium text-primary transition hover:bg-primary/25 disabled:opacity-50",children:e(qe?"settings.saving":"common.save")}),s.jsx("button",{type:"button",disabled:qe,onClick:()=>{Lc()},className:"rounded-full bg-surface px-3 py-1.5 text-[11px] font-medium text-muted-foreground transition hover:bg-surface-elevated disabled:opacity-50",children:e("settings.resetAutoName")})]}),s.jsxs("div",{className:"mt-3 space-y-1.5 text-[11px]",children:[ye.url&&s.jsxs("button",{type:"button",onClick:()=>{Gn(ye.url,"lan")},className:"flex w-full items-center justify-between gap-2 rounded-lg bg-surface px-2.5 py-2 text-left text-muted-foreground transition hover:bg-surface-elevated",children:[s.jsxs("span",{className:"min-w-0 truncate",children:["Branded: ",ye.url]}),s.jsx("span",{className:"shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-medium",children:he==="lan"?"Copied":e("common.copy")})]}),ye.interfaces.length>0&&s.jsxs("details",{className:"rounded-lg bg-surface px-2.5 py-2 text-muted-foreground",open:!1,children:[s.jsx("summary",{className:"cursor-pointer text-[11px] font-medium text-foreground/80",children:"IP fallback addresses"}),s.jsx("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:ye.interfaces.map(C=>{const O=C.url??`${ye.httpsEnabled?"https":"http"}://${C.address}:9834`;return s.jsxs("div",{className:"rounded-lg bg-surface-2 p-2",children:[s.jsxs("div",{className:"text-[11px] font-medium text-foreground/85",children:[C.label," (",C.name,")"]}),s.jsx("div",{className:"mt-0.5 text-[10px] text-muted-foreground",children:C.address}),C.qrDataUrl&&s.jsx("div",{className:"mt-2 inline-block rounded-lg bg-[var(--background)] p-1.5",children:s.jsx("img",{src:C.qrDataUrl,alt:`QR code for ${O}`,className:"h-28 w-28"})}),s.jsxs("button",{type:"button",onClick:()=>{Gn(O,`ip-${C.address}`)},className:"mt-2 flex w-full items-center justify-between gap-2 rounded-md bg-surface px-2 py-1.5 text-left text-[11px] transition hover:bg-surface-elevated",children:[s.jsx("span",{className:"min-w-0 truncate",children:O}),s.jsx("span",{className:"shrink-0 text-[10px]",children:he===`ip-${C.address}`?"Copied":e("common.copy")})]})]},`${C.name}-${C.address}`)})})]}),s.jsxs("div",{className:"text-muted-foreground",children:[ye.httpsEnabled?e("settings.httpsActive"):e("settings.httpsInactive"),!ye.caAvailable&&` · ${e("settings.caMissing")}`]}),ye.reason&&s.jsx("div",{className:"text-[color:var(--warning)]",children:ye.reason}),Y&&s.jsx("div",{className:"text-destructive",children:Y})]})]})]})]}),ea&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:()=>ta(!1)}),s.jsxs("div",{className:"fixed left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-xl flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)] sm:top-[10%] sm:bottom-auto sm:max-h-[80vh]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-4 py-4 sm:px-6",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.notifications")}),s.jsx("h2",{className:"section-title mt-1",children:e("settings.notificationsTitle")})]}),s.jsx("button",{type:"button",onClick:()=>ta(!1),className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":"Close notifications settings",children:s.jsx(jn,{size:18})})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[s.jsx("p",{className:"text-[12px] leading-relaxed text-muted-foreground",children:e("settings.notificationsPageHint")}),s.jsxs("div",{className:"mt-4 rounded-2xl bg-surface-2 p-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsMaster")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:J==="denied"?e("settings.notificationsDenied"):yh()?e("settings.notificationsMasterHint"):e("settings.notificationsUnsupported")}),yh()&&!_A()&&s.jsx("div",{className:"mt-1.5 text-[11px] leading-relaxed text-[var(--warning)]",children:e("settings.notificationsIOSInstallHint")})]}),s.jsx("button",{type:"button",onClick:()=>{Oi()},disabled:!yh()||J==="denied",className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":S,children:s.jsx(vl,{checked:S,disabled:!yh()||J==="denied"})})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-[11px]",children:[s.jsxs("span",{className:`rounded-full px-2 py-0.5 ${J==="granted"?"bg-primary/15 text-primary":"bg-surface text-muted-foreground"}`,children:[e("settings.notificationsPermission"),": ",Gi()?e("settings.notificationsPermissionSystem"):J]}),s.jsx("button",{type:"button",disabled:!S||J!=="granted"||xs==="checking",onClick:()=>{Vr()},className:"rounded-full bg-surface px-3 py-1.5 font-medium text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",children:e(xs==="checking"?"settings.notificationsTestChecking":"settings.notificationsTest")}),Gi()?.openNotificationSettings&&s.jsx("button",{type:"button",onClick:()=>{Gi()?.openNotificationSettings?.()},className:"rounded-full bg-surface px-3 py-1.5 font-medium text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground",children:e("settings.notificationsOpenSystemSettings")})]}),xs!=="idle"&&xs!=="checking"&&s.jsx("div",{className:`mt-2 text-[11px] leading-relaxed ${xs==="delivered"?"text-primary":"text-[var(--warning)]"}`,children:e(xs==="delivered"?"settings.notificationsTestDelivered":"settings.notificationsTestFailed")})]}),s.jsxs("div",{className:"mt-4 rounded-2xl bg-surface-2 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsAlertStyle")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:e("settings.notificationsAlertStyleHint")}),s.jsx("div",{className:"mt-3 grid grid-cols-3 gap-1 rounded-xl bg-surface p-1",children:[["normal",e("settings.notificationsStyleNormal"),e("settings.notificationsStyleNormalHint")],["quiet",e("settings.notificationsStyleQuiet"),e("settings.notificationsStyleQuietHint")],["persistent",e("settings.notificationsStylePersistent"),e("settings.notificationsStylePersistentHint")]].map(([C,O,fe])=>{const nt=U===C;return s.jsxs("button",{type:"button",disabled:!S,onClick:()=>Kl(C),className:`min-w-0 rounded-lg px-2 py-2 text-left transition ${nt&&S?"bg-primary/15 text-primary":S?"text-muted-foreground hover:bg-surface-elevated hover:text-foreground":"cursor-not-allowed text-muted-foreground/40"}`,title:fe,children:[s.jsx("span",{className:"block truncate text-[11px] font-semibold",children:O}),s.jsx("span",{className:"mt-0.5 block truncate text-[9px] opacity-80",children:fe})]},C)})})]}),s.jsxs("div",{className:"mt-4",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.notificationsEvents")}),s.jsxs("div",{className:"mt-2 rounded-2xl bg-surface-2 p-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsAiFinished")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:e("settings.notificationsAiFinishedHint")})]}),s.jsx("button",{type:"button",disabled:!S,onClick:()=>yn(!N),className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":N&&S,children:s.jsx(vl,{checked:N&&S,disabled:!S})})]}),s.jsxs("div",{className:"mt-3 flex items-start justify-between gap-3 border-t border-border/10 pt-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:e("settings.notificationsSessionExited")}),s.jsx("div",{className:"mt-1 text-[11px] leading-relaxed text-muted-foreground",children:e("settings.notificationsSessionExitedHint")})]}),s.jsx("button",{type:"button",disabled:!S,onClick:()=>Bs(!$),className:"shrink-0 transition disabled:cursor-not-allowed","aria-pressed":$&&S,children:s.jsx(vl,{checked:$&&S,disabled:!S})})]})]}),s.jsx("p",{className:"mt-2 text-[10px] text-muted-foreground",children:e("settings.notificationsFutureHint")})]})]})]})]}),Li&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:()=>Ga(!1)}),s.jsxs("div",{className:"fixed left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-4xl flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-4 py-4 sm:px-6",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.mobileKeyboard")}),s.jsx("h2",{className:"section-title mt-1",children:e("settings.toolbarPresets")})]}),s.jsx("button",{type:"button",onClick:()=>Ga(!1),className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":"Close toolbar presets",children:s.jsx(jn,{size:18})})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:s.jsx(rU,{presets:Ds,selectedPresetId:rl,onSelectPreset:ka,onUpdatePreset:(C,O)=>{_a(fe=>Hu(fe.map(nt=>nt.id===C?O(nt):nt)))},onAddPreset:()=>{const C=`preset-${Date.now()}`;_a(O=>Hu([...O,{id:C,label:`Preset ${O.length}`,programs:[],includeAlt:!1,rowLayout:[3,3],actions:[],showOnDesktop:!1}])),ka(C)},onRemovePreset:C=>{_a(O=>Hu(O.filter(fe=>fe.id!==C)))},onResetDefaults:()=>{_a(D0()),ka("default")}})})]})]}),Qo&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-modal-backdrop bg-[var(--app-backdrop)] backdrop-blur-sm cursor-default",onClick:()=>ue(!1)}),s.jsxs("div",{className:"fixed left-[max(0.75rem,env(safe-area-inset-left,0px))] right-[max(0.75rem,env(safe-area-inset-right,0px))] top-[max(1.5rem,env(safe-area-inset-top,0px))] bottom-[max(1.5rem,env(safe-area-inset-bottom,0px))] z-modal-panel mx-auto flex max-w-4xl flex-col overflow-hidden rounded-2xl bg-surface border border-border/15 shadow-[0_28px_70px_var(--app-shadow-strong),0_14px_32px_var(--app-shadow-soft)]",children:[s.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-border/15 px-4 py-4 sm:px-6",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.aiAgentDetection")}),s.jsx("h2",{className:"section-title mt-1",children:e("settings.detectionRules")})]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("button",{type:"button",onClick:()=>ue(!1),className:"shrink-0 rounded-full bg-surface-2 p-2 text-muted-foreground transition hover:bg-surface-elevated hover:text-foreground","aria-label":"Close agent rules",children:s.jsx(jn,{size:18})})})]}),s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-6",children:[s.jsx("p",{className:"mb-4 text-[11px] text-muted-foreground",children:e("settings.agentHooksHint")}),s.jsx(sU,{}),s.jsxs("div",{className:"mt-6 border-t border-border/15 pt-4",children:[s.jsx("div",{className:"ui-kicker",children:e("settings.programLabelResolution")}),s.jsx("h3",{className:"mt-1 text-sm font-semibold text-foreground",children:e("settings.rawCommandMapping")}),s.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:e("settings.rawCommandMappingHint")}),s.jsx("div",{className:"mt-3 space-y-2 rounded-xl bg-surface-2 p-3",children:Tt.map(C=>{const O=Ht.get(C.id),fe=O?.activeProgramRaw??null,nt=O?.activeProgram??null;return s.jsxs("div",{className:"rounded-lg bg-surface/60 px-2.5 py-2",children:[s.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:C.name}),s.jsxs("div",{className:"mt-0.5 text-[11px] text-foreground",children:[s.jsx("span",{className:"text-muted-foreground",children:"display:"})," ",nt||"—"]}),s.jsxs("div",{className:"mt-0.5 break-all font-mono text-[10px] text-muted-foreground",children:[s.jsx("span",{className:"text-muted-foreground/80",children:"raw:"})," ",fe||"—"]})]},`raw-${C.id}`)})}),s.jsxs("div",{className:"mt-3 space-y-3",children:[[{key:"genericProgramNames",label:e("settings.genericProgramNames"),hint:e("settings.genericProgramNamesHint")},{key:"wrapperScriptNames",label:e("settings.wrapperScriptNames"),hint:e("settings.wrapperScriptNamesHint")},{key:"shellNames",label:e("settings.shellNamesConfig"),hint:e("settings.shellNamesHint")}].map(({key:C,label:O,hint:fe})=>s.jsxs("div",{children:[s.jsx("div",{className:"mb-0.5 text-[11px] font-medium text-foreground",children:O}),s.jsx("div",{className:"text-[10px] text-muted-foreground",children:fe}),s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1",children:[Ir[C].map(nt=>s.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded-full bg-surface-2 px-2 py-0.5 text-[11px] font-mono text-foreground",children:[nt,s.jsx("button",{type:"button",onClick:()=>{const kt={...Ir,[C]:Ir[C].filter(Kt=>Kt!==nt)};ln(kt),C==="shellNames"&&(Da=new Set(kt.shellNames)),$x(kt).catch(()=>{})},className:"ml-0.5 text-muted-foreground hover:text-destructive",children:"×"})]},nt)),s.jsx("input",{placeholder:e("settings.addTag"),className:"w-16 rounded bg-surface px-1.5 py-0.5 text-[11px] font-mono",onKeyDown:nt=>{if(nt.key!=="Enter")return;const kt=nt.target.value.trim().toLowerCase();if(!kt||Ir[C].includes(kt))return;const Kt={...Ir,[C]:[...Ir[C],kt]};ln(Kt),C==="shellNames"&&(Da=new Set(Kt.shellNames)),nt.target.value="",$x(Kt).catch(()=>{})}})]})]},C)),s.jsx("button",{type:"button",onClick:()=>{kA().then(C=>{ln(C),Da=new Set(C.shellNames)}).catch(()=>{})},className:"rounded-full bg-surface-2 px-3 py-1 text-[11px] text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:e("settings.resetDefaults")})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"mb-1 text-[11px] font-medium text-foreground",children:e("settings.customRules")}),M.map((C,O)=>s.jsx("div",{className:"mb-2 rounded-lg bg-surface-2 p-2.5",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:C.enabled!==!1,onChange:fe=>{const nt=M.map((kt,Kt)=>Kt===O?{...kt,enabled:fe.target.checked}:kt);B(nt),Yn(ja,nt),Be(!0),wu(nt).then(kt=>{B(kt),Yn(ja,kt)}).catch(()=>{}).finally(()=>Be(!1))}}),s.jsxs("select",{value:C.matchType,onChange:fe=>{const nt=M.map((kt,Kt)=>Kt===O?{...kt,matchType:fe.target.value}:kt);B(nt),Yn(ja,nt),Be(!0),wu(nt).then(kt=>{B(kt),Yn(ja,kt)}).catch(()=>{}).finally(()=>Be(!1))},className:"rounded bg-surface px-2 py-1 text-[11px]",children:[s.jsx("option",{value:"includes",children:"includes"}),s.jsx("option",{value:"exact",children:"exact"}),s.jsx("option",{value:"prefix",children:"prefix"}),s.jsx("option",{value:"regex",children:"regex"})]}),s.jsx("input",{value:C.pattern,onChange:fe=>{const nt=M.map((kt,Kt)=>Kt===O?{...kt,pattern:fe.target.value}:kt);B(nt),Yn(ja,nt)},onBlur:()=>{Be(!0),wu(M).then(fe=>{B(fe),Yn(ja,fe)}).catch(()=>{}).finally(()=>Be(!1))},placeholder:"pattern",className:"min-w-[180px] flex-1 rounded bg-surface px-2 py-1 text-[11px] font-mono"}),s.jsx("input",{value:C.output,onChange:fe=>{const nt=M.map((kt,Kt)=>Kt===O?{...kt,output:fe.target.value}:kt);B(nt),Yn(ja,nt)},onBlur:()=>{Be(!0),wu(M).then(fe=>{B(fe),Yn(ja,fe)}).catch(()=>{}).finally(()=>Be(!1))},placeholder:"output",className:"w-28 rounded bg-surface px-2 py-1 text-[11px]"}),s.jsx("button",{type:"button",onClick:()=>{const fe=M.filter((nt,kt)=>kt!==O);B(fe),Yn(ja,fe),Be(!0),wu(fe).then(nt=>{B(nt),Yn(ja,nt)}).catch(()=>{}).finally(()=>Be(!1))},className:"rounded bg-surface px-2 py-1 text-[11px] text-muted-foreground hover:text-destructive",children:e("common.delete")})]})},C.id)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{const C=[...M,{id:`rule-${Date.now()}`,enabled:!0,priority:100,matchType:"includes",pattern:"",output:""}];B(C),Yn(ja,C),Be(!0),wu(C).then(O=>{B(O),Yn(ja,O)}).catch(()=>{}).finally(()=>Be(!1))},className:"rounded-full bg-primary/15 px-3 py-1.5 text-[11px] font-medium text-primary hover:bg-primary/25",children:e("settings.addRule")}),s.jsx("button",{type:"button",onClick:()=>{Be(!0),LA().then(C=>{B(C),Yn(ja,C)}).catch(()=>{}).finally(()=>Be(!1))},className:"rounded-full bg-surface-2 px-3 py-1.5 text-[11px] font-medium text-muted-foreground hover:bg-surface-elevated hover:text-foreground",children:e("settings.resetDefaults")}),s.jsx("span",{className:"text-[11px] text-muted-foreground",children:Se?e("settings.saving"):G?`${M.length} rules`:"…"})]})]})]})]})]})]}),Ve&&s.jsx(Z$,{isOpen:Ve,onClose:()=>bt(!1)}),!ri&&s.jsx(my,{isOpen:ne,drawerWidthPx:Bo,onClose:()=>Nn("left-sidebar"),onOpen:Fa,sessions:Tt,activeSessionId:Ct,sessionStates:Ht,onNewSession:C=>ho(C),recoverableTmuxSessions:Jl,recoverableTmuxSessionsLoading:De,onRefreshRecoverableTmuxSessions:()=>{kl()},onCloseRecoverableTmuxSession:pu,onCloseSession:Xl,onSplitSession:Ec,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:ht,onSetSplitLayout:vd,onReorderSplitWorkspace:sl,onRenameSplitWorkspace:wd,onCombineSplitSessions:mu,onReorderSessions:_i,onSessionMenu:xd,onOpenSettings:Pi,onJumpToNextAttention:sa.length>0?_l:void 0,onOpenQuota:()=>bt(!0),updateState:ie,updateActionPending:Fe,onConfirmUpdateRestart:mn,onRetryUpdate:hn,serverHealthState:Ge,tmuxAvailable:tr.available,defaultSessionMode:ns,onTogglePinned:lr?ci:void 0}),!Nc&&s.jsx(gy,{isOpen:Ye,sessionId:Ct,drawerWidthPx:Jn,onClose:()=>Nn("right-sidebar"),onOpen:$a,rightSidebarFilePreviewOpen:Pa,rightSidebarFilePreviewCloseSignal:sr,onOpenRightSidebarFilePreview:Vl,onCloseRightSidebarFilePreview:Ci,rightSidebarRepoPickerOpen:Xt,rightSidebarRepoPickerCloseSignal:ir,onOpenRightSidebarRepoPicker:oo,onCloseRightSidebarRepoPicker:$s,markdownOutlineOpen:Je,markdownOutlineCloseSignal:Et,onOpenMarkdownOutline:Aa,onCloseMarkdownOutline:Sl,markdownImageLightboxOpen:vt,markdownImageLightboxCloseSignal:Me,onOpenMarkdownImageLightbox:es,onCloseMarkdownImageLightbox:ti,onTogglePinned:lr?io:void 0}),wt&&!c&&s.jsx("button",{type:"button",onClick:Yl,className:"fixed inset-0 z-toast flex cursor-default items-center justify-center bg-[var(--app-backdrop-soft)] px-6 text-left backdrop-blur-[1px]","aria-label":t==="zh"?"继续使用 Termdock":"Continue using Termdock",children:s.jsxs("div",{className:"max-w-[18rem] rounded-2xl border border-border/15 bg-surface/95 px-5 py-4 text-center shadow-[0_18px_50px_var(--app-shadow-strong)] backdrop-blur animate-fade-in",children:[s.jsx("div",{className:"text-[14px] font-semibold text-foreground",children:t==="zh"?"建议使用 Home":"Use Home instead"}),s.jsx("div",{className:"mt-1.5 text-[12px] leading-relaxed text-muted-foreground",children:t==="zh"?"按 Home 退后台,点任意位置继续。":"Use Home to leave. Tap anywhere to continue."}),s.jsx("div",{className:"mt-3 text-[11px] font-medium text-muted-foreground/80",children:t==="zh"?"轻点关闭提示":"Tap to dismiss"})]})}),Oe&&s.jsxs("div",{className:`fixed inset-x-3 bottom-4 z-toast mx-auto flex max-w-md items-center gap-2 rounded-xl border px-4 py-3 text-[12px] shadow-lg animate-fade-in ${Oe.tone==="success"?"border-[rgb(var(--success-rgb)_/_0.24)] bg-surface-elevated text-foreground":"border-destructive/30 bg-surface-elevated text-destructive"}`,role:Oe.tone==="error"?"alert":"status",children:[Oe.tone==="success"?s.jsx(qc,{size:14,className:"shrink-0 text-[color:var(--success)]"}):s.jsx(_f,{size:14,className:"shrink-0"}),s.jsx("span",{className:"min-w-0 flex-1",children:Oe.message}),s.jsx("button",{type:"button",onClick:()=>ft(null),className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-muted-foreground transition hover:bg-surface-2 hover:text-foreground","aria-label":e("common.close"),children:s.jsx(jn,{size:12})})]}),l&&s.jsxs(s.Fragment,{children:[!lr&&s.jsx(RC,{onClose:()=>d(!1)}),s.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-toast hidden max-h-48 overflow-y-auto border-t border-border/15 bg-surface p-3 animate-fade-in md:block",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("h4",{className:"ui-kicker",children:"Debug Info"}),s.jsx("button",{type:"button",onClick:()=>d(!1),className:"text-xs text-muted-foreground hover:text-foreground",children:"Close"})]}),s.jsx("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(At,null,2)})]})]})]}),ch=rt?null:s.jsx(NA,{className:"z-modal-panel",status:"正在恢复终端…"});return lr?s.jsxs("div",{className:"w-screen h-full flex flex-row",children:[ri&&s.jsx(s.Fragment,{children:s.jsxs("div",{ref:wa,className:"relative",style:{width:Jt,flexShrink:0,height:"100%"},children:[s.jsx(my,{isOpen:ne,drawerWidthPx:Jt,onClose:ei,onOpen:Fa,sessions:Tt,activeSessionId:Ct,sessionStates:Ht,onNewSession:C=>ho(C),recoverableTmuxSessions:Jl,recoverableTmuxSessionsLoading:De,onRefreshRecoverableTmuxSessions:()=>{kl()},onCloseRecoverableTmuxSession:pu,onCloseSession:Xl,onSplitSession:Ec,onCloseSplit:C=>window.dispatchEvent(new CustomEvent("close-terminal-split",{detail:C})),onRemoveFromSplit:C=>window.dispatchEvent(new CustomEvent("remove-terminal-split-pane",{detail:C})),splitWorkspaces:ht,onSetSplitLayout:vd,onReorderSplitWorkspace:sl,onRenameSplitWorkspace:wd,onCombineSplitSessions:mu,onReorderSessions:_i,onSessionMenu:xd,onOpenSettings:Pi,onJumpToNextAttention:sa.length>0?_l:void 0,onOpenQuota:()=>bt(!0),updateState:ie,updateActionPending:Fe,onConfirmUpdateRestart:mn,onRetryUpdate:hn,serverHealthState:Ge,tmuxAvailable:tr.available,defaultSessionMode:ns,pinned:!0,onTogglePinned:ci}),s.jsx("div",{role:"separator",tabIndex:-1,className:"absolute inset-y-0 right-0 z-20 w-[5px] cursor-col-resize hover:bg-border/30 active:bg-border/50 transition-colors",onMouseDown:Ua})]})}),s.jsxs("div",{className:"relative flex-1 min-w-0 h-full overflow-hidden",children:[Sd,Nc&&s.jsxs("div",{className:"absolute inset-y-0 right-0 z-20 flex",style:{width:il},children:[s.jsx("div",{role:"separator",tabIndex:-1,className:"h-full w-[5px] shrink-0 cursor-col-resize bg-border/10 transition-colors hover:bg-primary/30 active:bg-primary/50",onMouseDown:_c}),s.jsx("div",{style:{width:po,flexShrink:0,height:"100%"},children:s.jsx(gy,{isOpen:!0,sessionId:Ct,drawerWidthPx:po,onClose:$n,onOpen:$a,pinned:!0,onTogglePinned:io,rightSidebarFilePreviewOpen:Pa,rightSidebarFilePreviewCloseSignal:sr,onOpenRightSidebarFilePreview:Vl,onCloseRightSidebarFilePreview:Ci,rightSidebarRepoPickerOpen:Xt,rightSidebarRepoPickerCloseSignal:ir,onOpenRightSidebarRepoPicker:oo,onCloseRightSidebarRepoPicker:$s,markdownOutlineOpen:Je,markdownOutlineCloseSignal:Et,onOpenMarkdownOutline:Aa,onCloseMarkdownOutline:Sl,markdownImageLightboxOpen:vt,markdownImageLightboxCloseSignal:Me,onOpenMarkdownImageLightbox:es,onCloseMarkdownImageLightbox:ti})})]})]}),s.jsx(Ey,{sessionId:Ct}),ch]}):s.jsxs(s.Fragment,{children:[Sd,s.jsx(Ey,{sessionId:Ct}),ch]})}const Tz=Object.freeze(Object.defineProperty({__proto__:null,default:NU,runServiceUpdateConfirmation:B4},Symbol.toStringTag,{value:"Module"}));export{CC as $,m0 as A,N0 as B,VF as C,wC as D,R0 as E,f3 as F,qF as G,qc as H,kf as I,b3 as J,p3 as K,m3 as L,eS as M,hS as N,PS as O,gS as P,b0 as Q,vn as R,Gl as S,u4 as T,u1 as U,XS as V,Ms as W,w3 as X,aC as Y,dC as Z,Wp as _,AC as a,$U as a0,OU as a1,L3 as a2,zU as a3,HU as a4,UU as a5,Mv as a6,wz as a7,x5 as a8,R1 as a9,Ig as aa,lp as ab,_y as ac,k3 as ad,sf as ae,mg as af,PC as ag,LF as ah,FU as ai,M1 as aj,EN as ak,ou as al,xy as am,r1 as an,Bi as ao,Az as ap,j3 as aq,If as b,$$ as c,Tz as d,SC as e,Cf as f,JA as g,KA as h,u3 as i,h3 as j,I0 as k,wF as l,kT as m,E0 as n,VO as o,qu as p,dg as q,WT as r,XT as s,sS as t,g3 as u,lS as v,x3 as w,TS as x,CS as y,kS as z};